Exemplo n.º 1
0
        public static void AssemblyWithEmbeddedResources()
        {
            // Note this is using SimpleAssemblyResolver in order to resolve names between assemblies.
            using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver()))
            {
                Assembly a = lc.LoadFromByteArray(TestData.s_AssemblyWithEmbeddedResourcesImage);

                string[] names = a.GetManifestResourceNames().OrderBy(s => s).ToArray();
                Assert.Equal <string>(new string[] { "MyRes1", "MyRes2", "MyRes3" }, names);
                foreach (string name in names)
                {
                    ManifestResourceInfo mri = a.GetManifestResourceInfo(name);
                    Assert.Equal(ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile, mri.ResourceLocation);
                    Assert.Null(mri.FileName);
                    Assert.Null(mri.ReferencedAssembly);
                }

                using (Stream s = a.GetManifestResourceStream("MyRes1"))
                {
                    byte[] res = s.ToArray();
                    Assert.Equal <byte>(TestData.s_MyRes1, res);
                }

                using (Stream s = a.GetManifestResourceStream("MyRes2"))
                {
                    byte[] res = s.ToArray();
                    Assert.Equal <byte>(TestData.s_MyRes2, res);
                }

                using (Stream s = a.GetManifestResourceStream("MyRes3"))
                {
                    byte[] res = s.ToArray();
                    Assert.Equal <byte>(TestData.s_MyRes3, res);
                }
            }
        }
Exemplo n.º 2
0
            public void bug78468(string assemblyFileName)
            {
                AssemblyName assemblyName = new AssemblyName();

                assemblyName.Name = "bug78468b";

                AssemblyBuilder ab = AppDomain.CurrentDomain
                                     .DefineDynamicAssembly(assemblyName,
                                                            AssemblyBuilderAccess.Save,
                                                            Path.GetDirectoryName(assemblyFileName),
                                                            AppDomain.CurrentDomain.Evidence);

                ab.AddResourceFile("read", "readme.txt");
                ab.Save(Path.GetFileName(assemblyFileName));

                Assembly assembly = Assembly.LoadFrom(assemblyFileName, AppDomain.CurrentDomain.Evidence);

                Assert.IsTrue(assembly.Location != string.Empty, "#B1");
                string[] resNames = assembly.GetManifestResourceNames();
                Assert.IsNotNull(resNames, "#B2");
                Assert.AreEqual(1, resNames.Length, "#B3");
                Assert.AreEqual("read", resNames[0], "#B4");
                ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo("read");

                Assert.IsNotNull(resInfo, "#B5");
                Assert.AreEqual("readme.txt", resInfo.FileName, "#B6");
                Assert.IsNull(resInfo.ReferencedAssembly, "#B7");
                Assert.AreEqual((ResourceLocation)0, resInfo.ResourceLocation, "#B8");
                Stream s = assembly.GetManifestResourceStream("read");

                Assert.IsNotNull(s, "#B9");
                s.Close();
                s = assembly.GetFile("readme.txt");
                Assert.IsNotNull(s, "#B10");
                s.Close();
            }
Exemplo n.º 3
0
        /// <summary>
        /// A helper function for creating a node description object for the specified model.
        /// </summary>
        /// <param name="model">The model</param>
        /// <returns>The description</returns>
        private TreeViewNode GetNodeDescription(IModel model)
        {
            TreeViewNode description = new TreeViewNode();

            description.Name = model.Name;

            description.ResourceNameForImage = "ApsimNG.Resources.TreeViewImages." + model.Name + ".png";
            ManifestResourceInfo info = Assembly.GetExecutingAssembly().GetManifestResourceInfo(description.ResourceNameForImage);

            if (info == null || (typeof(IModel).Assembly.DefinedTypes.Any(t => string.Equals(t.Name, model.Name, StringComparison.Ordinal)) && model.GetType().Name != model.Name))
            {
                description.ResourceNameForImage = "ApsimNG.Resources.TreeViewImages." + model.GetType().Name + ".png";
            }
            if (typeof(Models.Functions.IFunction).IsAssignableFrom(model.GetType()))
            {
                description.ToolTip = model.GetType().Name;
            }

            description.Children = new List <TreeViewNode>();
            foreach (Model child in model.Children)
            {
                if (!child.IsHidden)
                {
                    description.Children.Add(this.GetNodeDescription(child));
                }
            }
            description.Strikethrough = !model.Enabled;
            description.Checked       = model.IncludeInDocumentation && showDocumentationStatus;

            /*
             * // Set the colour here
             * System.Drawing.Color colour = model.Enabled ? System.Drawing.Color.Black : System.Drawing.Color.Red;
             * description.Colour = colour;
             */
            return(description);
        }
Exemplo n.º 4
0
        /// <summary>Populate the main menu tool strip.</summary>
        /// <param name="menuDescriptions">Descriptions for each item.</param>
        public void Populate(List <MenuDescriptionArgs> menuDescriptions)
        {
            menu.Clear();
            foreach (MenuDescriptionArgs description in menuDescriptions)
            {
                MenuItem item;
                if (description.ShowCheckbox)
                {
                    CheckMenuItem checkItem = new CheckMenuItem(description.Name);
                    checkItem.Active = description.Checked;
                    item             = checkItem;
                }
                else
                {
                    ManifestResourceInfo info = Assembly.GetExecutingAssembly().GetManifestResourceInfo(description.ResourceNameForImage);
                    if (info != null)
                    {
                        MenuItem imageItem = WidgetExtensions.CreateImageMenuItem(description.Name, new Gtk.Image(null, description.ResourceNameForImage));
                        item = imageItem;
                    }
                    else
                    {
                        item = new MenuItem(description.Name);
                    }
                }

                if (!String.IsNullOrEmpty(description.ShortcutKey))
                {
                    string           keyName  = String.Empty;
                    Gdk.ModifierType modifier = Gdk.ModifierType.None;
                    string[]         keyNames = description.ShortcutKey.Split(new Char[] { '+' });
                    foreach (string name in keyNames)
                    {
                        if (name == "Ctrl")
                        {
                            modifier |= Gdk.ModifierType.ControlMask;
                        }
                        else if (name == "Shift")
                        {
                            modifier |= Gdk.ModifierType.ShiftMask;
                        }
                        else if (name == "Alt")
                        {
                            modifier |= Gdk.ModifierType.Mod1Mask;
                        }
                        else if (name == "Del")
                        {
                            keyName = "Delete";
                        }
                        else
                        {
                            keyName = name;
                        }
                    }
                    try
                    {
                        Gdk.Key accelKey = (Gdk.Key)Enum.Parse(typeof(Gdk.Key), keyName, false);
                        item.AddAccelerator("activate", Accelerators, (uint)accelKey, modifier, AccelFlags.Visible);
                    }
                    catch
                    {
                    }
                }
                item.Activated += description.OnClick;
                if (description.FollowsSeparator && (menu.Children.Length > 0))
                {
                    menu.Append(new SeparatorMenuItem());
                }
                menu.Append(item);
            }
            menu.ShowAll();
        }
