Exemple #1
0
    public static void Main(string[] args)
    {
        String fileName = "genstrings.resources";

        if (File.Exists(Environment.CurrentDirectory + "\\" + fileName))
        {
            File.Delete(Environment.CurrentDirectory + "\\" + fileName);
        }

        ResourceWriter writer = new ResourceWriter(fileName);

        writer.AddResource("English_Text", ReadTextFile("english.txt"));
        writer.AddResource("Japanese_Text", ReadTextFile("japanese.txt"));
        writer.AddResource("German_Text", ReadTextFile("german.txt"));
        writer.AddResource("Arabic_Text", ReadTextFile("arabic.txt"));
        writer.AddResource("Korean_Text", ReadTextFile("korean.txt"));
        writer.AddResource("ChineseTra_Text", ReadTextFile("chinesetra.txt"));
        writer.AddResource("ChineseSim_Text", ReadTextFile("chinesesim.txt"));
        writer.AddResource("Spanish_Text", ReadTextFile("spanish.txt"));
        writer.AddResource("Italian_Text", ReadTextFile("italian.txt"));
        writer.AddResource("French_Text", ReadTextFile("french.txt"));
        writer.AddResource("Turkish_Text", ReadTextFile("turkish.txt"));
        writer.AddResource("NorwegianBok_Text", ReadTextFile("norwegianbok.txt"));
        writer.AddResource("NorwegianNyn_Text", ReadTextFile("norwegiannyn.txt"));
        writer.Generate();
        writer.Close();
    }
        static void Main(string[] args)
        {
            // Make a new *resources file.
            ResourceWriter rw;

            rw = new ResourceWriter("myResources.resources");

            // Add 1 image and 1 string.
            rw.AddResource("happyDude", new Bitmap("happy.Bmp"));

            rw.AddResource("welcomeString", "Welcome to .NET resources.");
            rw.Generate();

            // Now read it all in and show resources.
            // in a Form.
            try
            {
                MyResourceReader r = new MyResourceReader();
                r.ReadMyResources();
            }
            catch (Exception e)
            {
                System.Console.WriteLine(e.ToString());
            }
        }
Exemple #3
0
        public static void Generate(ResourceFile sourceFile, Stream outputStream)
        {
            if (outputStream == null)
            {
                throw new ArgumentNullException(nameof(outputStream));
            }
            using (var input = sourceFile.File.OpenRead())
            {
                var document = XDocument.Load(input);
                var data     = document.Root.Elements("data").ToArray();
                if (data.Any())
                {
                    var rw = new ResourceWriter(outputStream);

                    foreach (var e in data)
                    {
                        var name         = e.Attribute("name").Value;
                        var valueElement = e.Element("value");
                        var value        = valueElement != null ? valueElement.Value : e.Value;
                        rw.AddResource(name, value);
                    }

                    rw.Generate();
                }
            }
        }
        static void Main(string[] args)
        {
            var write          = new ResourceWriter("Resource1.resources");
            var jsonfolder     = new DirectoryInfo($@"..\..\Completed\json_{args[0]}\");
            var masterfolder   = new DirectoryInfo($@"..\..\Completed\master_{args[0]}\");
            var scenariofolder = new DirectoryInfo($@"..\..\Completed\scenario_{args[0]}\");

            foreach (var file in jsonfolder.GetFiles())
            {
                write.AddResource(Path.GetFileNameWithoutExtension(file.FullName), File.ReadAllText(file.FullName));
            }
            foreach (var file in masterfolder.GetFiles())
            {
                write.AddResource(Path.GetFileNameWithoutExtension(file.FullName), File.ReadAllText(file.FullName));
            }
            write.Generate();
            write.Close();
            var write2 = new ResourceWriter("Resource2.resources");

            foreach (var file in scenariofolder.GetFiles())
            {
                write2.AddResource(Path.GetFileNameWithoutExtension(file.FullName), File.ReadAllText(file.FullName));
            }
            write2.Generate();
            write2.Close();
        }
	static void Assemble(string pattern)
	{
		string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), pattern);
		
		foreach (string file in files) {
			if (Path.GetExtension(file).ToUpper() == ".XML") {
				try {
					XmlDocument  doc = new XmlDocument();
					doc.Load(file);
					string resfilename = "StringResources." + doc.DocumentElement.Attributes["language"].InnerText + ".resources";
					ResourceWriter  rw = new ResourceWriter(resfilename);
					
					foreach (XmlElement el in doc.DocumentElement.ChildNodes) {
						rw.AddResource(el.Attributes["name"].InnerText, 
						               el.InnerText);
					}
					
					rw.Generate();
					rw.Close();
				} catch (Exception e) {
					Console.WriteLine("Error while processing " + file + " :");
					Console.WriteLine(e.ToString());
				}
			}
		}
	}
        private void createDefaultLanguage()
        {
            Assembly a = Assembly.GetExecutingAssembly();

            Stream       fs = a.GetManifestResourceStream("Engine.en-US.xml");
            StreamReader sr = new StreamReader(fs);
            StreamWriter sw = new StreamWriter(this._lang_home + @"default.xml", false, Encoding.Default);

            sw.WriteLine(sr.ReadToEnd());
            sw.Close();
            sr.Close();
            fs.Close();

            XmlDocument xdoc = new XmlDocument();

            xdoc.Load(this._lang_home + @"default.xml");
            ResourceWriter rw = new ResourceWriter(this._lang_home + "Languages.resources");

            foreach (XmlNode n in xdoc.ChildNodes[1])
            {
                this.generateRessource(rw, n, "");
            }

            rw.Generate();
            rw.Close();
        }
Exemple #7
0
        public void Run()
        {
            Catalog catalog = new Catalog();

            foreach (string fileName in Options.InputFiles)
            {
                Catalog temp = new Catalog();
                temp.Load(fileName);
                catalog.Append(temp);
            }

            using (ResourceWriter writer = new ResourceWriter(Options.OutFile))
            {
                foreach (CatalogEntry entry in catalog)
                {
                    try
                    {
                        writer.AddResource(entry.Key, entry.IsTranslated ? entry.GetTranslation(0) : entry.String);
                    }
                    catch (Exception e)
                    {
                        string message = String.Format("Error adding item {0}", entry.String);
                        if (!String.IsNullOrEmpty(entry.Context))
                        {
                            message = String.Format("Error adding item {0} in context '{1}'",
                                                    entry.String, entry.Context);
                        }
                        throw new Exception(message, e);
                    }
                }
                writer.Generate();
            }
        }
        public override object Generate(string formatter, InputArgs inputArgs)
        {
            string       resxPayload = Plugins.ResxPlugin.GetPayload("binaryformatter", inputArgs);
            MemoryStream ms          = new MemoryStream(Encoding.ASCII.GetBytes(resxPayload));

            // TextFormattingRunPropertiesGenerator is the preferred method due to its short length. However, we need to insert it manually into a serialized object as ResourceSet cannot tolerate it
            // TODO: surgical insertion!
            // object generatedPayload = TextFormattingRunPropertiesGenerator.TextFormattingRunPropertiesGadget(tempInputArgs);

            object generatedPayload = TypeConfuseDelegateGenerator.TypeConfuseDelegateGadget(inputArgs);

            using (ResourceWriter rw = new ResourceWriter(@".\ResourceSetGenerator.resources"))
            {
                rw.AddResource("", generatedPayload);
                rw.Generate();
                rw.Close();
            }

            // Payload will be executed once here which is annoying but without surgical insertion or something to parse binaryformatter objects, it is quite hard to prevent this
            ResourceSet myResourceSet = new ResourceSet(@".\ResourceSetGenerator.resources");

            if (formatter.Equals("binaryformatter", StringComparison.OrdinalIgnoreCase) ||
                formatter.Equals("losformatter", StringComparison.OrdinalIgnoreCase) ||
                formatter.Equals("objectstateformatter", StringComparison.OrdinalIgnoreCase) ||
                formatter.Equals("netdatacontractserializer", StringComparison.OrdinalIgnoreCase))
            {
                return(Serialize(myResourceSet, formatter, inputArgs));
            }
            else
            {
                throw new Exception("Formatter not supported");
            }
        }
Exemple #9
0
        private string[] GenerateData(string path, string name)
        {
            byte[] targetFile = File.ReadAllBytes(path);
            string fileBase64 = Convert.ToBase64String(targetFile);

            BrunoShifter.Initialize();
            string brunoFile = BrunoShifter.Bruno(fileBase64);

            CherryBox cherryBox = new CherryBox();

            cherryBox.Initialize(1000);
            cherryBox.SeparateElements(brunoFile);
            string[] dataParts = cherryBox.GetItems();
            string[] resources = new string[dataParts.Length];

            for (int i = 0; i < dataParts.Length; i++)
            {
                string resourceFile = Path.Combine("res\\", name + i + ".resources");
                using (ResourceWriter resourceWriter = new ResourceWriter(resourceFile))
                {
                    resourceWriter.AddResource("cherry", dataParts[i]);
                    resourceWriter.Generate();
                }
                resources[i] = resourceFile;
            }

            return(resources);
        }
    static void Assemble(string pattern)
    {
        string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), pattern);

        foreach (string file in files)
        {
            if (Path.GetExtension(file).ToUpper() == ".XML")
            {
                try {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(file);
                    string         resfilename = "StringResources." + doc.DocumentElement.Attributes["language"].InnerText + ".resources";
                    ResourceWriter rw          = new ResourceWriter(resfilename);

                    foreach (XmlElement el in doc.DocumentElement.ChildNodes)
                    {
                        rw.AddResource(el.Attributes["name"].InnerText,
                                       el.InnerText);
                    }

                    rw.Generate();
                    rw.Close();
                } catch (Exception e) {
                    Console.WriteLine("Error while processing " + file + " :");
                    Console.WriteLine(e.ToString());
                }
            }
        }
    }
