Пример #1
0
 private static string GetCodeElementName(string xmlName)
 {
     // Legacy support. Remove later. (Written 2014-01-10)
     xmlName = xmlName.Replace("__sbo__", "<").Replace("__sbc__", ">");
     return(XmlConvert.DecodeName(xmlName));
 }
Пример #2
0
 private void WritePrimitive(XElement element, object obj)
 {
     if (obj is bool)
     {
         element.Value = XmlConvert.ToString((bool)obj);
     }
     else if (obj is byte)
     {
         element.Value = XmlConvert.ToString((byte)obj);
     }
     else if (obj is char)
     {
         element.Value = XmlConvert.EncodeName(XmlConvert.ToString((char)obj));
     }
     else if (obj is sbyte)
     {
         element.Value = XmlConvert.ToString((sbyte)obj);
     }
     else if (obj is short)
     {
         element.Value = XmlConvert.ToString((short)obj);
     }
     else if (obj is ushort)
     {
         element.Value = XmlConvert.ToString((ushort)obj);
     }
     else if (obj is int)
     {
         element.Value = XmlConvert.ToString((int)obj);
     }
     else if (obj is uint)
     {
         element.Value = XmlConvert.ToString((uint)obj);
     }
     else if (obj is long)
     {
         element.Value = XmlConvert.ToString((long)obj);
     }
     else if (obj is ulong)
     {
         element.Value = XmlConvert.ToString((decimal)(ulong)obj);
     }
     else if (obj is float)
     {
         element.Value = XmlConvert.ToString((float)obj);
     }
     else if (obj is double)
     {
         element.Value = XmlConvert.ToString((double)obj);
     }
     else if (obj is decimal)
     {
         element.Value = XmlConvert.ToString((decimal)obj);
     }
     else if (obj is string)
     {
         string strVal = obj as string;
         if (IsValidXmlString(strVal))
         {
             element.Value = strVal;
         }
         else
         {
             element.Add(new XCData(Convert.ToBase64String(Encoding.UTF8.GetBytes(strVal))));
         }
     }
     else if (obj == null)
     {
         throw new ArgumentNullException("obj");
     }
     else
     {
         throw new ArgumentException(string.Format("Type '{0}' is not a primitive.", obj.GetType()));
     }
 }
        /// <summary>
        /// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or
        /// xdt:yearMonthDuration rules.
        /// </summary>
        internal string ToString(DurationType durationType)
        {
            StringBuilder sb = new StringBuilder(20);
            int           nanoseconds, digit, zeroIdx, len;

            if (IsNegative)
            {
                sb.Append('-');
            }

            sb.Append('P');

            if (durationType != DurationType.DayTimeDuration)
            {
                if (this.years != 0)
                {
                    sb.Append(XmlConvert.ToString(this.years));
                    sb.Append('Y');
                }

                if (this.months != 0)
                {
                    sb.Append(XmlConvert.ToString(this.months));
                    sb.Append('M');
                }
            }

            if (durationType != DurationType.YearMonthDuration)
            {
                if (this.days != 0)
                {
                    sb.Append(XmlConvert.ToString(this.days));
                    sb.Append('D');
                }

                if (this.hours != 0 || this.minutes != 0 || this.seconds != 0 || Nanoseconds != 0)
                {
                    sb.Append('T');
                    if (this.hours != 0)
                    {
                        sb.Append(XmlConvert.ToString(this.hours));
                        sb.Append('H');
                    }

                    if (this.minutes != 0)
                    {
                        sb.Append(XmlConvert.ToString(this.minutes));
                        sb.Append('M');
                    }

                    nanoseconds = Nanoseconds;
                    if (this.seconds != 0 || nanoseconds != 0)
                    {
                        sb.Append(XmlConvert.ToString(this.seconds));
                        if (nanoseconds != 0)
                        {
                            sb.Append('.');

                            len        = sb.Length;
                            sb.Length += 9;
                            zeroIdx    = sb.Length - 1;

                            for (int idx = zeroIdx; idx >= len; idx--)
                            {
                                digit   = nanoseconds % 10;
                                sb[idx] = (char)(digit + '0');

                                if (zeroIdx == idx && digit == 0)
                                {
                                    zeroIdx--;
                                }

                                nanoseconds /= 10;
                            }

                            sb.Length = zeroIdx + 1;
                        }
                        sb.Append('S');
                    }
                }

                // Zero is represented as "PT0S"
                if (sb[sb.Length - 1] == 'P')
                {
                    sb.Append("T0S");
                }
            }
            else
            {
                // Zero is represented as "T0M"
                if (sb[sb.Length - 1] == 'P')
                {
                    sb.Append("0M");
                }
            }

            return(sb.ToString());
        }