Exemplo n.º 5
0
        /// <summary>[埋め込まれたリソースXMLファイル]から文字列を読み込む。</summary>
        /// <param name="assemblyString">
        /// アセンブリ名
        /// http://msdn.microsoft.com/ja-jp/library/k8xx4k69.aspx
        /// </param>
        /// <param name="loadfileName">[埋め込まれたリソースXMLファイル]の名前(名前空間付き)</param>
        /// <returns>[埋め込まれたリソースXMLファイル]から読み込んだ文字列</returns>
        /// <remarks>自由に利用できる。</remarks>
        public static string LoadXMLAsString(string assemblyString, string loadfileName)
        {
            // エントリのアセンブリ
            Assembly             thisAssembly         = null;
            ManifestResourceInfo manifestResourceInfo = null;

            // ストリーム
            StreamReader sr = null;
            // リーダ(XML)
            XmlTextReader xtr = null;

            // 例外処理
            try
            {
                thisAssembly         = EmbeddedResourceLoader.GetEntryAssembly(assemblyString);
                manifestResourceInfo = thisAssembly.GetManifestResourceInfo(loadfileName);
            }
            catch (Exception)
            {
                // なにもしない。
            }

            try
            {
                // 存在チェック
                if (manifestResourceInfo != null)
                {
                    if (0 != (manifestResourceInfo.ResourceLocation
                              & (ResourceLocation.ContainedInManifestFile | ResourceLocation.Embedded)))
                    {
                        // 存在する。
                    }
                    else
                    {
                        // 存在しない。
                        throw new ArgumentException(String.Format(
                                                        PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName));
                    }
                }
                else
                {
                    // 存在しない。
                    throw new ArgumentException(String.Format(
                                                    PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName));
                }

                // 既定のエンコーディングでロードして、
                sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName));

                // XML宣言を取得して、
                // <?xml version="1.0" encoding="xxxx" ?>
                string xmlDeclaration = sr.ReadLine();
                sr.Close();

                // エンコーディング オブジェクトの取得
                Encoding enc;

                try
                {
                    // エンコーディング文字列を取得し、
                    string searchString = "encoding=\"";
                    int    start        = xmlDeclaration.IndexOf(searchString, 0) + searchString.Length;
                    int    end          = xmlDeclaration.IndexOf('\"', start);

                    // エンコーディング オブジェクトに変換
                    enc = Encoding.GetEncoding(xmlDeclaration.Substring(start, end - start));
                }
                catch (Exception)
                {
                    // ここでエラーとなった場合、
                    throw new ArgumentException(String.Format(
                                                    PublicExceptionMessage.XML_DECLARATION_ERROR, xmlDeclaration));
                }

                // 指定のエンコーディングで再ロード
                sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName), enc);

                // 読む
                return(sr.ReadToEnd());
            }
            finally
            {
                // nullチェック
                if (xtr == null)
                {
                    // 何もしない。
                }
                else
                {
                    // 閉じる
                    xtr.Close();
                }

                // nullチェック
                if (sr == null)
                {
                    // 何もしない。
                }
                else
                {
                    // 閉じる
                    sr.Close();
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>[埋め込まれたリソース ファイル]から文字列を読み込む。</summary>
        /// <param name="assemblyString">
        /// アセンブリ名
        /// http://msdn.microsoft.com/ja-jp/library/k8xx4k69.aspx
        /// </param>
        /// <param name="loadfileName">[埋め込まれたリソース ファイル]の名前(名前空間付き)</param>
        /// <param name="enc">エンコード</param>
        /// <returns>[埋め込まれたリソース ファイル]から読み込んだ文字列</returns>
        /// <remarks>自由に利用できる。</remarks>
        public static string LoadAsString(string assemblyString, string loadfileName, Encoding enc)
        {
            // エントリのアセンブリ
            Assembly             thisAssembly         = null;
            ManifestResourceInfo manifestResourceInfo = null;

            // ストリーム
            StreamReader sr = null;

            // 例外処理
            try
            {
                thisAssembly         = EmbeddedResourceLoader.GetEntryAssembly(assemblyString);
                manifestResourceInfo = thisAssembly.GetManifestResourceInfo(loadfileName);
            }
            catch (Exception)
            {
                // なにもしない。
            }

            try
            {
                // 存在チェック
                if (manifestResourceInfo != null)
                {
                    if (0 != (manifestResourceInfo.ResourceLocation
                              & (ResourceLocation.ContainedInManifestFile | ResourceLocation.Embedded)))
                    {
                        // 存在する。
                    }
                    else
                    {
                        // 存在しない。
                        throw new ArgumentException(String.Format(
                                                        PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName));
                    }
                }
                else
                {
                    // 存在しない。
                    throw new ArgumentException(String.Format(
                                                    PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName));
                }

                // 開く
                sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName), enc);

                // 読む
                return(sr.ReadToEnd());
            }
            finally
            {
                // nullチェック
                if (sr == null)
                {
                    // 何もしない。
                }
                else
                {
                    // 閉じる
                    sr.Close();
                }
            }
        }
Exemplo n.º 7
0
 public abstract ManifestResourceInfo ProjectManifestResource(ManifestResourceInfo value);
Exemplo n.º 8
0
        public ResourceWebResponse(Uri uri, IDictionary <String, Assembly> assemblyMap, IDictionary <string, string> pluginAliasMap, String staticFileFolder)
        {
            this.uri = uri;
            //得到插件名
            var pluginName = uri.Host;

            if (pluginName == "0" ||
                pluginName == "0.0.0.0")
            {
                pluginName = ".";
            }
            //得到资源名
            resourceName = uri.LocalPath;

            pluginName = pluginName.ToLower();
            //获取到程序集
            if (assemblyMap.ContainsKey(pluginName))
            {
                Assembly   = assemblyMap[pluginName];
                pluginName = Assembly.GetName().Name;
            }
            //设置资源搜索目录
            List <String> searchFolderList = new List <string>();

            searchFolderList.Add(Path.Combine(staticFileFolder, pluginName));
            if (pluginAliasMap != null && pluginAliasMap.ContainsKey(pluginName))
            {
                pluginName = pluginAliasMap[pluginName];
                searchFolderList.Add(Path.Combine(staticFileFolder, pluginName));
            }
            //开始在文件系统上搜索资源
            String fullFilePath = null;

            foreach (var searchFolder in searchFolderList)
            {
                fullFilePath = ResourceUtils.findFilePath(searchFolder, resourceName);
                if (fullFilePath != null)
                {
                    break;
                }
            }
            if (fullFilePath != null)
            {
                fileInfo = new FileInfo(fullFilePath);
            }
            else if (pluginName == ".")
            {
            }
            else
            {
                if (Assembly == null)
                {
                    return;
                }
                String assemblyName = Assembly.GetName().Name;
                while (resourceName.StartsWith("/"))
                {
                    resourceName = resourceName.Substring(1);
                }

                Func <string, string> dirHandler      = t => t.Replace("-", "_");
                Func <string, string> fileNameHandler = t => t.Replace("/", ".");

                List <string> resourceNameList = new List <string>();
                resourceNameList.Add(fileNameHandler.Invoke(resourceName));

                var lastDotIndex = resourceName.LastIndexOf('.');
                if (lastDotIndex > 0)
                {
                    var dirName  = Path.GetDirectoryName(resourceName);
                    var fileName = Path.GetFileName(resourceName);

                    dirName = dirName.Replace(Path.DirectorySeparatorChar, '/');
                    dirName = dirHandler(dirName);
                    dirName = dirName.Replace(".", "._");

                    resourceNameList.Add(fileNameHandler.Invoke($"{dirName}/{fileName}"));
                }
                resourceNameList.Add(resourceName);

                if (lastDotIndex < 0)
                {
                    lastDotIndex = 0;
                }
                resourceNameList.Add(fileNameHandler.Invoke(resourceName.Insert(lastDotIndex, ".")));

                foreach (var currentResourceName in resourceNameList)
                {
                    var fullResourceName = $"{assemblyName}.{currentResourceName}";
                    resourceInfo = Assembly.GetManifestResourceInfo(fullResourceName);
                    if (resourceInfo != null)
                    {
                        resourceName = fullResourceName;
                        break;
                    }
                }
            }
        }
