private string ApplyTransform(string inputFile, XmlNode node, ProgressDialogWorkingOn dlg)
        {
            string progressPrompt = XmlUtils.GetManditoryAttributeValue(node, "progressPrompt");

            UpdateProgress(progressPrompt, dlg);
            string stylesheetName     = XmlUtils.GetManditoryAttributeValue(node, "stylesheetName");
            string stylesheetAssembly = XmlUtils.GetManditoryAttributeValue(node, "stylesheetAssembly");
            string outputFile         = Path.Combine(m_outputDirectory, Cache.ProjectId.Name + stylesheetName + "Result." + GetExtensionFromNode(node));

            XsltArgumentList        argumentList = CreateParameterList(node);
            IWritingSystemContainer wsContainer  = Cache.ServiceLocator.WritingSystems;

            if (argumentList.GetParam("prmVernacularFontSize", "") != null)
            {
                argumentList.RemoveParam("prmVernacularFontSize", "");
                argumentList.AddParam("prmVernacularFontSize", "", GetNormalStyleFontSize(wsContainer.DefaultVernacularWritingSystem.Handle));
            }
            if (argumentList.GetParam("prmGlossFontSize", "") != null)
            {
                argumentList.RemoveParam("prmGlossFontSize", "");
                argumentList.AddParam("prmGlossFontSize", "", GetNormalStyleFontSize(wsContainer.DefaultAnalysisWritingSystem.Handle));
            }

            var xmlReaderSettings = new XmlReaderSettings {
                DtdProcessing = DtdProcessing.Parse
            };

            using (var writer = new StreamWriter(outputFile))
                using (var reader = XmlReader.Create(inputFile, xmlReaderSettings))
                    GetTransform(stylesheetName, stylesheetAssembly).Transform(reader, argumentList, writer);
            return(outputFile);
        }
Exemple #2
0
        public object setParameter(string ns, object name, [Optional] string value)
        {
            PhpArray array = name as PhpArray;

            if (array != null)
            {
                // set all name => value pairs contained in the array
                foreach (KeyValuePair <IntStringKey, object> pair in array)
                {
                    if (!pair.Key.IsString)
                    {
                        PhpException.Throw(PhpError.Warning, Resources.InvalidParameterKey);
                        return(false);
                    }

                    if (xsltArgumentList.GetParam(pair.Key.String, ns) != null)
                    {
                        xsltArgumentList.RemoveParam(pair.Key.String, ns);
                    }
                    xsltArgumentList.AddParam(pair.Key.String, ns, XsltConvertor.PhpToDotNet(pair.Value));
                }
            }
            else
            {
                string name_str = PHP.Core.Convert.ObjectToString(name);

                if (xsltArgumentList.GetParam(name_str, ns) != null)
                {
                    xsltArgumentList.RemoveParam(name_str, ns);
                }
                xsltArgumentList.AddParam(name_str, ns, XsltConvertor.PhpToDotNet(value));
            }

            return(true);
        }
        public static XsltArgumentList GetArgumentListFromUrl()
        {
            XsltArgumentList arg = new XsltArgumentList();

            if (HttpContext.Current.Request.Url.Query == null ||
                HttpContext.Current.Request.Url.Query.Trim().Length == 0)
            {
                return(arg);
            }

            string uriPrms = HttpContext.Current.Request.Url.Query;

            if (uriPrms.Trim().Length > 0)
            {
                string   bfr  = uriPrms.Replace("?", "&");
                string[] prms = bfr.Split('&');
                foreach (string prmAndValue in prms)
                {
                    int equalPos = prmAndValue.IndexOf("="); //don't use split, may contain '=' in the value
                    if (equalPos > 0)
                    {
                        string prmName = System.Web.HttpUtility.HtmlDecode(prmAndValue.Substring(0, equalPos)).Trim();

                        if (arg.GetParam(prmName, "") == null)
                        {
                            string value = prmAndValue.Substring(equalPos + 1, prmAndValue.Length - equalPos - 1);
                            arg.AddParam(prmName, "", value);
                        }
                    }
                }
            }
            return(arg);
        }
Exemple #4
0
        public void AddXslParameter(string name, object value)
        {
            if (value == null)
            {
                return;
            }

            var arg = _args.GetParam(name, "");

            if (arg != null)
            {
                _args.RemoveParam(name, "");
            }

            _args.AddParam(name, "", value);
        }