Пример #4
0
 private static string GetXmlElementName(string codeName)
 {
     return(XmlConvert.EncodeName(codeName));
 }
Пример #5
0
        private object ReadObjectData(XElement element)
        {
            // Empty element without type data? Return null
            if (element.IsEmpty && !element.HasAttributes)
            {
                return(null);
            }

            // Read data type header
            string objIdString = element.GetAttributeValue("id");
            string dataTypeStr = element.GetAttributeValue("dataType");
            string typeStr     = element.GetAttributeValue("type");

            uint objId = objIdString == null ? 0 : XmlConvert.ToUInt32(objIdString);

            DataType dataType = DataType.Unknown;

            if (!Enum.TryParse <DataType>(dataTypeStr, out dataType))
            {
                if (dataTypeStr == "Class")                 // Legacy support (Written 2014-03-10)
                {
                    dataType = DataType.Struct;
                }
                if (dataTypeStr == "MethodInfo" ||                 // Legacy support (Written 2015-06-07)
                    dataTypeStr == "ConstructorInfo" ||
                    dataTypeStr == "PropertyInfo" ||
                    dataTypeStr == "FieldInfo" ||
                    dataTypeStr == "EventInfo")
                {
                    dataType = DataType.MemberInfo;
                }
                else
                {
                    dataType = DataType.Unknown;
                }
            }

            Type type = null;

            if (typeStr != null)
            {
                type = this.ResolveType(typeStr, objId);
            }

            ObjectHeader header = (type != null) ?
                                  new ObjectHeader(objId, dataType, GetSerializeType(type)) :
                                  new ObjectHeader(objId, dataType, typeStr);

            if (header.DataType == DataType.Unknown)
            {
                this.LocalLog.WriteError("Unable to process DataType: {0}.", dataTypeStr);
                return(null);
            }

            // Read object
            object result = null;

            try
            {
                // Read the objects body
                result = this.ReadObjectBody(element, header);
            }
            catch (Exception e)
            {
                this.LocalLog.WriteError("Error reading object: {0}", Log.Exception(e));
            }

            return(result);
        }
