Exemple #1
0
        public void ResourcesNamespaceProviderKeywords()
        {
            // not validated against provider keywords in .net framework
            string output, expected;

            string []          unmatchables;
            CodeCompileUnit    ccu;
            CodeMemberProperty resourceManager;
            CodeVariableDeclarationStatement cvds;

            foreach (string input in keywords)
            {
                ccu = StronglyTypedResourceBuilder.Create(testResources,
                                                          "TestClass",
                                                          "TestNamespace",
                                                          input,
                                                          provider,
                                                          true,
                                                          out unmatchables);

                expected        = input + ".TestClass";
                resourceManager = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> (
                    "ResourceManager", ccu);
                cvds   = ((CodeVariableDeclarationStatement)((CodeConditionStatement)resourceManager.GetStatements [0]).TrueStatements [0]);
                output = ((CodePrimitiveExpression)((CodeObjectCreateExpression)cvds.InitExpression).Parameters [0]).Value.ToString();

                Assert.AreEqual(expected, output);
            }
        }
Exemple #2
0
        public void ResourcesNamespaceNull()
        {
            // when ResourcesNamespace is null generatedCodeNamespace is used in its place
            string[]           unmatchables;
            string             input, output, expected;
            CodeCompileUnit    ccu;
            CodeMemberProperty resourceManager;
            CodeVariableDeclarationStatement cvds;

            input = null;

            expected = "TestNameSpace.TestClass";

            ccu = StronglyTypedResourceBuilder.Create(testResources,
                                                      "TestClass",
                                                      "TestNameSpace",
                                                      input,
                                                      provider,
                                                      true,
                                                      out unmatchables);

            resourceManager = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> (
                "ResourceManager", ccu);
            cvds   = ((CodeVariableDeclarationStatement)((CodeConditionStatement)resourceManager.GetStatements [0]).TrueStatements [0]);
            output = ((CodePrimitiveExpression)((CodeObjectCreateExpression)cvds.InitExpression).Parameters [0]).Value.ToString();

            Assert.AreEqual(expected, output);
        }
Exemple #3
0
        public void ResourcesNamespaceSpecialChars()
        {
            // ResourcesNamespace doesnt seem to be validated at all in .NET framework
            string []          unmatchables;
            string             input, output, expected;
            CodeCompileUnit    ccu;
            CodeMemberProperty resourceManager;
            CodeVariableDeclarationStatement cvds;

            foreach (char c in specialChars)
            {
                input = "test" + c.ToString();

                expected = input + ".TestClass";

                ccu = StronglyTypedResourceBuilder.Create(testResources,
                                                          "TestClass",
                                                          "TestNameSpace",
                                                          input,
                                                          provider,
                                                          true,
                                                          out unmatchables);

                resourceManager = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> (
                    "ResourceManager", ccu);
                cvds   = ((CodeVariableDeclarationStatement)((CodeConditionStatement)resourceManager.GetStatements [0]).TrueStatements [0]);
                output = ((CodePrimitiveExpression)((CodeObjectCreateExpression)cvds.InitExpression).Parameters [0]).Value.ToString();

                Assert.AreEqual(expected, output);
            }
        }
Exemple #4
0
        private static void WriteDesigner(this ProjectItem projectItem, CremaDataTable dataTable, bool isPublic)
        {
            var project          = projectItem.ContainingProject;
            var projectPath      = Path.GetDirectoryName(project.GetFullName());
            var designerFileName = Path.Combine(projectPath, projectItem.GetCustomToolOutput());
            var resxFileName     = projectItem.GetFullPath();
            var ss            = StringUtility.SplitPath(Path.GetDirectoryName(projectItem.GetLocalPath()));
            var codeNamespace = $"{project.GetRootNamespace()}.{string.Join(".", ss)}";
            var baseName      = Path.GetFileNameWithoutExtension(projectItem.GetLocalPath());

            using (var sw = new StreamWriter(designerFileName))
            {
                var errors   = null as string[];
                var provider = new CSharpCodeProvider();
                var code     = StronglyTypedResourceBuilder.Create(resxFileName, baseName, codeNamespace, provider, isPublic == false, out errors);
                if (errors.Length > 0)
                {
                    foreach (var error in errors)
                    {
                        Console.WriteLine(error);
                    }
                    return;
                }

                provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
                Console.WriteLine(designerFileName);
            }
        }