Exemple #5
0
        internal object?GetGlobalParameter(XmlQualifiedName qname)
        {
            object?parameter = _args.GetParam(qname.Name, qname.Namespace);

            if (parameter == null)
            {
                return(null);
            }
            if (
                parameter is XPathNodeIterator ||
                parameter is XPathNavigator ||
                parameter is bool ||
                parameter is double ||
                parameter is string
                )
            {
                // doing nothing
            }
            else if (
                parameter is short || parameter is ushort ||
                parameter is int || parameter is uint ||
                parameter is long || parameter is ulong ||
                parameter is float || parameter is decimal
                )
            {
                parameter = XmlConvert.ToXPathDouble(parameter);
            }
            else
            {
                parameter = parameter.ToString();
            }
            return(parameter);
        }
        /// <summary>
        /// Recupera o valor da variável do usuário
        /// </summary>
        /// <param name="xsltContext">Contexto</param>
        /// <returns></returns>
        public object Evaluate(XsltContext xsltContext)
        {
            XsltArgumentList vars = ((CustomContext)xsltContext).ArgList;

            // O método GetParam é do contexto atual e é responsável por recuperar o valor da variável.
            return(vars.GetParam(VarName, Prefix));
        }
        internal object GetGlobalParameter(XmlQualifiedName qname)
        {
            object parameter = args.GetParam(qname.Name, qname.Namespace);

            if (parameter == null)
            {
                return(null);
            }
            if (
                parameter is XPathNodeIterator ||
                parameter is XPathNavigator ||
                parameter is Boolean ||
                parameter is Double ||
                parameter is String
                )
            {
                // doing nothing
            }
            else if (
                parameter is Int16 || parameter is UInt16 ||
                parameter is Int32 || parameter is UInt32 ||
                parameter is Int64 || parameter is UInt64 ||
                parameter is Single || parameter is Decimal
                )
            {
                parameter = XmlConvert.ToXPathDouble(parameter);
            }
            else
            {
                parameter = parameter.ToString();
            }
            return(parameter);
        }
Exemple #8
0
        public static StringWriter ShowListLabelNoPageIn(params string[] strString)
        {
            StringWriter output = new StringWriter();

            try
            {
                string           LableName = "";
                XsltArgumentList argsList  = new XsltArgumentList();
                argsList.AddExtensionObject("WP:BaseClass", new BaseClass());
                LableName = strString[0].Split('=')[1];
                string XMLPath        = BaseClass.GetListLabel() + LableName + ".config";
                string LableSqlString = XMLExplainer.GetXMLValue("root", "LabelSqlString", XMLPath);
                string LabelSqlCount  = XMLExplainer.GetXMLValue("root", "LabelSqlCount", XMLPath);
                string XsltString     = XMLExplainer.GetXMLValue("root", "LabelTemplate", XMLPath);
                for (int i = 1; i < strString.Length; i++)
                {
                    string   strObject  = strString[i];
                    string[] strObjects = strObject.Split('=');
                    LableSqlString = LableSqlString.Replace("@" + strObjects[0], strObjects[1]);
                    argsList.AddParam(strObjects[0], "", strObjects[1]);
                }
                DataTable DT = XMLExplainer.GetXMLValues("attributes", XMLPath);
                for (int i = 0; i < DT.Rows.Count; i++)
                {
                    LableSqlString = LableSqlString.Replace("@" + DT.Rows[i]["name"].ToString(), DT.Rows[i]["default"].ToString());
                    string tempstring = (string)argsList.GetParam(DT.Rows[i]["name"].ToString(), "");
                    try
                    {
                        argsList.AddParam(DT.Rows[i]["name"].ToString(), "", DT.Rows[i]["default"].ToString());
                    }
                    catch
                    {
                        continue;
                    }
                }
                XDocument source  = new XDocument();
                XDocument newTree = new XDocument();
                using (XmlWriter writer = newTree.CreateWriter())
                {
                    XslCompiledTransform xslt = new XslCompiledTransform();
                    xslt.Load(XmlReader.Create(new StringReader(XsltString)));
                    DataTable DTT = PersistenceLayer.Query.ProcessSql(LableSqlString, Names.DBName);
                    DataSet   DS  = new DataSet();
                    DS.Tables.Add(DTT);
                    string XmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
                    XmlStr = XmlStr + DS.GetXml().ToString();
                    XmlDocument XmlDoc = new XmlDocument();
                    XmlDoc.LoadXml(XmlStr);
                    XPathNavigator navgator = XmlDoc.CreateNavigator();
                    xslt.Transform(navgator, argsList, output);
                    return(output);
                }
            }
            catch (Exception ex)
            {
                output.Write(ex.Message.ToString());
                return(output);
            }
        }
 /// <summary>
 ///
 /// </summary>
 /// <param name="name"></param>
 /// <param name="value"></param>
 private void PutTransformParam(String name, Object value)
 {
     if (m_transformArguments.GetParam(name, String.Empty) != null)
     {
         m_transformArguments.RemoveParam(name, String.Empty);
     }
     m_transformArguments.AddParam(name, String.Empty, value);
 }