Пример #6
0
        private object ReadStruct(XElement element, ObjectHeader header)
        {
            // Read struct type
            string customString    = element.GetAttributeValue("custom");
            string surrogateString = element.GetAttributeValue("surrogate");
            bool   custom          = customString != null && XmlConvert.ToBoolean(customString);
            bool   surrogate       = surrogateString != null && XmlConvert.ToBoolean(surrogateString);

            // Retrieve surrogate if requested
            ISerializeSurrogate objSurrogate = null;

            if (surrogate && header.SerializeType != null)
            {
                objSurrogate = header.SerializeType.Surrogate;
            }

            // Construct object
            object obj = null;

            if (header.ObjectType != null)
            {
                if (objSurrogate != null)
                {
                    custom = true;

                    // Set fake object reference for surrogate constructor: No self-references allowed here.
                    this.idManager.Inject(null, header.ObjectId);

                    CustomSerialIO customIO            = new CustomSerialIO();
                    XElement       customHeaderElement = element.Element(CustomSerialIO.HeaderElement) ?? element.Elements().FirstOrDefault();
                    if (customHeaderElement != null)
                    {
                        customIO.Deserialize(this, customHeaderElement);
                    }
                    try { obj = objSurrogate.ConstructObject(customIO, header.ObjectType); }
                    catch (Exception e) { this.LogCustomDeserializationError(header.ObjectId, header.ObjectType, e); }
                }
                if (obj == null)
                {
                    obj = header.ObjectType.CreateInstanceOf();
                }
            }

            // Prepare object reference
            this.idManager.Inject(obj, header.ObjectId);

            // Read custom object data
            if (custom)
            {
                CustomSerialIO customIO          = new CustomSerialIO();
                XElement       customBodyElement = element.Element(CustomSerialIO.BodyElement) ?? element.Elements().ElementAtOrDefault(1);
                if (customBodyElement != null)
                {
                    customIO.Deserialize(this, customBodyElement);
                }

                ISerializeExplicit objAsCustom;
                if (objSurrogate != null)
                {
                    objSurrogate.RealObject = obj;
                    objAsCustom             = objSurrogate.SurrogateObject;
                }
                else
                {
                    objAsCustom = obj as ISerializeExplicit;
                }

                if (objAsCustom != null)
                {
                    try { objAsCustom.ReadData(customIO); }
                    catch (Exception e) { this.LogCustomDeserializationError(header.ObjectId, header.ObjectType, e); }
                }
                else if (obj != null && header.ObjectType != null)
                {
                    this.LocalLog.WriteWarning(
                        "Object data (Id {0}) is flagged for custom deserialization, yet the objects Type ('{1}') does not support it. Guessing associated fields...",
                        header.ObjectId,
                        Log.Type(header.ObjectType));
                    this.LocalLog.PushIndent();
                    foreach (var pair in customIO.Data)
                    {
                        this.AssignValueToField(header.SerializeType, obj, pair.Key, pair.Value);
                    }
                    this.LocalLog.PopIndent();
                }
            }
            // Red non-custom object data
            else if (!element.IsEmpty)
            {
                // Read fields
                object fieldValue;
                foreach (XElement fieldElement in element.Elements())
                {
                    fieldValue = this.ReadObjectData(fieldElement);
                    this.AssignValueToField(header.SerializeType, obj, GetCodeElementName(fieldElement.Name.LocalName), fieldValue);
                }
            }

            return(obj);
        }
Пример #7
0
 private void ReadArrayData(XElement element, out int[] array)
 {
     this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToInt32(s));
 }
Пример #8
0
 private void WriteEnum(XElement element, Enum obj, ObjectHeader header)
 {
     element.SetAttributeValue("name", obj.ToString());
     element.SetAttributeValue("value", XmlConvert.ToString(Convert.ToInt64(obj)));
 }
Пример #9
0
 private void ReadArrayData(XElement element, out bool[] array)
 {
     this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToBoolean(s));
 }
Пример #10
0
 private void ReadArrayData(XElement element, out sbyte[] array)
 {
     this.ReadPrimitiveArrayData(element, out array, s => (sbyte)XmlConvert.ToInt16(s));
 }
Пример #11
0
 internal override void WriteChar(char value)
 {
     WriteString(XmlConvert.ToString(value));
 }
Пример #12
0
        /// <summary>
        /// Gets the value for the specified <see cref="XAttribute"/>.
        /// </summary>
        /// <typeparam name="T">The resultant value <see cref="Type"/>.</typeparam>
        /// <param name="xml">The <see cref="XElement"/>.</param>
        /// <param name="name">The <see cref="XAttribute"/> name.</param>
        /// <param name="defaultVal">The default value where not found.</param>
        /// <param name="mandatory">Indicates that the attribute value is mandatory and must exist.</param>
        /// <returns>The attribute value.</returns>
        internal static T GetXmlVal <T>(XElement xml, string name, T defaultVal, bool mandatory)
        {
            if (xml.Attribute(name) == null)
            {
                if (mandatory)
                {
                    throw new CodeGenException($"Attribute '{name}' value not found; is mandatory.");
                }
                else
                {
                    return(defaultVal);
                }
            }

            string val = xml.Attribute(name).Value;

            try
            {
                if (typeof(T) == typeof(string))
                {
                    if (val.Length == 0)
                    {
                        if (mandatory)
                        {
                            throw new CodeGenException($"Attribute '{name}' has no value; is mandatory.");
                        }
                        else
                        {
                            return(defaultVal);
                        }
                    }
                    else
                    {
                        return((T)(object)val);
                    }
                }
                else if (typeof(T) == typeof(bool))
                {
                    return((T)(object)XmlConvert.ToBoolean(val));
                }
                else if (typeof(T) == typeof(int))
                {
                    return((T)(object)XmlConvert.ToInt32(val));
                }
                else if (typeof(T) == typeof(Enum))
                {
                    return((T)Enum.Parse(typeof(T), val));
                }
                else
                {
                    throw new CodeGenException($"Attribute '{name} value can not be converted to Type {typeof(T).Name}.");
                }
            }
            catch (FormatException fex)
            {
                throw new CodeGenException($"Attribute '{name}' value can not be converted to Type {typeof(T).Name}: {fex.Message}");
            }
            catch (ArgumentException aex)
            {
                throw new CodeGenException($"Attribute '{name}' value can not be converted to Type {typeof(T).Name}: {aex.Message}");
            }
        }