Exemple #5
0
        private void GenerateResourceCodeBehind(string basePath, string resourceFileName, string targetFileName)
        {
            using (CurrentDirectorySetter.SetCurrentDirectory(basePath))
                using (var codeProvider = new CSharpCodeProvider())
                {
                    string[] unmatchedElements;
                    var      code = StronglyTypedResourceBuilder.Create(
                        resourceFileName,
                        Path.GetFileNameWithoutExtension(resourceFileName),
                        _configuration.ReplacementsDictionary["$safeprojectname$"],
                        codeProvider,
                        true,
                        out unmatchedElements
                        );

                    using (var writer = new StreamWriter(targetFileName, false, Encoding.UTF8))
                    {
                        codeProvider.GenerateCodeFromCompileUnit(
                            code,
                            writer,
                            new CodeGeneratorOptions()
                            );
                    }
                }
        }
Exemple #6
0
        /// <summary>
        /// Generates a C# designer class.
        /// </summary>
        /// <param name="resXFile">The source resx file.</param>
        /// <param name="className">The base class name.</param>
        /// <param name="namespaceName">The namespace for the generated code.</param>
        /// <param name="publicClass">Specifies if the class has public or public access level.</param>
        /// <returns>false if generation of at least one property failed.</returns>
        public static bool GenerateDesignerFile(string resXFile, string className, string namespaceName, bool publicClass)
        {
            if (!File.Exists(resXFile))
            {
                ThrowExceptions.Custom(Exc.GetStackTrace(), type, Exc.CallingMethod(), $"The file '{resXFile}' could not be found");
            }
            if (string.IsNullOrEmpty(className))
            {
                ThrowExceptions.Custom(Exc.GetStackTrace(), type, Exc.CallingMethod(), $"The class name must not be empty or null");
            }
            if (string.IsNullOrEmpty(namespaceName))
            {
                ThrowExceptions.Custom(Exc.GetStackTrace(), type, Exc.CallingMethod(), $"The namespace name must not be empty or null");
            }
            string[] unmatchedElements;
            //System.Resources.Tools.
            var codeProvider = new Microsoft.CSharp.CSharpCodeProvider();

            System.CodeDom.CodeCompileUnit code =
                StronglyTypedResourceBuilder.Create(
                    resXFile,
                    className,
                    namespaceName,
                    codeProvider,
                    publicClass,
                    out unmatchedElements);
            var designerFileName = Path.Combine(Path.GetDirectoryName(resXFile), $"{className}.Designer.cs");

            using (StreamWriter writer = new StreamWriter(designerFileName, false, System.Text.Encoding.UTF8))
            {
                codeProvider.GenerateCodeFromCompileUnit(code, writer, new System.CodeDom.Compiler.CodeGeneratorOptions());
            }
            return(unmatchedElements.Length == 0);
        }
Exemple #7
0
        public void Start()
        {
            CreateResXFile();

            var sw       = new StreamWriter(DesignerFileName);
            var provider = new CSharpCodeProvider();
            var code     = StronglyTypedResourceBuilder.Create(
                ResxFileName,      // resxFile
                BaseName,          // baseName
                NameSpace,         // generatedCodeNamespace
                ResourceNameSpace, // resourcesNamespace
                provider,          // codeProvider
                false,             // internalClass
                out string[] errors);

            if (errors.Length > 0)
            {
                foreach (var error in errors)
                {
                    Console.WriteLine(error);
                }
            }

            provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
            sw.Close();
        }