Exemplo n.º 9
0
 internal ManifestResourceInfo GetManifestResourceInfo(string resourceName)
 {
     for (int i = 0; i < ManifestResource.records.Length; i++)
     {
         if (resourceName == GetString(ManifestResource.records[i].Name))
         {
             ManifestResourceInfo info = new ManifestResourceInfo(this, i);
             Assembly asm = info.ReferencedAssembly;
             if (asm != null && !asm.__IsMissing && asm.GetManifestResourceInfo(resourceName) == null)
             {
                 return null;
             }
             return info;
         }
     }
     return null;
 }
Exemplo n.º 10
0
        // TODO: Put strings into the resources.
        //
        public static bool GetManifestResourceStream(Assembly mainAssembly, string resourceName, bool throwIfMissing, out ManifestResourceInfo info, out Stream stream, CultureInfo culture = default)
        {
            //
            if (mainAssembly is null)
            {
                throw new ArgumentNullException(paramName: nameof(mainAssembly));
            }
            else if (resourceName is null)
            {
                throw new ArgumentNullException(paramName: nameof(resourceName));
            }
            else if (resourceName == string.Empty)
            {
                throw new ArgumentOutOfRangeException(paramName: nameof(resourceName), message: "Cannot be an empty string.");
            }
            //
            culture = culture ?? Thread.CurrentThread.CurrentCulture;
            var      neutralLanguage = mainAssembly.GetCustomAttribute <NeutralResourcesLanguageAttribute>();
            Assembly selectedAssembly;

            if (string.Equals(a: culture.Name, b: neutralLanguage?.CultureName, comparisonType: CultureNameUtilities.Comparison))
            {
                selectedAssembly = neutralLanguage?.Location == UltimateResourceFallbackLocation.MainAssembly ? mainAssembly : getSatelliteAssembly(locMainAssembly: mainAssembly, locCulture: culture, locThrowIfMissing: throwIfMissing);
            }
            else
            {
                try {
                    selectedAssembly = getSatelliteAssembly(locMainAssembly: mainAssembly, locCulture: culture, locThrowIfMissing: true);
                }
                catch (Exception exception) {
                    if (neutralLanguage is null)
                    {
                        if (throwIfMissing)
                        {
                            throw;
                        }
                        else
                        {
                            selectedAssembly = null;
                        }
                    }
                    else
                    {
                        try {
                            if (neutralLanguage.Location == UltimateResourceFallbackLocation.Satellite)
                            {
                                selectedAssembly = getSatelliteAssembly(locMainAssembly: mainAssembly, locCulture: CultureInfo.GetCultureInfo(name: neutralLanguage.CultureName), locThrowIfMissing: throwIfMissing);
                            }
                            else
                            {
                                selectedAssembly = mainAssembly;
                            }
                        }
                        catch (Exception secondException) {
                            throw new AggregateException(exception, secondException);
                        }
                    }
                }
            }
            return(getResource(locAssembly: selectedAssembly, locResourceName: resourceName, locThrowIfMissing: throwIfMissing, locInfo: out info, locStream: out stream));

            //
            Assembly getSatelliteAssembly(Assembly locMainAssembly, CultureInfo locCulture, bool locThrowIfMissing)
            {
                try {
                    return(locMainAssembly.GetSatelliteAssembly(culture: locCulture));
                }
                catch (Exception locException) {
                    var locParentCulture = locCulture.Parent;
                    if (locParentCulture is null || ReferenceEquals(locParentCulture, locParentCulture.Parent))
                    {
                        if (locThrowIfMissing)
                        {
                            throw;
                        }
                        else
                        {
                            return(null);
                        }
                    }
Exemplo n.º 11
0
        public void CompileFromFileBatch_Library_InMemory()
        {
            // create source file
            string sourceFile1 = Path.Combine(_tempDir, "file1." + _codeProvider.FileExtension);

            using (FileStream f = new FileStream(sourceFile1, FileMode.Create)) {
                using (StreamWriter s = new StreamWriter(f)) {
                    s.Write(_sourceLibrary1);
                    s.Close();
                }
                f.Close();
            }

            string sourceFile2 = Path.Combine(_tempDir, "file2." + _codeProvider.FileExtension);

            using (FileStream f = new FileStream(sourceFile2, FileMode.Create)) {
                using (StreamWriter s = new StreamWriter(f)) {
                    s.Write(_sourceLibrary2);
                    s.Close();
                }
                f.Close();
            }

            CompilerParameters options = new CompilerParameters();

            options.GenerateExecutable = false;
            options.GenerateInMemory   = true;
            options.TempFiles          = new TempFileCollection(_tempDir);
            options.EmbeddedResources.Add(sourceFile1);
            options.LinkedResources.Add(sourceFile2);

            ICodeCompiler   compiler = _codeProvider.CreateCompiler();
            CompilerResults results  = compiler.CompileAssemblyFromFileBatch(options,
                                                                             new string [] { sourceFile1, sourceFile2 });

            // verify compilation was successful
            AssertCompileResults(results, true);

            Assembly compiledAssembly = results.CompiledAssembly;

            Assert.IsNotNull(compiledAssembly, "#A1");
            Assert.AreEqual(string.Empty, compiledAssembly.Location, "#A2");
            Assert.IsNull(results.PathToAssembly, "#A3");
            Assert.IsNotNull(options.OutputAssembly, "#A4");
            Assert.AreEqual(".dll", Path.GetExtension(options.OutputAssembly), "#A5");
            Assert.AreEqual(_tempDir, Path.GetDirectoryName(options.OutputAssembly), "#A6");
            Assert.IsFalse(File.Exists(options.OutputAssembly), "#A7");

            Assert.IsNotNull(compiledAssembly.GetType("Test1"), "#B1");
            Assert.IsNotNull(compiledAssembly.GetType("Test2"), "#B2");

            // verify we don't cleanup files in temp directory too agressively
            string [] tempFiles = Directory.GetFiles(_tempDir);
            Assert.AreEqual(2, tempFiles.Length, "#C1");
            Assert.IsTrue(File.Exists(sourceFile1), "#C2");
            Assert.IsTrue(File.Exists(sourceFile2), "#C3");

            string[] resources = compiledAssembly.GetManifestResourceNames();
            Assert.IsNotNull(resources, "#D1");
            Assert.AreEqual(2, resources.Length, "#D2");

            Assert.IsTrue(resources[0] == "file1.cs" || resources [0] == "file2.cs", "#E1");
            Assert.IsNull(compiledAssembly.GetFile("file1.cs"), "#E2");
            Assert.IsNotNull(compiledAssembly.GetManifestResourceStream("file1.cs"), "#E3");
            ManifestResourceInfo info = compiledAssembly.GetManifestResourceInfo("file1.cs");

            Assert.IsNotNull(info, "#E4");
            Assert.IsNull(info.FileName, "#E5");
            Assert.IsNull(info.ReferencedAssembly, "#E6");
            Assert.AreEqual((ResourceLocation.Embedded | ResourceLocation.ContainedInManifestFile), info.ResourceLocation, "#E7");

            Assert.IsTrue(resources[1] == "file1.cs" || resources [1] == "file2.cs", "#F1");
            try {
                compiledAssembly.GetFile("file2.cs");
                Assert.Fail("#F2");
            } catch (FileNotFoundException) {
            }
            try {
                compiledAssembly.GetManifestResourceStream("file2.cs");
                Assert.Fail("#F3");
            } catch (FileNotFoundException) {
            }
            info = compiledAssembly.GetManifestResourceInfo("file2.cs");
            Assert.IsNotNull(info, "#F4");
            Assert.IsNotNull(info.FileName, "#F5");
            Assert.AreEqual("file2.cs", info.FileName, "#F6");
            Assert.IsNull(info.ReferencedAssembly, "#F7");
            Assert.AreEqual((ResourceLocation)0, info.ResourceLocation, "#F8");
        }
Exemplo n.º 12
0
        //--------------------------------------------------
        // The function follows Managed code parser
        // implementation. in the future, maybe they should
        // share the same code
        //--------------------------------------------------
        private static void GenerateAssembly(LocBamlOptions options, TranslationDictionariesReader dictionaries)
        {
            // there are many names to be used when generating an assembly
            string sourceAssemblyFullName  = options.Input;                                                // source assembly full path
            string outputAssemblyDir       = options.Output;                                               // output assembly directory
            string outputAssemblyLocalName = GetOutputFileName(options);                                   // output assembly name
            string moduleLocalName         = GetAssemblyModuleLocalName(options, outputAssemblyLocalName); // the module name within the assmbly

            // get the source assembly
            byte[]   sourceContents = File.ReadAllBytes(sourceAssemblyFullName);
            Assembly srcAsm         = Assembly.Load(sourceContents);

            // obtain the assembly name
            AssemblyName targetAssemblyNameObj = srcAsm.GetName();

            // store the culture info of the source assembly
            CultureInfo srcCultureInfo = targetAssemblyNameObj.CultureInfo;

            // update it to use it for target assembly
            targetAssemblyNameObj.Name        = Path.GetFileNameWithoutExtension(outputAssemblyLocalName);
            targetAssemblyNameObj.CultureInfo = options.CultureInfo;

            // we get a assembly builder
            AssemblyBuilder targetAssemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(
                targetAssemblyNameObj,                  // name of the assembly
                AssemblyBuilderAccess.RunAndSave,       // access rights
                outputAssemblyDir                       // storage dir
                );

            // we create a module builder for embeded resource modules
            ModuleBuilder moduleBuilder = targetAssemblyBuilder.DefineDynamicModule(
                moduleLocalName,
                outputAssemblyLocalName
                );

            Dictionary <string, IResourceWriter> resourceWriters = new Dictionary <string, IResourceWriter>();

            // If the output assembly already exists, copy the embedded resources to the new assembly
            string existingAssemblyName = Path.Combine(Directory.GetCurrentDirectory(), options.CultureInfo.Name, outputAssemblyLocalName);

            if (File.Exists(existingAssemblyName))
            {
                // Use ReadAllBytes() so we don't hold a file handle open, which would prevent
                // us from overwriting the file at the end.
                Assembly existingAssembly      = Assembly.Load(File.ReadAllBytes(existingAssemblyName));
                string[] existingResourceNames = existingAssembly.GetManifestResourceNames();
                foreach (string resourceName in existingResourceNames)
                {
                    ManifestResourceInfo info = existingAssembly.GetManifestResourceInfo(resourceName);
                    if ((info.ResourceLocation & ResourceLocation.Embedded) != ResourceLocation.Embedded)
                    {
                        continue;
                    }
                    IResourceWriter writer;
                    if (!resourceWriters.TryGetValue(resourceName, out writer))
                    {
                        writer = moduleBuilder.DefineResource(
                            resourceName,             // resource name
                            resourceName,             // resource description
                            ResourceAttributes.Public // visibilty of this resource to other assembly
                            );
                        resourceWriters.Add(resourceName, writer);
                    }
                    Stream resourceStream = existingAssembly.GetManifestResourceStream(resourceName);
                    using (ResourceReader reader = new ResourceReader(resourceStream))
                    {
                        foreach (DictionaryEntry entry in reader)
                        {
                            string key   = entry.Key.ToString();
                            object value = entry.Value;
                            if (key.EndsWith(".baml"))
                            {
                                // Skip it, we're going to get this from the untranslated assembly
                                continue;
                            }
                            writer.AddResource(key, value);
                        }
                    }
                }
            }

            // Add assembly info, trying to preserver original values as close as possible
            CopyAssemblyVersion(targetAssemblyBuilder, srcAsm);

            options.WriteLine(StringLoader.Get("GenerateAssembly"));

            // now for each resource in the assembly
            foreach (string resourceName in srcAsm.GetManifestResourceNames())
            {
                // get the resource location for the resource
                ResourceLocation resourceLocation = srcAsm.GetManifestResourceInfo(resourceName).ResourceLocation;

                // if this resource is in another assemlby, we will skip it
                if ((resourceLocation & ResourceLocation.ContainedInAnotherAssembly) != 0)
                {
                    continue;   // in resource assembly, we don't have resource that is contained in another assembly
                }

                // gets the neutral resource name, giving it the source culture info
                string neutralResourceName = GetNeutralResModuleName(resourceName, srcCultureInfo);

                // gets the target resource name, by giving it the target culture info
                string targetResourceName = GetCultureSpecificResourceName(neutralResourceName, options.CultureInfo);

                // resource stream
                Stream resourceStream = srcAsm.GetManifestResourceStream(resourceName);

                // see if it is a .resources
                if (neutralResourceName.ToLower(CultureInfo.InvariantCulture).EndsWith(".resources"))
                {
                    // now we think we have resource stream
                    // get the resource writer
                    IResourceWriter writer;
                    // check if it is a embeded assembly
                    if (!resourceWriters.TryGetValue(targetResourceName, out writer))
                    {
                        if ((resourceLocation & ResourceLocation.Embedded) != 0)
                        {
                            // gets the resource writer from the module builder
                            writer = moduleBuilder.DefineResource(
                                targetResourceName,         // resource name
                                targetResourceName,         // resource description
                                ResourceAttributes.Public   // visibilty of this resource to other assembly
                                );
                        }
                        else
                        {
                            // it is a standalone resource, we get the resource writer from the assembly builder
                            writer = targetAssemblyBuilder.DefineResource(
                                targetResourceName,         // resource name
                                targetResourceName,         // description
                                targetResourceName,         // file name to save to
                                ResourceAttributes.Public   // visibility of this resource to other assembly
                                );
                        }
                        resourceWriters.Add(targetResourceName, writer);
                    }

                    // get the resource reader
                    IResourceReader reader = new ResourceReader(resourceStream);

                    // generate the resources
                    GenerateResourceStream(options, resourceName, reader, writer, dictionaries);

                    // we don't call writer.Generate() or writer.Close() here
                    // because the AssemblyBuilder will call them when we call Save() on it.
                }
                else
                {
                    // else it is a stand alone untyped manifest resources.
                    string extension = Path.GetExtension(targetResourceName);

                    string fullFileName = Path.Combine(outputAssemblyDir, targetResourceName);

                    // check if it is a .baml, case-insensitive
                    if (string.Compare(extension, ".baml", true, CultureInfo.InvariantCulture) == 0)
                    {
                        // try to localized the the baml
                        // find the resource dictionary
                        BamlLocalizationDictionary dictionary = dictionaries[resourceName];

                        // if it is null, just create an empty dictionary.
                        if (dictionary != null)
                        {
                            // it is a baml stream
                            using (Stream output = File.OpenWrite(fullFileName))
                            {
                                options.Write("    ");
                                options.WriteLine(StringLoader.Get("GenerateStandaloneBaml", fullFileName));
                                GenerateBamlStream(resourceStream, output, dictionary, options);
                                options.WriteLine(StringLoader.Get("Done"));
                            }
                        }
                        else
                        {
                            // can't find localization of it, just copy it
                            GenerateStandaloneResource(fullFileName, resourceStream);
                        }
                    }
                    else
                    {
                        // it is an untyped resource stream, just copy it
                        GenerateStandaloneResource(fullFileName, resourceStream);
                    }

                    // now add this resource file into the assembly
                    targetAssemblyBuilder.AddResourceFile(
                        targetResourceName,           // resource name
                        targetResourceName,           // file name
                        ResourceAttributes.Public     // visibility of the resource to other assembly
                        );
                }
            }

            // at the end, generate the assembly
            targetAssemblyBuilder.Save(outputAssemblyLocalName);
            options.WriteLine(StringLoader.Get("DoneGeneratingAssembly"));
        }
Exemplo n.º 13
0
 public static Stream RequireManifestResourceStream(Assembly mainAssembly, string resourceName, out ManifestResourceInfo info, CultureInfo culture = default)
 {
     GetManifestResourceStream(mainAssembly: mainAssembly, culture: culture, resourceName: resourceName, throwIfMissing: true, info: out info, stream: out var stream);
     return(stream);
 }
Exemplo n.º 14
0
        private void ProcessEmbeddedResource(
            IResourceBuildHelper helper,
            string source,
            out string preProcessed,
            out string compacted,
            List <ParseException> errors)
        {
            preProcessed = source.Replace(" ", "");
            string[] parts = preProcessed.Split(TypeDelims, 2, StringSplitOptions.RemoveEmptyEntries);

            if (parts.Length < 2 ||
                String.IsNullOrEmpty(parts[0]) ||
                String.IsNullOrEmpty(parts[1]))
            {
                compacted = preProcessed = null;
                return;
            }

            parts[0] = MergeResourceCodeProvider.ScrubResourceName(parts[0]);

            // load resources from Assembly
            Assembly assembly = Assembly.Load(parts[1]);

            helper.AddAssemblyDependency(assembly);

            ManifestResourceInfo info = assembly.GetManifestResourceInfo(parts[0]);

            if (info == null)
            {
                compacted = preProcessed = null;
                return;
            }

            using (Stream stream = assembly.GetManifestResourceStream(parts[0]))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    preProcessed = reader.ReadToEnd();
                    compacted    = null;
                }
            }

            string       ext      = Path.GetExtension(parts[0]).Trim('.');
            CompilerType compiler = helper.GetDefaultCompilerTypeForLanguage(ext);

            if (!typeof(ResourceCodeProvider).IsAssignableFrom(compiler.CodeDomProviderType))
            {
                // don't know how to process any further
                compacted = preProcessed;
                return;
            }

            ResourceCodeProvider provider = (ResourceCodeProvider)Activator.CreateInstance(compiler.CodeDomProviderType);

            try
            {
                // concatenate the preprocessed source for current merge phase
                provider.ProcessResource(
                    helper,
                    parts[0],
                    preProcessed,
                    out preProcessed,
                    out compacted,
                    errors);
            }
            catch (ParseException ex)
            {
                errors.Add(ex);
            }
            catch (Exception ex)
            {
                errors.Add(new ParseError(ex.Message, parts[0], 0, 0, ex));
            }

            if (!this.isMimeSet &&
                !String.IsNullOrEmpty(provider.ContentType) &&
                !String.IsNullOrEmpty(provider.FileExtension))
            {
                this.contentType   = provider.ContentType;
                this.fileExtension = provider.FileExtension;
                this.isMimeSet     = true;
            }
        }
        public Server(int port)
        {
            httpServer                  = new HttpServer();
            httpServer.EndPoint         = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
            httpServer.RequestReceived += (s, e) =>
            {
                string name = "ManagementServer" + e.Request.Path.Replace('/', '.');
                ManifestResourceInfo resourceInfo = Assembly.GetExecutingAssembly().GetManifestResourceInfo(name);
                if (resourceInfo != null)
                {
                    e.Response.ContentType = MimeTypes.GetMimeType(new FileInfo(name));
                    using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
                    {
                        resourceStream.CopyTo(e.Response.OutputStream);
                    }
                    return;
                }

                using (var writer = new StreamWriter(e.Response.OutputStream))
                {
                    if (e.Request.Path == "/")
                    {
                        e.Response.Redirect("/index.html");
                    }
                    else if (e.Request.Path == "/localization.js")
                    {
                        name         = "ManagementServer.Scripts.lang-" + CultureInfo.CurrentCulture.ThreeLetterISOLanguageName + ".js";
                        resourceInfo = Assembly.GetExecutingAssembly().GetManifestResourceInfo(name);
                        if (resourceInfo != null)
                        {
                            e.Response.ContentType = MimeTypes.GetMimeType(new FileInfo(name));
                            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
                            {
                                resourceStream.CopyTo(e.Response.OutputStream);
                            }
                            return;
                        }
                        else
                        {
                            name = "ManagementServer.Scripts.lang-neutral.js";
                            e.Response.ContentType = MimeTypes.GetMimeType(new FileInfo(name));
                            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
                            {
                                resourceStream.CopyTo(e.Response.OutputStream);
                            }
                            return;
                        }
                    }
                    else if (e.Request.Path == "/tree")
                    {
                        e.Response.ContentType = "application/json";
                        Node.SerializeTree(writer);
                    }
                    else if (e.Request.Path == "/mbean")
                    {
                        string id  = e.Request.Params["id"];
                        IMBean obj = Node.GetObject(id);
                        if (obj == null)
                        {
                            e.Response.StatusCode        = 404;
                            e.Response.StatusDescription = "Object not found on this server";
                        }
                        else
                        {
                            e.Response.ContentType = "application/json";
                            obj.Serialize(id, writer);
                        }
                    }
                    else if (e.Request.Path == "/set-prop")
                    {
                        try
                        {
                            string id       = e.Request.Params["id"];
                            string propName = e.Request.Params["propName"];
                            string value    = e.Request.Params["val"];

                            IMBean obj = Node.GetObject(id);
                            obj.SetProperty(propName, value);

                            e.Response.ContentType = "application/json";
                            writer.WriteLine("{ \"result\": " + JsonConvert.ToString("ok")
                                             + ", \"message\": " + JsonConvert.ToString(ManagementServer.strings.PROP_SET_SUCCESSFULLY) + "}");
                        }
                        catch (Exception ex)
                        {
                            e.Response.ContentType = "application/json";
                            writer.WriteLine("{ \"result\": " + JsonConvert.ToString("error")
                                             + ", \"message\": " + JsonConvert.ToString(ex.Message) + "}");
                        }
                    }
                    else if (e.Request.Path == "/invoke")
                    {
                        try
                        {
                            string id              = e.Request.Params["object-id"];
                            string methodName      = e.Request.Params["method-name"];
                            string methodSignature = e.Request.Params["method-signature"];

                            IMBean     obj        = Node.GetObject(id);
                            MethodInfo methodInfo = obj.FindMethod(methodName, methodSignature);
                            if (methodInfo == null)
                            {
                                throw new ArgumentException(ManagementServer.strings.ERR_METHOD_NOT_FOUND);
                            }
                            object val = obj.InvokeMethod(methodInfo, e.Request.Params);

                            e.Response.ContentType = "application/json";
                            if (methodInfo.ReturnType == typeof(void))
                            {
                                writer.WriteLine("{ \"result\": " + JsonConvert.ToString("ok")
                                                 + ", \"message\": " + JsonConvert.ToString(ManagementServer.strings.VOID_INVOKED_SUCCESSFULLY)
                                                 + "}");
                            }
                            else
                            {
                                writer.WriteLine("{ \"result\": " + JsonConvert.ToString("ok")
                                                 + ", \"message\": " + JsonConvert.ToString(
                                                     string.Format(ManagementServer.strings.METHOD_INVOKED_SUCCESSFULLY, (val == null ? "null" : val.ToString()))
                                                     ) + "}");
                            }
                        }
                        catch (Exception ex)
                        {
                            e.Response.ContentType = "application/json";
                            writer.WriteLine("{ \"result\": " + JsonConvert.ToString("error")
                                             + ", \"message\": " + JsonConvert.ToString(ex.Message) + "}");
                        }
                    }
                    else
                    {
                        e.Response.StatusCode        = 404;
                        e.Response.StatusDescription = "File not found on this server";
                    }
                }
            };
        }
Exemplo n.º 16
0
        public UcShortCut(IHsLabelValue item, string icon)
        {
            this.Orientation = StackOrientation.Vertical;

            AbsoluteLayout layout = new AbsoluteLayout()
            {
                HorizontalOptions = LayoutOptions.Center,
                VerticalOptions   = LayoutOptions.FillAndExpand,
            };

            Image image = new Image()
            {
                WidthRequest  = 60,
                HeightRequest = 80,
                Aspect        = Aspect.AspectFit
            }; //.AspectFit };

            string iconResName = $"Hungsum.Framework.Assets.Imgs.{(icon == null ? "icon_1" : icon)}.png";

            Assembly             assembly = typeof(Assets.HsImage).GetTypeInfo().Assembly;
            ManifestResourceInfo mri      = assembly.GetManifestResourceInfo(iconResName);

            if (mri == null)
            {
                iconResName = $"Hungsum.Framework.Assets.Imgs.icon_1.png";
            }

            image.Source = ImageSource.FromResource(iconResName, typeof(Assets.HsImage));
            image.Aspect = Aspect.AspectFit;


            AbsoluteLayout.SetLayoutBounds(image, new Rectangle(0, 0, 1, 1));
            AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.All);

            Button button = new Button(); //{ BackgroundColor = Color.Purple, Opacity = 0.5 };

            AbsoluteLayout.SetLayoutBounds(button, new Rectangle(0, 0, 1, 1));
            AbsoluteLayout.SetLayoutFlags(button, AbsoluteLayoutFlags.All);

            button.Clicked += new EventHandler((sender, e) =>
            {
                this.Click?.Invoke(this, new HsEventArgs <IHsLabelValue>()
                {
                    Data = item
                });
            });

            layout.Children.Add(image);
            layout.Children.Add(button);

            Label label = new Label()
            {
                FontSize          = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
                Text              = item.Label,
                LineBreakMode     = LineBreakMode.NoWrap,
                HorizontalOptions = LayoutOptions.Center
            };


            this.Children.Add(layout);
            this.Children.Add(label);
        }