Пример #13
0
        internal static XElement CreateTable(int rowCount, int[] columnWidths)
        {
            XElement newTable =
                new XElement
                (
                    XName.Get("tbl", DocX.w.NamespaceName),
                    new XElement
                    (
                        XName.Get("tblPr", DocX.w.NamespaceName),
                        new XElement(XName.Get("tblStyle", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "TableGrid")),
                        new XElement(XName.Get("tblW", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), "5000"), new XAttribute(XName.Get("type", DocX.w.NamespaceName), "auto")),
                        new XElement(XName.Get("tblLook", DocX.w.NamespaceName), new XAttribute(XName.Get("val", DocX.w.NamespaceName), "04A0"))
                    )
                );

            XElement tableGrid = new XElement(XName.Get("tblGrid", DocX.w.NamespaceName));

            for (int i = 0; i < columnWidths.Length; i++)
            {
                tableGrid.Add(new XElement(XName.Get("gridCol", DocX.w.NamespaceName), new XAttribute(XName.Get("w", DocX.w.NamespaceName), XmlConvert.ToString(columnWidths[i]))));
            }

            newTable.Add(tableGrid);

            for (int i = 0; i < rowCount; i++)
            {
                XElement row = new XElement(XName.Get("tr", DocX.w.NamespaceName));

                for (int j = 0; j < columnWidths.Length; j++)
                {
                    XElement cell = CreateTableCell();
                    row.Add(cell);
                }

                newTable.Add(row);
            }
            return(newTable);
        }
Пример #14
0
        private void WriteArray(XElement element, object obj, ObjectHeader header)
        {
            Array    objAsArray      = obj as Array;
            TypeInfo arrayTypeInfo   = header.ObjectType;
            Type     elementType     = arrayTypeInfo.GetElementType();
            TypeInfo elementTypeInfo = elementType.GetTypeInfo();

            if (objAsArray.Rank != 1)
            {
                throw new NotSupportedException("Non single-Rank arrays are not supported");
            }
            if (objAsArray.GetLowerBound(0) != 0)
            {
                throw new NotSupportedException("Non zero-based arrays are not supported");
            }

            // If it's a primitive array, save the values as a comma-separated list
            if (elementType == typeof(bool))
            {
                this.WriteArrayData(element, objAsArray as bool[]);
            }
            else if (elementType == typeof(byte))
            {
                this.WriteArrayData(element, objAsArray as byte[]);
            }
            else if (elementType == typeof(sbyte))
            {
                this.WriteArrayData(element, objAsArray as sbyte[]);
            }
            else if (elementType == typeof(short))
            {
                this.WriteArrayData(element, objAsArray as short[]);
            }
            else if (elementType == typeof(ushort))
            {
                this.WriteArrayData(element, objAsArray as ushort[]);
            }
            else if (elementType == typeof(int))
            {
                this.WriteArrayData(element, objAsArray as int[]);
            }
            else if (elementType == typeof(uint))
            {
                this.WriteArrayData(element, objAsArray as uint[]);
            }
            else if (elementType == typeof(long))
            {
                this.WriteArrayData(element, objAsArray as long[]);
            }
            else if (elementType == typeof(ulong))
            {
                this.WriteArrayData(element, objAsArray as ulong[]);
            }
            else if (elementType == typeof(float))
            {
                this.WriteArrayData(element, objAsArray as float[]);
            }
            else if (elementType == typeof(double))
            {
                this.WriteArrayData(element, objAsArray as double[]);
            }
            else if (elementType == typeof(decimal))
            {
                this.WriteArrayData(element, objAsArray as decimal[]);
            }
            // Any non-trivial object data will be serialized recursively
            else
            {
                int nonDefaultElementCount = this.GetArrayNonDefaultElementCount(objAsArray, elementTypeInfo);

                // Write Array elements
                for (int i = 0; i < nonDefaultElementCount; i++)
                {
                    XElement itemElement = new XElement("item");
                    element.Add(itemElement);

                    this.WriteObjectData(itemElement, objAsArray.GetValue(i));
                }

                // Write original length, in case trailing elements were omitted or we have an (XML-ambiguous) zero-element array.
                if (nonDefaultElementCount != objAsArray.Length || nonDefaultElementCount == 0)
                {
                    element.SetAttributeValue("length", XmlConvert.ToString(objAsArray.Length));
                }
            }
        }