Exemple #8
0
        public void GeneratedCodeNamespaceProviderKeywordsMultipart()
        {
            // .NET framework does not check individiual elements of multipart namespace
            string expected, input;

            string []       unmatchables;
            CodeCompileUnit ccu;

            foreach (string word in keywords)
            {
                input = "Primary." + word;

                ccu = StronglyTypedResourceBuilder.Create(testResources,
                                                          "TestClass",
                                                          input,
                                                          "TestResourcesNameSpace",
                                                          provider,
                                                          true,
                                                          out unmatchables);

                expected = provider.CreateValidIdentifier(input);

                Assert.AreEqual(expected, ccu.Namespaces [0].Name);
            }
        }
Exemple #9
0
        public void TestFixtureSetup()
        {
            testResources = new Dictionary <string, object> ();

            Bitmap       bmp = new Bitmap(100, 100);
            MemoryStream wav = new MemoryStream(1000);
            // generate icon
            Bitmap icoBmp = new Bitmap(50, 50);
            Icon   ico    = Icon.FromHandle(icoBmp.GetHicon());

            DateTime dt = DateTime.Now;

            testResources.Add("astring", "myvalue");              // dont use key of "string" as its a keyword
            testResources.Add("bmp", bmp);
            testResources.Add("wav", wav);
            testResources.Add("ico", ico);
            testResources.Add("datetime", dt);

            sampleCcu = StronglyTypedResourceBuilder.Create(testResources,
                                                            "TestRes",
                                                            "TestNamespace",
                                                            "TestResourcesNamespace",
                                                            new CSharpCodeProvider(),
                                                            true,
                                                            out unmatchables);

            wav.Close();
        }
        public void VerifyResourceNameEmpty()
        {
            // should return _
            string output = StronglyTypedResourceBuilder.VerifyResourceName(string.Empty, provider);

            Assert.AreEqual("_", output);
        }
Exemple #11
0
        static void WriteDesigner(string outputPath, ProjectInfo projectInfo, ResxInfo resxInfo)
        {
            var resxFileName     = Path.Combine(outputPath, resxInfo.FileName);
            var designerFileName = Path.Combine(outputPath, resxInfo.ResgenFileName);
            var ss            = Ntreev.Library.StringUtility.SplitPath(Path.GetDirectoryName(resxInfo.FileName));
            var codeNamespace = $"{projectInfo.RootNamespace}.{string.Join(".", ss)}";
            var baseName      = Path.GetFileNameWithoutExtension(resxInfo.FileName);

            using (var sw = new StreamWriter(designerFileName))
            {
                var errors   = null as string[];
                var provider = new CSharpCodeProvider();
                var code     = StronglyTypedResourceBuilder.Create(resxFileName, baseName, codeNamespace, provider, resxInfo.IsPublic == false, out errors);
                if (errors.Length > 0)
                {
                    foreach (var error in errors)
                    {
                        Console.WriteLine(error);
                    }
                    return;
                }

                provider.GenerateCodeFromCompileUnit(code, sw, new CodeGeneratorOptions());
                Console.WriteLine(designerFileName);
            }
        }
Exemple #12
0
        public void GeneratedCodeNamespaceSpecialChars()
        {
            // invalid chars replaced with _ noting (. and :) are allowed by .NET framework
            string [] unmatchables;
            string    input, output, expected;

            CodeCompileUnit ccu;

            foreach (char c in specialChars)
            {
                input = "test" + c.ToString();

                if (c == '.' || c == ':')
                {
                    expected = input;
                }
                else
                {
                    expected = StronglyTypedResourceBuilder.VerifyResourceName(input, provider);
                }

                ccu = StronglyTypedResourceBuilder.Create(testResources,
                                                          "TestClass",
                                                          input,
                                                          "TestResourcesNameSpace",
                                                          provider,
                                                          true,
                                                          out unmatchables);

                output = ccu.Namespaces [0].Name;

                Assert.AreEqual(expected, output);
            }
        }
