Close() public méthode

public Close ( ) : void
Résultat void
 /// <summary>
 /// 写入 中文 资源文件.
 /// </summary>
 public void WriteChinaResource()
 {
     // 构造写入器.
     ResourceWriter rw = new ResourceWriter("China.resource");
     rw.AddResource("Hello", "你好");
     rw.Close();
 }
        public SpecialResourceWriter()
        {
            // Load all bunlde
            IList<IResourceBundle> allBundle = new List<IResourceBundle>(20);
            allBundle.Add(ResourceBundleFactory.CreateBundle("CanonMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("CasioMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("Commons", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("ExifInteropMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("ExifMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("FujiFilmMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("GpsMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("IptcMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("JpegMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("KodakMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("KyoceraMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("NikonTypeMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("OlympusMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("PanasonicMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("PentaxMarkernote", null, ResourceBundleFactory.USE_TXTFILE));
            allBundle.Add(ResourceBundleFactory.CreateBundle("SonyMarkernote", null, ResourceBundleFactory.USE_TXTFILE));

            foreach(IResourceBundle bdl in allBundle)
            {
                ResourceWriter rw = new ResourceWriter(bdl.Fullname+".resources");
                IDictionary<string,string> idic = bdl.Entries;
                IDictionaryEnumerator enumDic =  (IDictionaryEnumerator)idic.GetEnumerator();
                while (enumDic.MoveNext())
                {
                    rw.AddResource((string)enumDic.Key, (string)enumDic.Value);
                }
                rw.Close();
                rw.Dispose();

            }
        }
 /// <summary>
 /// 写入 英文 资源文件.
 /// </summary>
 public void WriteEnglishResource()
 {
     // 构造写入器.
     ResourceWriter rw = new ResourceWriter("English.resource");
     rw.AddResource("Hello", "Hello");
     rw.Close();
 }
        static void Main(string[] args)
        {
            ResourceWriter myResource = new ResourceWriter("Images.resources");
            myResource.AddResource("flash", new Bitmap("flashScreen.png"));
            Image simpleImage = new Image();
            simpleImage.Margin = new Thickness(0);

            BitmapImage bi = new BitmapImage();
            //BitmapImage.UriSource must be in a BeginInit/EndInit block
            bi.BeginInit();





            bi.UriSource = new Uri(@"pack://siteoforigin:,,,/alarm3.png");
            bi.EndInit();
            //set image source
            simpleImage.Source = bi;
            //        simpleImage.Stretch = Stretch.None;
            simpleImage.HorizontalAlignment = HorizontalAlignment.Center;
            simpleImage.Visibility = Visibility.Hidden;
            simpleImage.Name = "AlarmIndicator";
            simpleImage.Width = 13;


            myResource.AddResource("alarm", new Image("alarm3.png"));
            myResource.Close(); 


        }
Exemple #5
0
 public static void AddFileAsStringResource(string resourceFile, string resourceName, string inputFile)
 {
     ResourceWriter writer = new ResourceWriter(resourceFile);
     StreamReader reader = new StreamReader(inputFile);
     string s = reader.ReadToEnd();
     reader.Close();
     writer.AddResource(resourceName, s);
     writer.Close();
 }
Exemple #6
0
 public static void InsertEmployee(ResourceObj emp)
 {
     l.Add(emp);
     ResourceWriter rsxw = new ResourceWriter(path);
     for (int i = 0; i < l.Count; i++)
     {
         rsxw.AddResource("obj" + i.ToString(), l[i]);
     }
     rsxw.Close();
 }
Exemple #7
0
        void GenerationData(int countOfObj)
        {
            Random rand = new Random();
            ResourceWriter rsxw = new ResourceWriter(Server.MapPath("~/Resources/") + "res.resx");
            for (int i = 0; i < countOfObj; i++)
            {

                rsxw.AddResource("obj" + i.ToString(), new ResourceObj(rand));
            }
            rsxw.Close();
        }
Exemple #8
0
        /// <summary>
        /// Creates a resources file with an image
        /// </summary>
        /// <param name="imageSourcePath"></param>
        /// <param name="outputPath"></param>
        public static void WriteImageResource(string imageSourcePath, string outputPath) {
            Debug.Assert(imageSourcePath.EndsWith(".png"));
            Debug.Assert(outputPath.EndsWith(".resources"));

            FileInfo fileInfo = new FileInfo(imageSourcePath);
            FileStream fsSource = fileInfo.OpenRead();
            byte[] bytes = new byte[fileInfo.Length + 1];
            int bytesRead = fsSource.Read(bytes, 0, bytes.Length);
            Debug.Assert(bytesRead == fileInfo.Length);
            MemoryStream memoryStream = new MemoryStream(bytes, 0, bytesRead);
            ResourceWriter resw = new ResourceWriter(outputPath);
            resw.AddResource(imageSourcePath.ToLowerInvariant(), memoryStream);
            resw.Close();
        }
 // Read all msgid/msgstr pairs (each string being NUL-terminated and
 // UTF-8 encoded) and write the .resources file to the given filename.
 WriteResource(String filename)
 {
     Stream input = new BufferedStream(Console.OpenStandardInput());
       reader = new StreamReader(input, new UTF8Encoding());
       if (filename.Equals("-")) {
     BufferedStream output = new BufferedStream(Console.OpenStandardOutput());
     // A temporary output stream is needed because ResourceWriter.Generate
     // expects to be able to seek in the Stream.
     MemoryStream tmpoutput = new MemoryStream();
     ResourceWriter rw = new ResourceWriter(tmpoutput);
     ReadAllInput(rw);
     #if __CSCC__
     // Use the ResourceReader to check against pnet-0.6.0 ResourceWriter
     // bug.
     try {
       ResourceReader rr = new ResourceReader(new MemoryStream(tmpoutput.ToArray()));
       foreach (System.Collections.DictionaryEntry entry in rr);
     } catch (IOException e) {
       throw new Exception("class ResourceWriter is buggy", e);
     }
     #endif
     tmpoutput.WriteTo(output);
     rw.Close();
     output.Close();
       } else {
     #if __CSCC__
     MemoryStream tmpoutput = new MemoryStream();
     ResourceWriter rw = new ResourceWriter(tmpoutput);
     ReadAllInput(rw);
     // Use the ResourceReader to check against pnet-0.6.0 ResourceWriter
     // bug.
     try {
       ResourceReader rr = new ResourceReader(new MemoryStream(tmpoutput.ToArray()));
       foreach (System.Collections.DictionaryEntry entry in rr);
     } catch (IOException e) {
       throw new Exception("class ResourceWriter is buggy", e);
     }
     BufferedStream output = new BufferedStream(new FileStream(filename, FileMode.Create, FileAccess.Write));
     tmpoutput.WriteTo(output);
     rw.Close();
     output.Close();
     #else
     ResourceWriter rw = new ResourceWriter(filename);
     ReadAllInput(rw);
     rw.Close();
     #endif
       }
 }
Exemple #10
0
        public static void UpdateEmployee(ASP_ex5.ResourceObj emp)
        {
            ResourceWriter rsxw = new ResourceWriter(path);
            for (int i = 0; i < l.Count; i++)
            {
                if (l[i].key == emp.key)
                {
                    l[i].comment = emp.comment;
                    l[i].key = emp.key;
                    l[i].value = emp.value;

                }
                rsxw.AddResource("obj" + i.ToString(), l[i]);
            }
            rsxw.Close();
        }
Exemple #11
0
        public static void InsertEmployee(string key, string value, string comment)
        {
            bool temp = false;
            for (int i = 0; i < l.Count; i++)
            {
                if (l[i].key == key)
                {
                    temp = true;
                }               
            }
            if(temp ==false)
                l.Add(new ResourceObj(key, value, comment));
            ResourceWriter rsxw = new ResourceWriter(path);

            for (int i = 0; i < l.Count; i++)
            {
                    rsxw.AddResource("obj" + i.ToString(), l[i]);
            }
            rsxw.Close();
        }
Exemple #12
0
 private void Comp()
 {
     if (radioButton1.Checked == true)
     {
         System.Resources.ResourceWriter w = new System.Resources.ResourceWriter("res.resources");            //Declaration du nouvelle ressource
         w.AddResource("file", Cryptoclass.DexEncrypt(System.IO.File.ReadAllBytes(textBox1.Text), this.key)); // lit tout les bytes du fichier source, les encrypt, et les ajout dans la ressource
         w.Close();
     }
     if (radioButton2.Checked == true)
     {
         System.Resources.ResourceWriter w = new System.Resources.ResourceWriter("res.resources");                   //Declaration du nouvelle ressource
         w.AddResource("file", Cryptoclass.RC4EncryptDecrypt(System.IO.File.ReadAllBytes(textBox1.Text), this.key)); // lit tout les bytes du fichier source, les encrypt, et les ajout dans la ressource
         w.Close();
     }
     if (radioButton4.Checked == true)
     {
         System.Resources.ResourceWriter w = new System.Resources.ResourceWriter("res.resources");                 //Declaration du nouvelle ressource
         w.AddResource("file", Cryptoclass.RijndaelEncrypt(System.IO.File.ReadAllBytes(textBox1.Text), this.key)); // lit tout les bytes du fichier source, les encrypt, et les ajout dans la ressource
         w.Close();
     }
 }
Exemple #13
0
        private void InitBarManager()
        {
            //string[] strMenus = { "系统管理", "会员管理", "财务管理", "报表管理", "基础资料", "货品管理", "客户管理", "物流管理" };
            //Utils.ImageCollection largeImgs;
            var query = CacheInfo.listMenuInfoModel().Where(p => p.MenuBig == true).ToList();

            if (query == null || query.Count() == 0)
            {
                return;
            }
            string imagePath = Application.StartupPath + "\\TempImage";
            int    imgindex  = 0;
            string fileName  = string.Empty;

            foreach (var model in query)
            {
                if (model.MenuBigImage == null)
                {
                    return;
                }
                //添加图标到资源文件
                fileName = string.Format("{0}.png", model.MenuFrmName);
                ImageTools.CreateImage(imagePath, fileName, model.MenuBigImage);
                System.Resources.IResourceWriter rw = new System.Resources.ResourceWriter("Resource.resx");
                rw.AddResource(model.MenuFrmName, (Image)Image.FromStream(new MemoryStream(model.MenuBigImage)).Clone());//Image.FromFile( imagePath + "\\" + fileName)
                rw.Close();
                //把资源文件中的图像添加到largeImgs中
                this.largeImgs.Images.Add((Image)Image.FromStream(new MemoryStream(model.MenuBigImage)).Clone(), model.MenuFrmName);
                //this.largeImgs.Images.SetKeyName(imgindex, fileName);
                //创建大图标菜单
                DevExpress.XtraBars.BarLargeButtonItem barLargeItem = new DevExpress.XtraBars.BarLargeButtonItem(barMain, model.MenuName);
                barLargeItem.LargeGlyph = largeImgs.Images[imgindex];//也可以设置 barLargeItem.LargeImageIndex,但是效果不是很好,可以试试
                barLargeItem.Hint       = model.MenuName;
                barLargeItem.Tag        = model.MenuName;
                barTop.LinksPersistInfo.Add(new DevExpress.XtraBars.LinkPersistInfo(barLargeItem, true));
                barMain.Items.Add(barLargeItem);
                imgindex++;
            }
        }
		public void Bug81759 ()
		{
			MemoryStream ms = new MemoryStream ();
			using (ResourceReader xr = new ResourceReader (
				"Test/resources/bug81759.resources")) {
				ResourceWriter rw = new ResourceWriter (ms);
				foreach (DictionaryEntry de in xr)
					rw.AddResource ((string) de.Key, de.Value);
				rw.Close ();
			}
			ResourceReader rr = new ResourceReader (new MemoryStream (ms.ToArray ()));
			foreach (DictionaryEntry de in rr) {
				Assert.AreEqual ("imageList.ImageSize", de.Key as string, "#1");
				Assert.AreEqual ("Size", de.Value.GetType ().Name, "#2");
			}
		}
		public void AddResource_Name_Duplicate ()
		{
			MemoryStream ms = new MemoryStream ();
			ResourceWriter writer = new ResourceWriter (ms);
			writer.AddResource ("FirstName", "Miguel");

			try {
				writer.AddResource ("FirstNaMe", "Chris");
				Assert.Fail ("#1");
			} catch (ArgumentException ex) {
				// Item has already been added. Key is dictionary:
				// 'FirstName'  Key being added: 'FirstNaMe'
				Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
				Assert.IsNull (ex.InnerException, "#3");
				Assert.IsNotNull (ex.Message, "#4");
				Assert.IsNull (ex.ParamName, "#5");
			}

			writer.AddResource ("Name", "Miguel");
			writer.Close ();
		}
		[Test] // AddResource (string, string)
		public void AddResource2_Value_Null ()
		{
			MemoryStream ms = new MemoryStream ();
			ResourceWriter writer = new ResourceWriter (ms);
			writer.AddResource ("Name", (string) null);
			writer.Generate ();

			ms.Position = 0;
			ResourceReader rr = new ResourceReader (ms);
			IDictionaryEnumerator enumerator = rr.GetEnumerator ();
			Assert.IsTrue (enumerator.MoveNext (), "#1");
			Assert.AreEqual ("Name", enumerator.Key, "#2");
			Assert.IsNull (enumerator.Value, "#3");
			Assert.IsFalse (enumerator.MoveNext (), "#4");

			writer.Close ();
		}
		[Test] // AddResource (string, string)
		public void AddResource2_Name_Null ()
		{
			MemoryStream ms = new MemoryStream ();
			ResourceWriter writer = new ResourceWriter (ms);

			try {
				writer.AddResource ((string) null, "abc");
				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 ("name", ex.ParamName, "#6");
			}

			writer.Close ();
		}
Exemple #18
0
        private bool CompileHere()
        {
            Console.WriteLine("Compiling " + FCSProjFile);

            XmlDocument doc = new XmlDocument();

            doc.Load(FCSProjFile);

            XmlNode propertyGroup = doc.DocumentElement.FirstChild;
            Dictionary <string, string>mainProperties = new Dictionary <string, string>();

            List <String>src = new List <string>();

            foreach (XmlNode propNode in propertyGroup.ChildNodes)
            {
                mainProperties.Add(propNode.Name, propNode.InnerText);
            }

            CSharpCodeProvider csc = new CSharpCodeProvider(
                new Dictionary <string, string>() {
                    { "CompilerVersion", "v4.0" }
                });
            CompilerParameters parameters = new CompilerParameters();

            parameters.GenerateInMemory = false;
            parameters.CompilerOptions = string.Empty;

            string OutputFile = Path.GetFullPath(Path.GetDirectoryName(FCSProjFile) + "/" + mainProperties["OutputPath"].Replace("\\", "/"));

            OutputFile += "/" + mainProperties["AssemblyName"];

            if (mainProperties["OutputType"].ToLower() == "library")
            {
                parameters.GenerateExecutable = false;
                OutputFile += ".dll";
            }
            else if (mainProperties["OutputType"].ToLower() == "winexe")
            {
                parameters.GenerateExecutable = true;
                parameters.CompilerOptions += " /target:winexe";
                OutputFile += ".exe";
            }
            else
            {
                parameters.GenerateExecutable = true;
                OutputFile += ".exe";
            }

            // needed because of sqlite3.dll, when compiling on Linux for Windows
            if (this.Project.PlatformName == "unix")
            {
                parameters.CompilerOptions += " /platform:x86";
            }

            parameters.OutputAssembly = OutputFile;
            parameters.WarningLevel = 4;

            if (mainProperties.ContainsKey("ApplicationManifest") && (mainProperties["ApplicationManifest"].Length > 0))
            {
                if (!this.Project.RuntimeFramework.Name.StartsWith("mono"))
                {
                    // we cannot include the manifest when compiling on Mono
                    parameters.CompilerOptions += " /win32manifest:\"APPMANIFEST\"";
                }
            }

            parameters.CompilerOptions += " /define:DEBUGMODE /doc:\"XMLOUTPUTFILE.xml\"";

            if (this.Project.PlatformName == "unix")
            {
                // command line options use - instead of /, eg. /define or -define
                parameters.CompilerOptions = parameters.CompilerOptions.Replace("/", "-");
            }

            // insert the path to the xml output file after the command line options thing has been done
            parameters.CompilerOptions = parameters.CompilerOptions.Replace("XMLOUTPUTFILE", OutputFile.Replace("\\", "/"));

            if (mainProperties.ContainsKey("ApplicationManifest") && (mainProperties["ApplicationManifest"].Length > 0))
            {
                parameters.CompilerOptions =
                    parameters.CompilerOptions.Replace("APPMANIFEST",
                        Path.GetFullPath(Path.GetDirectoryName(FCSProjFile) + "/" + mainProperties["ApplicationManifest"].Replace("\\", "/")));
            }

            String FrameworkDLLPath = Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(typeof(System.Type)).Location);

            foreach (XmlNode ProjectNodeChild in doc.DocumentElement)
            {
                if (ProjectNodeChild.Name == "ItemGroup")
                {
                    foreach (XmlNode ItemNode in ProjectNodeChild)
                    {
                        if (ItemNode.Name == "Reference")
                        {
                            if (ItemNode.HasChildNodes && (ItemNode.ChildNodes[0].Name == "HintPath"))
                            {
                                if (ItemNode.ChildNodes[0].InnerText.Contains(".."))
                                {
                                    parameters.ReferencedAssemblies.Add(Path.GetFullPath(Path.GetDirectoryName(FCSProjFile) + "/" +
                                            ItemNode.ChildNodes[0].InnerText.Replace("\\", "/")));
                                }
                                else
                                {
                                    parameters.ReferencedAssemblies.Add(ItemNode.ChildNodes[0].InnerText);
                                }
                            }
                            else
                            {
                                // .net dlls
                                parameters.ReferencedAssemblies.Add(
                                    FrameworkDLLPath + Path.DirectorySeparatorChar +
                                    ItemNode.Attributes["Include"].Value + ".dll");
                            }
                        }
                        else if (ItemNode.Name == "ProjectReference")
                        {
                            string ReferencedProjectName = ItemNode.ChildNodes[1].InnerText;
                            parameters.ReferencedAssemblies.Add(
                                Path.GetFullPath(Path.GetDirectoryName(OutputFile) + "/" +
                                    ReferencedProjectName.Replace("\\", "/") + ".dll"));
                        }
                        else if (ItemNode.Name == "Compile")
                        {
                            if (ItemNode.Attributes["Include"].Value.Contains(".."))
                            {
                                src.Add(Path.GetFullPath(Path.GetDirectoryName(FCSProjFile) + "/" +
                                        ItemNode.Attributes["Include"].Value.Replace("\\", "/")));
                            }
                            else
                            {
                                src.Add(ItemNode.Attributes["Include"].Value);
                            }
                        }
                        else if (ItemNode.Name == "EmbeddedResource")
                        {
                            string ResourceXFile = ItemNode.Attributes["Include"].Value;

                            if (ResourceXFile.StartsWith(".."))
                            {
                                ResourceXFile = Path.GetFullPath(Path.GetDirectoryName(FCSProjFile) + "/" +
                                    ResourceXFile.Replace("\\", "/"));
                            }

                            if (ResourceXFile.EndsWith(".resx"))
                            {
                                string NamespaceAndClass = Path.GetFileNameWithoutExtension(ResourceXFile);

                                if (ItemNode.HasChildNodes && (ItemNode.FirstChild.Name == "DependentUpon"))
                                {
                                    string CSFile = ItemNode.FirstChild.InnerText;

                                    if (CSFile.StartsWith(".."))
                                    {
                                        CSFile = Path.GetFullPath(Path.GetDirectoryName(FCSProjFile) + "/" +
                                            CSFile.Replace("\\", "/"));
                                    }
                                    else if (!Path.IsPathRooted(CSFile))
                                    {
                                        CSFile = Path.GetFullPath(Path.GetDirectoryName(ResourceXFile) + "/" +
                                            CSFile);
                                    }

                                    NamespaceAndClass = GetNamespaceAndClass(CSFile);
                                }

                                //"../../../../tmp/" +
                                string ResourcesFile = NamespaceAndClass + ".resources";

                                if (File.Exists(ResourceXFile))
                                {
                                    Environment.CurrentDirectory = Path.GetDirectoryName(ResourceXFile);

                                    ResXResourceReader ResXReader = new ResXResourceReader(ResourceXFile);
                                    FileStream fs = new FileStream(ResourcesFile, FileMode.OpenOrCreate, FileAccess.Write);
                                    IResourceWriter writer = new ResourceWriter(fs);

                                    foreach (DictionaryEntry d in ResXReader)
                                    {
                                        writer.AddResource(d.Key.ToString(), d.Value);
                                    }

                                    writer.Close();

                                    parameters.EmbeddedResources.Add(ResourcesFile);
                                }
                                else
                                {
                                    Console.WriteLine("Warning: cannot find resource file " + ResourceXFile);
                                }
                            }
                            else
                            {
                                parameters.EmbeddedResources.Add(ResourceXFile);
                            }
                        }
                    }
                }
            }

            CompilerResults results = csc.CompileAssemblyFromFile(parameters, src.ToArray());

            bool result = true;

            foreach (CompilerError error in results.Errors)
            {
                Console.WriteLine(error.ToString());

                if (!error.IsWarning)
                {
                    result = false;
                }
            }

            if (!result)
            {
                FailTask fail = new FailTask();
                this.CopyTo(fail);
                fail.Message = "compiler error(s)";
                fail.Execute();
            }

            return result;
        }
		public void Generate_Closed ()
		{
			MemoryStream ms = new MemoryStream ();
			ResourceWriter writer = new ResourceWriter (ms);
			writer.AddResource ("Name", "Miguel");
			writer.Close ();

			try {
				writer.Generate ();
				Assert.Fail ("#B1");
			} catch (InvalidOperationException ex) {
				// The resource writer has already been closed
				// and cannot be edited
				Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2");
				Assert.IsNull (ex.InnerException, "#B3");
				Assert.IsNotNull (ex.Message, "#B4");
			}
		}
Exemple #20
0
		private static void CompileEmbeddedRes(PlgxPluginInfo plgx)
		{
			foreach(string strResSrc in plgx.EmbeddedResourceSources)
			{
				string strResFileName = plgx.BaseFileName + "." + UrlUtil.ConvertSeparators(
					UrlUtil.MakeRelativePath(plgx.CsprojFilePath, strResSrc), '.');
				string strResFile = UrlUtil.GetFileDirectory(plgx.CsprojFilePath, true,
					true) + strResFileName;

				if(strResSrc.EndsWith(".resx", StrUtil.CaseIgnoreCmp))
				{
					PrepareResXFile(strResSrc);

					string strRsrc = UrlUtil.StripExtension(strResFile) + ".resources";
					ResXResourceReader r = new ResXResourceReader(strResSrc);
					ResourceWriter w = new ResourceWriter(strRsrc);

					r.BasePath = UrlUtil.GetFileDirectory(strResSrc, false, true);

					foreach(DictionaryEntry de in r)
						w.AddResource((string)de.Key, de.Value);

					w.Generate();
					w.Close();
					r.Close();

					if(File.Exists(strRsrc))
					{
						plgx.CompilerParameters.EmbeddedResources.Add(strRsrc);
						Program.TempFilesPool.Add(strRsrc);
					}
				}
				else
				{
					File.Copy(strResSrc, strResFile, true);
					plgx.CompilerParameters.EmbeddedResources.Add(strResFile);
				}
			}
		}
Exemple #21
0
        public static void UpdateEmployee(string key, string value, string comment)
        {
            ResourceWriter rsxw = new ResourceWriter(path);
            for (int i = 0; i < l.Count; i++)
            {
                if (l[i].key == key)
                {
                    l[i].comment = comment;
                    l[i].key = key;
                    l[i].value = value;

                }
                rsxw.AddResource("obj" + i.ToString(), l[i]);
            }
            rsxw.Close();
        }
Exemple #22
0
        public static string GenerateCCDtransmit()
        {
            string InputFileName = @"D:\CCD\testFile\1097421_JOHN_30-01-12_05-50-13.xml";
            string TempFileName = "enc_using_stream_13";
            string Password = VICEncryption.CreateRandomPassword(12);
            string OutputFile = TempFileName + ".xml";
            string hashKey = VICEncryption.GenerateHash(File.ReadAllText(InputFileName));
            string SourceFileName = @"D:\PROJECTS\Tests\R_N_D\CompileCode\skeleton\skeleton.cs";
            string OutputAsmblyName = @"D:\ccd\VIC.com";

            FileStream fs = new FileStream(InputFileName, FileMode.Open);

            VICEncryption.Encrypt(fs, OutputFile, Password);
             Console.WriteLine(   VICEncryption.GenerateHash(VICEncryption.Decrypt(File.OpenRead(OutputFile), Password)));
            string resourceFileName = TempFileName + ".resource";
            StreamWriter wr = File.CreateText(resourceFileName);
            wr.Close();

            IResourceWriter writer = new ResourceWriter(resourceFileName);

            Console.WriteLine(Password);
            writer.AddResource("CCD_PASS", VICEncryption.Encrypt(Password, hashKey));
            writer.AddResource("CCD_HASH", hashKey);
            // Writes the resources to the file or stream, and closes it.
            writer.Close();

            List<string> filesToEmbed = new List<string>();
            filesToEmbed.Add(resourceFileName);
            filesToEmbed.Add(OutputFile);
            CompileCode(CodeDomProvider.CreateProvider("CSharp"), SourceFileName, filesToEmbed, OutputAsmblyName);
            string exeFile = @"D:\CCD\Encrypt\Makezip.exe";
            //Process p = new Process();
            //p.StartInfo.UseShellExecute = false;
            //p.StartInfo.RedirectStandardOutput = true;
            //p.StartInfo.FileName = exeFile;// +" " + OutputAsmblyName + " " + @"D:\CCD\Encrypt\a.zip";

            //p.Start();
            Process.Start(exeFile, OutputAsmblyName + " " + @"D:\CCD\Encrypt\a.zip");
               // ZipFile(OutputAsmblyName, @"D:\CCD\Encrypt\a.zip");
            return Password;
        }
        /// <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;
                }
            }
        }
Exemple #24
0
 public static void DeleteEmployee(string key, string value, string comment)
 {
     ResourceWriter rsxw = new ResourceWriter(path);
     for (int i = 0; i < l.Count; i++)
     {
         if (l[i].key != key)
         {
             rsxw.AddResource("obj" + i.ToString(), l[i]);
         }
     }
     rsxw.Close();
 }
Exemple #25
0
        public static void DeleteEmployee(ASP_ex5.ResourceObj emp)
        {
            ResourceWriter rsxw = new ResourceWriter(path);
            for (int i = 0; i < l.Count; i++)
            {
                if (l[i].key != emp.key)
                {
                    rsxw.AddResource("obj" + i.ToString(), l[i]);
                }
            }
            rsxw.Close();

        }
		public void Close ()
		{
			MemoryStream ms = new MemoryStream ();
			ResourceWriter writer = new ResourceWriter (ms);
			writer.AddResource ("Name", "Miguel");
			Assert.IsTrue (ms.CanWrite, "#A1");
			Assert.IsTrue (ms.GetBuffer ().Length == 0, "#A2");
			writer.Close ();
			Assert.IsFalse (ms.CanWrite, "#B1");
			Assert.IsFalse (ms.GetBuffer ().Length == 0, "#B2");
			writer.Close ();
		}
		[Test] // bug #339074
		public void Close_NoResources ()
		{
			string tempFile = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
				"test.resources");

			ResourceWriter writer = new ResourceWriter (tempFile);
			writer.Close ();

			using (FileStream fs = File.OpenRead (tempFile)) {
				Assert.IsFalse (fs.Length == 0, "#1");

				using (ResourceReader reader = new ResourceReader (fs)) {
					Assert.IsFalse (reader.GetEnumerator ().MoveNext (), "#2");
				}
			}
		}
        private void CompileResourceFile()
        {
            ResXResourceReader resxReader = new ResXResourceReader(ResourcesFilePath);
            IDictionaryEnumerator resxEnumerator = resxReader.GetEnumerator();

            using (IResourceWriter writer = new ResourceWriter(CompiledResourcesFilePath))
            {
                while (resxEnumerator.MoveNext())
                {
                    try
                    {
                        writer.AddResource(resxEnumerator.Key.ToString(), resxEnumerator.Value);
                    }
                    catch (Exception ex)
                    {
                        throw new FrameworkException(string.Format("Error while compiling resource file \"{0}\" on key \"{1}\".", ResourcesFileName, resxEnumerator.Key.ToString()), ex);
                    }
                }

                writer.Generate();
                writer.Close();
            }
            resxReader.Close();
        }
		[Test] // AddResource (string, byte [])
		public void AddResource0 ()
		{
			byte [] value = new byte [] { 5, 7 };

			MemoryStream ms = new MemoryStream ();
			ResourceWriter writer = new ResourceWriter (ms);
			writer.AddResource ("Name", value);
			writer.Generate ();

			try {
				writer.AddResource ("Address", new byte [] { 8, 12 });
				Assert.Fail ("#A1");
			} catch (InvalidOperationException ex) {
				// The resource writer has already been closed
				// and cannot be edited
				Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#A2");
				Assert.IsNull (ex.InnerException, "#A3");
				Assert.IsNotNull (ex.Message, "#A4");
			}

			ms.Position = 0;
			ResourceReader rr = new ResourceReader (ms);
			IDictionaryEnumerator enumerator = rr.GetEnumerator ();
			Assert.IsTrue (enumerator.MoveNext (), "#B1");
			Assert.AreEqual ("Name", enumerator.Key, "#B3");
			Assert.AreEqual (value, enumerator.Value, "#B4");
			Assert.IsFalse (enumerator.MoveNext (), "#B5");

			writer.Close ();
		}
Exemple #30
0
        /// <summary>
        /// CompileSatelliteAssemblies()
        /// </summary>
        /// <param name="targetCulture"></param>
        /// <param name="ds"></param>
        public void CompileSatelliteAssemblies(string targetCulture, GlobalizationDataSet ds)
        {
            //all columns are required except SourceValue

            string tempPath = Path.GetTempPath();
            applicationPath = applicationPath.Trim().ToLower();

            if (applicationPath[applicationPath.Length - 1] != Path.DirectorySeparatorChar)
                applicationPath += Path.DirectorySeparatorChar;

            this.AppendToLog(SharedStrings.INSTALLING_LANGUAGE, targetCulture);

            GlobalizationDataSet.CulturalResourcesDataTable cultureTable = ds.CulturalResources;//.SelectFilter("CultureName='" + targetCulture + "'");

            GlobalizationDataSet.CulturalResourcesDataTable assembliesTable = cultureTable.SelectDistinct("AssemblyName");
            foreach (GlobalizationDataSet.CulturalResourcesRow assemblyRow in assembliesTable)
            {
                List<string> resourceList = new List<string>();

                GlobalizationDataSet.CulturalResourcesDataTable resourceTable = ds.CulturalResources.SelectFilter("AssemblyName='" + assemblyRow.AssemblyName + "'").SelectDistinct("ManifestResourceName");
                foreach (GlobalizationDataSet.CulturalResourcesRow resourceRow in resourceTable)
                {

                    string resourceFilename;
                    resourceFilename = resourceRow.ManifestResourceName.Substring(0, resourceRow.ManifestResourceName.Length - "resources".Length);
                    resourceFilename = Path.Combine(tempPath, resourceFilename + targetCulture + ".resources");

                    try
                    {
                        using (ResourceWriter writer = new ResourceWriter(resourceFilename))
                        {
                            GlobalizationDataSet.CulturalResourcesDataTable itemTable = ds.CulturalResources.SelectFilter("AssemblyName='" + assemblyRow.AssemblyName + "'").SelectFilter("ManifestResourceName='" + resourceRow.ManifestResourceName + "'");
                            foreach (GlobalizationDataSet.CulturalResourcesRow itemRow in itemTable)
                            {
                                writer.AddResource(itemRow.ResourceName, itemRow.ResourceValue);
                            }
                            writer.Close();
                        }

                        resourceList.Add(resourceFilename);
                    }
                    catch
                    {
                        foreach (string tempResourceFile in resourceList)
                        {
                            try
                            {
                                File.Delete(tempResourceFile);
                            }
                            catch
                            {
                                //eat
                            }
                        }

                        // kickout
                        throw;
                    }
                }

                string assemblyFilename = targetCulture + Path.DirectorySeparatorChar + assemblyRow.AssemblyName + ".resources.dll";
                assemblyFilename = Path.Combine(applicationPath, assemblyFilename);

                this.AppendToLog("Compiling " + assemblyRow.AssemblyName + " satellite assembly.");

                if (!Directory.Exists(Path.GetDirectoryName(assemblyFilename)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(assemblyFilename));
                }
                else if (File.Exists(assemblyFilename))
                {
                    File.Delete(assemblyFilename);
                }

                CSharpCodeProvider prov = new CSharpCodeProvider();
                CompilerParameters p = new CompilerParameters();
                p.EmbeddedResources.AddRange(resourceList.ToArray());
                p.GenerateInMemory = false;
                p.OutputAssembly = assemblyFilename;

                // setup references
                p.ReferencedAssemblies.Add("System.dll");

                Assembly mainAssembly = Assembly.Load(assemblyRow.AssemblyName);

                string version = GetSatelliteContractVersion(mainAssembly).ToString();
                if (version != assemblyRow.ResourceVersion.Trim())
                {
                    // warning! resource mismatch
                }

                string code = "[assembly: System.Reflection.AssemblyVersion(\"" + version + "\")] " +
                "[assembly: System.Reflection.AssemblyFileVersion(\"" + version + "\")] " +
                "[assembly: System.Reflection.AssemblyCulture(\"" + targetCulture + "\")]";
                CompilerResults res = prov.CompileAssemblyFromSource(p, code);

                foreach (string tempResourceFile in resourceList)
                {
                    File.Delete(tempResourceFile);
                }

                if (res.Errors.HasErrors)
                {
                    throw new GeneralException(GetString(res.Output));
                }
            }
        }
		public void SaveFile(string filename, Stream stream)
		{
			switch (Path.GetExtension(filename).ToLowerInvariant()) {
					
					// write XML resource
				case ".resx":
					ResXResourceWriter rxw = new ResXResourceWriter(stream);
					foreach (KeyValuePair<string, ResourceItem> entry in resources) {
						if (entry.Value != null) {
							ResourceItem item = entry.Value;
							rxw.AddResource(item.Name, item.ResourceValue);
						}
					}
					foreach (KeyValuePair<string, ResourceItem> entry in metadata) {
						if (entry.Value != null) {
							ResourceItem item = entry.Value;
							rxw.AddMetadata(item.Name, item.ResourceValue);
						}
					}
					rxw.Generate();
					rxw.Close();
					break;
					
					// write default resource
				default:
					ResourceWriter rw = new ResourceWriter(stream);
					foreach (KeyValuePair<string, ResourceItem> entry in resources) {
						ResourceItem item = (ResourceItem)entry.Value;
						rw.AddResource(item.Name, item.ResourceValue);
					}
					rw.Generate();
					rw.Close();
					break;
			}
		}
Exemple #32
0
        private void WriteResourcesFile()
        {
            IResourceWriter resourceWriter = new ResourceWriter(ResourcesFileName);

            foreach (var resource in resources)
            {
                resourceWriter.AddResource(resource.Name, resource.ValueString);
            }

            resourceWriter.Close();
        }