Пример #15
0
 private void ReadArrayData(XElement element, out ulong[] array)
 {
     this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToUInt64(s));
 }
Пример #16
0
        private void WriteStruct(XElement element, object obj, ObjectHeader header)
        {
            ISerializeExplicit  objAsCustom  = obj as ISerializeExplicit;
            ISerializeSurrogate objSurrogate = header.SerializeType.Surrogate;

            // If we're serializing a value type, skip the entire object body if
            // it equals the zero-init struct. This will keep struct-heavy data a lot
            // more concise.
            if (header.ObjectType.IsValueType &&
                object.Equals(obj, header.SerializeType.DefaultValue))
            {
                return;
            }

            // Write information about custom or surrogate serialization
            if (objAsCustom != null)
            {
                element.SetAttributeValue("custom", XmlConvert.ToString(true));
            }
            if (objSurrogate != null)
            {
                element.SetAttributeValue("surrogate", XmlConvert.ToString(true));
            }

            if (objSurrogate != null)
            {
                objSurrogate.RealObject = obj;
                objAsCustom             = objSurrogate.SurrogateObject;

                CustomSerialIO customIO = new CustomSerialIO();
                try { objSurrogate.WriteConstructorData(customIO); }
                catch (Exception e) { this.LogCustomSerializationError(header.ObjectId, header.ObjectType, e); }

                XElement customHeaderElement = new XElement(CustomSerialIO.HeaderElement);
                element.Add(customHeaderElement);
                customIO.Serialize(this, customHeaderElement);
            }

            if (objAsCustom != null)
            {
                CustomSerialIO customIO = new CustomSerialIO();
                try { objAsCustom.WriteData(customIO); }
                catch (Exception e) { this.LogCustomSerializationError(header.ObjectId, header.ObjectType, e); }

                XElement customBodyElement = new XElement(CustomSerialIO.BodyElement);
                element.Add(customBodyElement);
                customIO.Serialize(this, customBodyElement);
            }
            else
            {
                // Write the structs fields
                foreach (FieldInfo field in header.SerializeType.Fields)
                {
                    if (this.IsFieldBlocked(field, obj))
                    {
                        continue;
                    }

                    XElement fieldElement = new XElement(GetXmlElementName(field.Name));
                    element.Add(fieldElement);

                    this.WriteObjectData(fieldElement, field.GetValue(obj));
                }
            }
        }
Пример #17
0
 private void ReadArrayData(XElement element, out float[] array)
 {
     this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToSingle(s));
 }
Пример #18
0
 private void WriteArrayData(XElement element, decimal[] array)
 {
     this.WritePrimitiveArrayData(element, array, v => XmlConvert.ToString(v));
 }