Exemple #13
0
        public void ResourceNamesDuplicate()
        {
            /*
             * DUPES CHECK HAPPENS AFTER VerifyResourceName called which changed eg.
             *   language keywords have _ appended to start
             *   string.emtpy converted to _
             *   various chars replaced
             */
            Dictionary <string, object> testResources = new Dictionary <string, object> ();

            string [] unmatchables;

            testResources.Add("for", "1");
            testResources.Add("_for", "2");
            testResources.Add("&", String.Empty);
            testResources.Add("_", String.Empty);
            testResources.Add("imok", "2");

            CodeCompileUnit ccu = StronglyTypedResourceBuilder.Create(testResources,
                                                                      "TestRes",
                                                                      "TestNamespace",
                                                                      "TestResourcesNameSpace",
                                                                      provider,
                                                                      true,
                                                                      out unmatchables);

            int matchedResources = testResources.Count - unmatchables.Length;
            int membersExpected  = matchedResources + 5;            // 5 standard members

            Assert.AreEqual(membersExpected, ccu.Namespaces [0].Types [0].Members.Count);
        }
        public static async Task GenerateFile(ResXGeneratorOptions options, ResXGeneratorResult result)
        {
            var inputFilePath        = options.InputFilePath;
            var targetsPcl2Framework = options.TargetPcl2Framework;
            var outputFilePath       = !string.IsNullOrEmpty(options.OutputFilePath) ? options.OutputFilePath
                : $"{Path.GetFileNameWithoutExtension(inputFilePath)}.Designer.cs";

            //no need to escape/cleanup, StronglyTypedResourceBuilder does that
            var className = !string.IsNullOrEmpty(options.ResultClassName) ? options.ResultClassName
                : Path.GetFileNameWithoutExtension(inputFilePath);

            var provider     = new CSharpCodeProvider();
            var resourceList = new Dictionary <object, object>();

            await Task.Run(() =>
            {
                if (className == null)
                {
                    result.Errors.Add(new CompilerError(inputFilePath, 0, 0, null,
                                                        "Class name cannot be null"));
                    return;
                }

                using (var r = new ResXResourceReader(inputFilePath))
                {
                    r.BasePath = Path.GetDirectoryName(inputFilePath);
                    foreach (DictionaryEntry e in r)
                    {
                        resourceList.Add(e.Key, e.Value);
                    }
                }

                string[] unmatchable;
                var ccu = StronglyTypedResourceBuilder.Create(resourceList, className, options.ResultNamespace, provider,
                                                              options.GenerateInternalClass, out unmatchable);

                if (targetsPcl2Framework)
                {
                    FixupPclTypeInfo(ccu, result);
                }


                foreach (var p in unmatchable)
                {
                    var msg = $"Could not generate property for resource ID '{p}'";
                    result.Errors.Add(new CompilerError(inputFilePath, 0, 0, null, msg));
                }

                // Avoid race if ResXFileCodeGenerator is called more than once for the same file
                using (var fw = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    using (var w = new StreamWriter(fw, Encoding.UTF8))
                        provider.GenerateCodeFromCompileUnit(ccu, w, new CodeGeneratorOptions());
                }
                result.GeneratedFilePath = outputFilePath;
            });
        }
        public void VerifyResourceNameProviderInvalidIdentifiers()
        {
            // function tests by means of provider.IsValidIdentifier after other checks
            string output;

            output = StronglyTypedResourceBuilder.VerifyResourceName("tes$t", provider);

            Assert.AreEqual(null, output);
        }
        public static Action GenerateFile(ProjectFile file, SingleFileCustomToolResult result, bool internalClass)
        {
            return(delegate {
                var dnp = file.Project as DotNetProject;
                if (dnp == null)
                {
                    var err = "ResXFileCodeGenerator can only be used with .NET projects";
                    result.Errors.Add(new CompilerError(null, 0, 0, null, err));
                    return;
                }

                var provider = dnp.LanguageBinding.GetCodeDomProvider();
                if (provider == null)
                {
                    var err = "ResXFileCodeGenerator can only be used with languages that support CodeDOM";
                    result.Errors.Add(new CompilerError(null, 0, 0, null, err));
                    return;
                }

                var outputfile = file.FilePath.ChangeExtension(".Designer." + provider.FileExtension);
                var ns = CustomToolService.GetFileNamespace(file, outputfile);
                var cn = provider.CreateValidIdentifier(file.FilePath.FileNameWithoutExtension);
                var rd = new Dictionary <object, object> ();

                using (var r = new ResXResourceReader(file.FilePath)) {
                    r.UseResXDataNodes = true;
                    r.BasePath = file.FilePath.ParentDirectory;

                    foreach (DictionaryEntry e in r)
                    {
                        rd.Add(e.Key, e.Value);
                    }
                }

                string[] unmatchable;
                var ccu = StronglyTypedResourceBuilder.Create(rd, cn, ns, provider, internalClass, out unmatchable);

                if (TargetsPcl2Framework(dnp))
                {
                    FixupPclTypeInfo(ccu);
                }

                foreach (var p in unmatchable)
                {
                    var msg = string.Format("Could not generate property for resource ID '{0}'", p);
                    result.Errors.Add(new CompilerError(file.FilePath, 0, 0, null, msg));
                }

                using (var w = new StreamWriter(outputfile, false, Encoding.UTF8))
                    provider.GenerateCodeFromCompileUnit(ccu, w, new CodeGeneratorOptions());

                result.GeneratedFilePath = outputfile;
            });
        }
        public void InternalClassFalse()
        {
            // check access modifiers for class, Culture, ResourceManager, string, stream and standard resource properties
            Dictionary <string, object> testResources = GetAllResourceTypes();

            string []          unmatchables;
            CodeCompileUnit    ccu;
            CodeMemberProperty cmp;

            bool isInternal = false;

            ccu = StronglyTypedResourceBuilder.Create(testResources,
                                                      "TestClass",
                                                      "TestNamespace",
                                                      "TestResourcesNameSpace",
                                                      provider,
                                                      isInternal,
                                                      out unmatchables);

            CodeTypeDeclaration resType = ccu.Namespaces [0].Types [0];

            Assert.IsTrue(resType.TypeAttributes == TypeAttributes.Public);

            cmp = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> (
                "ResourceManager", ccu);
            Assert.IsTrue(cmp.Attributes == (MemberAttributes.Abstract
                                             | MemberAttributes.Final
                                             | MemberAttributes.FamilyAndAssembly
                                             | MemberAttributes.FamilyOrAssembly));

            cmp = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> ("Culture", ccu);
            Assert.IsTrue(cmp.Attributes == (MemberAttributes.Abstract
                                             | MemberAttributes.Final
                                             | MemberAttributes.FamilyAndAssembly
                                             | MemberAttributes.FamilyOrAssembly));

            cmp = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> ("astring", ccu);
            Assert.IsTrue(cmp.Attributes == (MemberAttributes.Abstract
                                             | MemberAttributes.Final
                                             | MemberAttributes.FamilyAndAssembly
                                             | MemberAttributes.FamilyOrAssembly));

            cmp = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> ("bmp", ccu);
            Assert.IsTrue(cmp.Attributes == (MemberAttributes.Abstract
                                             | MemberAttributes.Final
                                             | MemberAttributes.FamilyAndAssembly
                                             | MemberAttributes.FamilyOrAssembly));

            cmp = StronglyTypedResourceBuilderCodeDomTest.Get <CodeMemberProperty> ("wav", ccu);
            Assert.IsTrue(cmp.Attributes == (MemberAttributes.Abstract
                                             | MemberAttributes.Final
                                             | MemberAttributes.FamilyAndAssembly
                                             | MemberAttributes.FamilyOrAssembly));
        }