Exemplo n.º 17
0
        private static bool Install(bool check_refs, string name, string package,
                                    string gacdir, string link_gacdir, string libdir, string link_libdir)
        {
            string    failure_msg = "Failure adding assembly {0} to the cache: ";
            ArrayList resources;

            if (!File.Exists(name))
            {
                WriteLine(string.Format(failure_msg, name) + "The system cannot find the file specified.");
                return(false);
            }

            Assembly     assembly = null;
            AssemblyName an       = null;

            try {
                assembly = ReflectionOnlyLoadFrom(name);
            } catch {
                WriteLine(string.Format(failure_msg, name) + "The file specified is not a valid assembly.");
                return(false);
            }

            an = assembly.GetName();

            switch (VerifyStrongName(an, name))
            {
            case VerificationResult.StrongNamed:
            case VerificationResult.Skipped:
                break;

            case VerificationResult.WeakNamed:
                WriteLine(string.Format(failure_msg, name) + "Attempt to install an assembly without a strong name"
                          + (in_bootstrap ? "(continuing anyway)" : string.Empty));
                if (!in_bootstrap)
                {
                    return(false);
                }
                break;

            case VerificationResult.DelaySigned:
                WriteLine(string.Format(failure_msg, name) + "Strong name cannot be verified for delay-signed assembly"
                          + (in_bootstrap ? "(continuing anyway)" : string.Empty));
                if (!in_bootstrap)
                {
                    return(false);
                }
                break;
            }

            resources = new ArrayList();
            foreach (string res_name in assembly.GetManifestResourceNames())
            {
                ManifestResourceInfo res_info = assembly.GetManifestResourceInfo(res_name);

                if ((res_info.ResourceLocation & ResourceLocation.Embedded) == 0)
                {
                    if (!File.Exists(res_info.FileName))
                    {
                        WriteLine(string.Format(failure_msg, name) + "The system cannot find resource " + res_info.FileName);
                        return(false);
                    }

                    resources.Add(res_info);
                }
            }

            if (check_refs && !CheckReferencedAssemblies(an))
            {
                WriteLine(string.Format(failure_msg, name) +
                          "Attempt to install an assembly that " +
                          "references non strong named assemblies " +
                          "with -check_refs enabled.");
                return(false);
            }

            string [] siblings      = { ".config", ".mdb" };
            string    version_token = an.Version + "_" +
                                      an.CultureInfo.Name.ToLower(CultureInfo.InvariantCulture) + "_" +
                                      GetStringToken(an.GetPublicKeyToken());
            string full_path = Path.Combine(Path.Combine(gacdir, an.Name), version_token);
            string asmb_file = Path.GetFileName(name);
            string asmb_path = Path.Combine(full_path, asmb_file);
            string asmb_name = assembly.GetName().Name;

            if (Path.GetFileNameWithoutExtension(asmb_file) != asmb_name)
            {
                WriteLine(string.Format(failure_msg, name) +
                          string.Format("the filename \"{0}\" doesn't match the assembly name \"{1}\"",
                                        asmb_file, asmb_name));
                return(false);
            }

            try {
                if (Directory.Exists(full_path))
                {
                    // Wipe out the directory. This way we ensure old assemblies
                    // config files, and AOTd files are removed.
                    Directory.Delete(full_path, true);
                }
                Directory.CreateDirectory(full_path);
            } catch {
                WriteLine(string.Format(failure_msg, name) +
                          "gac directories could not be created, " +
                          "possibly permission issues.");
                return(false);
            }

            Copy(name, asmb_path, true);

            var name_pdb = Path.ChangeExtension(name, ".pdb");

            if (File.Exists(name_pdb))
            {
                Copy(name_pdb, Path.ChangeExtension(asmb_path, ".pdb"), true);
            }

            foreach (string ext in siblings)
            {
                string sibling = String.Concat(name, ext);
                if (File.Exists(sibling))
                {
                    Copy(sibling, String.Concat(asmb_path, ext), true);
                }
            }

            foreach (ManifestResourceInfo resource_info in resources)
            {
                try {
                    Copy(resource_info.FileName, Path.Combine(full_path, Path.GetFileName(resource_info.FileName)), true);
                } catch {
                    WriteLine("ERROR: Could not install resource file " + resource_info.FileName);
                    Environment.Exit(1);
                }
            }

            if (package != null)
            {
                string ref_dir  = Path.Combine(libdir, package);
                string ref_path = Path.Combine(ref_dir, asmb_file);

                if (File.Exists(ref_path))
                {
                    File.Delete(ref_path);
                }
                try {
                    Directory.CreateDirectory(ref_dir);
                } catch {
                    WriteLine("ERROR: Could not create package dir file.");
                    Environment.Exit(1);
                }
                if (Path.DirectorySeparatorChar == '/')
                {
                    string pkg_path_abs = Path.Combine(gacdir, Path.Combine(an.Name, Path.Combine(version_token, asmb_file)));
                    string pkg_path     = AbsoluteToRelativePath(ref_dir, pkg_path_abs);
                    symlink(pkg_path, ref_path);

                    var pdb_pkg_path = Path.ChangeExtension(pkg_path, ".pdb");
                    var pdb_ref_path = Path.ChangeExtension(ref_path, ".pdb");

                    if (File.Exists(pdb_pkg_path))
                    {
                        symlink(pdb_pkg_path, pdb_ref_path);
                    }
                    else
                    {
                        try {
                            File.Delete(pdb_ref_path);
                        } catch {
                            // Ignore error, just delete files that should not be there.
                        }
                    }

                    foreach (string ext in siblings)
                    {
                        string sibling = String.Concat(pkg_path, ext);
                        string sref    = String.Concat(ref_path, ext);

                        if (File.Exists(sibling))
                        {
                            symlink(sibling, sref);
                        }
                        else
                        {
                            try {
                                File.Delete(sref);
                            } catch {
                                // Ignore error, just delete files that should not be there.
                            }
                        }
                    }
                    WriteLine("Package exported to: {0} -> {1}", ref_path, pkg_path);
                }
                else
                {
                    // string link_path = Path.Combine (Path.Combine (link_gacdir, an.Name), version_token);
                    //
                    // We can't use 'link_path' here, since it need not be a valid path at the time 'gacutil'
                    // is run, esp. when invoked in a DESTDIR install.
                    Copy(name, ref_path, true);
                    WriteLine("Package exported to: " + ref_path);
                }
            }

            WriteLine("Installed {0} into the gac ({1})", name,
                      gacdir);

            return(true);
        }