Пример #19
0
 private void ReadArrayData(XElement element, out double[] array)
 {
     this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToDouble(s));
 }
Пример #20
0
        private Array ReadArray(XElement element, ObjectHeader header)
        {
            Array arrObj;
            Type  elementType = (header.ObjectType != null) ? header.ObjectType.GetElementType() : null;

            // Determine the array length based on child elements or explicit value
            string explicitLengthString = element.GetAttributeValue("length");
            int    explicitLength       = explicitLengthString == null ? -1 : XmlConvert.ToInt32(explicitLengthString);

            // Expect the "complex" array format, if there are child elements or an explicit length (children may be omitted)
            bool isComplex = element.Elements().Any() || explicitLength != -1;
            bool isEmpty   = explicitLength == 0 || (!isComplex && string.IsNullOrEmpty(element.Value));

            // Early-out: Create an empty array
            if (isEmpty)
            {
                arrObj = elementType != null?Array.CreateInstance(elementType, 0) : null;

                this.idManager.Inject(arrObj, header.ObjectId);
            }
            // Read a primitive value array
            else if (!isComplex)
            {
                if (elementType == typeof(bool))
                {
                    bool[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(byte))
                {
                    byte[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(sbyte))
                {
                    sbyte[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(short))
                {
                    short[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(ushort))
                {
                    ushort[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(int))
                {
                    int[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(uint))
                {
                    uint[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(long))
                {
                    long[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(ulong))
                {
                    ulong[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(float))
                {
                    float[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(double))
                {
                    double[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else if (elementType == typeof(decimal))
                {
                    decimal[] array; this.ReadArrayData(element, out array); arrObj = array;
                }
                else
                {
                    this.LocalLog.WriteWarning("Can't read primitive value array. Unknown element type '{0}'. Discarding data.", Log.Type(elementType));
                    arrObj = elementType != null?Array.CreateInstance(elementType, 0) : null;
                }

                // Set object reference
                this.idManager.Inject(arrObj, header.ObjectId);
            }
            // Read a complex value array, where each item is an XML element
            else
            {
                SerializeType elementSerializeType = GetSerializeType(elementType);
                int           arrLength            = explicitLength != -1 ? explicitLength : element.Elements().Count();

                // Prepare object reference
                arrObj = elementType != null?Array.CreateInstance(elementType, arrLength) : null;

                this.idManager.Inject(arrObj, header.ObjectId);

                int itemIndex = 0;
                foreach (XElement itemElement in element.Elements())
                {
                    object item = this.ReadObjectData(itemElement);
                    this.AssignValueToArray(elementSerializeType, arrObj, itemIndex, item);

                    itemIndex++;
                    if (itemIndex >= arrLength)
                    {
                        break;
                    }
                }
            }

            return(arrObj);
        }
Пример #21
0
 private void ReadArrayData(XElement element, out decimal[] array)
 {
     this.ReadPrimitiveArrayData(element, out array, s => XmlConvert.ToDecimal(s));
 }
Пример #22
0
        /// <summary>
        /// Generates C# code for the task
        /// </summary>
        public string GenerateCSharpCode()
        {
            string customTaskCode = "";

            customTaskCode += "[TaskName(\"" + _tagName + "\")]\n";
            customTaskCode += "public class " + _tagName + " : Task\n";
            customTaskCode += "{\n";
            customTaskCode += "\n";
            customTaskCode += "    static private string _originalXml = XmlConvert.DecodeName(\"" + XmlConvert.EncodeLocalName(_tasks.Xml.OuterXml) + "\");\n";
            customTaskCode += "\n";

            // generate named string parameters
            Log(Level.Verbose, "Number of string parameters: " + StringParams.Count);
            foreach (StringParam stringParam in StringParams)
            {
                customTaskCode += "    private string __" + stringParam.ParameterName + " = string.Empty ;\n";
                customTaskCode += "\n";
                customTaskCode += "    [TaskAttribute(\"" + stringParam.ParameterName + "\", Required=" + stringParam.Required.ToString().ToLower() + ")]\n";
                customTaskCode += "    public string _" + stringParam.ParameterName + "\n";
                customTaskCode += "    {\n";
                customTaskCode += "        get { return __" + stringParam.ParameterName + "; }\n";
                customTaskCode += "        set { __" + stringParam.ParameterName + " = value; }\n";
                customTaskCode += "    }\n";
                customTaskCode += "\n";
            }

            // generate named xml-node parameters
            Log(Level.Verbose, "Number of node parameters: " + NodeParams.Count);
            foreach (NodeParam nodeParam in NodeParams)
            {
                customTaskCode += "    private RawXml __" + nodeParam.ParameterName + ";\n";
                customTaskCode += "\n";
                customTaskCode += "    [BuildElement(\"" + nodeParam.ParameterName + "\", Required=" + nodeParam.Required.ToString().ToLower() + ")]\n";
                customTaskCode += "    public RawXml _" + nodeParam.ParameterName + "\n";
                customTaskCode += "    {\n";
                customTaskCode += "        get { return __" + nodeParam.ParameterName + "; }\n";
                customTaskCode += "        set { __" + nodeParam.ParameterName + " = value; }\n";
                customTaskCode += "    }\n";
                customTaskCode += "\n";
            }

            customTaskCode += "    protected override void ExecuteTask()\n";
            customTaskCode += "    {\n";

            customTaskCode += "        Log(Level.Verbose, \"Running custom script\");\n";
            customTaskCode += "        Log(Level.Verbose, \"Original script : \" + _originalXml);\n";
            customTaskCode += "        string xml = _originalXml;\n";

            customTaskCode += "        XmlDocument scriptDom = new XmlDocument();\n";
            customTaskCode += "        scriptDom.LoadXml(xml);\n";

            // generate string replacements for each nodeParam
            if (NodeParams.Count > 0)
            {
                customTaskCode += "        XmlNodeList nodes;\n";
            }
            foreach (NodeParam nodeParam in NodeParams)
            {
                customTaskCode += "        nodes = scriptDom.SelectNodes(\"//*[local-name()='__" + nodeParam.ParameterName + "__']\");\n";
                customTaskCode += "        foreach (XmlNode node in nodes)\n";
                customTaskCode += "        {\n";
                customTaskCode += "            if (_" + nodeParam.ParameterName + " != null)\n";
                customTaskCode += "            {\n";
                customTaskCode += "                foreach (XmlNode task in _" + nodeParam.ParameterName + ".Xml.ChildNodes)\n";
                customTaskCode += "                {\n";
                customTaskCode += "                    node.ParentNode.InsertBefore(scriptDom.ImportNode(task, true), node);\n";
                customTaskCode += "                }\n";
                customTaskCode += "            }\n";
                customTaskCode += "            node.ParentNode.RemoveChild(node);\n";
                customTaskCode += "        }\n";
            }

            // generate string replacements for each stringParam
            customTaskCode += "        xml = scriptDom.OuterXml;\n";
            foreach (StringParam stringParam in StringParams)
            {
                customTaskCode += "        xml = xml.Replace(\"__" + stringParam.ParameterName + "__\", _" + stringParam.ParameterName + ");\n";
            }
            customTaskCode += "        scriptDom.LoadXml(xml);\n";

            customTaskCode += "        Log(Level.Verbose, \"Generated script: \" + scriptDom.InnerXml);\n";
            customTaskCode += "        foreach (XmlNode node in scriptDom.ChildNodes[0].ChildNodes)\n";
            customTaskCode += "        {\n";
            customTaskCode += "            if (node.Name == \"#comment\")\n";
            customTaskCode += "                continue;\n";
            customTaskCode += "            Log(Level.Verbose, \"Running task: \" + node.OuterXml);\n";
            customTaskCode += "            Project.CreateTask(node).Execute();\n";
            customTaskCode += "        }\n";

            customTaskCode += "    }\n";
            customTaskCode += "}\n";

            return(customTaskCode);
        }
Пример #23
0
        static string RemoveInvalidXmlChars(string text)
        {
            var validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();

            return(new string(validXmlChars));
        }