Ejemplo n.º 1
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);
            }
        }
        public void VerifyResourceNameEmpty()
        {
            // should return _
            string output = StronglyTypedResourceBuilder.VerifyResourceName(string.Empty, provider);

            Assert.AreEqual("_", output);
        }
        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);
        }
Ejemplo n.º 4
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);
            }
        }
        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);
            }
        }
Ejemplo n.º 7
0
        public GeneratorArguments(bool domainsAllowed, string inputFile, IProjectItem item, IProjectInfo projectInfo)
        {
            _domainsAllowed = domainsAllowed;
            _help           = new StringWriter();
            _files          = new List <OutputFile>();
            Check.NotNull(item);
            _variables = new Dictionary <string, string>(Check.NotNull(projectInfo).GetProjectVariables(), StringComparer.OrdinalIgnoreCase);

            inputFile = Path.GetFullPath(inputFile);

            _variables["CmdToolDir"]       = Path.GetDirectoryName(GetType().Assembly.Location).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
            _variables["DefaultNamespace"] = item.DefaultNamespace;
            _variables["Namespace"]        = item.Namespace;
            _variables["ClassName"]        = StronglyTypedResourceBuilder.VerifyResourceName(Path.GetFileNameWithoutExtension(inputFile), new CSharpCodeProvider());
            _variables["PseudoPath"]       = item.FullPseudoPath;
            _variables["InputPath"]        = inputFile;
            _variables["InputName"]        = Path.GetFileName(inputFile);
            _variables["InputDir"]         = Path.GetDirectoryName(inputFile).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + Path.DirectorySeparatorChar;
        }
Ejemplo n.º 8
0
        public void BaseNameSpecialChars()
        {
            // StronglyTypedResourceBuilder.VerifyResourceName seems to be used
            string []       unmatchables;
            CodeCompileUnit ccu;
            string          input, expected;

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

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

                expected = StronglyTypedResourceBuilder.VerifyResourceName(input, provider);

                Assert.AreEqual(expected, ccu.Namespaces [0].Types [0].Name);
            }
        }