Exemplo n.º 18
0
        public void bug78468()
        {
            string assemblyFileNameA = Path.Combine(Path.GetTempPath(),
                                                    "bug78468a.dll");
            string resourceFileName = Path.Combine(Path.GetTempPath(),
                                                   "readme.txt");

            using (StreamWriter sw = File.CreateText(resourceFileName)) {
                sw.WriteLine("FOO");
                sw.Close();
            }

            try {
                AssemblyName assemblyName = new AssemblyName();
                assemblyName.Name = "bug78468a";

                AssemblyBuilder ab = AppDomain.CurrentDomain
                                     .DefineDynamicAssembly(assemblyName,
                                                            AssemblyBuilderAccess.Save,
                                                            Path.GetTempPath(),
                                                            AppDomain.CurrentDomain.Evidence);
                ab.AddResourceFile("read", "readme.txt");
                ab.Save(Path.GetFileName(assemblyFileNameA));

                Assembly assembly;

                using (FileStream fs = File.OpenRead(assemblyFileNameA)) {
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    assembly = Assembly.Load(buffer);
                    fs.Close();
                }

                Assert.AreEqual(string.Empty, assembly.Location, "#A1");
                string[] resNames = assembly.GetManifestResourceNames();
                Assert.IsNotNull(resNames, "#A2");
                Assert.AreEqual(1, resNames.Length, "#A3");
                Assert.AreEqual("read", resNames[0], "#A4");
                ManifestResourceInfo resInfo = assembly.GetManifestResourceInfo("read");
                Assert.IsNotNull(resInfo, "#A5");
                Assert.AreEqual("readme.txt", resInfo.FileName, "#A6");
                Assert.IsNull(resInfo.ReferencedAssembly, "#A7");
                Assert.AreEqual((ResourceLocation)0, resInfo.ResourceLocation, "#A8");
                try {
                    assembly.GetManifestResourceStream("read");
                    Assert.Fail("#A9");
                } catch (FileNotFoundException) {
                }
                try {
                    assembly.GetFile("readme.txt");
                    Assert.Fail("#A10");
                } catch (FileNotFoundException) {
                }

                string assemblyFileNameB = Path.Combine(Path.GetTempPath(),
                                                        "bug78468b.dll");

                AppDomain         testDomain        = CreateTestDomain(AppDomain.CurrentDomain.BaseDirectory, false);
                CrossDomainTester crossDomainTester = CreateCrossDomainTester(testDomain);
                try {
                    crossDomainTester.bug78468(assemblyFileNameB);
                } finally {
                    AppDomain.Unload(testDomain);
                    File.Delete(assemblyFileNameB);
                }
            } finally {
                File.Delete(assemblyFileNameA);
                File.Delete(resourceFileName);
            }
        }