Exemple #10
0
        /// <summary>
        ///  Sets value for a parameter.
        /// </summary>
        /// <param name="ns">The namespace URI of the XSLT parameter.</param>
        /// <param name="name">The local name of the XSLT parameter or an array of name =&gt; option pairs.</param>
        /// <param name="value">The new value of the XSLT parameter.</param>
        /// <returns><B>True</B> or <B>false</B>.</returns>
        public bool setParameter(string ns, PhpArray name, string value = null)
        {
            // set all name => value pairs contained in the array
            foreach (var pair in name)
            {
                if (!pair.Key.IsString)
                {
                    PhpException.Throw(PhpError.Warning, Resources.InvalidParameterKey);
                    return(false);
                }

                if (xsltArgumentList.GetParam(pair.Key.String, ns) != null)
                {
                    xsltArgumentList.RemoveParam(pair.Key.String, ns);
                }
                xsltArgumentList.AddParam(pair.Key.String, ns, XsltConvertor.PhpToDotNet(_ctx, pair.Value));
            }

            return(true);
        }
Exemple #11
0
        /// <summary>
        /// 根据静态类样式展现HTML
        /// </summary>
        /// <returns></returns>
        public static StringWriter ShowStaticLabel(params string[] strString)
        {
            StringWriter output = new StringWriter();

            try
            {
                string           LableName = "";
                XsltArgumentList argsList  = new XsltArgumentList();
                argsList.AddExtensionObject("WP:BaseClass", new BaseClass());
                LableName = strString[0].Split('=')[1];
                string XMLPath    = BaseClass.GetStaticLabel() + LableName + ".config";
                string XsltString = XMLExplainer.GetXMLValue("root", "LabelTemplate", XMLPath);
                for (int i = 1; i < strString.Length; i++)
                {
                    string   strObject  = strString[i];
                    string[] strObjects = strObject.Split('=');
                    argsList.AddParam(strObjects[0], "", strObjects[1]);
                }
                DataTable DT = XMLExplainer.GetXMLValues("attributes", XMLPath);
                for (int i = 0; i < DT.Rows.Count; i++)
                {
                    string tempstring = (string)argsList.GetParam(DT.Rows[i]["name"].ToString(), "");
                    if ("".Equals(tempstring) || tempstring == null)
                    {
                        argsList.AddParam(DT.Rows[i]["name"].ToString(), "", DT.Rows[i]["default"].ToString());
                    }
                }
                XDocument source  = new XDocument();
                XDocument newTree = new XDocument();
                using (XmlWriter writer = newTree.CreateWriter())
                {
                    XslCompiledTransform xslt = new XslCompiledTransform();
                    xslt.Load(XmlReader.Create(new StringReader(XsltString)));
                    XmlDocument    XmlDoc   = new XmlDocument();
                    XPathNavigator navgator = XmlDoc.CreateNavigator();
                    xslt.Transform(navgator, argsList, output);
                    return(output);
                }
            }
            catch (Exception ex)
            {
                output.Write(ex.InnerException.ToString());
                return(output);
            }
        }