Exemple #18
0
        public static string Execute(string language, ITaskItem resx, string rootNamespace, TaskLoggingHelper log)
        {
            var resxFile = resx.GetMetadata("FullPath");
            // Same logic as ResXFileCodeGenerator.
            var resourcesTypeName = Path.GetFileNameWithoutExtension(resxFile);
            var targetNamespace   = resx.GetMetadata("CustomToolNamespace");
            var resourceName      = resx.GetMetadata("ManifestResourceName");;
            var relativeDir       = resx.GetMetadata("CanonicalRelativeDir");
            var makePublic        = false;

            bool.TryParse(resx.GetMetadata("Public"), out makePublic);

            if (string.IsNullOrEmpty(targetNamespace))
            {
                // Note that the custom tool namespace in newer versions of VS is saved
                // as item metadata. On older versions, it would have to be manually
                // set.
                targetNamespace = rootNamespace + "." + relativeDir
                                  .TrimEnd(Path.DirectorySeparatorChar)
                                  .Replace(Path.DirectorySeparatorChar, '.');

                log.LogMessage(MessageImportance.Low, "No CustomToolNamespace metadata found, determined TargetNamespace=" + targetNamespace);
            }
            else
            {
                log.LogMessage(MessageImportance.Low, "Using provided CustomToolNamespace={0} metadata as TargetNamespace for {1}", targetNamespace, resx.ItemSpec);
            }

            var lastDot           = resourceName.LastIndexOf('.');
            var resourceNamespace = resourceName.Remove(lastDot, resourceName.Length - lastDot);

            log.LogMessage(MessageImportance.Low, "Using ResourceNamespace={0}", resourceNamespace);

            var targetClassName = Path.GetFileNameWithoutExtension(resxFile);
            var builder         = new System.Text.StringBuilder();

            using (var writer = new StringWriter(builder)) {
                string[]           errors   = null;
                CSharpCodeProvider provider = new CSharpCodeProvider();
                CodeCompileUnit    code     = StronglyTypedResourceBuilder.Create(resxFile, targetClassName, targetNamespace, resourceNamespace, provider, !makePublic, out errors);
                if (errors.Length > 0)
                {
                    foreach (var error in errors)
                    {
                        log.LogError("Error generating from '{0}'. {1}", resxFile, error);
                    }
                }

                provider.GenerateCodeFromCompileUnit(code, writer, new CodeGeneratorOptions());
            }

            return(builder.ToString());
        }
