예제 #1
0
        bool ProcessItem(ResxGenItem item, ref ResXDataNode node, List <ResXDataNode> allNodes)
        {
            if (NextMessageId < 0)
            {
                return(false);
            }

            if (node.FileRef != null)
            {
                return(false);
            }
            try
            {
                if (typeof(String) != Type.GetType(node.GetValueTypeName(new System.Reflection.AssemblyName[0])))
                {
                    return(false);
                }
            }
            catch { return(false); }

            string hr;

            if (!item.TryGetOption("MessageId", out hr))
            {
                bool hasOptions = node.Comment.IndexOf('#') >= 0;
                node.Comment = String.Format("{0}{1}MessageId={2}", node.Comment, !hasOptions ? " #" : ", ", NextMessageId++).Trim();
                return(true);
            }

            return(false);
        }
 void WriteAutoLog(CsWriter code, ResxGenItem item)
 {
     code.WriteSummaryXml("Prepares the arguments as strings and writes the event");
     using (code.WriteBlock("private void WriteEvent({0})", item.Parameters(true)))
     {
         WriteEventLogCall(code, item);
     }
 }
        void WriteEventLogCall(CsWriter code, ResxGenItem item)
        {
            Dictionary <int, string> formatting = new Dictionary <int, string>();

            for (int i = 0; i < item.Args.Count; i++)
            {
                formatting[i] = "{0}";
            }
            foreach (Match m in RegexPatterns.FormatSpecifier.Matches(item.Value))
            {
                Group field = m.Groups["field"];
                int   ix;
                if (int.TryParse(field.Value, out ix))
                {
                    formatting[ix] = String.Format("{0}0{1}",
                                                   m.Value.Substring(0, field.Index - m.Index),
                                                   m.Value.Substring(field.Index + field.Length - m.Index));
                }
            }

            code.WriteLine("string[] ctorEventArguments = new string[] {");
            for (int i = 0; i < item.Args.Count; i++)
            {
                code.WriteLine("{0}.ExceptionStrings.SafeFormat(@\"{1}\", {2}),", _fullClassName, formatting[i], item.Args[i].ParamName);
            }
            code.WriteLine("};");

            using (code.WriteBlock("try"))
            {
                EventLogEntryType etype = item.MessageId < 0x80000000
                                              ? EventLogEntryType.Information
                                              : ((item.MessageId & 0xC0000000) == 0xC0000000)
                                                    ? EventLogEntryType.Error
                                                    : EventLogEntryType.Warning;
                string logMethod = String.IsNullOrEmpty(_eventLogger)
                                       ? String.Format("{0}.WriteEvent", _fullClassName)
                                       : _eventLogger;
                code.WriteLine("{0}(", logMethod);
                code.Indent++;
                code.WriteLine("{0}.EventLogName,", _fullClassName);
                code.WriteLine("{0}.EventSourceName,", _fullClassName);
                code.WriteLine("{0}.EventCategoryId,", _fullClassName);
                code.WriteLine("System.Diagnostics.EventLogEntryType.{0},", etype);
                code.WriteLine("0x0{0:X8}L, ctorEventArguments, {1});", item.MessageId, item.IsException ? "this" : "null");
                code.Indent--;
            }
            code.WriteLine("catch { }");
        }
예제 #4
0
        public IEnumerable <ResxGenItem> ReadFile(string filePath)
        {
            _defaultName = Path.GetFileNameWithoutExtension(filePath);
            bool   dirty                = false;
            string basePath             = Path.GetDirectoryName(filePath);
            List <ResXDataNode> options = new List <ResXDataNode>();
            List <ResXDataNode> nodes   = new List <ResXDataNode>();
            List <ResxGenItem>  items   = new List <ResxGenItem>();

            using (ResXResourceReader reader = new ResXResourceReader(filePath))
            {
                reader.BasePath         = basePath;
                reader.UseResXDataNodes = true;
                foreach (DictionaryEntry entry in reader)
                {
                    ResXDataNode node = (ResXDataNode)entry.Value;

                    if (ReadOption(node))
                    {
                        options.Add(node);
                    }
                    else
                    {
                        nodes.Add(node);
                    }
                }
            }

            for (int i = 0; i < nodes.Count; i++)
            {
                ResXDataNode node = nodes[i];
                ResxGenItem  item = new ResxGenItem(this, node);

                if (ProcessItem(item, ref node, nodes))
                {
                    dirty    = true;
                    nodes[i] = node;
                    item     = new ResxGenItem(this, node);
                }

                items.Add(item);
            }

            if (dirty)
            {
                DateTime modified = new FileInfo(filePath).LastWriteTime;
                using (ResXResourceWriter writer = new ResXResourceWriter(filePath))
                {
                    writer.BasePath = basePath;

                    foreach (ResXDataNode node in UpdateOptions(options))
                    {
                        writer.AddResource(node);
                    }
                    foreach (ResXDataNode node in nodes)
                    {
                        writer.AddResource(node);
                    }

                    writer.Generate();
                }

                //This is stupid, but VStudio will continue to build if we don't
                new FileInfo(filePath).LastWriteTime = modified;
                Console.Error.WriteLine("Contents modified: {0}", filePath);
            }

            return(items);
        }
        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));
                }
            }
        }