Exemple #12
0
        public void Process(XPathNavigator root, Outputter outputtter, XsltArgumentList args, XmlResolver resolver)
        {
            this.args     = args;
            this.root     = root;
            this.resolver = resolver != null ? resolver : new XmlUrlResolver();
            this.outputStylesheetXmlns = true;
            this.currentOutputUri      = String.Empty;

            XPathExpression exp = root.Compile(".");

            PushNodeset(root.Select(exp, this.XPathContext));

            // have to evaluate the params first, as Global vars may
            // be dependant on them
            if (args != null)
            {
                foreach (XslGlobalVariable v in CompiledStyle.Variables.Values)
                {
                    if (v is XslGlobalParam)
                    {
                        object p = args.GetParam(v.Name.Name, v.Name.Namespace);
                        if (p != null)
                        {
                            ((XslGlobalParam)v).Override(this, p);
                        }

                        v.Evaluate(this);
                    }
                }
            }

            foreach (XslGlobalVariable v in CompiledStyle.Variables.Values)
            {
                if (args == null || !(v is XslGlobalParam))
                {
                    v.Evaluate(this);
                }
            }

            PopNodeset();

            this.PushOutput(outputtter);
            this.ApplyTemplates(root.Select(exp, this.XPathContext), QName.Empty, null);
            this.PopOutput();
        }
Exemple #13
0
        /// <summary>
        /// Adds a new xsl parameter with to the specified argument list.
        /// </summary>
        /// <param name="name">The name of the parameter.</param>
        /// <param name="value">The value of the parameter.</param>
        /// <param name="parameters">The parameter list.</param>
        /// <returns>Whether the parameter was added.</returns>
        /// <remarks>Does not add the parameter
        /// when a parameter with the same name is already part of the <paramref name="parameters"/>.</remarks>
        private bool AddParameter(string name, string value, XsltArgumentList parameters)
        {
            bool result;

            if (parameters.GetParam(name, string.Empty) == null)
            {
                parameters.AddParam(name, string.Empty, value);

                Log.LogMessage(MessageImportance.Low, Resources.XsltAddingParameter, name, value);

                result = true;
            }
            else
            {
                // don't add the parameter when already provided by other xml metadata
                result = false;
            }
            return(result);
        }
		public void Process(XPathNavigator root, Outputter outputtter, XsltArgumentList args, XmlResolver resolver)
		{
			this.args = args;
			this.root = root;
			this.resolver = ((resolver == null) ? new XmlUrlResolver() : resolver);
			this.currentOutputUri = string.Empty;
			this.PushNodeset(new SelfIterator(root, this.XPathContext));
			this.CurrentNodeset.MoveNext();
			if (args != null)
			{
				foreach (object obj in this.CompiledStyle.Variables.Values)
				{
					XslGlobalVariable xslGlobalVariable = (XslGlobalVariable)obj;
					if (xslGlobalVariable is XslGlobalParam)
					{
						object param = args.GetParam(xslGlobalVariable.Name.Name, xslGlobalVariable.Name.Namespace);
						if (param != null)
						{
							((XslGlobalParam)xslGlobalVariable).Override(this, param);
						}
						xslGlobalVariable.Evaluate(this);
					}
				}
			}
			foreach (object obj2 in this.CompiledStyle.Variables.Values)
			{
				XslGlobalVariable xslGlobalVariable2 = (XslGlobalVariable)obj2;
				if (args == null || !(xslGlobalVariable2 is XslGlobalParam))
				{
					xslGlobalVariable2.Evaluate(this);
				}
			}
			this.PopNodeset();
			this.PushOutput(outputtter);
			this.ApplyTemplates(new SelfIterator(root, this.XPathContext), XmlQualifiedName.Empty, null);
			this.PopOutput();
		}
Exemple #15
0
 public object GetParam(string name, string ns)
 {
     return(args.GetParam(name, ns));
 }
Exemple #16
0
        //-----------------------------------------------
        // External parameters
        //-----------------------------------------------

        /// <summary>
        /// Get a named parameter from the external argument list.  Return null if no argument list was provided, or if
        /// there is no parameter by that name.
        /// </summary>
        public object GetParameter(string localName, string namespaceUri)
        {
            return((_argList != null) ? _argList.GetParam(localName, namespaceUri) : null);
        }