Exemple #19
0
        public McCompiler(McFileGenerator genInfo, string mcFile)
        {
            _genInfo = genInfo;
            _mcFile  = mcFile;
            _verInfo = new VersionInfoBuilder();

            string[] ns = Path.GetFileNameWithoutExtension(_mcFile).Trim('.').Split('.');
            for (int i = 0; i < ns.Length; i++)
            {
                ns[i] = StronglyTypedResourceBuilder.VerifyResourceName(ns[i], Csharp);
            }
            _namespace = String.Join(".", ns);
        }
        public void VerifyResourceNameProviderKeywords()
        {
            // not complete list, doesnt really need to be
            string expected, output;

            foreach (string input in keywords)
            {
                output = StronglyTypedResourceBuilder.VerifyResourceName(input, provider);

                expected = provider.CreateValidIdentifier(input);

                Assert.AreEqual(expected, output);
            }
        }
Exemple #21
0
        private void GenerateStronglyTypedClass(AssemblyBuilder assemblyBuilder, IResourceReader reader)
        {
            IDictionary resourceList;

            string[] strArray;
            using (reader)
            {
                resourceList = this.GetResourceList(reader);
            }
            CodeDomProvider codeDomProvider = assemblyBuilder.CodeDomProvider;
            CodeCompileUnit compileUnit     = StronglyTypedResourceBuilder.Create(resourceList, this._typeName, this._ns, codeDomProvider, false, out strArray);

            assemblyBuilder.AddCodeCompileUnit(this, compileUnit);
        }