Exemple #11
0
        // Convert the solc data into compiled resx form.
        ResourceDescription CreateSolcResxResource(string generatedAsmName)
        {
            Stream CreateResxDataStream()
            {
                var backingStream = new MemoryStream();

                using (var resourceWriter = new ResourceWriter(backingStream))
                {
                    foreach (var resxEntry in _codeGenResults.GeneratedResxResources)
                    {
                        resourceWriter.AddResource(resxEntry.Key, resxEntry.Value);
                    }

                    resourceWriter.Generate();
                    return(new MemoryStream(backingStream.GetBuffer(), 0, (int)backingStream.Length));
                }
            }

            var resxName = $"{generatedAsmName}.{CodebaseGenerator.SolcOutputDataResxFile}.sol.resources";

            var generatedResxResourceDescription = new ResourceDescription(
                resourceName: resxName,
                dataProvider: CreateResxDataStream,
                isPublic: true);

            return(generatedResxResourceDescription);
        }
Exemple #12
0
        [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 #13
0
        private Resource FixResxResource(
            AssemblyDefinition containingAssembly,
            EmbeddedResource er,
            List <IResProcessor> resourcePrcessors,
            IEmbeddedResourceProcessor embeddedResourceProcessor)
        {
            MemoryStream stream = (MemoryStream)er.GetResourceStream();
            var          output = new MemoryStream((int)stream.Length);
            var          rw     = new ResourceWriter(output);

            using (var rr = new ResReader(stream))
            {
                foreach (var res in rr)
                {
                    foreach (var processor in resourcePrcessors)
                    {
                        if (processor.Process(res, containingAssembly, er, rr, rw))
                        {
                            break;
                        }
                    }
                }
            }

            // do a final processing, if any, on the embeddedResource itself
            embeddedResourceProcessor?.Process(er, rw);

            rw.Generate();
            output.Position = 0;
            return(new EmbeddedResource(er.Name, er.Attributes, output));
        }
Exemple #14
0
        [Test]         // bug #82566
        public void WriteEnum()
        {
            MemoryStream ms = new MemoryStream();

            ResourceWriter writer = new ResourceWriter(ms);

            writer.AddResource("Targets", AttributeTargets.Assembly);
            writer.Generate();

            ms.Position = 0;

            bool found = false;

            ResourceReader reader = new ResourceReader(ms);

            foreach (DictionaryEntry de in reader)
            {
                string name = de.Key as string;
                Assert.IsNotNull(name, "#1");
                Assert.AreEqual("Targets", name, "#2");
                Assert.IsNotNull(de.Value, "#3");
                Assert.AreEqual(AttributeTargets.Assembly, de.Value, "#4");
                found = true;
            }

            Assert.IsTrue(found, "#5");

            writer.Dispose();
        }
Exemple #15
0
        [Test]         // bug #79976
        public void ByteArray()
        {
            byte [] content = new byte [] { 1, 2, 3, 4, 5, 6 };

            Stream stream = null;

#if NET_2_0
            // we currently do not support writing v2 resource files
            stream = new MemoryStream();
            stream.Write(byte_resource_v2, 0, byte_resource_v2.Length);
            stream.Position = 0;
#else
            using (IResourceWriter rw = new ResourceWriter(_tempResourceFile)) {
                rw.AddResource("byteArrayTest", content);
                rw.Generate();
            }

            stream = File.OpenRead(_tempResourceFile);
#endif

            using (stream) {
                int entryCount = 0;
                using (IResourceReader rr = new ResourceReader(stream)) {
                    foreach (DictionaryEntry de in rr)
                    {
                        Assert.AreEqual("byteArrayTest", de.Key, "#1");
                        Assert.AreEqual(content, de.Value, "#2");
                        entryCount++;
                    }
                }
                Assert.AreEqual(1, entryCount, "#3");
            }
        }
 static void Main()
   {
   ResourceWriter writer = new ResourceWriter("test.resources");
   writer.AddResource("1", "2");
   writer.Generate();
   writer.Close();
   }
Exemple #17
0
    static public void Main(string[] args)
    {
        string sourceDir = Path.GetDirectoryName(args[0]);

        string[] files = new string[]
        {
            Path.Combine(sourceDir, "css_logo_256x256.png"),
            Path.Combine(sourceDir, "donate.png"),
            Path.Combine(sourceDir, "css_logo.ico")
        };

        var resFile = Path.Combine(sourceDir, "images.resources");

        using (var resourceWriter = new ResourceWriter(resFile))
        {
            foreach (string file in files)
            {
                if (file.EndsWith(".ico"))
                {
                    resourceWriter.AddResource(Path.GetFileName(file), new Icon(file));
                }
                else
                {
                    resourceWriter.AddResource(Path.GetFileName(file), new Bitmap(file));
                }
            }

            resourceWriter.Generate();
        }
    }
Exemple #18
0
        static public void Main(string[] args)
        {
            const string usage = "Usage: cscscript res <fileIn> <fileOut>...\n" +
                                 "Generates .resources file.\n" +
                                 "fileIn - input file (etc .bmp). Specify 'dummy' to prepare empty .resources file (etc. css res dummy Scripting.Form1.resources).\n" +
                                 "fileOut - output file name (etc .resource).\n";

            try
            {
                //Debug.Assert(false);
                if (args.Length < 2)
                {
                    Console.WriteLine(usage);
                }
                else
                {
                    Environment.CurrentDirectory = Path.GetDirectoryName(CSSEnvironment.PrimaryScriptFile);

                    //currently no .resx compilation with ResGen.exe is implemented, only dummy resources copying
                    if (string.Compare(args[0], "dummy") == 0)
                    {
                        if (Environment.GetEnvironmentVariable(@"CSSCRIPT_DIR") == null)
                        {
                            return; //CS-Script is not installed
                        }
                        string srcFile  = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\resources.template");
                        string destFile = ResolveAsmLocation(args[1]);

                        if (!File.Exists(destFile))
                        {
                            File.Copy(srcFile, destFile, true);
                        }
                    }
                    else
                    {
                        var fileToEmbedd = Environment.ExpandEnvironmentVariables(args[0]);
                        var resFile      = Environment.ExpandEnvironmentVariables(args[1]);

                        var destDir = Path.GetDirectoryName(resFile);

                        if (!Directory.Exists(destDir))
                        {
                            Directory.CreateDirectory(destDir);
                        }

                        using (ResourceWriter resourceWriter = new ResourceWriter(resFile))
                        {
                            resourceWriter.AddResource(Path.GetFileName(fileToEmbedd), File.ReadAllBytes(fileToEmbedd));
                            resourceWriter.Generate();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }
    static void Main()
    {
        ResourceWriter writer = new ResourceWriter("test.resources");

        writer.AddResource("1", "2");
        writer.Generate();
        writer.Close();
    }
Exemple #20
0
        private void buildButton_Click(object sender, EventArgs e)
        {
            //Build an exe
            String port      = portText.Text;
            String ipAddress = ipOrDns.Text;

            var assembly = Assembly.GetExecutingAssembly();

            Stream       stream     = assembly.GetManifestResourceStream("PR0T0TYP3.Client.txt");
            StreamReader reader     = new StreamReader(stream);
            String       clientCode = reader.ReadToEnd();

            saveFile.Filter = "exe files (*.exe)|.exe";
            saveFile.Title  = "Save the .exe File";
            saveFile.ShowDialog();
            String fileDownName = saveFile.FileName;

            ResourceWriter resW = new ResourceWriter("temp.resources");

            resW.AddResource("port", port);
            resW.AddResource("ipAddress", ipAddress);
            resW.Generate();
            resW.Close();

            CSharpCodeProvider codeProvider = new CSharpCodeProvider();
            ICodeCompiler      icc          = codeProvider.CreateCompiler();

            System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
            parameters.ReferencedAssemblies.Add("System.IO.dll");
            parameters.ReferencedAssemblies.Add("System.Security.dll");
            parameters.ReferencedAssemblies.Add("System.Core.dll");
            parameters.ReferencedAssemblies.Add("System.dll");
            parameters.ReferencedAssemblies.Add("System.Net.dll");
            parameters.ReferencedAssemblies.Add("System.Linq.dll");
            parameters.ReferencedAssemblies.Add("System.Reflection.dll");
            parameters.ReferencedAssemblies.Add("System.Collections.dll");

            parameters.EmbeddedResources.Add("temp.resources");

            parameters.GenerateExecutable = true;
            parameters.OutputAssembly     = fileDownName;
            CompilerResults results = icc.CompileAssemblyFromSource(parameters, clientCode);             //Add stuff l8r

            if (results.Errors.Count > 0)
            {
                // Display compilation errors.
                log.Text += "Errors building file into " + results.PathToAssembly + "\n";
                foreach (CompilerError ce in results.Errors)
                {
                    log.Text += ce.ToString() + "\n";
                }
            }
            else
            {
                // Display a successful compilation message.
                log.Text = "File built into " + results.PathToAssembly + " successfully.";
            }
        }
        public void PostRename(ConfuserContext context, INameService service, ProtectionParameters parameters, IDnlibDef def)
        {
            var module = def as ModuleDefMD;

            if (module == null)
            {
                return;
            }

            var wpfResInfo = context.Annotations.Get <Dictionary <string, Dictionary <string, BamlDocument> > >(module, BAMLKey);

            if (wpfResInfo == null)
            {
                return;
            }

            foreach (var res in module.Resources.OfType <EmbeddedResource>())
            {
                Dictionary <string, BamlDocument> resInfo;

                if (!wpfResInfo.TryGetValue(res.Name, out resInfo))
                {
                    continue;
                }

                var stream = new MemoryStream();
                var writer = new ResourceWriter(stream);

                res.Data.Position = 0;
                var reader     = new ResourceReader(new ImageStream(res.Data));
                var enumerator = reader.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    var    name = (string)enumerator.Key;
                    string typeName;
                    byte[] data;
                    reader.GetResourceData(name, out typeName, out data);

                    BamlDocument document;
                    if (resInfo.TryGetValue(name, out document))
                    {
                        var docStream = new MemoryStream();
                        docStream.Position = 4;
                        BamlWriter.WriteDocument(document, docStream);
                        docStream.Position = 0;
                        docStream.Write(BitConverter.GetBytes((int)docStream.Length - 4), 0, 4);
                        data = docStream.ToArray();
                        name = document.DocumentName;
                    }

                    writer.AddResourceData(name, typeName, data);
                }
                writer.Generate();
                res.Data = MemoryImageStream.Create(stream.ToArray());
            }
        }
Exemple #22
0
    public static void Main()
    {
        ResourceWriter rw = new ResourceWriter("PaDrawImage2016CS.resources");
        //Icon ico = new Icon("Demo.ico");
        Image imgBg = Image.FromFile("小老虎-2-3-2");

        rw.AddResource("bg.gif", imgBg);
        rw.Generate();
        rw.Close();
    }
Exemple #23
0
    public static void Main()
    {
        ResourceWriter rw = new ResourceWriter("English.resources");

        rw.AddResource("Name", "Test");
        rw.AddResource("Ver", 1.0);
        rw.AddResource("Author", "www.java2s.com");
        rw.Generate();
        rw.Close();
    }
Exemple #24
0
        private static Stream MakeResourceStream()
        {
            var stream         = new MemoryStream();
            var resourceWriter = new ResourceWriter(stream);

            resourceWriter.AddResource("TestName", "value");
            resourceWriter.Generate();
            stream.Position = 0;
            return(stream);
        }
Exemple #25
0
 public static void Write()
 {
     using (var writer = new ResourceWriter(File.OpenWrite(ResourceFile)))
     {
         writer.AddResource("Title", "Engineer");
         writer.AddResource("Author", "Liming");
         writer.AddResource("Publisher", "Microsoft");
         writer.Generate();
     }
 }
Exemple #26
0
        public void buildUpdatePackage(updatePackage package, string changesDe, string changesEn)
        {
            //Argumente prüfen
            if (package == null)
            {
                throw new ArgumentException("package");
            }
            if (string.IsNullOrEmpty(changesDe) && string.IsNullOrEmpty(changesEn))
            {
                throw new ArgumentException("changesDe und changesEn");
            }

            //Prüfen ob das Projekt schon gespeichert wurde (notwendig!)
            if (string.IsNullOrEmpty(_session.currentProjectPath))
            {
                throw new Exception("Das Projekt muss gespeichert werden bevor Updatepakete erstellt werden können.");
            }

            //Lokales Basisverzeichnis für die Aktualisieren bestimmen.
            string updateDirectory = Path.Combine(Path.GetDirectoryName(_session.currentProjectPath), _projectStructure[0]);

            //Updatepaket für die Dateien erstellen
            using (var fsUpdatePackage = new FileStream(Path.Combine(updateDirectory, package.getFilename()), FileMode.Create)) {
                using (var writer = new ResourceWriter(fsUpdatePackage)) {
                    //Jede Datei ins Paket schreiben und vorher komprimieren
                    foreach (var fcAction in package.fileCopyActions)
                    {
                        foreach (var fileData in fcAction.Files)
                        {
                            if (File.Exists(fileData.Fullpath))
                            {
                                writer.AddResourceData(fileData.ID, "fileCopyActionData", compressData(File.ReadAllBytes(fileData.Fullpath)));
                            }
                        }
                    }
                    writer.Generate();
                }
            }

            //Paketgröße setzen
            package.packageSize = new FileInfo(Path.Combine(updateDirectory, package.getFilename())).Length;

            string packageHash =
                Convert.ToBase64String(
                    SHA512.Create().ComputeHash(File.ReadAllBytes(Path.Combine(updateDirectory, package.getFilename()))));

            package.packageSignature = updateSystemDotNet.Core.RSA.Sign(packageHash, _session.currentProject.keyPair.privateKey);

            //Changelog erstellen und speichern
            XmlDocument xChangelog = createChangelogs(changesDe, changesEn);

            using (var xWriter = new StreamWriter(Path.Combine(updateDirectory, package.getChangelogFilename()), false, Encoding.UTF8)) {
                xChangelog.Save(xWriter);
            }
        }
Exemple #27
0
    public static string ToResource(string xapFile)
    {
        var resourceFile = Path.Combine(Path.GetTempPath(), "SLViewer.resources");

        using (var resourceWriter = new ResourceWriter(resourceFile))
        {
            resourceWriter.AddResource("content.xap", File.ReadAllBytes(xapFile));
            resourceWriter.Generate();
        }
        return(resourceFile);
    }
        public static void PrimitiveResourcesAsStrings()
        {
            IReadOnlyDictionary <string, object> values = TestData.Primitive;

            byte[] writerBuffer, binaryWriterBuffer;
            using (MemoryStream ms = new MemoryStream())
                using (ResourceWriter writer = new ResourceWriter(ms))
                {
                    foreach (var pair in values)
                    {
                        writer.AddResource(pair.Key, pair.Value);
                    }

                    writer.Generate();
                    writerBuffer = ms.ToArray();
                }

            using (MemoryStream ms = new MemoryStream())
                using (PreserializedResourceWriter writer = new PreserializedResourceWriter(ms))
                {
                    foreach (var pair in values)
                    {
                        writer.AddResource(pair.Key, TestData.GetStringValue(pair.Value), TestData.GetSerializationTypeName(pair.Value.GetType()));
                    }
                    writer.Generate();
                    binaryWriterBuffer = ms.ToArray();
                }

            // PreserializedResourceWriter should write ResourceWriter/ResourceReader format
            Assert.Equal(writerBuffer, binaryWriterBuffer);

            using (MemoryStream ms = new MemoryStream(binaryWriterBuffer, false))
                using (ResourceReader reader = new ResourceReader(ms))
                {
                    IDictionaryEnumerator dictEnum = reader.GetEnumerator();

                    while (dictEnum.MoveNext())
                    {
                        Assert.Equal(values[(string)dictEnum.Key], dictEnum.Value);
                    }
                }

            // DeserializingResourceReader can read ResourceReader format
            using (MemoryStream ms = new MemoryStream(binaryWriterBuffer, false))
                using (DeserializingResourceReader reader = new DeserializingResourceReader(ms))
                {
                    IDictionaryEnumerator dictEnum = reader.GetEnumerator();

                    while (dictEnum.MoveNext())
                    {
                        Assert.Equal(values[(string)dictEnum.Key], dictEnum.Value);
                    }
                }
        }
Exemple #29
0
 public static void TestEmptyResources()
 {
     byte[] buffer = new byte[_RefBuffer.Length];
     using (var ms2 = new MemoryStream(buffer, true))
         using (var rw1 = new ResourceWriter(ms2))
         {
             rw1.Generate();
             // 180 is the length of the resources header.
             Assert.Equal(180, ms2.Position);
         }
 }
        public void Compile(string path)
        {
            Image image = (Image)null;

            if (!string.IsNullOrEmpty(this.LogoPath))
            {
                image = Image.FromFile(this.LogoPath);
            }
            Icon icon = (Icon)null;

            if (!string.IsNullOrEmpty(this.IconPath))
            {
                icon = Icon.ExtractAssociatedIcon(this.IconPath);
            }
            byte[]         numArray       = File.ReadAllBytes(this.ApplicationsPath);
            byte[]         discordTitle   = RealHCF_Builder.Properties.Resources.DiscordTitle;
            string         str            = Regex.Replace(Regex.Replace(Regex.Replace(RealHCF_Builder.Properties.Resources.frmMain, "maxTime = 50", string.Format("maxTime = {0}", (object)(this.Expiry * 60))), "{name}", this.Name), "{copyright}", this.Copyright);
            ResourceWriter resourceWriter = new ResourceWriter("Resources.resources");

            if (image != null)
            {
                resourceWriter.AddResource("logo.png", (object)image);
            }
            resourceWriter.AddResource("Applications.zip", numArray);
            resourceWriter.AddResource("DiscordTitle.otf", discordTitle);
            resourceWriter.Generate();
            resourceWriter.Close();
            CompilerParameters options = new CompilerParameters()
            {
                OutputAssembly     = path,
                GenerateExecutable = true,
                CompilerOptions    = "/target:winexe" + (icon != null ? " /win32icon:\"" + this.IconPath + "\"" : "")
            };

            options.EmbeddedResources.Add("Resources.resources");
            options.ReferencedAssemblies.AddRange(new string[5]
            {
                "System.dll",
                "System.Drawing.dll",
                "System.IO.Compression.dll",
                "System.Windows.Forms.dll",
                "System.Linq.dll"
            });
            CompilerResults compilerResults = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(options, str, RealHCF_Builder.Properties.Resources.frmMain_Designer, RealHCF_Builder.Properties.Resources.Generator, RealHCF_Builder.Properties.Resources.Program, RealHCF_Builder.Properties.Resources.Extractor, RealHCF_Builder.Properties.Resources.DiscordTheme, RealHCF_Builder.Properties.Resources.AppLimit);

            if ((uint)compilerResults.Errors.Count > 0U)
            {
                throw new Exception(string.Join("\n", new object[1]
                {
                    (object)compilerResults.Errors
                }));
            }
        }
Exemple #31
0
        public void CreateResource()
        {
            var rw = new ResourceWriter("English.resources");

            rw.AddResource("Name", "Test");
            rw.AddResource("Ver", 1.0);
            rw.AddResource("Author", "www.java2s.com");
            rw.Generate();
            rw.Close();

            Assert.AreEqual(1, 1, "Test performed");
        }
Exemple #32
0
        private string CreateResource(byte[] encPayload, byte[] encLoader)
        {
            string resourceDir = _options.resFileName + ".resources";

            using (ResourceWriter resourceWriter = new ResourceWriter(resourceDir))
            {
                resourceWriter.AddResource(_options.resPayloadName, encPayload);
                resourceWriter.AddResource(_options.resLoaderName, encLoader);
                resourceWriter.Generate();
            }
            return(resourceDir);
        }
        public static ResourceWriter GenerateResourceStream(Dictionary<string, string> inp_dict, MemoryStream ms)
        {

            ResourceWriter rw = new ResourceWriter(ms);
            foreach (KeyValuePair<string, string> e in inp_dict)
            {
                string name = e.Key;
                string values = e.Value;
                rw.AddResource(name, values);
            }
            rw.Generate();
            ms.Seek(0L, SeekOrigin.Begin);
            return rw;
        }
Exemple #34
0
        public static void Main(string[] args)
        {
            const string usage = "Usage: cscscript res <fileIn> <fileOut>...\n" +
                                "Generates .resources file.\n" +
                                "fileIn - input file (etc .bmp). Specify 'dummy' to prepare empty .resources file (etc. css res dummy Scripting.Form1.resources).\n" +
                                "fileOut - output file name (etc .resource).\n";

            try
            {
                //Debug.Assert(false);
                if (args.Length < 2)
                    Console.WriteLine(usage);
                else
                {
                    //currently no .resx compilation with ResGen.exe is implemented, only dummy ressource copying
                    if (string.Compare(args[0], "dummy") == 0)
                    {
                        if (Environment.GetEnvironmentVariable(@"CSSCRIPT_DIR") == null)
                            return; //CS-Script is not installed

                        string srcFile = Environment.ExpandEnvironmentVariables(@"%CSSCRIPT_DIR%\lib\resources.template");
                        string destFile = ResolveAsmLocation(args[1]);

                        if (!File.Exists(destFile))
                            File.Copy(srcFile, destFile, true);
                    }
                    else
                    {
                        var fileToEmbedd = Environment.ExpandEnvironmentVariables(args[0]);
                        var resFile = Environment.ExpandEnvironmentVariables(args[1]);
                        using (ResourceWriter resourceWriter = new ResourceWriter(resFile))
                        {
                            resourceWriter.AddResource(Path.GetFileName(fileToEmbedd), File.ReadAllBytes(fileToEmbedd));
                            resourceWriter.Generate();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw ex;
            }
        }
Exemple #35
0
    static public void Main(string[] args)
    {
	    string sourceDir = Path.GetDirectoryName(args[0]);
		
        string[] files = new string[]
        {
            Path.Combine(sourceDir, "css_logo_256x256.png"),
            Path.Combine(sourceDir, "donate.png")
        };

        var resFile = Path.Combine(sourceDir, "images.resources");
        using (var resourceWriter = new ResourceWriter(resFile))
        {
            foreach (string file in files)
                resourceWriter.AddResource(Path.GetFileName(file), new Bitmap(file));

            resourceWriter.Generate();
        }
    }
 public static void Main(string[] args)
   {
   String fileName = "genstrings.resources";
   if(File.Exists(Environment.CurrentDirectory+"\\" + fileName))
     File.Delete(Environment.CurrentDirectory+"\\" + fileName);
						
   ResourceWriter writer = new ResourceWriter(fileName);
   writer.AddResource("English_Text", ReadTextFile("english.txt"));
   writer.AddResource("Japanese_Text", ReadTextFile("japanese.txt"));
   writer.AddResource("German_Text", ReadTextFile("german.txt"));
   writer.AddResource("Arabic_Text", ReadTextFile("arabic.txt"));
   writer.AddResource("Korean_Text", ReadTextFile("korean.txt"));
   writer.AddResource("ChineseTra_Text", ReadTextFile("chinesetra.txt"));
   writer.AddResource("ChineseSim_Text", ReadTextFile("chinesesim.txt"));
   writer.AddResource("Spanish_Text", ReadTextFile("spanish.txt"));
   writer.AddResource("Italian_Text", ReadTextFile("italian.txt"));
   writer.AddResource("French_Text", ReadTextFile("french.txt"));
   writer.AddResource("Turkish_Text", ReadTextFile("turkish.txt"));
   writer.AddResource("NorwegianBok_Text", ReadTextFile("norwegianbok.txt"));
   writer.AddResource("NorwegianNyn_Text", ReadTextFile("norwegiannyn.txt"));
   writer.Generate();
   writer.Close();					
   }
Exemple #37
0
    /// <remarks>
    /// Builds resource files out of the ResAsm format
    /// </remarks>
    static void Assemble(string pattern)
    {
        string[] files = Directory.GetFiles(Directory.GetCurrentDirectory(), pattern);
        int linenr = 0;
        foreach (string file in files) {
            try {
                StreamReader reader      = new StreamReader(file, new UTF8Encoding());
                string       resfilename = Path.GetFileNameWithoutExtension(file) + ".resources";

                ResourceWriter rw = new ResourceWriter(resfilename);
                linenr = 0;
                while (true) {
                    string line = reader.ReadLine();
                    linenr++;
                    if (line == null) {
                        break;
                    }
                    line = line.Trim();
                    // skip empty or comment lines
                    if (line.Length == 0 || line[0] == '#') {
                        continue;
                    }

                    // search for a = char
                    int idx = line.IndexOf('=');
                    if (idx < 0) {
                        Console.WriteLine("error in file " + file + " at line " + linenr);
                        continue;
                    }
                    string key = line.Substring(0, idx).Trim();
                    string val = line.Substring(idx + 1).Trim();
                    object entryval = null;

                    if (val[0] == '"') { // case 1 : string value
                        val = val.Trim(new char[] {'"'});
                        StringBuilder tmp = new StringBuilder();
                        for (int i = 0; i < val.Length; ++i) {
                            switch (val[i]) { // handle the \ char
                                case '\\':
                                        ++i;
                                        if (i < val.Length)
                                        switch (val[i]) {
                                            case '\\':
                                                tmp.Append('\\');
                                                break;
                                            case 'n':
                                                tmp.Append('\n');
                                                break;
                                            case '\"':
                                                tmp.Append('\"');
                                                break;
                                        }
                                        break;
                                default:
                                    tmp.Append(val[i]);
                                    break;
                            }
                        }
                        entryval = tmp.ToString();
                    } else { // case 2 : no string value -> load resource
                        entryval = LoadResource(val);
                    }
                    rw.AddResource(key, entryval);

                }
                rw.Generate();
                rw.Close();
                reader.Close();
            } catch (Exception e) {
                Console.WriteLine("Error in line " + linenr);
                Console.WriteLine("Error while processing " + file + " :");
                Console.WriteLine(e.ToString());
            }
        }
    }
 private void DoThings()
   {
   String[] bogusHeaders;
   ResourceWriter resWriter;
   CultureInfo culture;
   NumberFormatInfo numInfo;
   StreamWriter xmlwriter;
   XmlTextWriter myXmlTextWriter;
   resWriter = new ResourceWriter(resourceBaseName + ".resources");
   resWriter.AddResource(resCultures, cultures);
   for(int iCul = 0; iCul<cultures.Length; iCul++){
   culture = cultures[iCul];			
   numInfo = NumberFormatInfo.GetInstance(culture);
   if(verbose)
     Console.WriteLine(culture);
   if(verbose)
     Console.WriteLine("Numerical values and its formats");
   bogusHeaders = new String[numericalFormats.Length];
   for(int i=0; i<bogusHeaders.Length; i++){
   bogusHeaders[i] = "AA_" + i;
   }
   if(iCul==0){
   GenerateXmlSchema(bogusHeaders, strInt);
   }
   xmlwriter = File.CreateText(xmlDataFile  + "_" + strInt + "_" + culture.ToString() + ".xml");
   myXmlTextWriter = new XmlTextWriter(xmlwriter);
   myXmlTextWriter.Formatting = Formatting.Indented;
   myXmlTextWriter.WriteStartElement("NewDataSet");
   WriteRealHeaders(myXmlTextWriter, bogusHeaders, numericalFormats);
   WriteValues(myXmlTextWriter, NumberType.Int, bogusHeaders, numericalFormats, numInfo);
   WriteDataToResourceFile(strInt, resWriter, culture);
   if(verbose)
     Console.WriteLine("Decimal values and its formats");
   bogusHeaders = new String[decimalFormats.Length];
   for(int i=0; i<bogusHeaders.Length; i++){
   bogusHeaders[i] = "AA_" + i;
   }
   if(iCul==0){
   GenerateXmlSchema(bogusHeaders, strDec);
   }
   xmlwriter = File.CreateText(xmlDataFile  + "_" + strDec + "_" + culture.ToString() + ".xml");
   myXmlTextWriter = new XmlTextWriter(xmlwriter);
   myXmlTextWriter.Formatting = Formatting.Indented;
   myXmlTextWriter.WriteStartElement("NewDataSet");
   WriteRealHeaders(myXmlTextWriter, bogusHeaders, decimalFormats);
   WriteValues(myXmlTextWriter, NumberType.Decimal, bogusHeaders, decimalFormats, numInfo);
   WriteDataToResourceFile(strDec, resWriter, culture);
   if(verbose)
     Console.WriteLine("Double values and its formats");
   bogusHeaders = new String[doubleFormats.Length];
   for(int i=0; i<bogusHeaders.Length; i++){
   bogusHeaders[i] = "AA_" + i;
   }
   if(iCul==0){
   GenerateXmlSchema(bogusHeaders, strDbl);
   }
   xmlwriter = File.CreateText(xmlDataFile  + "_" + strDbl + "_" + culture.ToString() + ".xml");
   myXmlTextWriter = new XmlTextWriter(xmlwriter);
   myXmlTextWriter.Formatting = Formatting.Indented;
   myXmlTextWriter.WriteStartElement("NewDataSet");
   WriteRealHeaders(myXmlTextWriter, bogusHeaders, doubleFormats);
   WriteValues(myXmlTextWriter, NumberType.Double, bogusHeaders, doubleFormats, numInfo);
   WriteDataToResourceFile(strDbl, resWriter, culture);
   if(verbose)
     Console.WriteLine("Picture values and its formats");
   GoDoPictureFormatting(culture, resWriter);						
   }
   resWriter.Generate();
   resWriter.Close();
   }
Exemple #39
0
	public virtual bool runTest()
	{
		Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strLoc = "Loc_000oo";
		ResourceWriter writer;
		ThreadStart tdst1;
		Thread[] thdPool;
		Boolean fLoopExit;
		try {
			do
			{
				iCountTestcases++;
				if(File.Exists(Environment.CurrentDirectory+"\\Co3878_A.resources"))
				File.Delete(Environment.CurrentDirectory+"\\Co3878_A.resources");
				writer = new ResourceWriter("Co3878_A.resources");
				for(int i=0; i<iNumberOfStringsInFile; i++)
				writer.AddResource("Key " + i, "Value " + i);
				writer.Generate();
				writer.Close();
				iThreadsCompleted = 0;
				thdPool = new Thread[iNumberOfThreads];
				for(int i=0; i<iNumberOfThreads; i++){
					tdst1 = new ThreadStart(this.RSMangerForEachThread);
					thdPool[i] = new Thread(tdst1);
				}
				for(int i=0; i<iNumberOfThreads; i++){
					thdPool[i].Start();
				}
				do {
                                        int numberAlive = 0;
					fLoopExit = false;
                                        Thread.Sleep(100);
					for(int i=0; i<iNumberOfThreads; i++){
						if(thdPool[i].IsAlive) {
						fLoopExit = true; 
                                                numberAlive ++; 
                                                }
					}
				}while(fLoopExit);
				if(iThreadsCompleted != iNumberOfThreads){
					iCountErrors++;
					Console.WriteLine("Err_67423csd! All the thrads didn't execute the function. Expected, " + iNumberOfThreads + " completed, " + iThreadsCompleted);
				}
				iCountTestcases++;
				if(File.Exists(Environment.CurrentDirectory+"\\Co3878_B.resources"))
				File.Delete(Environment.CurrentDirectory+"\\Co3878_B.resources");
				writer = new ResourceWriter("Co3878_B.resources");
				for(int i=0; i<iNumberOfStringsInFile; i++)
				writer.AddResource("Key " + i, "Value " + i);
				writer.Generate();
				writer.Close();
				manager = ResourceManager.CreateFileBasedResourceManager("Co3878_B", Environment.CurrentDirectory, null);
				iThreadsCompleted = 0;
				thdPool = new Thread[iNumberOfThreads];
				for(int i=0; i<iNumberOfThreads; i++){
					tdst1 = new ThreadStart(this.RSMangerForAllThreads);
					thdPool[i] = new Thread(tdst1);
				}
				for(int i=0; i<iNumberOfThreads; i++){
					thdPool[i].Start();
				}
				do {
					fLoopExit = false;
                                        Thread.Sleep(100);
					for(int i=0; i<iNumberOfThreads; i++){
						if(thdPool[i].IsAlive)
						fLoopExit = true;
					}
				}while(fLoopExit);
				if(iThreadsCompleted != iNumberOfThreads){
					iCountErrors++;
					Console.WriteLine("Err_7539cd! All the threads didn't execute the function. Expected, " + iNumberOfThreads + " completed, " + iThreadsCompleted);
				}
				manager.ReleaseAllResources();
			} while (false);
			} catch (Exception exc_general ) {
			++iCountErrors;
			Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general);
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
			return true;
		}
		else
		{
			Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
 private void DoThings()
 {
     String[] bogusHeaders;
     ResourceWriter resWriter;
     String[] dateInfoCustomFormats;
     Hashtable dupTable;
     CultureInfo culture;
     DateTimeFormatInfo dateInfo;
     StreamWriter xmlwriter;
     XmlTextWriter myXmlTextWriter;
     Calendar otherCalendar;
     Calendar gregorian;
     Hashtable calendars;
     String[] tempFormats;
     calendars = new Hashtable();
     calendars.Add(0x0401, new HijriCalendar());
     calendars.Add(0x0404, new TaiwanCalendar());
     calendars.Add(0x040D, new HebrewCalendar());
     calendars.Add(0x0411, new JapaneseCalendar());
     calendars.Add(0x0412, new KoreanCalendar());
     calendars.Add(0x041E, new ThaiBuddhistCalendar());
     otherCalendar = null;
     gregorian = new GregorianCalendar();
     resWriter = new ResourceWriter(resourceBaseName + ".resources");
     resWriter.AddResource(resCultures, cultures);
     WriteXMLForCultures(cultures);
     for(int iCul = 0; iCul<cultures.Length; iCul++)
     {
         culture = cultures[iCul];			
         dateInfo = DateTimeFormatInfo.GetInstance(culture);
         try
         {
             otherCalendar = (Calendar)calendars[culture.LCID];
         }
         catch
         {
         }
         bogusHeaders = new String[formalFormats.Length];
         for(int i=0; i<bogusHeaders.Length; i++)
         {
             bogusHeaders[i] = "AA_" + i;
         }
         if(iCul==0)
         {
             GenerateXmlSchema(bogusHeaders, fileFormalFormats, false, culture);
         }
         if(calendars.ContainsKey(culture.LCID))
         {
             xmlwriter = File.CreateText(xmlDataFile  + "_" + fileFormalFormats + "_" + culture.ToString() + "_" + otherCalendarString + ".xml");
             myXmlTextWriter = new XmlTextWriter(xmlwriter);
             myXmlTextWriter.Formatting = Formatting.Indented;
             myXmlTextWriter.WriteStartElement("NewDataSet");
             tempFormats = new String[formalFormats.Length];
             formalFormats.CopyTo(tempFormats, 0);
             for(int i=0; i<tempFormats.Length; i++)
             {
                 if(Char.IsUpper(tempFormats[i][0]))
                     tempFormats[i] = tempFormats[i] + " ";
             }
             WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats);
             WriteValues(myXmlTextWriter, bogusHeaders, formalFormats, culture, otherCalendar);
             WriteDataToResourceFile(fileFormalFormats, resWriter, culture, false, true);
         }
         xmlwriter = File.CreateText(xmlDataFile  + "_" + fileFormalFormats + "_" + culture.ToString() + ".xml");
         myXmlTextWriter = new XmlTextWriter(xmlwriter);
         myXmlTextWriter.Formatting = Formatting.Indented;
         myXmlTextWriter.WriteStartElement("NewDataSet");
         tempFormats = new String[formalFormats.Length];
         formalFormats.CopyTo(tempFormats, 0);
         for(int i=0; i<tempFormats.Length; i++)
         {
             if(Char.IsUpper(tempFormats[i][0]))
                 tempFormats[i] = tempFormats[i] + " ";
         }
         WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats);
         WriteValues(myXmlTextWriter, bogusHeaders, formalFormats, culture, gregorian);
         WriteDataToResourceFile(fileFormalFormats, resWriter, culture, false, false);
         dateInfoCustomFormats = DateTimeFormatInfo.GetInstance(culture).GetAllDateTimePatterns();
         dupTable = new Hashtable();
         for(int i=0; i<dateInfoCustomFormats.Length; i++)
         {
             try
             {
                 dupTable.Add(dateInfoCustomFormats[i], null);
             }
             catch
             {
             }
         }
         dateInfoCustomFormats = new String[dupTable.Count];
         Int32 iTemp1=0;
         foreach(String strN in dupTable.Keys)
             dateInfoCustomFormats[iTemp1++] = strN;
         bogusHeaders = new String[dateInfoCustomFormats.Length];
         for(int i=0; i<bogusHeaders.Length; i++)
         {
             bogusHeaders[i] = "AA_" + i;
         }
         GenerateXmlSchema(bogusHeaders, fileDateTimePatterns, true, culture);
         if(calendars.ContainsKey(culture.LCID))
         {
             xmlwriter = File.CreateText(xmlDataFile  + "_" + fileDateTimePatterns + "_" + culture.ToString() + "_" + otherCalendarString + ".xml");
             myXmlTextWriter = new XmlTextWriter(xmlwriter);
             myXmlTextWriter.Formatting = Formatting.Indented;
             myXmlTextWriter.WriteStartElement("NewDataSet");
             WriteRealHeaders(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats);
             WriteValues(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats, culture, otherCalendar);
             WriteDataToResourceFile(fileDateTimePatterns, resWriter, culture, true, true);
         }
         xmlwriter = File.CreateText(xmlDataFile  + "_" + fileDateTimePatterns + "_" + culture.ToString() + ".xml");
         myXmlTextWriter = new XmlTextWriter(xmlwriter);
         myXmlTextWriter.Formatting = Formatting.Indented;
         myXmlTextWriter.WriteStartElement("NewDataSet");
         WriteRealHeaders(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats);
         WriteValues(myXmlTextWriter, bogusHeaders, dateInfoCustomFormats, culture, gregorian);
         WriteDataToResourceFile(fileDateTimePatterns, resWriter, culture, true, false);
         bogusHeaders = new String[ourOwnCustomFormats.Length];
         for(int i=0; i<bogusHeaders.Length; i++)
         {
             bogusHeaders[i] = "AA_" + i;
         }
         if(iCul==0)
         {
             GenerateXmlSchema(bogusHeaders, fileCustomFormats, false, culture);
         }
         if(calendars.ContainsKey(culture.LCID))
         {
             xmlwriter = File.CreateText(xmlDataFile  + "_" + fileCustomFormats + "_" + culture.ToString() + "_" + otherCalendarString + ".xml");
             myXmlTextWriter = new XmlTextWriter(xmlwriter);
             myXmlTextWriter.Formatting = Formatting.Indented;
             myXmlTextWriter.WriteStartElement("NewDataSet");
             tempFormats = new String[ourOwnCustomFormats.Length];
             ourOwnCustomFormats.CopyTo(tempFormats, 0);
             for(int i=0; i<tempFormats.Length; i++)
             {
                 if(ourOwnCustomFormats[i]=="DD")
                     tempFormats[i] = tempFormats[i] + " ";
             }
             WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats);
             WriteValues(myXmlTextWriter, bogusHeaders, ourOwnCustomFormats, culture, otherCalendar);
             WriteDataToResourceFile(fileCustomFormats, resWriter, culture, false, true);
         }
         xmlwriter = File.CreateText(xmlDataFile  + "_" + fileCustomFormats + "_" + culture.ToString() + ".xml");
         myXmlTextWriter = new XmlTextWriter(xmlwriter);
         myXmlTextWriter.Formatting = Formatting.Indented;
         myXmlTextWriter.WriteStartElement("NewDataSet");
         tempFormats = new String[ourOwnCustomFormats.Length];
         ourOwnCustomFormats.CopyTo(tempFormats, 0);
         for(int i=0; i<tempFormats.Length; i++)
         {
             if(ourOwnCustomFormats[i]=="DD")
                 tempFormats[i] = tempFormats[i] + " ";
         }
         WriteRealHeaders(myXmlTextWriter, bogusHeaders, tempFormats);
         WriteValues(myXmlTextWriter, bogusHeaders, ourOwnCustomFormats, culture, gregorian);
         WriteDataToResourceFile(fileCustomFormats, resWriter, culture, false, false);
     }
     resWriter.Generate();
     resWriter.Close();
 }
    private static void CreateResourceFile(
        string csFile, string resFile, string outputDir, out string sourceHash, out int viewCount)
    {
        viewCount = -1;
        sourceHash = string.Empty;

        var codeProvider = new CSharpCodeProvider();
        var inMemoryCodeCompiler = codeProvider.CreateCompiler();
        var parameters = new CompilerParameters();
        parameters.ReferencedAssemblies.Add("System.Data.Entity.dll");
        parameters.GenerateInMemory = true;
        CompilerResults results = inMemoryCodeCompiler.CompileAssemblyFromFile(parameters, csFile);

        if (results.Errors.Count == 0)
        {
            Assembly resultingAssembly = results.CompiledAssembly;
            Type[] typeList = resultingAssembly.GetTypes();
            foreach (Type type in typeList)
            {
                if (type.BaseType == typeof(EntityViewContainer))
                {
                    MethodInfo[] methodInfo = type.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance);
                    var instance = (EntityViewContainer)Activator.CreateInstance(type);
                    sourceHash = instance.HashOverAllExtentViews;
                    viewCount = instance.ViewCount;
                    using (var resWriter = new ResourceWriter(Path.Combine(outputDir, resFile)))
                    {
                        foreach (MethodInfo method in methodInfo)
                        {
                            if (char.IsDigit(method.Name, method.Name.Length - 1))
                            {
                                var result = (KeyValuePair<string, string>)method.Invoke(instance, null);
                                resWriter.AddResource(method.Name.Replace("GetView", string.Empty), result);
                            }
                        }

                        resWriter.Generate();
                        resWriter.Close();
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("Unable to Generate Resource File");
        }
    }
Exemple #42
0
  /// <summary>
  /// This method generates resource files directly using the ResourceWriter class.
  /// </summary>
  public void GenerateResourceFiles()
  {
    // Generate the New Zealand resource file.
    ResourceWriter rw = new ResourceWriter(EN_NZRESFILE);
    rw.AddResource("promptValidDeg", "Please enter a viable outside temperature (-100 to 60).");
    rw.AddResource("dist1", "(in kilometres) ==>");
    rw.AddResource("degree1", "in Celsius ==>");
    rw.AddResource("degree2", "-100");
    rw.AddResource("degree3", "60");
    rw.Generate();
    rw.Close();
    Console.WriteLine("Generating resource file: {0}", EN_NZRESFILE);

    // Generate the Germand resource file.
    rw = new ResourceWriter(DERESFILE);
    rw.AddResource("promptName", "Geben Sie Ihren Namen ein ==>");
    rw.AddResource("promptAge", "Geben Sie Ihr Alter ein ==>");
    rw.AddResource("promptDegrees", "Geben Sie die aktuelle Temperatur ein,");
    rw.AddResource("promptMissing", "Stellen Sie sicher, dass Sie einen gültigen Wert eingeben.");
    rw.AddResource("promptValidAge", "Geben Sie ein gültiges Alter für einen Erwachsenen ein (15 und älter).");    
    rw.AddResource("promptDist", "Geben Sie an, wie weit Sie zur Arbeit fahren");
    rw.AddResource("promptValidDist", "Geben Sie einen gültigen Abstand ein (größer als Null).");
    rw.AddResource("promptValidDeg", "Geben Sie eine Außentemperatur ein (-60C bis 60F).");
    rw.AddResource("promptEntries", "Sie trugen die folgenden Informationen ein:");
    rw.AddResource("dist1", "(in den Kilometern) ==>");
    rw.AddResource("degree1", "in Celsius ==>");
    rw.AddResource("degree2", "-60");
    rw.AddResource("degree3", "60");
    rw.AddResource("outputName", "Name:");
    rw.AddResource("outputAge", "Alter:");
    rw.AddResource("outputDegrees", "Temperatur:");
    rw.AddResource("outputDist", "Abstand Zur Arbeit:");
    rw.Generate();
    rw.Close();
    Console.WriteLine("Generating resource file: {0}", DERESFILE);
  }//GenerateResourceFiles()
 public bool runTest()
   {
   Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
   int iCountErrors = 0;
   int iCountTestcases = 0;
   String strLoc = "Loc_000oo";
   String strValue = String.Empty;
   IDictionaryEnumerator idic;
   try
     {
     ResourceWriter resWriter;
     ResourceReader resReader;
     Stream stream = null;
     MemoryStream ms;
     FileStream fs;
     if(File.Exists(Environment.CurrentDirectory+"\\Co5445.resources"))
       File.Delete(Environment.CurrentDirectory+"\\Co5445.resources");
     strLoc = "Loc_20xcy";
     stream = null;
     iCountTestcases++;
     try {
     resWriter = new ResourceWriter(stream);
     iCountErrors++;
     printerr( "Error_29vc8! ArgumentNullException expected");
     } catch ( ArgumentNullException aExc) {
     } catch ( Exception exc) {
     iCountErrors++;
     printerr( "Error_10s9x! ArgumentNullException expected , got exc=="+exc.ToString());
     }
     strLoc = "Loc_3f98d";
     new FileStream("Co5445.resources", FileMode.Create).Close();
     fs = new FileStream("Co5445.resources", FileMode.Open, FileAccess.Read, FileShare.None);
     iCountTestcases++;
     try {
     resWriter = new ResourceWriter(fs);
     iCountErrors++;
     printerr( "Error_2c88s! ArgumentException expected");
     } catch (ArgumentException aExc) {
     } catch ( Exception exc) {
     iCountErrors++;
     printerr( "Error_2x0zu! ArgumentException expected, got exc=="+exc.ToString());
     }
     strLoc = "Loc_f0843";
     ms = new MemoryStream();
     resWriter = new ResourceWriter(ms);
     resWriter.AddResource("Harrison", "Ford");
     resWriter.AddResource("Mark", "Hamill");
     resWriter.Generate();
     ms.Position = 0;
     resReader = new ResourceReader(ms);
     idic = resReader.GetEnumerator();
     idic.MoveNext();
     iCountTestcases++;
     if(!idic.Value.Equals("Ford"))
       {
       iCountErrors++;
       printerr( "Error_2d0s9 Expected==Ford, value=="+idic.Value.ToString());
       }
     idic.MoveNext();
     iCountTestcases++;
     if(!idic.Value.Equals("Hamill"))
       {
       iCountErrors++;
       printerr( "Error_2ce80 Expected==Hamill, value=="+idic.Value.ToString());
       }
     strLoc = "Loc_20984";
     iCountTestcases++;
     if(idic.MoveNext())
       {
       iCountErrors++;
       printerr( "Error_f4094! Should have hit the end of the stream already");
       }
     fs.Close();
     strLoc = "Loc_04853fd";
     if(File.Exists(Environment.CurrentDirectory+"\\Co5445.resources"))
       File.Delete(Environment.CurrentDirectory+"\\Co5445.resources");
     } catch (Exception exc_general ) {
     ++iCountErrors;
     Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general.ToString());
     }
   if ( iCountErrors == 0 )
     {
     Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
     return true;
     }
   else
     {
     Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
     return false;
     }
   }
 public Boolean runTest()
   {
   Console.WriteLine(s_strTFPath + " " + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
   int iCountErrors = 0;
   int iCountTestcases = 0;
   String strLoc = "Loc_000oo";
   String strValue = String.Empty;
   Co5209AddResource_str_ubArr cc = new Co5209AddResource_str_ubArr();
   IDictionaryEnumerator idic;
   try {
   do
     {
     ResourceWriter resWriter;
     ResourceReader resReader;
     int statusBits = 0;
     int resultBits = 0;
     Byte[] ubArr = null;
     if(File.Exists(Environment.CurrentDirectory+"\\Co5209.resources"))
       File.Delete(Environment.CurrentDirectory+"\\Co5209.resources");
     strLoc = "Loc_204gh";
     resWriter = new ResourceWriter("Co5209.resources");
     strLoc = "Loc_209tj";
     try
       {
       iCountTestcases++;
       resWriter.AddResource(null, ubArr);
       iCountErrors++;
       printerr("Error_20fhs! Expected Exception not thrown");
       }
     catch (ArgumentException) {}
     catch (Exception exc)
       {
       iCountErrors++;
       printerr("Error_2t0jg! Unexpected exception exc=="+exc.ToString());
       }
     strLoc = "Loc_t4j80";
     ubArr = null;
     iCountTestcases++;
     try
       {
       resWriter.AddResource("key with null value", ubArr);
       }
     catch (Exception exc)
       {
       iCountErrors++;
       printerr("Error_59ufd! Unexpected exc=="+exc.ToString());
       }
     Byte[] ubArr1 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'1',};
     Byte[] ubArr2 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'2',};
     Byte[] ubArr3 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'3',};
     Byte[] ubArr4 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'4',};
     Byte[] ubArr5 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'5',};
     Byte[] ubArr6 = {(Byte)'v', (Byte)'a', (Byte)'l', (Byte)'u', (Byte)'e', (Byte)' ', (Byte)'6',};
     strLoc = "Loc_59ugd";
     resWriter.AddResource("key 1", ubArr1);
     resWriter.AddResource("key 2", ubArr2);
     resWriter.AddResource("key 3", ubArr3);
     resWriter.AddResource("key 4", ubArr4);
     resWriter.AddResource("key 5", ubArr5);
     resWriter.AddResource("key 6", ubArr6);
     strLoc = "Loc_230rj";
     iCountTestcases++;
     try
       {
       resWriter.AddResource("key 1", ubArr6);
       iCountErrors++;
       printerr("Error_2th8e! Names are not unique");
       }
     catch (ArgumentException) {}
     catch (Exception exc)
       {
       iCountErrors++;
       printerr("Error_298hg! Unexpected exception=="+exc.ToString());
       }
     resWriter.Generate();
     iCountTestcases++;
     if(!File.Exists(Environment.CurrentDirectory+"\\Co5209.resources"))
       {
       iCountErrors++;
       printerr("Error_23094! Expected file was not created");
       }
     resWriter.Close();
     strLoc = "Loc_30tud";
     resReader = new ResourceReader(Environment.CurrentDirectory+"\\Co5209.resources");
     strLoc = "Loc_0576cd";
     byte[] btTemp;
     Boolean fNotEqual;
     IDictionaryEnumerator resEnumerator = resReader.GetEnumerator();
     idic = resReader.GetEnumerator();
     while(idic.MoveNext())
       {
       if(idic.Key.Equals("key 1")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr1[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x1;
       } else if(idic.Key.Equals("key 2")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr2[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x2;
       } else if(idic.Key.Equals("key 3")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr3[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x4;
       } else if(idic.Key.Equals("key 4")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr4[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x8;
       } else if(idic.Key.Equals("key 5")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr5[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x10;
       } else if(idic.Key.Equals("key 6")) {
       btTemp = (byte[])idic.Value;
       fNotEqual = false;
       for(int i=0;i<btTemp.Length; i++) {
       if(btTemp[i]!=ubArr6[i])
	 fNotEqual = true;
       }
       if(!fNotEqual)
	 statusBits = statusBits | 0x20;
       }
       }
     resultBits = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20;
     iCountTestcases++;
     if(statusBits != resultBits)
       {
       iCountErrors++;
       printerr("Error_238fh! The names are incorrect, StatusBits=="+statusBits);
       }
     strLoc = "Loc_t0dds";
     iCountTestcases++;
     if(idic.MoveNext())
       {
       iCountErrors++;
       printerr("Error_2398r! , There shouldn't have been more elementes : GetValue=="+idic.Value);
       }
     resReader.Close();
     strLoc = "Loc_957fd";
     } while (false);
   } catch (Exception exc_general ) {
   ++iCountErrors;
   Console.WriteLine (s_strTFAbbrev + " : Error Err_8888yyy!  strLoc=="+ strLoc +", exc_general=="+exc_general);
   }
   if ( iCountErrors == 0 )
     {
     Console.WriteLine( "paSs.   "+s_strTFPath +" "+s_strTFName+" ,iCountTestcases=="+iCountTestcases);
     return true;
     }
   else
     {
     Console.WriteLine("FAiL!   "+s_strTFPath+" "+s_strTFName+" ,iCountErrors=="+iCountErrors+" , BugNums?: "+s_strActiveBugNums );
     return false;
     }
   }
Exemple #45
0
 public static string ToResource(string xapFile)
 {
     var resourceFile = Path.Combine(Path.GetTempPath(), "SLViewer.resources");
     using (var resourceWriter = new ResourceWriter(resourceFile))
     {
         resourceWriter.AddResource("content.xap", File.ReadAllBytes(xapFile));
         resourceWriter.Generate();
     }
     return resourceFile;
 }