Exemple #17
0
        // Function to return the value of the specified user-defined variable.
        // The GetParam method of the XsltArgumentList property of the active
        // XsltContext object returns value assigned to the specified variable.
        public object Evaluate(XsltContext xsltContext)
        {
            XsltArgumentList vars = ((EasyXsltContext)xsltContext).ArgList;

            return(vars.GetParam(varName, prefix));
        }
 public object Get(string name)
 {
     return(xsltArgList.GetParam(name, NS));
 }
            // Function to return the value of the specified user-defined variable.
            // The GetParam method of the XsltArgumentList property of the active
            // XsltContext object returns value assigned to the specified variable.
            public object Evaluate(System.Xml.Xsl.XsltContext xsltContext)
            {
                XsltArgumentList vars = ((CustomContext)xsltContext).ArgList;

                return(vars.GetParam(varName, prefix));
            }
Exemple #20
0
        //-----------------------------------------------
        // External parameters
        //-----------------------------------------------

        /// <summary>
        /// Get a named parameter from the external argument list.  Return null if no argument list was provided, or if
        /// there is no parameter by that name.
        /// </summary>
        public object?GetParameter(string localName, string namespaceUri)
        {
            return(_argList?.GetParam(localName, namespaceUri));
        }
Exemple #21
0
        /// <summary>
        /// Gets the value of the variable specified
        /// </summary>
        /// <param name="xsltContext">Context in which this variable is used</param>
        /// <returns>Value of the variable</returns>
        public object Evaluate(XsltContext xsltContext)
        {
            XsltArgumentList args = ((ExtendedXPathFunctions)xsltContext).ArgumentList;

            return(args.GetParam(Name, ""));
        }
Exemple #22
0
        /// <summary>
        /// Gets the value of the variable specified
        /// </summary>
        /// <param name="xsltContext">Context in which this variable is used</param>
        /// <returns>Value of the variable</returns>
        public object Evaluate(XsltContext xsltContext)
        {
            XsltArgumentList args = ((CustomContext)xsltContext).ArgumentList;

            return(args.GetParam(Name, ""));
        }
Exemple #23
0
 /// <summary>
 /// This method gets a parameter by name.
 /// </summary>
 /// <param name="name">The name of the parameter</param>
 public object GetParam(string name)
 {
     return(_argumentList.GetParam(name, string.Empty));
 }