Exemple #22
0
        public void ResXFilenameEmpty()
        {
            // in .NET framework throws exception
            string [] unmatchables;

            string resx = String.Empty;

            StronglyTypedResourceBuilder.Create(resx,
                                                "TestRes",
                                                "TestNamespace",
                                                "TestResourcesNameSpace",
                                                provider,
                                                true,
                                                out unmatchables);
        }
        public void ProviderNull()
        {
            // should throw exception
            Dictionary <string, object> testResources = GetTestResources();

            string [] unmatchables;

            StronglyTypedResourceBuilder.Create(testResources,
                                                "TestClass",
                                                "TestNamespace",
                                                "TestResourcesNameSpace",
                                                null,         //setting provider to null
                                                true,
                                                out unmatchables);
        }
        public void VerifyResourceNameSpecialChars()
        {
            // should replace with _
            string input, expected, output;

            foreach (char c in specialChars)
            {
                input    = string.Format("{0}a{0}b{0}", c);
                expected = string.Format("{0}a{0}b{0}", '_');

                output = StronglyTypedResourceBuilder.VerifyResourceName(input, provider);

                Assert.AreEqual(expected, output);
            }
        }
Exemple #25
0
        public void ResXFilenameNull()
        {
            //should throw exception
            string [] unmatchables;

            string resx = null;

            StronglyTypedResourceBuilder.Create(resx,
                                                "TestRes",
                                                "TestNamespace",
                                                "TestResourcesNameSpace",
                                                provider,
                                                true,
                                                out unmatchables);
        }
        /// <summary>
        /// Generates a strongly typed assembly from the resources
        ///
        /// UNDER CONSTRUCTION.
        /// Doesn't work correctly for Web forms due to hard coded resource managers.
        /// </summary>
        /// <param name="ResourceSetName"></param>
        /// <param name="Namespace"></param>
        /// <param name="Classname"></param>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public bool CreateStronglyTypedResource(string ResourceSetName, string Namespace, string Classname, string FileName)
        {
            try
            {
                //wwDbResourceDataManager Data = new wwDbResourceDataManager();
                //IDictionary ResourceSet = Data.GetResourceSet("", ResourceSetName);

                // *** Use the custom ResourceManage to retrieve a ResourceSet
                wwDbResourceManager   Man        = new wwDbResourceManager(ResourceSetName);
                ResourceSet           rs         = Man.GetResourceSet(CultureInfo.InvariantCulture, false, false);
                IDictionaryEnumerator Enumerator = rs.GetEnumerator();

                // *** We have to turn into a concret Dictionary
                Dictionary <string, object> Resources = new Dictionary <string, object>();
                while (Enumerator.MoveNext())
                {
                    DictionaryEntry Item = (DictionaryEntry)Enumerator.Current;
                    Resources.Add(Item.Key as string, Item.Value);
                }

                string[]        UnmatchedElements;
                CodeDomProvider CodeProvider = null;

                string FileExtension = Path.GetExtension(FileName).TrimStart('.').ToLower();
                if (FileExtension == "cs")
                {
                    CodeProvider = new Microsoft.CSharp.CSharpCodeProvider();
                }
                else if (FileExtension == "vb")
                {
                    CodeProvider = new Microsoft.VisualBasic.VBCodeProvider();
                }

                CodeCompileUnit Code = StronglyTypedResourceBuilder.Create(Resources,
                                                                           ResourceSetName, Namespace, CodeProvider, false, out UnmatchedElements);

                StreamWriter writer = new StreamWriter(FileName);
                CodeProvider.GenerateCodeFromCompileUnit(Code, writer, new CodeGeneratorOptions());
                writer.Close();
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.Message;
                return(false);
            }

            return(true);
        }