Ejemplo n.º 9
0
        public string CreateConstants(string header)
        {
            string content = File.ReadAllText(header);

            Regex pattern = new Regex(@"^#define\s+(?<id>[\w_]*)\s+\(?(?:\(long\))?(?<value>.*?)\)?\s*?$",
                                      RegexOptions.Multiline | RegexOptions.IgnoreCase);

            Dictionary <string, string> defines = new Dictionary <string, string>();

            foreach (Match m in pattern.Matches(content))
            {
                if (!m.Groups["id"].Value.StartsWith("CATEGORY_", StringComparison.Ordinal) &&
                    !m.Groups["id"].Value.StartsWith("FACILITY_", StringComparison.Ordinal))
                {
                    defines.Add(m.Groups["id"].Value, m.Groups["value"].Value);
                }
            }


            using (CsWriter code = new CsWriter())
            {
                code.WriteLine("// ReSharper disable InconsistentNaming");
                code.WriteLine("#pragma warning disable 1591 //disable missing xml comments");
                code.WriteLine();

                using (code.WriteNamespace(Namespace))
                {
                    if (_genInfo != null)
                    {
                        Dictionary <int, string> items = _genInfo.Facilities;
                        using (code.WriteBlock("public enum Facilities"))
                        {
                            List <int> sorted = new List <int>(items.Keys);
                            sorted.Sort();
                            foreach (int key in sorted)
                            {
                                code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(items[key], Csharp), key);
                            }
                        }
                        code.WriteLine();
                        items = _genInfo.Categories;
                        using (code.WriteBlock("public enum Categories"))
                        {
                            List <int> sorted = new List <int>(items.Keys);
                            sorted.Sort();
                            foreach (int key in sorted)
                            {
                                code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(items[key], Csharp), key);
                            }
                        }
                        code.WriteLine();
                    }

                    using (code.WriteBlock("public enum HResults : long"))
                    {
                        List <string> sorted = new List <string>(defines.Keys);
                        sorted.Sort();
                        foreach (string key in sorted)
                        {
                            code.WriteLine("{0} = {1},", StronglyTypedResourceBuilder.VerifyResourceName(key, Csharp), defines[key]);
                        }
                    }
                }
                return(code.ToString());
            }
        }
        public void GenerateCode(FileProjectItem item, CustomToolContext context)
        {
            /*context.GenerateCodeDomAsync(item, context.GetOutputFileName(item, ".Designer"),
             *                           delegate {
             *                              return GenerateCodeDom();
             *                           });*/
            string inputFilePath = item.FileName;

            // Ensure that the generated code will not conflict with an
            // existing class.
            if (context.Project != null)
            {
                IProjectContent pc = ParserService.GetProjectContent(context.Project);
                if (pc != null)
                {
                    IClass existingClass = pc.GetClass(context.OutputNamespace + "." + StronglyTypedResourceBuilder.VerifyResourceName(Path.GetFileNameWithoutExtension(inputFilePath), pc.Language.CodeDomProvider), 0);
                    if (existingClass != null)
                    {
                        if (!IsGeneratedResourceClass(existingClass))
                        {
                            context.MessageView.AppendLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, ResourceService.GetString("ResourceEditor.ResourceCodeGeneratorTool.ClassConflict"), inputFilePath, existingClass.FullyQualifiedName));
                            return;
                        }
                    }
                }
            }

            IResourceReader reader;

            if (string.Equals(Path.GetExtension(inputFilePath), ".resx", StringComparison.OrdinalIgnoreCase))
            {
                reader = new ResXResourceReader(inputFilePath);
                ((ResXResourceReader)reader).BasePath = Path.GetDirectoryName(inputFilePath);
            }
            else
            {
                reader = new ResourceReader(inputFilePath);
            }

            Hashtable resources = new Hashtable();

            foreach (DictionaryEntry de in reader)
            {
                resources.Add(de.Key, de.Value);
            }

            string[] unmatchable = null;

            context.WriteCodeDomToFile(
                item,
                context.GetOutputFileName(item, ".Designer"),
                StronglyTypedResourceBuilder.Create(
                    resources,                                          // resourceList
                    Path.GetFileNameWithoutExtension(inputFilePath),    // baseName
                    context.OutputNamespace,                            // generatedCodeNamespace
                    context.OutputNamespace,                            // resourcesNamespace
                    context.Project.LanguageProperties.CodeDomProvider, // codeProvider
                    createInternalClass,                                // internal class
                    out unmatchable
                    ));

            foreach (string s in unmatchable)
            {
                context.MessageView.AppendLine(String.Format(System.Globalization.CultureInfo.CurrentCulture, ResourceService.GetString("ResourceEditor.ResourceCodeGeneratorTool.CouldNotGenerateResourceProperty"), s));
            }
        }
        void ProjectTreeScanningBackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            if (this.project == null)
            {
                return;
            }

            ProjectResourceInfo selectedProjectResource = e.Argument as ProjectResourceInfo;

            IProjectContent projectContent = ParserService.GetProjectContent(this.project);

            TreeNode root           = new TreeNode(this.project.Name, 0, 0);
            TreeNode preSelection   = null;
            TreeNode lastFileNode   = null;
            int      fileNodesCount = 0;

            foreach (FileProjectItem item in this.project.GetItemsOfType(ItemType.EmbeddedResource).OfType <FileProjectItem>().OrderBy(fpi => Path.GetFileName(fpi.VirtualName)))
            {
                if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                {
                    e.Cancel = true;
                    break;
                }

                // Skip files where the generated class name
                // would conflict with an existing class.
                string namespaceName = item.GetEvaluatedMetadata("CustomToolNamespace");
                if (string.IsNullOrEmpty(namespaceName))
                {
                    namespaceName = CustomToolsService.GetDefaultNamespace(item.Project, item.FileName);
                }
                IClass existingClass = projectContent.GetClass(namespaceName + "." + StronglyTypedResourceBuilder.VerifyResourceName(Path.GetFileNameWithoutExtension(item.FileName), projectContent.Language.CodeDomProvider), 0);
                if (existingClass != null)
                {
                    if (!ProjectResourceService.IsGeneratedResourceClass(existingClass))
                    {
                        continue;
                    }
                }

                bool     selectedFile = (selectedProjectResource != null) && FileUtility.IsEqualFileName(selectedProjectResource.ResourceFile, item.FileName);
                TreeNode file         = null;

                try {
                    foreach (KeyValuePair <string, object> r in this.GetResources(item.FileName).OrderBy(pair => pair.Key))
                    {
                        if (this.projectTreeScanningBackgroundWorker.CancellationPending)
                        {
                            e.Cancel = true;
                            break;
                        }

                        if (file == null)
                        {
                            file = CreateAndAddFileNode(root, item);
                        }

                        TreeNode resNode = new TreeNode(r.Key, 3, 3);
                        resNode.Tag = r.Value;
                        file.Nodes.Add(resNode);

                        if (selectedFile)
                        {
                            if (String.Equals(r.Key, selectedProjectResource.ResourceKey, StringComparison.Ordinal))
                            {
                                preSelection = resNode;
                            }
                        }
                    }

                    if (file != null)
                    {
                        lastFileNode = file;
                        ++fileNodesCount;
                    }
                } catch (Exception ex) {
                    if (file == null)
                    {
                        file = CreateAndAddFileNode(root, item);
                    }
                    TreeNode error = new TreeNode(ex.Message, 4, 4);
                    file.Nodes.Add(error);
                }
            }

            if (e.Cancel)
            {
                DisposeNodeImages(root);
            }
            else
            {
                // Preselect the file node if there is only one
                if (preSelection == null && fileNodesCount == 1)
                {
                    preSelection = lastFileNode;
                }
                e.Result = new TreeScanResult(root, preSelection);
            }
        }
        void WriteException(CsWriter code, List <ResxGenItem> lst)
        {
            if (lst.Count == 0 || lst[0].IsException == false)
            {
                return;
            }

            ResxGenItem first  = lst[0];
            string      exName = StronglyTypedResourceBuilder.VerifyResourceName(first.ItemName, Csharp);

            string baseName = ": " + _baseException;

            foreach (ResxGenItem item in lst)
            {
                if (item.Comments.StartsWith(":"))
                {
                    baseName = item.Comments;
                }
            }

            code.WriteSummaryXml("Exception class: {0} {1}\r\n{2}", exName, baseName, first.Value);
            code.WriteLine("[System.SerializableAttribute()]");
            using (
                code.WriteClass("public {2}{3}class {0} {1}", exName, baseName, _sealed ? "sealed " : "",
                                _partial ? "partial " : ""))
            {
                code.WriteSummaryXml("Serialization constructor");
                code.WriteBlock(
                    "{1} {0}(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context)",
                    exName, _sealed ? "internal" : "protected")
                .Dispose();

                WriteStaticFactory(code, exName);

                Dictionary <string, ResxGenArgument> publicData = new Dictionary <string, ResxGenArgument>();
                foreach (ResxGenItem item in lst)
                {
                    foreach (ResxGenArgument arg in item.Args)
                    {
                        if (arg.IsPublic)
                        {
                            publicData[arg.Name] = arg;
                        }
                    }
                }

                foreach (ResxGenArgument pd in publicData.Values)
                {
                    if (pd.Name == "HResult" || pd.Name == "HelpLink" || pd.Name == "Source")
                    {
                        continue; //uses base properties
                    }
                    code.WriteLine();
                    code.WriteSummaryXml("The {0} parameter passed to the constructor", pd.ParamName);
                    code.WriteLine(
                        "public {1} {0} {{ get {{ if (Data[\"{0}\"] is {1}) return ({1})Data[\"{0}\"]; else return default({1}); }} }}",
                        pd.Name, pd.Type);
                }
                code.WriteLine();

                foreach (ResxGenItem item in lst)
                {
                    string formatNm   = String.Format("{0}.ExceptionStrings.{1}", _fullClassName, item.Identifier);
                    string formatFn   = _fullClassName + ".ExceptionStrings.SafeFormat";
                    string baseArgs   = item.IsFormatter ? formatFn + "({0}, {1})" : "{0}";
                    string argList    = item.HasArguments ? ", " + item.Parameters(true) : "";
                    string strHResult = item.HResult != 0 ? String.Format("unchecked((int)0x{0:X8}U)", item.HResult) : "-1";

                    code.WriteSummaryXml(item.Value);
                    code.WriteLine("public {0}({1})", exName, item.Parameters(true));
                    using (code.WriteBlock("\t: this((System.Exception)null, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, item.Parameters(false))))
                    {
                        foreach (ResxGenArgument arg in item.Args)
                        {
                            WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName);
                        }
                        if (item.AutoLog)
                        {
                            code.WriteLine("WriteEvent({0});", item.Parameters(false));
                        }
                    }
                    code.WriteSummaryXml(item.Value);
                    code.WriteLine("public {0}({1}{2}System.Exception innerException)", exName, item.Parameters(true), item.HasArguments ? ", " : "");
                    using (code.WriteBlock("\t: this(innerException, {0}, {1})", strHResult, String.Format(baseArgs, formatNm, item.Parameters(false))))
                    {
                        foreach (ResxGenArgument arg in item.Args)
                        {
                            WriteSetProperty(code, arg.IsPublic, arg.Name, arg.ParamName);
                        }
                        if (item.AutoLog)
                        {
                            code.WriteLine("WriteEvent({0});", item.Parameters(false));
                        }
                    }

                    if (item.AutoLog)
                    {
                        WriteAutoLog(code, item);
                    }

                    code.WriteSummaryXml("if(condition == false) throws {0}", item.Value);
                    using (code.WriteBlock("public static void Assert(bool condition{0})", argList))
                        code.WriteLine("if (!condition) throw new {0}({1});", exName, item.Parameters(false));
                }
            }
        }
        bool SerializeProjectResource(IDesignerSerializationManager manager, object value, MemberDescriptor descriptor, CodeStatementCollection statements)
        {
            var propDesc = descriptor as PropertyDescriptor;

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

            var component = value as IComponent;

            if (component == null || component.Site == null)
            {
                return(false);
            }

            if (!propDesc.ShouldSerializeValue(component))
            {
                return(false);
            }

            var dictService = component.Site.GetService(typeof(IDictionaryService)) as IDictionaryService;

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

            var resourceInfo = dictService.GetValue(ProjectResourceService.ProjectResourceKey + propDesc.Name) as ProjectResourceInfo;

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

            if (!Object.ReferenceEquals(resourceInfo.OriginalValue, propDesc.GetValue(value)))
            {
                LoggingService.Info("Value of property '" + propDesc.Name + "' on component '" + value.ToString() + "' is not equal to stored project resource value. Ignoring this resource.");
                return(false);
            }


            // Find the generated file with the resource accessing class.

            var prs = manager.GetService(typeof(ProjectResourceService)) as ProjectResourceService;

            if (prs == null)
            {
                LoggingService.Warn("ProjectResourceService not found");
                return(false);
            }

            IProject project = prs.ProjectContent;

            if (project == null)
            {
                LoggingService.Warn("Serializer cannot proceed because project is not an IProject");
                return(false);
            }

            string resourceFileDirectory = Path.GetDirectoryName(resourceInfo.ResourceFile);
            string resourceFileName      = Path.GetFileName(resourceInfo.ResourceFile);
            var    items = project.Items
                           .OfType <FileProjectItem>()
                           .Where(
                fpi =>
                FileUtility.IsEqualFileName(Path.GetDirectoryName(fpi.FileName), resourceFileDirectory) &&
                FileUtility.IsEqualFileName(fpi.DependentUpon, resourceFileName) &&
                fpi.ItemType == ItemType.Compile &&
                fpi.VirtualName.ToUpperInvariant().Contains("DESIGNER")
                ).ToList();

            if (items.Count != 1)
            {
                LoggingService.Info("Did not find exactly one possible file that contains the generated class for the resource file '" + resourceInfo.ResourceFile + "'. Ignoring this resource.");
                return(false);
            }

            FileName resourceCodeFile = items.Single().FileName;

            // We expect a single class to be in this file.
            var resourceClass = SD.ParserService.GetExistingUnresolvedFile(resourceCodeFile).TopLevelTypeDefinitions.Single();
            // Here we assume that VerifyResourceName is the same name transform that
            // was used when generating the resource code file.
            // This should be true as long as the code is generated using the
            // custom tool in SharpDevelop or Visual Studio.
            string resourcePropertyName = StronglyTypedResourceBuilder.VerifyResourceName(resourceInfo.ResourceKey, prs.ProjectContent.CreateCodeDomProvider() ?? new CSharpCodeProvider());

            if (resourcePropertyName == null)
            {
                throw new InvalidOperationException("The resource name '" + resourceInfo.ResourceKey + "' could not be transformed to a name that is valid in the current programming language.");
            }


            // Now do the actual serialization.

            LoggingService.Debug("Serializing project resource: Component '" + component.ToString() + "', Property: '" + propDesc.Name + "', Resource class: '" + resourceClass.FullName + "', Resource property: '" + resourcePropertyName + "'");

            var targetObjectExpr = base.SerializeToExpression(manager, value);

            if (targetObjectExpr == null)
            {
                LoggingService.Info("Target object could not be serialized: " + value.ToString());
                return(false);
            }

            if (propDesc.SerializationVisibility == DesignerSerializationVisibility.Content)
            {
                LoggingService.Debug("-> is a content property, ignoring this.");
                return(false);
            }

            var propRefSource =
                Easy.Type(
                    new CodeTypeReference(resourceClass.FullName, CodeTypeReferenceOptions.GlobalReference)
                    ).Property(resourcePropertyName);

            var extAttr = propDesc.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute;

            if (extAttr != null && extAttr.Provider != null)
            {
                // This is an extender property.
                var extProvider = base.SerializeToExpression(manager, extAttr.Provider);
                if (extProvider == null)
                {
                    throw new InvalidOperationException("Could not serialize the extender provider '" + extAttr.Provider.ToString() + "'.");
                }

                statements.Add(
                    extProvider.InvokeMethod(
                        "Set" + propDesc.Name,
                        targetObjectExpr,
                        propRefSource
                        )
                    );
            }
            else
            {
                // This is a standard property.
                statements.Add(
                    new CodeAssignStatement(
                        new CodePropertyReferenceExpression(targetObjectExpr, propDesc.Name),
                        propRefSource)
                    );
            }

            return(true);
        }
 public void VerifyResourceNameProviderNull()
 {
     // should throw exception
     StronglyTypedResourceBuilder.VerifyResourceName("tes$t", null);
 }
 public void VerifyResourceNameNull()
 {
     // should throw exception
     StronglyTypedResourceBuilder.VerifyResourceName(null, provider);
 }
Ejemplo n.º 16
0
        public void Write(TextWriter writerIn)
        {
            Dictionary <int, string> catId = new Dictionary <int, string>();
            Dictionary <int, string> facId = new Dictionary <int, string>();

            IndentedTextWriter writer = new IndentedTextWriter(writerIn);

            writer.WriteLine("MessageIdTypedef=long");
            writer.WriteLine("LanguageNames=(English=0x409:MSG00409)");//need to discover language from resx?
            writer.WriteLine();

            writer.WriteLine("SeverityNames=(");
            writer.Indent++;
            writer.WriteLine("Success=0x0");
            writer.WriteLine("Information=0x1");
            writer.WriteLine("Warning=0x2");
            writer.WriteLine("Error=0x3");
            writer.Indent--;
            writer.WriteLine(")");
            writer.WriteLine();

            if (_facilities.Count > 0)
            {
                List <int> keys = new List <int>(_facilities.Keys);
                keys.Sort();
                writer.WriteLine("FacilityNames=(");
                writer.Indent++;
                foreach (int key in keys)
                {
                    facId[key] = "FACILITY_" + StronglyTypedResourceBuilder.VerifyResourceName(_facilities[key], Csharp).ToUpper();
                    writer.WriteLine("{0}=0x{1:x}", facId[key], key);
                }
                writer.Indent--;
                writer.WriteLine(")");
                writer.WriteLine();
            }
            if (_categories.Count > 0)
            {
                List <int> keys = new List <int>(_categories.Keys);
                keys.Sort();
                writer.WriteLine(";// CATEGORIES");
                writer.WriteLine();
                foreach (int key in keys)
                {
                    catId[key] = "CATEGORY_" + StronglyTypedResourceBuilder.VerifyResourceName(_categories[key], Csharp).ToUpper();
                    writer.WriteLine("MessageId       = 0x{0:x}", key);
                    writer.WriteLine("SymbolicName    = {0}", catId[key]);
                    writer.WriteLine("Language        = English");
                    writer.WriteLine(_categories[key]);
                    writer.WriteLine(".");
                    writer.WriteLine();
                }
            }

            writer.WriteLine(";// MESSAGES");
            writer.WriteLine();

            foreach (KeyValuePair <uint, ResxGenItem> pair in _itemsByHResult)
            {
                ResxGenItem item = pair.Value;
                uint        hr   = pair.Key;
                writer.WriteLine("MessageId       = 0x{0:x}", hr & 0x0FFFF);
                writer.WriteLine("Severity        = {0}", (hr & 0x80000000) == 0 ? "Information" : (hr & 0x40000000) == 0 ? "Warning" : "Error");
                if (0 != (int)((hr >> 16) & 0x3FF))
                {
                    writer.WriteLine("Facility        = {0}", facId[(int)((hr >> 16) & 0x3FF)]);
                }
                writer.WriteLine("SymbolicName    = {0}", item.Identifier.ToUpper());
                writer.WriteLine("Language        = English");

                int    ordinal       = 1;
                string messageFormat = null;
                string messageText   = String.Empty;

                if (item.Options.ContainsKey("EventMessageFormat") && !String.IsNullOrEmpty(item.Options["EventMessageFormat"]))
                {
                    FormatNumbering numbering = new FormatNumbering(ordinal);
                    messageFormat = StringUtils.Transform(
                        item.Options["EventMessageFormat"].Replace("%", "%%"),
                        RegexPatterns.FormatSpecifier,
                        numbering.Transform);
                    ordinal = 1 + numbering.MaxIdentifier;
                }

                messageText = StringUtils.Transform(
                    item.Value.Replace("%", "%%"),
                    RegexPatterns.FormatSpecifier,
                    new FormatNumbering(ordinal).Transform);

                if (messageFormat != null)
                {
                    messageText = String.Format("{0}\r\n{1}", messageText, messageFormat);
                }

                writer.WriteLine(
                    messageText
                    .Replace("{{", "{")
                    .Replace("}}", "}")
                    .Replace("\r\n", "\n")
                    .Replace("\n", "%n\r\n")
                    .Replace("\r\n.", "\r\n%.")
                    .Replace("!", "%!")
                    );

                writer.WriteLine(".");
                writer.WriteLine();
            }
        }
        public ResxGenItem(ResXOptions options, ResXDataNode node)
        {
            Node    = node;
            Ignored = true;            //and clear upon complete...

            Options = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
            Args    = new List <ResxGenArgument>();
            try
            {
                if (node.FileRef != null)
                {
                    return;
                }
                Type type = Type.GetType(node.GetValueTypeName(AllowedNames));
                if (type == null || type != typeof(String))
                {
                    return;
                }
                Value = (String)node.GetValue(AllowedNames);
            }
            catch { return; }

            MemberName = Identifier = StronglyTypedResourceBuilder.VerifyResourceName(node.Name, Csharp);
            FullName   = ItemName = node.Name;

            Comments = node.Comment;
            string rawArgs = null;

            IsFormatter = FormatingMatch.IsMatch(Value);
            IsException = ExceptionMatch.IsMatch(node.Name);
            //if (!IsFormatter && !IsException)
            //    return;

            int pos;

            if ((pos = ItemName.IndexOf('(')) > 0)
            {
                rawArgs    = ItemName.Substring(pos);
                ItemName   = ItemName.Substring(0, pos);
                MemberName = StronglyTypedResourceBuilder.VerifyResourceName(ItemName, Csharp);
            }
            else if (Comments.StartsWith("(") && (pos = Comments.IndexOf(')')) > 0)
            {
                rawArgs  = Comments.Substring(0, 1 + pos);
                Comments = Comments.Substring(pos + 1).Trim();
            }
            if (!String.IsNullOrEmpty(rawArgs))
            {
                Args.AddRange(new ResxGenArgParser(rawArgs));
            }

            //now thats out of the way... let's transform the format string into something usable:
            Value = StringUtils.Transform(Value, FormatingMatch,
                                          delegate(Match m)
            {
                return("{" + GetArg(null, m.Groups["field"].Value) + m.Groups["suffix"].Value + "}");
            }
                                          );

            if (Comments.StartsWith(":") && Comments.IndexOf("Exception") > 0)
            {
                IsException = true;
            }

            bool parsedOptions = ParseOptions(ref Comments);

            FacilityId = options.FacilityId;
            bool hasId = GetMessageIdForItem(out MessageId);

            hasId |= GetHResultForItem(out HResult);

            HasArguments = Args.Count > 0;
            if (HasArguments || IsFormatter || IsException || hasId)
            {
                Ignored = false;
                if (!parsedOptions)
                {
                    throw new ApplicationException(String.Format("Unable to parse comment options: '{0}'", Comments));
                }
            }
            AutoLog = hasId && MessageId != 0 && options.AutoLog && GetOption("log", true);
        }
        /// <summary>
        /// Appends static properties used for event logging
        /// </summary>
        void WriteProperties(CsWriter code)
        {
            if (_options.AutoLog || !String.IsNullOrEmpty(_options.EventSource))
            {
                code.WriteLine();
                code.WriteSummaryXml("The event source used to write events");
                code.WriteLine("internal static readonly string EventSourceName = @\"{0}\";",
                               String.IsNullOrEmpty(_options.EventSource) ? _fullClassName : _options.EventSource);

                code.WriteLine();
                code.WriteSummaryXml("The category id used to write events");
                using (code.WriteBlock("public static bool TryCreateException(int hResult, string message, out System.Exception exception)"))
                    using (code.WriteBlock("switch (unchecked((uint)hResult))"))
                    {
                        Dictionary <uint, bool> visited = new Dictionary <uint, bool>();
                        foreach (List <ResxGenItem> lst in _items.Values)
                        {
                            foreach (ResxGenItem item in lst)
                            {
                                if (!item.IsException)
                                {
                                    break;
                                }
                                if (item.HResult != 0 && !visited.ContainsKey(item.HResult))
                                {
                                    visited.Add(item.HResult, true);
                                    string exName = StronglyTypedResourceBuilder.VerifyResourceName(item.ItemName, Csharp);
                                    code.WriteLine("case 0x{0:x8}U: exception = {1}.{2}.Create(hResult, message); return true;", item.HResult, _nameSpace, exName);
                                }
                            }
                        }
                        code.WriteLine("default: exception = null; return false;");
                    }
            }
            if (_options.FacilityId > 0)
            {
                code.WriteLine();
                code.WriteSummaryXml("The the event log facility id of events defined in this resource file");
                code.WriteLine("internal static readonly int EventFacilityId = {0};", _options.FacilityId);
            }
            if (_options.AutoLog)
            {
                if (String.IsNullOrEmpty(_options.EventSource))
                {
                    Console.Error.WriteLine("Warning: AutoLog == true, but no event source name was defined.");
                }

                code.WriteLine();
                code.WriteSummaryXml("The the event log used to write events for this resource file");
                code.WriteLine("internal static readonly string EventLogName = @\"{0}\";", String.IsNullOrEmpty(_options.EventLog) ? "Application" : _options.EventLog);

                code.WriteLine();
                code.WriteSummaryXml("The category id used to write events for this resource file");
                code.WriteLine("internal static readonly int EventCategoryId = {0};", Math.Max(0, _options.EventCategoryId));

                if (String.IsNullOrEmpty(_eventLogger))
                {
                    code.WriteLine();
                    code.WriteSummaryXml("Writes an event log for the specified message id and arguments");
                    using (code.WriteBlock("internal static void WriteEvent(string eventLog, string eventSource, int category, System.Diagnostics.EventLogEntryType eventType, long eventId, object[] arguments, System.Exception error)"))
                        using (code.WriteBlock("using (System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(eventLog, \".\", eventSource))"))
                            code.WriteLine("log.WriteEvent(new System.Diagnostics.EventInstance(eventId, category, eventType), null, arguments);");
                }
            }
        }