Exemplo n.º 19
0
 // print out manifest resource
 void PrintManifestResource(ManifestResourceInfo msi)
 {
     //.mresource [public | private] <dottedname>  [( <QSTRING> )] { <manResDecl>* }
     //!! Is there customAttribute on Resource?? Is there public private resource?
     if (msi.FileName != null)
     {
         sw.WriteLine("{ .file " + msi.FileName + "}");
     }
     else if (msi.ReferencedAssembly != null)
     {
         if (!msi.ReferencedAssembly.Equals(CurrentAssembly))
             sw.WriteLine("{.assmebly extern " + msi.ReferencedAssembly.GetName().Name + "}");
     }
 }
Exemplo n.º 20
0
        /// ////////////////////////////////////////////////////////////////
        public static Image GetImage(Type tp)
        {
            if (tp == null)
            {
                return(null);
            }
            Image img = null;

            if (m_cacheImages.TryGetValue(tp, out img))
            {
                return(img);
            }
            object[] attribs = tp.GetCustomAttributes(typeof(DynamicIconAttribute), true);
            if (attribs != null && attribs.Length > 0)
            {
                DynamicIconAttribute att = attribs[0] as DynamicIconAttribute;
                if (att != null)
                {
                    img = att.GetImage();
                    if (img != null)
                    {
                        m_cacheImages[tp] = img;
                    }
                    return(img);
                }
            }
            string[]        strNoms      = tp.ToString().Split('.');
            string          strNomImage  = "." + strNoms[strNoms.Length - 1].ToUpper() + ".";
            string          strNomClasse = strNoms[strNoms.Length - 1];
            ResourceManager rm           = new ResourceManager("MyResource", tp.Assembly);

            try
            {
                //Cherche l'image du nom de la classe
                foreach (string strResource in tp.Assembly.GetManifestResourceNames())
                {
                    System.Console.WriteLine(strResource);
                    ManifestResourceInfo info = tp.Assembly.GetManifestResourceInfo(strResource);
                    bool bPrendre             = strResource == strNomImage;
                    if (!bPrendre)
                    {
                        int nIndex = strResource.ToUpper().IndexOf(strNomImage);
                        if (nIndex >= 0)
                        {
                            string strSuite = strResource.Substring(nIndex + strNomImage.Length).ToUpper();
                            if ("JPG PNG BMP GIF".Contains(strSuite))
                            {
                                bPrendre = true;
                            }
                        }
                    }
                    if (bPrendre)
                    {
                        try
                        {
                            img = new Bitmap(tp.Assembly.GetManifestResourceStream(strResource));
                            if (img != null)
                            {
                                m_cacheImages[tp] = img;
                                return(img);
                            }
                        }
                        catch { }
                    }
                }
            }
            catch { }
            m_cacheImages[tp] = null;
            return(img);
        }