Exemple #27
0
        public void BaseNameNull()
        {
            // should throw exception
            string [] unmatchables;
            string    input;

            input = null;

            StronglyTypedResourceBuilder.Create(testResources,
                                                input,
                                                "TestNamespace",
                                                "TestResourcesNameSpace",
                                                provider,
                                                true,
                                                out unmatchables);
        }
Exemple #28
0
        public void BaseNameInvalidIdentifier()
        {
            // identifier invalid after Going through provider.CreateValidIdentifier throw exception in .NET framework
            string [] unmatchables;
            string    input;

            input = "cla$ss";

            StronglyTypedResourceBuilder.Create(testResources,
                                                input,
                                                "TestNamespace",
                                                "TestResourcesNameSpace",
                                                provider,
                                                true,
                                                out unmatchables);
        }
Exemple #29
0
        string CreateResources()
        {
            //Now we've loaded our own type data, we need to generate the resource accessors:
            string[] errors;

            Hashtable all = new Hashtable();

            foreach (ResXDataNode node in _xnodes)
            {
                all[node.Name] = node;
            }

            CodeCompileUnit unit = StronglyTypedResourceBuilder.Create(all,
                                                                       _className, _nameSpace, _resxNameSpace, Csharp, !_public, out errors);

            foreach (string error in errors)
            {
                Console.Error.WriteLine("Warning: {0}", error);
            }

            CodeGeneratorOptions options = new CodeGeneratorOptions();

            options.BlankLinesBetweenMembers = false;
            options.BracingStyle             = "C";
            options.IndentString             = "    ";

            string result;

            using (StringWriter swCode = new StringWriter())
            {
                Csharp.GenerateCodeFromCompileUnit(unit, swCode, options);
                result = swCode.ToString();
            }

            if (_partial)
            {
                result = result.Replace(" class ", " partial class ");
            }

            result = Regex.Replace(
                result,
                @"(?im-snx:(?<=^//\s*Runtime\s*Version\s*:\s*)\d{1,5}(\.\d{1,5}){0,3})",
                m => new Version(m.Value).ToString(2)
                );

            return(result);
        }
Exemple #30
0
        /// <summary>
        /// Generates the RESX code.
        /// </summary>
        /// <param name="resXFileName">Res XF ile name.</param>
        /// <param name="nameSpace">Name space.</param>
        /// <param name="className">Class name.</param>
        /// <param name="generatedFileName">Generated file name.</param>
        /// <param name="intern">If set to <c>true</c> intern.</param>
        public static void generateResxCode(string resXFileName,
                                            string nameSpace, string className, string generatedFileName,
                                            bool partial = false, bool intern = true, bool targetsPcl = false, string resFileNamePrefix = null)
        {
            StreamWriter sw = new StreamWriter(generatedFileName);

            string[] errors = null;
            Dictionary <string, string> provOptions =
                new Dictionary <string, string>();

            provOptions.Add("CompilerVersion", "v12.0");
            // Get the provider for Microsoft.CSharp
            CSharpCodeProvider csProvider = new CSharpCodeProvider(provOptions);


            CodeCompileUnit code = StronglyTypedResourceBuilder.Create(resXFileName, className,
                                                                       nameSpace, csProvider,
                                                                       intern, out errors);

            if (targetsPcl)
            {
                FixupPclTypeInfo(code);
            }
            if (resFileNamePrefix != null)
            {
                FixResourcePathPrefix(code, resFileNamePrefix);
            }
            if (partial)
            {
                FixupClassDeclarationForPartial(code);
            }


            if (errors.Length > 0)
            {
                foreach (var error in errors)
                {
                    Console.Error.WriteLine(error);
                }
            }
            var options = new CodeGeneratorOptions();

            csProvider.GenerateCodeFromCompileUnit(code, sw, options);
            sw.Close();
            Trace($"Generated: {generatedFileName}");
        }