Exemple #24
0
        // Function to return the value of the specified user-defined variable.
        // The GetParam method of the XsltArgumentList property of the active
        // XsltContext object returns value assigned to the specified variable.
        public object Evaluate(XsltContext Context)
        {
            XsltArgumentList vars = ((CustomContext)Context).ArgList;

            return(vars.GetParam(m_VarName, m_Prefix));
        }
        /// <summary>
        /// Generate a code file for the current xml file contents. Loads
        /// settings for the file off the Plix.xml settings file in the project to
        /// get the generation transform and other settings to apply to the specific file.
        /// </summary>
        /// <param name="fileContents">Contents of an xml file to transform</param>
        /// <param name="defaultNamespace">The namespace provided in the property grid</param>
        /// <returns>Contents of the corresponding code file</returns>
        private string GenerateCode(string fileContents, string defaultNamespace)
        {
                        #if VerifyUIThread
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                        #endif

            // Make sure we have a CodeDomProvider
            CodeDomProvider provider = CodeDomProvider;
            if (provider == null)
            {
                return(string.Empty);
            }

            // Get the current project item and project information
            EnvDTE.ProjectItem projectItem     = CurrentProjectItem;
            string             sourceFile      = (string)projectItem.Properties.Item("LocalPath").Value;
            EnvDTE.Project     project         = projectItem.ContainingProject;
            string             projectFile     = (string)project.Properties.Item("LocalPath").Value;
            string             projectLocation = projectFile.Substring(0, projectFile.LastIndexOf('\\') + 1);

            // If this is the Plix.xml settings file, then regenerate all other mentioned NUPlixLoader files
            if (0 == string.Compare(projectItem.Name, PlixProjectSettingsFile, true, CultureInfo.InvariantCulture))
            {
                RunCustomTool(
                    project.ProjectItems,
                    projectItem,
                    delegate(EnvDTE.ProjectItem matchItem)
                {
                                                #if VerifyUIThread
                    Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                                                #endif

                    VSProjectItem vsProjItem = matchItem.Object as VSProjectItem;
                    if (vsProjItem != null)
                    {
                        vsProjItem.RunCustomTool();
                    }
                });
                StringWriter writer = new StringWriter();
                provider.GenerateCodeFromStatement(new CodeCommentStatement(
                                                       @"Empty file generated by NUPlixLoader for Plix.xml.

Setting NUPlixLoader as the custom tool on the Plix.xml settings file enables automatic
regeneration of other NUPlixLoader files in the project when the settings file is changed.

There is no way to both successfully trigger regeneration and avoid writing this file."), writer, null);
                return(writer.ToString());
            }

            // Load a language formatter for this file extension
            string fileExtension = CodeDomProvider.FileExtension;
            if (fileExtension.StartsWith("."))
            {
                fileExtension = fileExtension.Substring(1);
            }
            XslCompiledTransform formatter = FormatterManager.GetFormatterTransform(fileExtension);
            if (formatter == null)
            {
                StringWriter writer = new StringWriter();
                provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "A PLiX formatter transform for the '{0}' language was not found.", fileExtension)), writer, null);
                return(writer.ToString());
            }

            // Get options for this xml file
            XsltArgumentList arguments = new XsltArgumentList();
            string           automationObjectName;
            string           transformFile = LoadProjectSettings(sourceFile, projectLocation, arguments, project, out automationObjectName);

            // MSBUG: Beta2 There's a nasty bug with single-file generators right now where
            // the text for an open file that is not in a text document is
            // passed through as encoded bytes in the string.
            EnvDTE.Document itemDocument = projectItem.Document;
            if (itemDocument != null && "XML" != itemDocument.Language)
            {
                if (fileContents.Length > 1)
                {
                    char[]   leadChars = fileContents.ToCharArray(0, 2);
                    byte[]   leadBytes = new byte[2 * sizeof(char)];
                    GCHandle handle    = GCHandle.Alloc(leadBytes, GCHandleType.Pinned);
                    Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), 2);
                    handle.Free();
                    EncodingInfo[] encodingInfos  = Encoding.GetEncodings();
                    int            encodingsCount = encodingInfos.Length;
                    for (int i = 0; i < encodingsCount; ++i)
                    {
                        EncodingInfo encodingInfo      = encodingInfos[i];
                        Encoding     encoding          = encodingInfo.GetEncoding();
                        byte[]       preamble          = encoding.GetPreamble();
                        int          preambleByteCount = preamble.Length;
                        if (preambleByteCount != 0)
                        {
                            Debug.Assert(preambleByteCount <= 4);
                            int j;
                            for (j = 0; j < preambleByteCount; ++j)
                            {
                                if (preamble[j] != leadBytes[j])
                                {
                                    break;
                                }
                            }
                            if (j == preambleByteCount)
                            {
                                Decoder decoder = encoding.GetDecoder();
                                leadChars = fileContents.ToCharArray();
                                int startCharCount = leadChars.Length;
                                leadBytes = new byte[startCharCount * sizeof(char)];
                                int      byteCount = leadBytes.Length - preambleByteCount;
                                GCHandle handle2   = GCHandle.Alloc(leadBytes, GCHandleType.Pinned);
                                Marshal.Copy(leadChars, 0, Marshal.UnsafeAddrOfPinnedArrayElement(leadBytes, 0), startCharCount);
                                handle2.Free();
                                int    finalCharCount = decoder.GetCharCount(leadBytes, preambleByteCount, byteCount, true);
                                char[] finalChars     = new char[finalCharCount + 1];
                                decoder.GetChars(leadBytes, preambleByteCount, byteCount, finalChars, 0, true);

                                // Hack within a hack to make sure that the Xml element has a trailing >,
                                // byte data in a string has a tendency to lose the last byte
                                char testChar = finalChars[finalCharCount - 1];;
                                if (testChar != '>' && !char.IsWhiteSpace(testChar))
                                {
                                    finalChars[finalCharCount] = '>';
                                    ++finalCharCount;
                                }
                                fileContents = new string(finalChars, 0, finalCharCount);
                            }
                        }
                    }
                }
            }

            // Resolve any file redirections here. File redirection allows the same source file
            // to generate multiple outputs via multiple transforms.
            string alternateSourceFile = null;
            using (StringReader stringReader = new StringReader(fileContents))
            {
                try
                {
                    using (XmlTextReader reader = new XmlTextReader(stringReader))
                    {
                        if (XmlNodeType.Element == reader.MoveToContent())
                        {
                            if (reader.NamespaceURI == RedirectNamespace &&
                                reader.LocalName == RedirectElementName)
                            {
                                string   relativeTargetSourceFile = reader.GetAttribute(RedirectTargetAttribute);
                                FileInfo targetSourceFileInfo     = new FileInfo(sourceFile.Substring(0, sourceFile.LastIndexOf('\\') + 1) + relativeTargetSourceFile);
                                if (targetSourceFileInfo.Exists)
                                {
                                    alternateSourceFile = targetSourceFileInfo.FullName;
                                    sourceFile          = alternateSourceFile;
                                    try
                                    {
                                        itemDocument = null;
                                        itemDocument = project.DTE.Documents.Item(alternateSourceFile);
                                    }
                                    catch (ArgumentException)
                                    {
                                        // Swallow if the document is not open
                                    }
                                }
                                else
                                {
                                    StringWriter writer = new StringWriter();
                                    provider.GenerateCodeFromStatement(new CodeCommentStatement(string.Format(CultureInfo.InvariantCulture, "Redirection target file '{0}' not found", relativeTargetSourceFile)), writer, null);
                                    return(writer.ToString());
                                }
                            }
                        }
                    }
                }
                catch (XmlException ex)
                {
                    return(GenerateExceptionInformation(ex, provider));
                }
            }

            // Add standard defined attributes to the argument list
            string projectNamespace = (string)project.Properties.Item("DefaultNamespace").Value;
            if (null == arguments.GetParam("ProjectPath", ""))
            {
                arguments.AddParam("ProjectPath", "", projectLocation);
            }
            if (null == arguments.GetParam("SourceFile", ""))
            {
                arguments.AddParam("SourceFile", "", sourceFile.Substring(projectLocation.Length));
            }
            if (null == arguments.GetParam("CustomToolNamespace", ""))
            {
                if (defaultNamespace == null || defaultNamespace.Length == 0)
                {
                    defaultNamespace = projectNamespace;
                }
                arguments.AddParam("CustomToolNamespace", "", defaultNamespace);
            }
            if (null == arguments.GetParam("ProjectNamespace", ""))
            {
                arguments.AddParam("ProjectNamespace", "", projectNamespace);
            }

            try
            {
                XslCompiledTransform transform = null;
                if (transformFile != null)
                {
                    transform = new XslCompiledTransform();
                    using (FileStream transformStream = new FileStream(transformFile, FileMode.Open, FileAccess.Read))
                    {
                        using (StreamReader reader = new StreamReader(transformStream))
                        {
                            transform.Load(new XmlTextReader(reader), XsltSettings.TrustedXslt, XmlUtility.CreateFileResolver(transformFile));
                        }
                    }
                }
                MemoryStream plixStream = (transform != null) ? new MemoryStream() : null;
                using (XmlWriter xmlTextWriter = (transform != null) ? XmlWriter.Create(plixStream, transform.OutputSettings) : null)
                {
                    // Variables that need to be disposed
                    TextReader reader    = null;
                    Stream     docStream = null;

                    try
                    {
                        // First try to get data from the live object
                        string docText = null;
                        if (itemDocument != null)
                        {
                            if (automationObjectName != null)
                            {
                                docStream = itemDocument.Object(automationObjectName) as Stream;
                                if (docStream != null)
                                {
                                    reader = new StreamReader(docStream);
                                }
                            }

                            // Fall back on getting the contents of the text buffer from the live document
                            if (reader == null)
                            {
                                EnvDTE.TextDocument textDoc = itemDocument.Object("TextDocument") as EnvDTE.TextDocument;
                                if (textDoc != null)
                                {
                                    docText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint);
                                    reader  = new StringReader(docText);
                                }
                            }
                        }

                        // If this is a redirection, then pull direction from the file
                        if (reader == null && alternateSourceFile != null)
                        {
                            reader = new StreamReader(alternateSourceFile);
                        }

                        // Fallback on the default reading mechanism
                        if (reader == null)
                        {
                            docText = fileContents;
                            reader  = new StringReader(fileContents);
                        }

                        if (transform == null)
                        {
                            XmlReaderSettings testPlixDocumentReaderSettings = new XmlReaderSettings();
                            testPlixDocumentReaderSettings.CloseInput = false;
                            bool plixDocument = false;
                            try
                            {
                                using (XmlReader testPlixDocumentReader = XmlReader.Create(reader, testPlixDocumentReaderSettings))
                                {
                                    testPlixDocumentReader.MoveToContent();
                                    if (testPlixDocumentReader.NodeType == XmlNodeType.Element && testPlixDocumentReader.NamespaceURI == PlixSchemaNamespace)
                                    {
                                        plixDocument = true;
                                    }
                                }
                            }
                            catch (XmlException ex)
                            {
                                return(GenerateExceptionInformation(ex, provider));
                            }
                            if (!plixDocument)
                            {
                                StringWriter writer = new StringWriter();
                                provider.GenerateCodeFromStatement(new CodeCommentStatement("Transform file not found"), writer, null);
                                GenerateNUPlixLoaderExceptionLine(writer, provider);
                                return(writer.ToString());
                            }
                            if (docText != null)
                            {
                                reader.Dispose();
                                reader = new StringReader(docText);
                            }
                            else
                            {
                                StreamReader streamReader = (StreamReader)reader;
                                streamReader.BaseStream.Position = 0;
                            }
                        }
                        else
                        {
                            // Use an XmlTextReader here instead of an XPathDocument
                            // so that our transforms support the xsl:preserve-space element
                            transform.Transform(new XmlTextReader(reader), arguments, xmlTextWriter, XmlUtility.CreateFileResolver(sourceFile));
                            plixStream.Position = 0;
                        }
                        // From the plix stream, generate the code
                        using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
                        {
                            using (XmlReader plixReader = (plixStream != null) ? XmlReader.Create(plixStream, PlixReaderSettings) : XmlReader.Create(reader, PlixReaderSettings))
                            {
                                formatter.Transform(plixReader, new XsltArgumentList(), writer);
                            }
                            return(writer.ToString());
                        }
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            (reader as IDisposable).Dispose();
                        }
                        if (docStream != null)
                        {
                            (docStream as IDisposable).Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(GenerateExceptionInformation(ex, provider));
            }
            finally
            {
                // Regardless of how we finish process this file, we need to find files redirected to this
                // one and regenerate them.
                if (alternateSourceFile == null)                 // We only redirect one level
                {
                    FileInfo sourceFileInfo = new FileInfo(sourceFile);
                    RunCustomTool(
                        project.ProjectItems,
                        projectItem,
                        delegate(EnvDTE.ProjectItem matchItem)
                    {
                                                        #if VerifyUIThread
                        Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
                                                        #endif

                        VSProjectItem vsProjItem = matchItem.Object as VSProjectItem;
                        if (vsProjItem != null)
                        {
                            string itemFile = (string)matchItem.Properties.Item("LocalPath").Value;
                            EnvDTE.Document liveDoc;
                            EnvDTE.TextDocument textDoc;
                            string liveText = null;
                            if (null != (liveDoc = matchItem.Document) &&
                                null != (textDoc = liveDoc.Object("TextDocument") as EnvDTE.TextDocument))
                            {
                                liveText = textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint);
                            }
                            try
                            {
                                using (FileStream fileStream = (liveText == null) ? new FileStream(itemFile, FileMode.Open, FileAccess.Read) : null)
                                {
                                    using (XmlTextReader reader = new XmlTextReader((liveText == null) ? new StreamReader(fileStream) as TextReader : new StringReader(liveText)))
                                    {
                                        if (XmlNodeType.Element == reader.MoveToContent())
                                        {
                                            if (reader.NamespaceURI == RedirectNamespace &&
                                                reader.LocalName == RedirectElementName)
                                            {
                                                FileInfo targetSourceFileInfo = new FileInfo(itemFile.Substring(0, itemFile.LastIndexOf('\\') + 1) + reader.GetAttribute(RedirectTargetAttribute));
                                                if (0 == string.Compare(sourceFileInfo.FullName, targetSourceFileInfo.FullName, true, CultureInfo.CurrentCulture))
                                                {
                                                    vsProjItem.RunCustomTool();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            catch (XmlException)
                            {
                                // Swallow anything that Xml gripes about
                            }
                        }
                    });
                }
            }
        }