Exemplo n.º 21
0
        public bool Synchronize(string pathToPopulate, out string error)
        {
            error = string.Empty;

            try
            {
                if (!Directory.Exists(pathToPopulate))
                {
                    error = "The destination path could not be found or created." + Environment.NewLine + pathToPopulate;;
                    Directory.CreateDirectory(pathToPopulate);
                }

                AssemblyName asmNameTmp = this.ASM.GetName();
                string       asmName    = asmNameTmp.Name;

                string[] resources = this.ASM.GetManifestResourceNames();
                foreach (string res in resources)
                {
                    ManifestResourceInfo mri = this.ASM.GetManifestResourceInfo(res);

                    string resPath = res.Replace(asmName, string.Empty);
                    resPath = resPath.TrimStart('.');
                    resPath = resPath.Replace('.', Path.DirectorySeparatorChar);

                    //If it looks like we had a file extension, repair that...
                    int lastSlash = resPath.LastIndexOf(Path.DirectorySeparatorChar);
                    if (lastSlash + 5 >= resPath.Length)
                    {
                        resPath = resPath.Insert(lastSlash, ".");
                        resPath = resPath.Remove(lastSlash + 1, 1);

                        //Get the new "last slash" so that we can find what the destination should be
                        lastSlash = resPath.LastIndexOf(Path.DirectorySeparatorChar);
                    }

                    string filename   = resPath.Substring(lastSlash + 1);
                    string subDirPath = pathToPopulate;
                    if (lastSlash >= 0)
                    {
                        string directory = resPath.Substring(0, lastSlash);
                        subDirPath = Path.Combine(pathToPopulate, directory);
                        if (!Directory.Exists(subDirPath))
                        {
                            error = "A subdirectory of the destination could not be found or created." + Environment.NewLine + subDirPath;
                            Directory.CreateDirectory(subDirPath);
                        }
                    }

                    string filePath = Path.Combine(subDirPath, filename);
                    this.File.Copy(resPath, filePath, true);

                    if (filePath.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
                    {
                        //we will have to unzip it... in place...
                        string[] files;
                        string   errorstr;
                        ZipUtils.TryUnzipAndUncompressFiles(filePath,
                                                            Path.GetDirectoryName(filePath), out files, out errorstr);
                    }
                }

                return(true);
            }
            catch {}

            return(false);
        }
Exemplo n.º 22
0
 private EmbeddedResource(ManifestResourceInfo info)
 {
     Info = info;
 }
Exemplo n.º 23
0
        /// <summary>
        /// A helper function for creating a node description object for the specified model.
        /// </summary>
        /// <param name="model">The model</param>
        /// <returns>The description</returns>
        public TreeViewNode GetNodeDescription(IModel model)
        {
            TreeViewNode description = new TreeViewNode();

            description.Name = model.Name;

            // We need to find an icon for this model. If the model is a ModelCollectionFromResource, we attempt to find
            // an image with the same name as the model.
            // Otherwise, we attempt to find an icon with the same name as the model's type.
            // e.g. A Graph called Biomass should use an icon called Graph.png
            // e.g. A Plant called Wheat should use an icon called Wheat.png

            if (model is ModelCollectionFromResource)
            {
                description.ResourceNameForImage = "ApsimNG.Resources.TreeViewImages." + model.Name + ".png";
            }
            else
            {
                string modelNamespace = model.GetType().FullName.Split('.')[1] + ".";
                description.ResourceNameForImage = "ApsimNG.Resources.TreeViewImages." + modelNamespace + model.GetType().Name + ".png";

                if (!MainView.MasterView.HasResource(description.ResourceNameForImage))
                {
                    description.ResourceNameForImage = "ApsimNG.Resources.TreeViewImages." + model.GetType().Name + ".png";
                }
            }


            //Check to see if you can find the image in the resource for this project.
            ManifestResourceInfo info = Assembly.GetExecutingAssembly().GetManifestResourceInfo(description.ResourceNameForImage);

            if (info == null)
            {
                // Try the opposite.
                if (model is ModelCollectionFromResource)
                {
                    description.ResourceNameForImage = "ApsimNG.Resources.TreeViewImages." + model.GetType().Name + ".png";
                }
                else
                {
                    description.ResourceNameForImage = "ApsimNG.Resources.TreeViewImages." + model.Name + ".png";
                }
            }

            description.ToolTip = model.GetType().Name;

            description.Children = new List <TreeViewNode>();
            foreach (Model child in model.Children)
            {
                if (!child.IsHidden)
                {
                    description.Children.Add(this.GetNodeDescription(child));
                }
            }
            description.Strikethrough = !model.Enabled;
            description.Checked       = model.IncludeInDocumentation && showDocumentationStatus;
            description.Colour        = System.Drawing.Color.Empty;

            /*
             * // Set the colour here
             * System.Drawing.Color colour = model.Enabled ? System.Drawing.Color.Black : System.Drawing.Color.Red;
             * description.Colour = colour;
             */
            return(description);
        }
Exemplo n.º 24
0
 public AManifestResource(ManifestResourceInfo mri, Assembly asm, string name)
 {
     _mri  = mri;
     _name = name;
     _asm  = asm;
 }
Exemplo n.º 25
0
 internal Stream GetManifestResourceStream(string resourceName)
 {
     for (int i = 0; i < ManifestResource.records.Length; i++)
     {
         if (resourceName == GetString(ManifestResource.records[i].Name))
         {
             if (ManifestResource.records[i].Implementation != 0x26000000)
             {
                 ManifestResourceInfo info = new ManifestResourceInfo(this, i);
                 switch (ManifestResource.records[i].Implementation >> 24)
                 {
                     case FileTable.Index:
                         string fileName = Path.Combine(Path.GetDirectoryName(location), info.FileName);
                         if (System.IO.File.Exists(fileName))
                         {
                             // note that, like System.Reflection, we return null for zero length files and
                             // ManifestResource.Offset is ignored
                             FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete);
                             if (fs.Length == 0)
                             {
                                 fs.Close();
                                 return null;
                             }
                             return fs;
                         }
                         return null;
                     case AssemblyRefTable.Index:
                         Assembly asm = info.ReferencedAssembly;
                         if (asm.__IsMissing)
                         {
                             return null;
                         }
                         return asm.GetManifestResourceStream(resourceName);
                     default:
                         throw new BadImageFormatException();
                 }
             }
             SeekRVA((int)cliHeader.Resources.VirtualAddress + ManifestResource.records[i].Offset);
             BinaryReader br = new BinaryReader(stream);
             int length = br.ReadInt32();
             return new MemoryStream(br.ReadBytes(length));
         }
     }
     return null;
 }
        /// <summary>[埋め込まれたリソースXMLファイル]から文字列を読み込む。</summary>
        /// <param name="assemblyString">
        /// アセンブリ名("既定の名前空間"とは異なる)
        /// </param>
        /// <param name="loadfileName">[埋め込まれたリソースXMLファイル]の名前(名前空間付き)</param>
        /// <returns>[埋め込まれたリソースXMLファイル]から読み込んだ文字列</returns>
        /// <remarks>自由に利用できる。</remarks>
        public static string LoadXMLAsString(string assemblyString, string loadfileName)
        {
            // エントリのアセンブリ
            Assembly             thisAssembly         = null;
            ManifestResourceInfo manifestResourceInfo = null;

            // ストリーム
            StreamReader sr = null;
            // リーダ(XML)
            XmlTextReader xtr = null;

            // 例外処理
            try
            {
                thisAssembly         = MyAssemblies.GetAssembly(assemblyString);
                manifestResourceInfo = thisAssembly.GetManifestResourceInfo(loadfileName);
            }
            catch (Exception)
            {
                // なにもしない。
            }

            try
            {
                // 存在チェック
                if (manifestResourceInfo != null)
                {
                    if (0 != (manifestResourceInfo.ResourceLocation
                              & (ResourceLocation.ContainedInManifestFile | ResourceLocation.Embedded)))
                    {
                        // 存在する。
                    }
                    else
                    {
                        // 存在しない。
                        throw new ArgumentException(String.Format(
                                                        PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName));
                    }
                }
                else
                {
                    // 存在しない。
                    throw new ArgumentException(String.Format(
                                                    PublicExceptionMessage.RESOURCE_FILE_NOT_FOUND, loadfileName));
                }

                // 既定のエンコーディングでロードして、
                sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName));

                // XML宣言を取得して、
                // <?xml version="1.0" encoding="xxxx" ?>
                string xmlDeclaration = sr.ReadLine();
                sr.Close();

                // エンコーディング オブジェクトの取得
                Encoding enc = XmlLib.GetEncodingFromXmlDeclaration(xmlDeclaration);

                // 指定のエンコーディングで再ロード
                sr = new StreamReader(thisAssembly.GetManifestResourceStream(loadfileName), enc);

                // 読む
                return(sr.ReadToEnd());
            }
            finally
            {
                // nullチェック
                if (xtr == null)
                {
                    // 何もしない。
                }
                else
                {
                    // 閉じる
                    xtr.Close();
                }

                // nullチェック
                if (sr == null)
                {
                    // 何もしない。
                }
                else
                {
                    // 閉じる
                    sr.Close();
                }
            }
        }