예제 #1
0
    protected void imgSearchIcon_Click(object sender, ImageClickEventArgs e)
    {
        string helpCultureName = _cultureCookie != null ? _cultureCookie.Value : string.Empty;
        string rootUrl = HelpSiteMapProvider.GetProviderRootUrlByCultureName(helpCultureName);
        string contentIndexName = "HelpContentIndex:" + rootUrl;
        ContentIndex myContentIndex = null;
        ContentSearchResult mySearchResult = null;
        XmlDocument doc = new XmlDocument();
        XslCompiledTransform xslt = new XslCompiledTransform();
        XsltArgumentList xsltArgs = new XsltArgumentList();
        StringWriter xsltResult = null;
        string exprPageTitle = @"(?si)(?:(?<=<meta\s*name\s*=\s*(?:""|')menuText(?:""|')\s*content\s*=\s*(?:""|'))(?<contentAttribute>.*?[^(?:"")]*)(?=(?:"")[^>]*>)|(?<=<meta\s*content\s*=\s*(?:""|'))(?<contentAttribute>.*?[^(?:"")]*)(?=(?:"")\s*name\s*=\s*(?:""|')menuText(?:""|')\s*[^>]*>))";

        if (txtSearch.Text.Length > 0)
        {
            try
            {
                myContentIndex = Application[contentIndexName] as ContentIndex;
                if (myContentIndex == null)
                {
                    myContentIndex = new ContentIndex(Page.MapPath(rootUrl), exprPageTitle);
                    Application[contentIndexName] = myContentIndex;
                }

                mySearchResult = myContentIndex.Search(txtSearch.Text);
                doc.LoadXml(mySearchResult.ToXml());
                xslt.Load(Server.MapPath("css/searchResult.xsl"));
                xsltArgs.AddParam("hrefPrefix", string.Empty, Request.Url.GetLeftPart(System.UriPartial.Path) + "?page=Help&content=");
                xsltArgs.AddParam("relativeURL", string.Empty, rootUrl);
                xsltArgs.AddParam("mappedURL", string.Empty, Page.MapPath(rootUrl));

                xsltResult = new StringWriter();
                xslt.Transform(doc, xsltArgs, xsltResult);

                litMainContent.Text = xsltResult.ToString();
            }
            catch (XmlException xmlEx)
            {
                if (xmlEx.Message.ToLowerInvariant().Contains("root"))
                {   //Missing root element.
                    litMainContent.Text = String.Format(GetLocalResourceObject("NoContentFound").ToString(), txtSearch.Text);
                }
                else
                {
                    litMainContent.Text = String.Format(GetLocalResourceObject("UnableToSearch").ToString(), xmlEx.Message);
                }
            }
            catch (Exception ex)
            {
                litMainContent.Text = String.Format(GetLocalResourceObject("UnableToSearch").ToString(), ex.Message);
            }
            finally
            {
                if (xsltResult != null)
                    xsltResult.Close();
            }
        }
    }
예제 #2
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     XsltArgumentList argsList = new XsltArgumentList();
     argsList.AddParam("calories", "", TextBox1.Text);
     Xml1.TransformArgumentList = argsList;
     Xml1.Visible = true;
 }
예제 #3
0
    public static object GetData(StageParams config)
    {
        XmlDocument input = Util.Validate<XmlDocument>( config.data, "XSLTStage" );

        string xslPath = config.context.Server.MapPath( config.map );
        if (!File.Exists(xslPath))
            throw new FileLoadException(String.Format("Style sheet {0} is not found", xslPath));

        XslCompiledTransform transform = new XslCompiledTransform();
        transform.Load(xslPath, new XsltSettings(false, true), new XmlUrlResolver());

        XsltArgumentList al = new XsltArgumentList();

        int index = 0;
        foreach (XmlNode node in config.stage)
            if ( node.Attributes["type"] != null )
                al.AddParam( node.Name, "", config.allParams[index++]);

        if (!config.last)
        {
            MemoryStream output = new MemoryStream();
            transform.Transform(input, al, output);
            return output;
        }
        else
        {
            transform.Transform(input, al, config.outputStream);
            return null;
        }
    }
예제 #4
0
 public XsltArgumentList ToXsltArgumentList()
 {
     XsltArgumentList result = new XsltArgumentList();
     for(int i=0; i<mKeys.Count; i++){
         result.AddParam((string)mKeys[i], "", (string)mVals[i]);
     }
     return result;
 }
예제 #5
0
        private static XsltArgumentList ProcessXsltArguments(string xsltParametersXml)
        {
            XsltArgumentList list = new XsltArgumentList();

            if (xsltParametersXml != null)
            {
                XmlDocument document = new XmlDocument();
                try
                {
                    document.LoadXml("<XsltParameters>" + xsltParametersXml + "</XsltParameters>");
                }
                catch (XmlException exception)
                {
                    throw new ArgumentException(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("XslTransform.XsltParameterNotWellFormed", new object[0]), exception);
                }
                XmlNodeList list2 = document.SelectNodes("/XsltParameters/*[local-name() = 'Parameter']");
                for (int i = 0; i < list2.Count; i++)
                {
                    XmlNode node = list2[i];
                    if (node.Attributes["Name"] == null)
                    {
                        throw new ArgumentException(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("XslTransform.XsltParameterNoAttribute", new object[] { "Name" }));
                    }
                    if (node.Attributes["Value"] == null)
                    {
                        throw new ArgumentException(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("XslTransform.XsltParameterNoAttribute", new object[] { "Value" }));
                    }
                    string namespaceUri = string.Empty;
                    if (node.Attributes["Namespace"] != null)
                    {
                        namespaceUri = node.Attributes["Namespace"].Value;
                    }
                    list.AddParam(node.Attributes["Name"].Value, namespaceUri, node.Attributes["Value"].Value);
                }
            }
            return(list);
        }
        /// <summary>
        /// This Method Generate Html File content as a Stream based on Xml Document and Xlst file
        /// </summary>
        /// <param name="xmlData">Data in XML format</param>
        /// <param name="xlstFilePath">Xlst File Path</param>
        /// <param name="xsltArgumentsDictionary">Xslt Arguments as a Dictionary</param>
        /// <returns>stream object</returns>
        public static String GenerateStringFile(string xmlData, string xlstFilePath, Dictionary <string, string> xsltArgumentsDictionary)
        {
            // Remove any namesapce if it is present
            // int startPosition = xmlData.IndexOf("xmlns", 0);
            // int endPosition = xmlData.IndexOf(".xsd", 0) + 5;
            // string changedXmlFile = xmlData.Remove(startPosition, endPosition - startPosition);
            string changedXmlFile = xmlData.Replace("xmlns:asp=\"remove\"", "");

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(changedXmlFile);

            MemoryStream mstream = new MemoryStream();
            StreamWriter swriter = new StreamWriter(mstream);

            XslCompiledTransform xslTransform = new XslCompiledTransform();

            xslTransform.Load(xlstFilePath);

            XsltArgumentList xsltArgumentList = null;

            if (xsltArgumentsDictionary != null)
            {
                xsltArgumentList = new XsltArgumentList();
                foreach (KeyValuePair <string, string> item in xsltArgumentsDictionary)
                {
                    xsltArgumentList.AddParam(item.Key, string.Empty, item.Value);
                }
            }

            xslTransform.Transform(xmlDoc, xsltArgumentList, mstream);
            mstream.Seek(0, SeekOrigin.Begin);

            StreamReader reader = new StreamReader(mstream);

            return(reader.ReadToEnd());
        }
예제 #7
0
        public void Translate()
        {
            // Translate XML into XHTML via XSLT
            StringWriter swXml = new StringWriter();

            XmlDocument doc = new XmlDocument();

            doc.Load(m_XmlDocument);

            // Modify the XML file.
            XmlElement root = doc.DocumentElement;

            // Create an XPathNavigator to use for the transform.
            XPathNavigator nav = root.CreateNavigator();

            // Transform the file.
            XslTransform xslt = new XslTransform();

            xslt.Load(m_XslDocument);

            // Setup xml arguments
            XsltArgumentList xslArguments = new XsltArgumentList();

            foreach (DictionaryEntry objEntry in m_Parameters)
            {
                xslArguments.AddParam(objEntry.Key.ToString(), "", objEntry.Value);
            }

            xslt.Transform(nav, xslArguments, swXml, null);

            // Write out results
            XmlDocument objDoc = new XmlDocument();

            objDoc.InnerXml = swXml.ToString();
            objDoc.Save(m_strOutputFileName);
        }
예제 #8
0
                              public static void Parse(
                                  XmlDocument xmlMetadata_in,
                                  string xsltTemplateURL_in,
                                  Hashtable xsltParameters_in,

                                  StringWriter parsedOutput_in
                                  )
                              {
                                  #region XsltArgumentList _xsltparameters = new XsltArgumentList().AddParam(...);
                                  XsltArgumentList      _xsltparameters = new XsltArgumentList();
                                  IDictionaryEnumerator _denum          = xsltParameters_in.GetEnumerator();
                                  _denum.Reset();
                                  while (_denum.MoveNext())
                                  {
                                      _xsltparameters.AddParam(
                                          _denum.Key.ToString(),
                                          "",
                                          System.Web.HttpUtility.UrlEncode(
                                              _denum.Value.ToString()
                                              )
                                          );
                                  }
                                  #endregion

                                  XPathNavigator _xpathnav      = xmlMetadata_in.CreateNavigator();
                                  XslTransform   _xslttransform = new XslTransform();
                                  _xslttransform.Load(
                                      xsltTemplateURL_in
                                      );
                                  _xslttransform.Transform(
                                      _xpathnav,
                                      _xsltparameters,
                                      parsedOutput_in,
                                      null
                                      );
                              }
        public List <Knowledge> Search(string input)
        {
            List <Knowledge> searchResult = new List <Knowledge>();
            var webRoot = _env.WebRootPath;
            var file    = System.IO.Path.Combine(webRoot, "Knowledgebase.xml");

            XmlSecureResolver resolver = new XmlSecureResolver(new XmlUrlResolver(), "https://*****:*****@"//knowledge[tags[contains(text(),$input)] and sensitivity/text()='Public']");

            XsltArgumentList varList = new XsltArgumentList();

            varList.AddParam("input", string.Empty, input);

            CustomContext context = new CustomContext(new NameTable(), varList);

            expr.SetContext(context);

            var matchedNodes = nav.Select(expr);

            foreach (XPathNavigator node in matchedNodes)
            {
                searchResult.Add(new Knowledge()
                {
                    Topic = node.SelectSingleNode(nav.Compile("topic")).Value, Description = node.SelectSingleNode(nav.Compile("description")).Value
                });
            }

            return(searchResult);
        }
예제 #10
0
        public static void Main()
        {
            StreamWriter output = new StreamWriter("Russian users.html", false);

            // Instantiate the XslTransform object
            XslTransform xslt = new XslTransform();

            // Load the XSLT style sheet
            xslt.Load("transform.xsl");

            // Create and define the XsltArgumentList.
            XsltArgumentList xslArg = new XsltArgumentList();

            xslArg.AddParam("TableOnly", "", "No");

            // Load XML source
            XPathDocument sourceXML = new XPathDocument("Russian users.xml");

            // Invoke the transform
            xslt.Transform(sourceXML, xslArg, output);

            // Close the StreamWriter
            output.Close();
        }
예제 #11
0
        protected void btnSubmit_Click(object sender, System.EventArgs e)
        {
            string        xslPath    = Server.MapPath("xsltExtension.xsl");
            XsltDateTime  xsltExtObj = new XsltDateTime();
            XmlTextReader xmlReader  = null;
            StringBuilder sb         = new StringBuilder();
            StringWriter  sw         = new StringWriter(sb);

            try {
                xmlReader = new XmlTextReader(xmlPath);

                //Instantiate the XPathDocument Class
                XPathDocument doc = new XPathDocument(xmlReader);

                //Instantiate the XslTransform Classes
                XslTransform transform = new XslTransform();
                transform.Load(xslPath);
                //Add Parameters
                XsltArgumentList args = new XsltArgumentList();
                args.AddParam("golferName", "", this.ddGolferName.SelectedItem.Value);
                args.AddExtensionObject("urn:xsltExtension-DateTime", xsltExtObj);
                //Call Transform() method
                transform.Transform(doc, args, sw);
                //Hide Panels
                this.pnlSelectGolfer.Visible     = false;
                this.pnlTransformation.Visible   = true;
                this.divTransformation.InnerHtml = sb.ToString();
            }
            catch (Exception excp) {
                Response.Write(excp.ToString());
            }
            finally {
                xmlReader.Close();
                sw.Close();
            }
        }
예제 #12
0
        internal static string Render(XElement element)
        {
            try
            {
                var xslCompiledTransform            = new XslCompiledTransform(true);
                System.IO.StringReader stringReader = new System.IO.StringReader(Properties.Resources.XmlToHtml10Basic);
                XmlReader    xmlReader    = XmlReader.Create(stringReader);
                XsltSettings xsltSettings = new XsltSettings(true, true);
                xslCompiledTransform.Load(xmlReader, xsltSettings, new XmlUrlResolver());

                XsltArgumentList a = new XsltArgumentList();
                // Need to pass the xml string as an input parameter so
                // we can do some parsing for extra bits that XSLT won't do.
                a.AddParam(@"xmlinput", string.Empty, element.ToString());
                var       stringBuilder = new StringBuilder();
                XmlWriter xmlWriter     = XmlWriter.Create(stringBuilder);             // Target not a chorus file so Palaso.Xml.CanonicalXmlSettings not needed here.
                xslCompiledTransform.Transform(element.CreateReader(), a, xmlWriter);
                return(stringBuilder.ToString());
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
예제 #13
0
        public void TransformToHtmlReport(string pathToXsltTemplate, FileStream input, FileStream output)
        {
            var xsltSettings = new XsltSettings
            {
                EnableScript = true
            };
            var xslt      = new XslCompiledTransform();
            var xmlReader = XmlReader.Create(pathToXsltTemplate);

            xslt.Load(xmlReader, xsltSettings, null);
            var document          = new XPathDocument(input);
            var xmlWriterSettings = new XmlWriterSettings
            {
                OmitXmlDeclaration = false,
                Indent             = true,
                ConformanceLevel   = ConformanceLevel.Fragment,
                CloseOutput        = false
            };
            var writer  = XmlWriter.Create(output, xmlWriterSettings);
            var argList = new XsltArgumentList();

            argList.AddParam("Date", "", DateTime.Now.ToString("f"));
            xslt.Transform(document, argList, writer);
        }
예제 #14
0
    public static void Main()
    {
        string inputFile  = @"C:\Users\donuric\Documents\Visual Studio 2015\Projects\Conversion\Conversion\XMLFile1.xml";
        string xsltFile   = @"C:\Users\donuric\Documents\Visual Studio 2015\Projects\Conversion\Conversion\XSLTFile1.xslt";
        string outputFile = @"C:\Users\donuric\Desktop\new.xml";
        // Create the XslCompiledTransform and load the stylesheet.
        XslCompiledTransform xslt = new XslCompiledTransform();

        xslt.Load(xsltFile);

        // Create the XsltArgumentList.
        XsltArgumentList xslArg = new XsltArgumentList();

        // Create a parameter which represents the current date and time.
        DateTime d = DateTime.Now;

        xslArg.AddParam("date", "", d.ToString());

        // Transform the file.
        using (XmlWriter w = XmlWriter.Create(outputFile))
        {
            xslt.Transform(inputFile, xslArg, w);
        }
    }
예제 #15
0
 /// <summary/>
 public static int Main(string[] args)
 {
     return(ConsoleApplication.Execute(args, (XsltConsoleParameters _) => {
         var xsl = new XslCompiledTransform();
         _.Log.Debug("Loading xslt...");
         xsl.Load(_.XsltFile, XsltSettings.TrustedXslt, new XmlUrlResolver());
         _.Log.Debug("Xslt ok...");
         using (var s = string.IsNullOrWhiteSpace(_.OutFile) ? Console.Out : new StreamWriter(_.OutFile)) {
             _.Log.Debug("Prepare args...");
             var xargs = new XsltArgumentList();
             foreach (var p in _.XsltParameters)
             {
                 xargs.AddParam(p.Key, "", p.Value);
             }
             xargs.AddExtensionObject("qorpent://std", new XsltStdExtensions());
             _.Log.Debug("Args ok...");
             _.Log.Debug("Start transform...");
             xsl.Transform(_.SourceFile, xargs, s);
             s.Flush();
             _.Log.Debug("Transform ok...");
         }
         return 0;
     }));
 }
예제 #16
0
        public void Transform(string inputFile, string outputFile, NameValueCollection parameters)
        {
            XsltArgumentList argumentList = new XsltArgumentList();

            foreach (string parameter in parameters)
            {
                if (parameters[parameter] != null)
                {
                    argumentList.AddParam(parameter, String.Empty, parameters[parameter]);
                }
            }

            Console.WriteLine("{0} > {1} ({2})", inputFile, outputFile, _xsltInformation.SourceFile);

            XmlWriterSettings xws = new XmlWriterSettings();

            xws.CloseOutput = true;

            const string xmlMethod  = "xml";
            const string textMethod = "text";

            if (_xsltInformation.Method == xmlMethod || _xsltInformation.Method == null)
            {
                using (XmlWriter xw = XmlWriter.Create(outputFile, xws))
                {
                    xslCompiledTransform.Transform(inputFile, argumentList, xw);
                }
            }
            if (_xsltInformation.Method == textMethod)
            {
                using (StreamWriter sw = new StreamWriter(outputFile))
                {
                    xslCompiledTransform.Transform(inputFile, argumentList, sw);
                }
            }
        }
예제 #17
0
        protected override void DoUofToOoxMainTransform(string inputFile, string outputFile, string resourceDir)
        {
            XmlUrlResolver    resourceResolver;
            XPathDocument     xslDoc;
            XmlReaderSettings xrs          = new XmlReaderSettings();
            XmlReader         source       = null;
            XmlWriter         writer       = null;
            string            mainOutput   = Path.GetDirectoryName(inputFile) + Path.AltDirectorySeparatorChar + "mainOutput.xml";
            string            equAfterMain = Path.GetDirectoryName(inputFile) + Path.AltDirectorySeparatorChar + "equAfterMain.xml";

            try
            {
                xrs.ProhibitDtd = true;
                string xslLocation = TranslatorConstants.UOFToOOX_XSL;
                if (outputFile == null)
                {
                    xslLocation = TranslatorConstants.UOFToOOX_COMPUTE_SIZE_XSL;
                }

                if (resourceDir == null)
                {
                    resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(),
                                                            this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + "Excel.uof2oox");
                    xslDoc          = new XPathDocument(((ResourceResolver)resourceResolver).GetInnerStream(xslLocation));
                    xrs.XmlResolver = resourceResolver;
                    source          = XmlReader.Create(inputFile);
                }
                else
                {
                    resourceResolver = new XmlUrlResolver();
                    xslDoc           = new XPathDocument(resourceDir + "/" + xslLocation);
                    source           = XmlReader.Create(resourceDir + "/" + TranslatorConstants.SOURCE_XML, xrs);
                }
                try
                {
                    XslCompiledTransform xslt     = new XslCompiledTransform();
                    XsltSettings         settings = new XsltSettings(true, false);
                    //Assembly ass = Assembly.Load("excel_uof2oox");
                    //Type t = ass.GetType("uof2oox");
                    // xslt.Load(t);
                    xslt.Load(xslDoc, settings, resourceResolver);
                    XsltArgumentList parameters = new XsltArgumentList();
                    parameters.XsltMessageEncountered += new XsltMessageEncounteredEventHandler(MessageCallBack);
                    //if (outputFile != null)
                    //{
                    //    parameters.AddParam("outputFile", "", outputFile);
                    //    writer = new OoxZipWriter(inputFile);
                    //}
                    //else
                    //{
                    //    writer = new XmlTextWriter(new StringWriter());
                    //}

                    //xslt.Transform(source, parameters, writer);
                    XmlTextWriter fs = new XmlTextWriter(mainOutput, Encoding.UTF8);
                    xslt.Transform(source, parameters, fs);
                    fs.Close();

                    SetDrawingTwoCellAnchorValue(mainOutput, equAfterMain);

                    // 增加对公式的互操作支持
                    // EquInter(mainOutput, equAfterMain);

                    xslLocation = TranslatorConstants.UOFToOOX_POSTTREAT_STEP1_XSL;

                    if (resourceDir == null)
                    {
                        resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(),
                                                                this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + "Excel.uof2oox");
                        xslDoc          = new XPathDocument(((ResourceResolver)resourceResolver).GetInnerStream(xslLocation));
                        xrs.XmlResolver = resourceResolver;
                        source          = XmlReader.Create(equAfterMain);
                    }
                    XslCompiledTransform xslt2     = new XslCompiledTransform();
                    XsltSettings         settings2 = new XsltSettings(true, false);
                    xslt.Load(xslDoc, settings2, resourceResolver);

                    XsltArgumentList parameters2 = new XsltArgumentList();
                    parameters.XsltMessageEncountered += new XsltMessageEncounteredEventHandler(MessageCallBack);
                    if (outputFile != null)
                    {
                        parameters2.AddParam("outputFile", "", outputFile);
                        writer = new OoxZipWriter(equAfterMain);
                    }
                    else
                    {
                        writer = new XmlTextWriter(new StringWriter());
                    }

                    xslt.Transform(source, parameters2, writer);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
                if (source != null)
                {
                    source.Close();
                }
            }
        }
예제 #18
0
    private void ProcessMenuRequest()
    {
        Ektron.Cms.ContentAPI myContent = new Ektron.Cms.ContentAPI();
        Ektron.Cms.CommonApi AppUI = new Ektron.Cms.CommonApi();
        Ektron.Cms.API.User.User myUser = new Ektron.Cms.API.User.User();

        long contentId = Convert.ToInt64(Request.QueryString["contentId"]);
        int languageId = -1;
        long taxonomyOverrideId = 0;
        if (Request.QueryString["dmsLanguageId"] != null)
        {
            if (Request.QueryString["dmsLanguageId"] != String.Empty)
            {
                languageId = Convert.ToInt32(Request.QueryString["dmsLanguageId"]);
                if (languageId == Ektron.Cms.Common.EkConstants.CONTENT_LANGUAGES_UNDEFINED || languageId == Ektron.Cms.Common.EkConstants.ALL_CONTENT_LANGUAGES)
                {
                    languageId = AppUI.DefaultContentLanguage;
                }
                AppUI.ContentLanguage = languageId;
                myContent.ContentLanguage = languageId;
            }
        }

        //createIeSpecificMenu is an argument passed to the constructor of the DMSMenuContentAPI class
        //This arg tells DMSMenuContentAPI whether or not to include the IE specific functionality
        //namely, this funcitonality is the office-specific stuff (Edit In Microsoft Office, View in Microsoft Office).
        Boolean createIeSpecificMenu = false;
        if (Request.QueryString["createIeSpecificMenu"] != String.Empty)
        {
            createIeSpecificMenu = Convert.ToBoolean(Request.QueryString["createIeSpecificMenu"]);
        }

        string dmsMenuType = String.Empty;
        string dmsMenuSubtype = String.Empty;
        long communityGroupID = 0;

        if (!String.IsNullOrEmpty(Request.QueryString["communityDocuments"]))
        {
            // Dms community menus may carry additional data (i.e. group id).
            string[] splitDmsMenuTypeInfo = Request.QueryString["communityDocuments"].Split(
                new char[] { '_' },
                StringSplitOptions.RemoveEmptyEntries);

            dmsMenuType = splitDmsMenuTypeInfo[0];

            if (splitDmsMenuTypeInfo.Length == 2)
            {
                long.TryParse(splitDmsMenuTypeInfo[1], out communityGroupID);
            }
        }

        Ektron.Cms.ContentData myContentData = new Ektron.Cms.ContentData();
        Ektron.Cms.API.Content.Content apiCont = new Ektron.Cms.API.Content.Content();
        Ektron.Cms.ContentStateData stateData = apiCont.GetContentState(contentId);
        if (stateData.Status == "A")
            myContentData = apiCont.GetContent(contentId, Ektron.Cms.ContentAPI.ContentResultType.Published);
        else
            myContentData = apiCont.GetContent(contentId, Ektron.Cms.ContentAPI.ContentResultType.Staged);

        string dmsMenuGuid;
        XsltArgumentList myDMSMenuArguments = new XsltArgumentList();
        Ektron.Cms.Workarea.Dms.DmsMenu myDMSMenu;
        if (dmsMenuType != "")
        {
            bool queryDynamicContentBox = false;
            string controlID = String.Empty;

            if (Request.QueryString["dynamicContentBox"] != null)
            {
                queryDynamicContentBox = Convert.ToBoolean(Request.QueryString["DynamicContentBox"]);
                if (dmsMenuType.ToLower() == "communityuser" || dmsMenuType.ToLower() == "communitygroup" && EkConstants.IsAssetContentType(myContentData.ContType, true) && myContentData.ContType !=(int) EkEnumeration.CMSContentType.Multimedia)
                {
                    if (myContentData.AssetData != null && !EkFunctions.IsImage("." + myContentData.AssetData.FileExtension) && myContentData.Type !=(int) EkEnumeration.CMSContentType.Multimedia)
                    {
                        queryDynamicContentBox = false;
                    }
                }

                myDMSMenuArguments.AddParam("dynamicContentBox", String.Empty, queryDynamicContentBox);
            }
            if (Request.QueryString["dmsEktControlID"] != null)
            {
                controlID = Request.QueryString["dmsEktControlID"].ToString();
                myDMSMenuArguments.AddParam("dmsEktControlID", String.Empty, controlID);
            }
            if (Request.QueryString["taxonomyOverrideId"] != null)
            {
                taxonomyOverrideId = Convert.ToInt64(Request.QueryString["taxonomyOverrideId"]);
            }
        }

        if (Request.QueryString["dmsMenuGuid"] != null)
        {
            dmsMenuGuid = Request.QueryString["dmsMenuGuid"].ToString();
            myDMSMenuArguments.AddParam("dmsMenuGuid", String.Empty, dmsMenuGuid);
        }

        Boolean IsPhotoGallery = true;
        if (Request.QueryString["dmsMenuSubtype"] != null)
        {
            dmsMenuSubtype = Request.QueryString["dmsMenuSubtype"].ToString();
            myDMSMenuArguments.AddParam("dmsMenuSubtype", String.Empty, dmsMenuSubtype);
            IsPhotoGallery = (dmsMenuSubtype == "photo");
        }

        string fromPage = String.Empty;
        if (Request.QueryString["fromPage"] != null)
        {
            fromPage = Request.QueryString["fromPage"].ToString();
            myDMSMenuArguments.AddParam("fromPage", String.Empty, fromPage);
        }

        switch (dmsMenuType.ToLower())
        {
            case "taxonomy":
                //Taxonomy Implementation
                //Use Taxnonomy constructor overload
                //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, int taxonomyOverrideId)
                if (Request.QueryString["communityGroupid"] != null)
                {
                    long.TryParse(Request.QueryString["communityGroupid"].ToString(), out communityGroupID);
                }
                myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.Taxonomy,
                    contentId, myUser.UserId, languageId, myContentData.FolderId,
                    myContentData.Type, createIeSpecificMenu, taxonomyOverrideId, communityGroupID);
                break;
            case "communityuser":
                //Community User Implementation
                //Use Community User constructor overload
                //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, Boolean isPhotoGallery)
                myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.CommunityUser,
                    contentId, myUser.UserId, languageId, myContentData.FolderId,
                    myContentData.Type, createIeSpecificMenu, IsPhotoGallery);
                break;
            case "communitygroup":
                //Community Group Implementation
                //Use Community Group constructor overload
                //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, int taxonomyOverrideId, int communityGroupId, Boolean isPhotoGallery)
                myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.CommunityGroup,
                    contentId, myUser.UserId, languageId, myContentData.FolderId, myContentData.Type,
                    createIeSpecificMenu, taxonomyOverrideId, communityGroupID, IsPhotoGallery, fromPage);
                break;
            case "favorites":
                //Favorites Menu Implementation
                //Use Favorites constructor overload
                //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu, int taxonomyOverrideId, int communityGroupId, Boolean isPhotoGallery)
                myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.Favorites,
                    contentId, myUser.UserId, languageId, myContentData.FolderId,
                    myContentData.Type, createIeSpecificMenu, taxonomyOverrideId,
                    communityGroupID, IsPhotoGallery, fromPage);
                break;
            case "workarea":
            default:
                //Workarea Implementation
                //Use Workarea constructor overload
                //public DmsMenu(ektronDmsMenuMenuType menuType, int contentId, int userId, int contentLanguage, int folderId, int contentType, Boolean createIESpecificMenu)
                myDMSMenu = new Ektron.Cms.Workarea.Dms.DmsMenu(ektronDmsMenuMenuType.Workarea,
                    contentId, myUser.UserId, languageId, myContentData.FolderId,
                    myContentData.Type, createIeSpecificMenu, fromPage);
                break;
        }

        DMSMenu.Text = myDMSMenu.GetDmsMenu(myDMSMenuArguments);
    }
예제 #19
0
    private XElement UpdateTreeView(XElement functionMarkupContainer)
    {
        // TODO: Do some compiled xslt caching

        XElement treeInput = CopyWithId(functionMarkupContainer);

        treeInput.Add(GetFunctionDescriptionElements(functionMarkupContainer));

        if (_state.AllowSelectingInputParameters)
        {
            CollapseGetInputParamaterFunctionCalls(treeInput, InputParameterNodeIDs);
        }

        // treeInput.Save(Request.MapPath("out.tmp.xml"));

        string xslFilePath = Request.MapPath("functioneditortree.xslt");
        XslCompiledTransform transform = GetTransformation(xslFilePath);

        var xsltTransformArguments = new XsltArgumentList();
        xsltTransformArguments.AddExtensionObject(XsltExtensionObjectNamespace, new TreeRenderingXsltExtensionObject(TreePathToIdMapping));
        xsltTransformArguments.AddParam("SelectedId", string.Empty, SelectedNode.IsNullOrEmpty() ? string.Empty : TreePathToIdMapping[SelectedNode]);

        XDocument transformedDoc = new XDocument();

        using (XmlWriter writer = transformedDoc.CreateWriter())
        {
            transform.Transform(treeInput.CreateReader(), xsltTransformArguments, writer);
        }

        WriteTo(transformedDoc, this.TreePlaceholder);

        return treeInput;
    }
예제 #20
0
        protected byte[] GenerateCode(string inputFileName, string fileNamespace, string baseFolder, string inputFileContent)
        {
            string xmlFilePath = inputFileName;
            string xslFilePath = ResolveXSLPath(xmlFilePath, baseFolder);

            if (string.IsNullOrEmpty(xslFilePath) == true)
            {
                string msg = string.Format("// XSL File not found ({0})", xslFilePath);
                return(System.Text.Encoding.UTF8.GetBytes(msg));
            }

            Debug.WriteLine("Original XmlFilePath: " + xmlFilePath);
            xmlFilePath = ResolveXmlPath(xmlFilePath);
            Debug.WriteLine("Resolved XmlFilePath: " + xmlFilePath);
            Debug.WriteLine("Resolved XslFilePath: " + xslFilePath);

#if DEBUG
            string txt2 = File.ReadAllText(xslFilePath);
#endif

            XslCompiledTransform xslt;
            XsltSettings         xst = XsltSettings.Default;
            xst.EnableScript = true;

            try
            {
                string xsltText = File.ReadAllText(xslFilePath);

                // 재활용한다.
                if (xsltDict.TryGetValue(xsltText, out xslt) == false)
                {
                    xslt = new XslCompiledTransform();

                    StringReader sr = new StringReader(xsltText);
                    using (XmlReader xr = XmlReader.Create(sr))
                    {
                        xslt.Load(xr, xst, null);
                    }

                    xsltDict.Add(xsltText, xslt);
                }
            }
            catch (Exception ex)
            {
                string output = string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.ToString());
                return(System.Text.Encoding.UTF8.GetBytes(output));
            }

            StringBuilder sb = new StringBuilder();
            using (StringWriter sw = new StringWriter(sb, CultureInfo.CurrentCulture))
            {
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.ConformanceLevel = ConformanceLevel.Auto;
                xws.Encoding         = Encoding.UTF8;

                XmlReaderSettings xrs = new XmlReaderSettings();

                XmlWriter writer = XmlTextWriter.Create(sw, xws);
                using (XmlReader reader = XmlReader.Create(xmlFilePath, xrs))
                {
                    XsltArgumentList xal = new XsltArgumentList();
                    // LoadXsltExtensionMethod(xal);
                    xal.AddParam("XCG_CurrentTime", string.Empty, DateTime.Now.ToString(CultureInfo.InvariantCulture));
                    xal.AddParam("XCG_Namespace", string.Empty, fileNamespace);
                    xal.AddParam("XCG_BaseFolder", string.Empty, baseFolder);
                    xal.AddParam("XCG_Version", string.Empty, "1.0");
                    xslt.Transform(reader, xal, writer);
                }

#if DEBUG
                string txt = sb.ToString();
#endif
            }

            return(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));
        }
예제 #21
0
        private string ProcessXslt(String rootPath)
        {
            var xslt = this.Xslt;
            var xml  = this.Xml;

            if (String.IsNullOrEmpty(this.Xslt))
            {
                throw new Exception("Must load xslt before calling Execute()");
            }
            else if (String.IsNullOrEmpty(this.Xml))
            {
                throw new Exception("No xml loaded for xslt to process");
            }
            else
            {
                String fileSet = String.Empty;

                Environment.CurrentDirectory = rootPath;

                ExsltTransform t = PrepareTransformationObject(rootPath, this.Xslt);

                XsltArgumentList al = new XsltArgumentList();
                al.AddParam("dish-root", String.Empty, rootPath);
                al.AddParam("codee-root", String.Empty, rootPath);
                al.AddParam("xml-root", String.Empty, rootPath);
                al.AddParam("xslt-root", String.Empty, rootPath);
                foreach (var dict in this.Parameters)
                {
                    al.AddParam(dict.Key, String.Empty, dict.Value);
                }

                String inputXml = this.Xml;

                String newFileContents = String.Empty;

                XmlDocument doc = new XmlDocument();
                inputXml = inputXml.Trim();
                doc.LoadXml(inputXml);
                MemoryStream ms = new MemoryStream();
                try
                {
                    t.Transform(doc.CreateNavigator(), al, ms);

                    ms.Position = 0;

                    String currentDoc = (new UTF8Encoding(true)).GetString(ms.GetBuffer(), 0, (int)ms.Length);
                    if (currentDoc.StartsWith("<?xml"))
                    {
                        currentDoc = currentDoc.Substring(currentDoc.IndexOf("?>") + 2);
                    }
                    currentDoc = currentDoc.Trim((char)65279);
                    if (currentDoc.Contains("<"))
                    {
                        currentDoc = currentDoc.Substring(currentDoc.IndexOf("<"));
                    }
                    if (!String.IsNullOrEmpty(currentDoc))
                    {
                        try
                        {
                            doc = new XmlDocument();
                            doc.LoadXml(currentDoc);
                            MemoryStream  wms    = new MemoryStream();
                            XmlTextWriter writer = new XmlTextWriter(wms, (new UTF8Encoding(true)));
                            writer.Formatting = Formatting.Indented;
                            doc.WriteContentTo(writer);
                            writer.Flush();
                            newFileContents = (new UTF8Encoding(true)).GetString(wms.GetBuffer(), 0, (int)writer.BaseStream.Length).Trim();
                            wms.Close();
                        }
                        catch (Exception ex)
                        {
                            throw ex;  // Shoudl really call kitchen service below
                            //KitchenService.ReportError(ex);
                            // Ignore formatting errors
                            newFileContents = currentDoc;
                        }
                    }
                }
                finally
                {
                    ms.Close();
                }


                return(newFileContents);

                /*
                 * String outputFileName = String.Format("{0}{1}", this.FileName, ".Output.xml");
                 *
                 * newFileContents = newFileContents.Replace(Environment.NewLine, "\n").Replace("\n", Environment.NewLine).Trim();
                 *
                 * this.PreviousFileSetZipped = newFileContents.Zip();
                 *
                 * this.Save();
                 *
                 * //File.WriteAllText(outputFileName, newFileContents);
                 * Dish.SplitContents(outputFileName, newFileContents, false, this.FileName);
                 *
                 *
                 *
                 * return fileSet;
                 */
            }
        }
예제 #22
0
        protected virtual void _Transform(string inputFile, string outputFile, ConversionOptions options)
        {
            // this throws an exception in the the following cases:
            // - input file is not a valid file
            // - input file is an encrypted file
            CheckFile(inputFile);

            XmlReader   source      = null;
            XmlWriter   writer      = null;
            ZipResolver zipResolver = null;

            string currentDirectory = Environment.CurrentDirectory;

            try
            {
                XslCompiledTransform xslt = this.Load(outputFile == null);
                zipResolver = new ZipResolver(inputFile);
                XsltArgumentList parameters = new XsltArgumentList();
                parameters.XsltMessageEncountered += new XsltMessageEncounteredEventHandler(MessageCallBack);

                if (options != null)
                {
                    // set working directory to the input document's path
                    // that way we can resolve references to relative links into the file system easily
                    Environment.CurrentDirectory = options.InputBaseFolder;

                    parameters.AddParam("documentType", "", options.DocumentType.ToString());
                    parameters.AddParam("generator", "", options.Generator);
                }
                else
                {
                    parameters.AddParam("generator", "", "OpenXML/ODF Translator");
                }

                if (outputFile != null)
                {
                    parameters.AddParam("outputFile", "", outputFile);

                    XmlWriter finalWriter;
                    if (this.packaging)
                    {
                        finalWriter = new ZipArchiveWriter(zipResolver, outputFile);
                    }
                    else
                    {
                        finalWriter = new XmlTextWriter(outputFile, System.Text.Encoding.UTF8);
                    }
                    writer = GetWriter(finalWriter);
                }
                else
                {
                    writer = new XmlTextWriter(new StringWriter());
                }

                source = this.Source(inputFile);
                // Apply the transformation

                xslt.Transform(source, parameters, writer, zipResolver);
            }
            finally
            {
                // restore working folder
                Environment.CurrentDirectory = currentDirectory;

                if (writer != null)
                {
                    writer.Close();
                }
                if (source != null)
                {
                    source.Close();
                }
                if (zipResolver != null)
                {
                    zipResolver.Dispose();
                }
            }
        }
예제 #23
0
        public void DrawProfilesModule()
        {
            //If your module performs a data request, based on the DataURI parameter then call ReLoadBaseData
            base.GetDataByURI();

            //If the two counts don't match then their are more header columns than data or more data than header.
            if (base.GetModuleParamXml("TableHeader").SelectNodes("Header/Column").Count != base.GetModuleParamXml("TableRow").SelectNodes("Data/Column").Count)
            {
                throw new Exception("TableHeader count does not match TableRow count in PresentationXML");
            }

            XmlDocument document = new XmlDocument();

            System.Text.StringBuilder documentdata = new System.Text.StringBuilder();
            XmlNode connectionnode;

            ////Format any URL Nodes that might exist, this uses a single hop parse for the Connection information within a Network.
            ////If your presentationXML has Connection data that needs to be parsed out of the XML data, you should use the HopParse method.
            ////This enables you to access (SingleHop) Entity/Network/Connection data and display it any way you need.
            ////[IE. You can map all of a single persons co-authors, but not their co-authors, co-authors.]
            //foreach (XmlNode col in base.TableRow.SelectNodes("Data/Column"))
            //{
            //    foreach (XmlNode node in base.BaseData.SelectNodes(base.NetworkListNode))
            //    {
            //        col["URL"].InnerText = CustomParse.HopParse(col["URL"].InnerText, base.BaseData,node);
            //    }
            //}

            documentdata.Append("<DetailTable");
            documentdata.Append(" Columns=\"");
            documentdata.Append(base.GetModuleParamXml("TableHeader").SelectNodes("Header/Column").Count);
            documentdata.Append("\"");
            documentdata.Append(" InfoCaption=\"");
            documentdata.Append(base.GetModuleParamString("InfoCaption"));
            documentdata.Append("\"");
            documentdata.Append(">");

            //Loop the Header Columns to build the first row of the table.
            documentdata.Append("<Row type=\"header\">");
            foreach (XmlNode header in base.GetModuleParamXml("TableHeader").SelectNodes("Header/Column"))
            {
                documentdata.Append("<Column Justify=\"" + header["Justify"].InnerText + "\"");
                documentdata.Append(" Width=\"" + header["Width"].InnerText + "\"");
                documentdata.Append(">" + header["Name"].InnerXml + "</Column>");
            }
            documentdata.Append("</Row>");

            //Loop the Data Columns to supply the rows after the header.
            foreach (XmlNode networknode in base.BaseData.SelectNodes(base.GetModuleParamString("NetworkListNode")))
            {
                documentdata.Append("<Row type=\"data\" url=\"" + Root.Domain + CustomParse.Parse(base.GetModuleParamString("RowURL"), networknode, base.Namespaces) + "\">");

                connectionnode = base.BaseData.SelectSingleNode(CustomParse.Parse(base.GetModuleParamString("ConnectionListNode"), networknode, base.Namespaces));

                foreach (XmlNode col in base.GetModuleParamXml("TableRow").SelectNodes("Data/Column"))
                {
                    documentdata.Append("<Column url=\"" + Root.Domain + CustomParse.Parse(col["URL"].InnerText, base.BaseData, networknode, base.Namespaces) + "\"");

                    if (col["Data"].InnerText.Contains("Profile"))
                    {
                        documentdata.Append(">" + CustomParse.Parse(col["Data"].InnerText, networknode, base.Namespaces) + "</Column>");
                    }
                    else
                    {
                        documentdata.Append(">" + CustomParse.Parse(col["Data"].InnerText, connectionnode, base.Namespaces) + "</Column>");
                    }
                }

                documentdata.Append("</Row>");
            }

            documentdata.Append("</DetailTable>");

            document.LoadXml(documentdata.ToString());

            XslCompiledTransform xslt = new XslCompiledTransform();
            XsltArgumentList     args = new XsltArgumentList();

            args.AddParam("root", "", Root.Domain);

            litNetworkDetails.Text = Utilities.XslHelper.TransformInMemory(Server.MapPath("~/framework/modules/NetworkDetails/NetworkDetails.xslt"), args, base.BaseData.OuterXml);
        }
예제 #24
0
        private void Construct()
        {
            string directoryPath       = Path.GetDirectoryName(Application.ExecutablePath);
            string constructDirPath    = Path.Combine(directoryPath, "Construct");
            string confObjectGroupPath = Path.Combine(constructDirPath, ConstructorType.ToString());
            string confObjectDirPath   = Path.Combine(confObjectGroupPath, ConfObjectName);

            System.IO.Directory.CreateDirectory(constructDirPath);
            System.IO.Directory.CreateDirectory(confObjectGroupPath);
            System.IO.Directory.CreateDirectory(confObjectDirPath);

            Configuration ConfNew = new Configuration();

            ConfNew.Name      = Conf.Name;
            ConfNew.NameSpace = Conf.NameSpace;

            switch (ConstructorType)
            {
            case ConstructorTypeBuild.Directory:
            {
                ConfNew.Directories.Add(ConfigurationDirectories.Name, ConfigurationDirectories);
                break;
            }

            case ConstructorTypeBuild.Document:
            {
                ConfNew.Documents.Add(ConfigurationDocuments.Name, ConfigurationDocuments);
                break;
            }
            }

            string confNewSavePath = Path.Combine(constructDirPath, "Conf.xml");

            Configuration.Save(confNewSavePath, ConfNew);

            XslCompiledTransform xsltCodeGnerator = new XslCompiledTransform();

            xsltCodeGnerator.Load(Path.Combine(directoryPath, "Constructor.xslt"), new XsltSettings(false, false), null);

            XsltArgumentList xsltArgumentList = new XsltArgumentList();

            xsltArgumentList.AddParam("ConstructorType", "", ConstructorType.ToString());
            xsltArgumentList.AddParam("ConfObjectName", "", ConfObjectName);

            xsltArgumentList.AddParam("Form", "", "DirectoryFormListDesigner");
            FileStream fileStreamDesignerList = new FileStream(Path.Combine(confObjectDirPath, $"Form_{ConfObjectName}.Designer.cs"), FileMode.Create);

            xsltCodeGnerator.Transform(confNewSavePath, xsltArgumentList, fileStreamDesignerList);
            fileStreamDesignerList.Close();

            xsltArgumentList.RemoveParam("Form", "");
            xsltArgumentList.AddParam("Form", "", "DirectoryFormList");
            FileStream fileStreamFormList = new FileStream(Path.Combine(confObjectDirPath, $"Form_{ConfObjectName}.cs"), FileMode.Create);

            xsltCodeGnerator.Transform(confNewSavePath, xsltArgumentList, fileStreamFormList);
            fileStreamFormList.Close();

            xsltArgumentList.RemoveParam("Form", "");
            xsltArgumentList.AddParam("Form", "", "DirectoryFormElementDesigner");
            FileStream fileStreamFormElementDesigner = new FileStream(Path.Combine(confObjectDirPath, $"Form_{ConfObjectName}Елемент.Designer.cs"), FileMode.Create);

            xsltCodeGnerator.Transform(confNewSavePath, xsltArgumentList, fileStreamFormElementDesigner);
            fileStreamFormElementDesigner.Close();

            xsltArgumentList.RemoveParam("Form", "");
            xsltArgumentList.AddParam("Form", "", "DirectoryFormElement");
            FileStream fileStreamFormElement = new FileStream(Path.Combine(confObjectDirPath, $"Form_{ConfObjectName}Елемент.cs"), FileMode.Create);

            xsltCodeGnerator.Transform(confNewSavePath, xsltArgumentList, fileStreamFormElement);
            fileStreamFormElement.Close();

            switch (ConstructorType)
            {
            case ConstructorTypeBuild.Directory:
            {
                foreach (ConfigurationObjectTablePart TablePart in ConfigurationDirectories.TabularParts.Values)
                {
                    xsltArgumentList.RemoveParam("Form", "");
                    xsltArgumentList.RemoveParam("ConfObjectTablePartName", "");
                    xsltArgumentList.AddParam("Form", "", "DirectoryFormTablePartDesigner");
                    xsltArgumentList.AddParam("ConfObjectTablePartName", "", TablePart.Name);
                    FileStream fileStreamFormTablePartDesigner = new FileStream(Path.Combine(confObjectDirPath, $"Form_{ConfObjectName}_ТабличнаЧастина_{TablePart.Name}.Designer.cs"), FileMode.Create);
                    xsltCodeGnerator.Transform(confNewSavePath, xsltArgumentList, fileStreamFormTablePartDesigner);
                    fileStreamFormTablePartDesigner.Close();

                    xsltArgumentList.RemoveParam("Form", "");
                    xsltArgumentList.RemoveParam("ConfObjectTablePartName", "");
                    xsltArgumentList.AddParam("Form", "", "DirectoryFormTablePart");
                    xsltArgumentList.AddParam("ConfObjectTablePartName", "", TablePart.Name);
                    FileStream fileStreamFormTablePart = new FileStream(Path.Combine(confObjectDirPath, $"Form_{ConfObjectName}_ТабличнаЧастина_{TablePart.Name}.cs"), FileMode.Create);
                    xsltCodeGnerator.Transform(confNewSavePath, xsltArgumentList, fileStreamFormTablePart);
                    fileStreamFormTablePart.Close();
                }

                break;
            }

            case ConstructorTypeBuild.Document:
            {
                break;
            }
            }
        }
        public static void DeployAggDesigns(ProjectItem projItem, DTE2 ApplicationObject)
        {
            Microsoft.AnalysisServices.Cube oCube = (Microsoft.AnalysisServices.Cube)projItem.Object;

            bool bFoundAggDesign = false;

            foreach (MeasureGroup mg in oCube.MeasureGroups)
            {
                if (mg.AggregationDesigns.Count > 0)
                {
                    bFoundAggDesign = true;
                    break;
                }
            }
            if (!bFoundAggDesign)
            {
                MessageBox.Show("There are no aggregation designs defined in this cube yet.");
                return;
            }

            if (MessageBox.Show("This command deploys just the aggregation designs in this cube. It does not change which aggregation design is assigned to each partition.\r\n\r\nYou should run a ProcessIndex command from Management Studio on this cube after aggregation designs have been deployed.\r\n\r\nDo you wish to continue?", "BIDS Helper - Deploy Aggregation Designs", MessageBoxButtons.YesNo) != DialogResult.Yes)
            {
                return;
            }

            try
            {
                ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(true, "Deploying Aggregation Designs", 1, 5);

                string sPartitionsFileName = projItem.get_FileNames(1);
                sPartitionsFileName = sPartitionsFileName.Substring(0, sPartitionsFileName.Length - 5) + ".partitions";

                // Check if the file is read-only (and probably checked in to a source control system)
                // before attempting to save. (issue: 10327 )
                FileAttributes fa = System.IO.File.GetAttributes(sPartitionsFileName);
                if ((fa & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
                {
                    //TODO - prompt before saving?
                    //Save the cube
                    projItem.Save("");
                }

                ApplicationObject.StatusBar.Progress(true, "Deploying Aggregation Designs", 2, 5);

                // extract deployment information
                DeploymentSettings deploySet = new DeploymentSettings(projItem);

                // use xlst to create xmla alter command
                XslCompiledTransform xslt = new XslCompiledTransform();
                XmlReader            xsltRdr;
                XmlReader            xrdr;

                // read xslt from embedded resource
                xsltRdr = XmlReader.Create(new StringReader(BIDSHelper.Resources.Common.DeployAggDesigns));
                using ((xsltRdr))
                {
                    // read content from .partitions file
                    xrdr = XmlReader.Create(sPartitionsFileName);
                    using (xrdr)
                    {
                        ApplicationObject.StatusBar.Progress(true, "Deploying Aggregation Designs", 3, 5);
                        // Connect to Analysis Services
                        Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
                        svr.Connect(deploySet.TargetServer);
                        ApplicationObject.StatusBar.Progress(true, "Deploying Aggregation Designs", 4, 5);
                        // execute the xmla
                        try
                        {
                            // Build up the Alter MdxScript command using XSLT against the .partitions file
                            XslCompiledTransform xslta = new XslCompiledTransform();
                            StringBuilder        sb    = new StringBuilder();
                            XmlWriterSettings    xws   = new XmlWriterSettings();
                            xws.OmitXmlDeclaration = true;
                            xws.ConformanceLevel   = ConformanceLevel.Fragment;
                            XmlWriter xwrtr = XmlWriter.Create(sb, xws);

                            xslta.Load(xsltRdr);
                            XsltArgumentList xslarg = new XsltArgumentList();

                            Database targetDB = svr.Databases.FindByName(deploySet.TargetDatabase);
                            if (targetDB == null)
                            {
                                throw new System.Exception(string.Format("A database called {0} could not be found on the {1} server", deploySet.TargetDatabase, deploySet.TargetServer));
                            }
                            xslarg.AddParam("TargetDatabase", "", targetDB.ID);
                            xslarg.AddParam("TargetCubeID", "", oCube.ID);
                            xslta.Transform(xrdr, xslarg, xwrtr);

                            Cube oServerCube = targetDB.Cubes.Find(oCube.ID);
                            if (oServerCube == null)
                            {
                                throw new System.Exception(string.Format("The {0} cube is not yet deployed to the {1} server.", oCube.Name, deploySet.TargetServer));
                            }

                            // update the agg designs
                            XmlaResultCollection xmlaRC = svr.Execute(sb.ToString());
                            StringBuilder        sbErr  = new StringBuilder();
                            for (int iRC = 0; iRC < xmlaRC.Count; iRC++)
                            {
                                for (int iMsg = 0; iMsg < xmlaRC[iRC].Messages.Count; iMsg++)
                                {
                                    if (!string.IsNullOrEmpty(xmlaRC[iRC].Messages[iMsg].Description))
                                    {
                                        sbErr.AppendLine(xmlaRC[iRC].Messages[iMsg].Description);
                                    }
                                }
                            }
                            if (sbErr.Length > 0)
                            {
                                MessageBox.Show(sbErr.ToString(), "BIDSHelper - Deploy Aggregation Designs");
                            }

                            projItem.DTE.Solution.SolutionBuild.BuildProject(projItem.DTE.Solution.SolutionBuild.ActiveConfiguration.Name, projItem.ContainingProject.UniqueName, false);
                        }
                        catch (System.Exception ex)
                        {
                            if (MessageBox.Show("The following error occured while trying to deploy the aggregation designs\r\n"
                                                + ex.Message
                                                + "\r\n\r\nDo you want to see a stack trace?"
                                                , "BIDSHelper - Deploy Aggregation Designs"
                                                , MessageBoxButtons.YesNo
                                                , MessageBoxIcon.Error
                                                , MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                            {
                                MessageBox.Show(ex.StackTrace);
                            }
                        }
                        finally
                        {
                            ApplicationObject.StatusBar.Progress(true, "Deploying Aggregation Designs", 5, 5);
                            svr.Disconnect();
                        }
                    }
                }
            }
            finally
            {
                ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(false, "Deploying Aggregation Designs", 5, 5);
            }
        }
            public static MvcHtmlString RenderXslt(string xslPath, string xmlString, List<KeyValuePair<string, string>> parameters = null)
            {
                string xsltResult = string.Empty;

                try
                {
                    // XML Settings
                    XmlReaderSettings xmlSettings = new XmlReaderSettings();
                    xmlSettings.XmlResolver = null;
                    xmlSettings.IgnoreComments = true;
                    xmlSettings.DtdProcessing = DtdProcessing.Ignore;
                    xmlSettings.ValidationType = ValidationType.None;

                    // Attaches an action to the valiation event handler. This will write out error messages in the Output pane.
                #if DEBUG
                    xmlSettings.ValidationEventHandler += (sender, e) =>
                    {
                        Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message));
                    };
                #endif

                    // XSLT Settings
                    XmlReaderSettings xsltSettings = new XmlReaderSettings();
                    xsltSettings.XmlResolver = null;
                    xsltSettings.DtdProcessing = DtdProcessing.Ignore;
                    xsltSettings.ValidationType = ValidationType.None;

                    // Attaches an action to the valiation event handler. This will write out error messages in the Output pane.
                #if DEBUG
                    xsltSettings.ValidationEventHandler += (sender, e) =>
                    {
                        Debug.WriteLine(string.Format("{0}({1},{2}): {3} - {4}", e.Exception.SourceUri, e.Exception.LineNumber, e.Exception.LinePosition, e.Severity, e.Message));
                    };
                #endif

                    // Init params
                    XsltArgumentList xslArgs = new XsltArgumentList();
                    if (parameters != null)
                    {
                        foreach (KeyValuePair<string, string> param in parameters)
                            xslArgs.AddParam(param.Key, string.Empty, param.Value);
                    }

                    // Load XML
                    using (XmlReader reader = XmlReader.Create(new StringReader(xmlString), xmlSettings))
                    {
                        // Load XSL
                        XsltSettings xslSettings = new XsltSettings(true, true); // Need to enable the document() fucntion

                        using (XmlReader xslSource = XmlReader.Create(xslPath, xsltSettings))
                        {
                            XslCompiledTransform xsltDoc = new XslCompiledTransform();
                            xsltDoc.Load(xslSource, xslSettings, new XmlUrlResolver());

                            // Transform
                            using (var sw = new UTF8StringWriter())
                            {
                                XmlWriterSettings settings = new XmlWriterSettings();
                                settings.Encoding = Encoding.UTF8;
                                settings.OmitXmlDeclaration = true;

                                using (var xw = XmlWriter.Create(sw, settings))
                                {
                                    xsltDoc.Transform(reader, xslArgs, sw);
                                }

                                xsltResult = sw.ToString();
                            }
                        }
                    }
                }
                catch { } // custom error handling here

                // Return result
                return MvcHtmlString.Create(xsltResult);
            }
예제 #27
0
파일: Blogs.ascx.cs 프로젝트: jaytem/minGit
    protected void MainView()
    {
        if (BlogId > 0)
        {
            //get type

            Ektron.Cms.Controls.BlogEntries boe = new Ektron.Cms.Controls.BlogEntries();
            boe.BlogID = BlogId;
            boe.Page = this.Page;
            boe.MaxResults = MaxResult;
            boe.Fill();

            if (!boe.XmlDoc.InnerXml.Equals(String.Empty))
            {
                XmlDocument xdBlogs = new XmlDocument();
                xdBlogs.InnerXml = boe.XmlDoc.InnerXml;

                XsltArgumentList xsltBlogsArgList = new XsltArgumentList();

                if (ShowComment == true)
                    xsltBlogsArgList.AddParam("ShowComment", "", "Yes");
                else xsltBlogsArgList.AddParam("ShowComment", "", "No");

                if (ShowSummary == true)
                    xsltBlogsArgList.AddParam("ShowSummary", "", "Yes");
                else xsltBlogsArgList.AddParam("ShowSummary", "", "No");

                if (ShowAuthor == true)
                    xsltBlogsArgList.AddParam("ShowAuthor", "", "Yes");
                else xsltBlogsArgList.AddParam("ShowAuthor", "", "No");

                if (ShowDate == true)
                    xsltBlogsArgList.AddParam("ShowDate", "", "Yes");
                else xsltBlogsArgList.AddParam("ShowDate", "", "No");

                xmlBlogList.DocumentContent = xdBlogs.InnerXml;
                xmlBlogList.TransformSource = _api.SitePath + "widgets/blogs/Blog.xsl";
                xmlBlogList.TransformArgumentList = xsltBlogsArgList;

            }
            else xmlBlogList.DocumentContent = null;

            phContent.Visible = true;
            phHelpText.Visible = false;
        }
        else
        {
            xmlBlogList.DocumentContent = null;
            phContent.Visible = false;
            phHelpText.Visible = true;
        }

        if (!(_host == null || _host.IsEditable == false))
        {
            divHelpText.Visible = true;
        }
        else
        {
            divHelpText.Visible = false;
        }
    }
예제 #28
0
        /// <summary>
        /// This is overridden to apply the XSL transformations to the document
        /// </summary>
        /// <param name="document">The document to transform</param>
        /// <param name="key">The topic key</param>
        /// <remarks><note type="important">An argument called <c>key</c> is automatically added to the argument
        /// list when each topic is transformed.  It will contain the current topic's key.</note></remarks>
        public override void Apply(XmlDocument document, string key)
        {
            // Raise a component event to signal that the topic is about to be transformed
            this.OnComponentEvent(new TransformingTopicEventArgs(key, document));

            foreach(Transform transform in transforms)
            {
                // Create the argument list and add the key as a parameter
                var transformArgs = new XsltArgumentList();

                foreach(var kv in transform.Arguments)
                    transformArgs.AddParam(kv.Key, String.Empty, kv.Value);

                transformArgs.AddParam("key", String.Empty, key);

                // Create a buffer into which output can be written
                using(MemoryStream buffer = new MemoryStream())
                {
                    // Do the transform, routing output to the buffer
                    XmlWriterSettings settings = transform.Xslt.OutputSettings;
                    XmlWriter writer = XmlWriter.Create(buffer, settings);

                    try
                    {
                        transform.Xslt.Transform(document, transformArgs, writer);
                    }
                    catch(XsltException e)
                    {
                        this.WriteMessage(key, MessageLevel.Error, "An error occurred while executing the " +
                            "transform '{0}', on line {1}, at position {2}. The error message was: {3}",
                            e.SourceUri, e.LineNumber, e.LinePosition, (e.InnerException == null) ? e.Message :
                            e.InnerException.Message);
                    }
                    catch(XmlException e)
                    {
                        this.WriteMessage(key, MessageLevel.Error, "An error occurred while executing the " +
                            "transform '{0}', on line {1}, at position {2}. The error message was: {3}",
                            e.SourceUri, e.LineNumber, e.LinePosition, (e.InnerException == null) ? e.Message :
                            e.InnerException.Message);
                    }
                    finally
                    {
                        writer.Close();
                    }

                    // Replace the document by the contents of the buffer
                    buffer.Seek(0, SeekOrigin.Begin);

                    // Some settings to ensure that we don't try to go get, parse, and validate using any
                    // referenced schemas or DTDs
                    XmlReaderSettings readerSettings = new XmlReaderSettings();

                    //!EFW - Update. Uses DtdProcessing property now rather than the obsolete ProhibitDtd property.
                    // The old property value was false which translates to Parse for the new property.
                    readerSettings.DtdProcessing = DtdProcessing.Parse;
                    readerSettings.XmlResolver = null;

                    XmlReader reader = XmlReader.Create(buffer, readerSettings);

                    try
                    {
                        document.Load(reader);
                    }
                    catch(XmlException e)
                    {
                        this.WriteMessage(key, MessageLevel.Error, "An error occurred while executing the " +
                            "transform '{0}', on line {1}, at position {2}. The error message was: {3}",
                            e.SourceUri, e.LineNumber, e.LinePosition, (e.InnerException == null) ? e.Message :
                            e.InnerException.Message);
                    }
                    finally
                    {
                        reader.Close();
                    }
                }
            }

            // Raise a component event to signal that the topic has been transformed
            this.OnComponentEvent(new TransformedTopicEventArgs(key, document));
        }
예제 #29
0
    public static string BuildTopNav()
    {
        Bijou.Level++;

        string root = FileUtils.BuildRelativePath(Bijou.Level);
        XsltArgumentList xslArg = new XsltArgumentList();
        if (Bijou.Index) {
            xslArg.AddParam("root", "", root);
            xslArg.AddParam("index", "", "index.html");
        } else if (!string.IsNullOrEmpty(Bijou.WebRoot)) {
            xslArg.AddParam("root", "", Bijou.WebRoot);
            xslArg.AddParam("index", "", "");
        } else {
            xslArg.AddParam("root", "", "");
            xslArg.AddParam("index", "", "");
        }

        if (Bijou.Home) {
            xslArg.AddParam("home", "", "1");
          	} else {
            xslArg.AddParam("home", "", "0");
          	}

        Bijou.Level--;

        return XmlUtils.Transform("template/navigation/topnav.xslt", Bijou.TopNavXml, xslArg);
    }
예제 #30
0
        /// <summary>
        /// Sends an email by using the XSLT template file. The template XML is transform over a IDictionary object
        /// to an XHTML document.
        /// </summary>
        /// <param name="sEmailTo">To email address</param>
        /// <param name="oXsltEmailTemplate">Xml Reader from XSLT template file </param>
        /// <param name="oParameters">Dictonary objects containing data to be inserted in the transformed doc.</param>
        static public void SendEmail(Dictionary <string, string> oToEmails, Dictionary <string, string> oCCEmails, string sEmailFrom, string sEmailFromName, string sEmailSubject, XmlReader oXsltEmailTemplate, IDictionary oParameters)
        {
            XslCompiledTransform oXslt;
            XmlDocument          oXmlDoc;
            XPathNavigator       oXpathNavigator;
            XsltArgumentList     oXslArguments;
            StringBuilder        oEmailBuilder;
            XmlTextWriter        oXmlWriter;
            string        sEmailBody;
            string        oListOfContacts;
            string        oListOfCCContacts;
            Authorization oAuthorization;
            RoleClaim     oCurrentRoleClaim;

            if (oXsltEmailTemplate != null)
            {
                oXslt = new XslCompiledTransform();

                oXslt.Load(oXsltEmailTemplate);

                oXmlDoc = new XmlDocument();
                oXmlDoc.AppendChild(oXmlDoc.CreateElement("DocumentRoot"));

                oXpathNavigator = oXmlDoc.CreateNavigator();


                oXslArguments = new XsltArgumentList();
                if (oParameters != null)
                {
                    foreach (DictionaryEntry entry in oParameters)
                    {
                        oXslArguments.AddParam(entry.Key.ToString(), string.Empty, entry.Value);
                    }
                }

                oEmailBuilder = new StringBuilder();

                oXmlWriter = new XmlTextWriter(new System.IO.StringWriter(oEmailBuilder));

                oXslt.Transform(oXpathNavigator, oXslArguments, oXmlWriter, null);

                if (oEmailBuilder.Length > 0)
                {
                    oAuthorization = Authorization.CurrentAuthorization;

                    if (oAuthorization != null && !oAuthorization.IsTestMode)
                    {
                        sEmailBody = HttpUtility.HtmlDecode(oEmailBuilder.ToString());

                        oListOfContacts = EmailsDictionaryToCommaDelimitedString(oToEmails);

                        oListOfCCContacts = EmailsDictionaryToCommaDelimitedString(oCCEmails);

                        if (oListOfContacts.Length > 0)
                        {
                            SendEmail(sEmailFrom, sEmailFromName, oListOfContacts, oListOfCCContacts, sEmailSubject, sEmailBody);
                        }
                        else
                        {
                            Sitecore.Diagnostics.Log.Error("SendEmail - Email could not be sent because it has no destination email addresses", typeof(Utilities.Email));
                        }
                    }
                }
            }
        }
예제 #31
0
    /// <summary>
    /// Display orchestration view pane...
    /// </summary>
    /// <param name="orchestrationName"></param>
    /// <param name="assemblyName"></param>
    private void DisplayOrchestration(string orchestrationName, string assemblyName)
    {
        try
        {
            BizTalkInstallation bizTalkInstallation = new BizTalkInstallation();
            bizTalkInstallation.Server = BCCOperator.BizTalkSQLServer();
            bizTalkInstallation.MgmtDatabaseName = BCCOperator.BizTalkMgmtDb();

            Orchestration oInstance = bizTalkInstallation.GetOrchestration(assemblyName, orchestrationName);

            if (oInstance != null)
            {
                string filePath = BuildFilePath(oInstance.Name);

                if (File.Exists(filePath))
                {
                    File.Delete(filePath);
                }

                if (oInstance.SaveAsImage(filePath))
                {
                    // Left side panel
                    this.leftSideView.Controls.Add(ShowOrchestration(oInstance.Name, orchestrationName));
                }

                if (oInstance.ShapeMap.Count > 0)
                {
                    XslCompiledTransform orchCodeTransform = new XslCompiledTransform();

                    XmlTextReader xr = new XmlTextReader(new StreamReader(StylesheetPath("Header")));
                    orchCodeTransform.Load(xr, XsltSettings.Default, new XmlUrlResolver());
                    xr.Close();

                    XsltArgumentList orchCodeXsltArgs = new XsltArgumentList();

                    string header = WriteTransformedXmlDataToString2(
                                      oInstance.GetXml(),
                                      orchCodeTransform,
                                      orchCodeXsltArgs);

                    Label lblOrchData = new Label();
                    lblOrchData.Text = header;
                    lblOrchData.BorderStyle = BorderStyle.Solid;
                    lblOrchData.BorderWidth = Unit.Pixel(2);
                    lblOrchData.ToolTip = "Orchestration header section";

                    // Right side panel
                    this.rightSideView.Controls.Add(lblOrchData);
                    // Right side panel
                    this.rightSideView.Controls.Add(new LiteralControl("<br/><br/>"));

                    // Orchestration data
                    orchCodeTransform = new XslCompiledTransform();

                    xr = new XmlTextReader(new StreamReader(StylesheetPath("Body") ) );
                    orchCodeTransform.Load(xr, XsltSettings.Default, new XmlUrlResolver());
                    xr.Close();

                    orchCodeXsltArgs = new XsltArgumentList();
                    orchCodeXsltArgs.AddParam("OrchName", string.Empty, oInstance.Name);

                    string body = WriteTransformedXmlDataToString(
                                      oInstance.ArtifactData,
                                      orchCodeTransform,
                                      orchCodeXsltArgs);

                    Label lblOrchData2 = new Label();
                    lblOrchData2.Text = body;
                    lblOrchData2.BorderStyle = BorderStyle.Solid;
                    lblOrchData2.BorderWidth = Unit.Pixel(2);
                    lblOrchData2.ToolTip = "Orchestration body section";

                    // Right side panel
                    this.rightSideView.Controls.Add(lblOrchData2);
                }
                else
                {
                    // Right side panel
                    this.rightSideView.Controls.Add(new LiteralControl("No orchestration shapes were found."));
                }
            }
        }
        catch (Exception exception)
        {
            this.leftSideView.Controls.Add(new LiteralControl("Exception:" + exception.Message + ". Try refreshing the page or recycling the application pool."));
        }
    }
예제 #32
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <exception cref="BuildException">
        /// <list type="bullet">
        /// <item>
        /// <description>If the <see cref="OutputFile"/> attribute is set and the <see cref="InFiles"/> element is used.</description>
        /// </item>
        /// <item>
        /// <description>If no source files are present.</description>
        /// </item>
        /// <item>
        /// <description>If the xslt file does not exist.</description>
        /// </item>
        /// <item>
        /// <description>If the xslt file cannot be retrieved by the specified URI.</description>
        /// </item>
        /// </list>
        /// </exception>
        protected override void ExecuteTask()
        {
            // ensure base directory is set, even if fileset was not initialized
            // from XML
            if (InFiles.BaseDirectory == null)
            {
                InFiles.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            StringCollection srcFiles = null;

            if (SrcFile != null)
            {
                srcFiles = new StringCollection();
                srcFiles.Add(SrcFile.FullName);
            }
            else if (InFiles.FileNames.Count > 0)
            {
                if (OutputFile != null)
                {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA1148")),
                                             Location);
                }
                srcFiles = InFiles.FileNames;
            }

            if (srcFiles == null || srcFiles.Count == 0)
            {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       ResourceUtils.GetString("NA1147")),
                                         Location);
            }

            if (XsltFile.IsFile)
            {
                FileInfo fileInfo = new FileInfo(XsltFile.LocalPath);

                if (!fileInfo.Exists)
                {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA1149"), fileInfo.FullName),
                                             Location);
                }
            }
            else
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(XsltFile);
                if (Proxy != null)
                {
                    request.Proxy = Proxy.GetWebProxy();
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA1149"), XsltFile),
                                             Location);
                }
            }

            foreach (string srcFile in srcFiles)
            {
                string destFile = null;

                if (OutputFile != null)
                {
                    destFile = OutputFile.FullName;
                }

                if (String.IsNullOrEmpty(destFile))
                {
                    // TODO: use System.IO.Path (gs)
                    // append extension if necessary
                    string ext    = Extension.IndexOf(".") > -1 ? Extension : "." + Extension;
                    int    extPos = srcFile.LastIndexOf('.');
                    if (extPos == -1)
                    {
                        destFile = srcFile + ext;
                    }
                    else
                    {
                        destFile = srcFile.Substring(0, extPos) + ext;
                    }
                    destFile = Path.GetFileName(destFile);
                }

                FileInfo srcInfo  = new FileInfo(srcFile);
                FileInfo destInfo = new FileInfo(Path.GetFullPath(Path.Combine(
                                                                      DestDir.FullName, destFile)));

                if (!srcInfo.Exists)
                {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA1150"), srcInfo.FullName),
                                             Location);
                }

                bool destOutdated = !destInfo.Exists ||
                                    srcInfo.LastWriteTime > destInfo.LastWriteTime;

                if (!destOutdated && XsltFile.IsFile)
                {
                    FileInfo fileInfo = new FileInfo(XsltFile.LocalPath);
                    destOutdated |= fileInfo.LastWriteTime > destInfo.LastWriteTime;
                }

                if (destOutdated)
                {
                    XmlReader  xmlReader = null;
                    XmlReader  xslReader = null;
                    TextWriter writer    = null;

                    try {
                        // store current directory
                        string originalCurrentDirectory = Directory.GetCurrentDirectory();

                        // initialize XPath document holding input XML
                        XPathDocument xml = null;

                        try {
                            // change current directory to directory containing
                            // XSLT file, to allow includes to be resolved
                            // correctly
                            Directory.SetCurrentDirectory(srcInfo.DirectoryName);

                            // load the xml that needs to be transformed
                            Log(Level.Verbose, "Loading XML file '{0}'.",
                                srcInfo.FullName);
                            xmlReader = CreateXmlReader(new Uri(srcInfo.FullName));
                            xml       = new XPathDocument(xmlReader);
                        } finally {
                            // restore original current directory
                            Directory.SetCurrentDirectory(originalCurrentDirectory);
                        }

                        // initialize xslt parameters
                        XsltArgumentList xsltArgs = new XsltArgumentList();

                        // set the xslt parameters
                        foreach (XsltParameter parameter in Parameters)
                        {
                            if (IfDefined && !UnlessDefined)
                            {
                                xsltArgs.AddParam(parameter.ParameterName,
                                                  parameter.NamespaceUri, parameter.Value);
                            }
                        }

                        // create extension objects
                        foreach (XsltExtensionObject extensionObject in ExtensionObjects)
                        {
                            if (extensionObject.IfDefined && !extensionObject.UnlessDefined)
                            {
                                object extensionInstance = extensionObject.CreateInstance();
                                xsltArgs.AddExtensionObject(extensionObject.NamespaceUri,
                                                            extensionInstance);
                            }
                        }

                        try {
                            if (XsltFile.IsFile)
                            {
                                // change current directory to directory containing
                                // XSLT file, to allow includes to be resolved
                                // correctly
                                FileInfo fileInfo = new FileInfo(XsltFile.LocalPath);
                                Directory.SetCurrentDirectory(fileInfo.DirectoryName);
                            }

                            // load the stylesheet
                            Log(Level.Verbose, "Loading stylesheet '{0}'.", XsltFile);
                            xslReader = CreateXmlReader(XsltFile);

                            // create writer for the destination xml
                            writer = CreateWriter(destInfo.FullName);

                            // do the actual transformation
                            Log(Level.Info, "Processing '{0}' to '{1}'.",
                                srcInfo.FullName, destInfo.FullName);

                            XslCompiledTransform xslt = new XslCompiledTransform();
                            string xslEngineName      = xslt.GetType().Name;

                            Log(Level.Verbose, "Using {0} to load '{1}'.",
                                xslEngineName, XsltFile);
                            xslt.Load(xslReader, new XsltSettings(true, true), new XmlUrlResolver());

                            Log(Level.Verbose, "Using {0} to process '{1}' to '{2}'.",
                                xslEngineName, srcInfo.FullName, destInfo.FullName);
                            xslt.Transform(xml, xsltArgs, writer);
                        } finally {
                            // restore original current directory
                            Directory.SetCurrentDirectory(originalCurrentDirectory);
                        }
                    } catch (Exception ex) {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                               ResourceUtils.GetString("NA1151"), srcInfo.FullName, XsltFile),
                                                 Location, ex);
                    } finally {
                        // ensure file handles are closed
                        if (xmlReader != null)
                        {
                            xmlReader.Close();
                        }
                        if (xslReader != null)
                        {
                            xslReader.Close();
                        }
                        if (writer != null)
                        {
                            writer.Close();
                        }
                    }
                }
            }
        }
예제 #33
0
파일: test.cs 프로젝트: mono/gert
	static int Main (string[] args)
	{
		// Load source XML into an XPathDocument object instance.
		XPathDocument xmldoc = new XPathDocument ("books.xml");
		// Create an XPathNavigator from the XPathDocument.
		XPathNavigator nav = xmldoc.CreateNavigator ();

		// The user-defined functions in this sample implement equivalents of the frequently-used
		// Left(string,length) and Right(string,length) Visual Basic string functions.

		// Compile two XPath query expressions that use the user-defined XPath functions and a user-defined variable.
		// The compilation step only checks the query expression for correct tokenization. It does not 
		// try to resolve or to verify the definition or validity of the function and the variable names
		// that are used in the query expression.
		XPathExpression expr1 = nav.Compile ("myFuncs:left(string(.),$length)");
		XPathExpression expr2 = nav.Compile ("myFuncs:right(string(.),$length)");

		// Create an instance of an XsltArgumentList object.
		XsltArgumentList varList = new XsltArgumentList ();
		// Add the user-defined variable to the XsltArgumentList object,
		// and then supply a value for it.
		varList.AddParam ("length", "", 5);

		// Create an instance of a custom XsltContext object. This object is used to 
		// resolve the references to the user-defined XPath extension functions and the
		// user-defined variable at execution time. 

		// Notice that in the Ctor, you also pass in the XsltArgumentList object 
		// in which the user-defined variable is defined.
		CustomContext cntxt = new CustomContext (new NameTable (), varList);

		// Add a namespace definition for the ns prefix that qualifies the user-defined 
		// function names in the expr1 and expr2 query expressions.
		cntxt.AddNamespace ("myFuncs", "http://myXPathExtensionFunctions");

		// Associate the custom XsltContext object with the two XPathExpression objects
		// whose query expressions use the custom XPath functions and the custom variable.
		expr1.SetContext (cntxt);
		expr2.SetContext (cntxt);

		XPathNodeIterator iter = nav.Select ("/Books/Title");
		if (iter.Count != 2) {
			Console.WriteLine ("#1");
			return 1;
		}

		iter.MoveNext ();
		nav = iter.Current;
		if (nav.Value != "A Brief History of Time") {
			Console.WriteLine ("#2: " + nav.Value);
			return 1;
		}
		if (((string) (nav.Evaluate (expr1))) != "A Bri") {
			Console.WriteLine ("#3: " + nav.Evaluate (expr1));
			return 1;
		}
		if (((string) (nav.Evaluate (expr2))) != " Time") {
			Console.WriteLine ("#4: " + nav.Evaluate (expr2));
			return 1;
		}

		iter.MoveNext ();
		nav = iter.Current;
		if (nav.Value != "Principle Of Relativity") {
			Console.WriteLine ("#5: " + nav.Value);
			return 1;
		}
		if (((string) (nav.Evaluate (expr1))) != "Princ") {
			Console.WriteLine ("#6: " + nav.Evaluate (expr1));
			return 1;
		}
		if (((string) (nav.Evaluate (expr2))) != "ivity") {
			Console.WriteLine ("#7: " + nav.Evaluate (expr2));
			return 1; 
		}
		return 0;
	}
예제 #34
0
        void ProcessDirectories(List <string> sourceDirectories)
        {
            if (sourceDirectories.Count == 0 || opts.dest == null || opts.dest == "")
            {
                throw new ApplicationException("The source and dest options must be specified.");
            }

            Directory.CreateDirectory(opts.dest);

            // Load the stylesheets, overview.xml, and resolver

            XslCompiledTransform overviewxsl = LoadTransform("overview.xsl", sourceDirectories);
            XslCompiledTransform stylesheet  = LoadTransform("stylesheet.xsl", sourceDirectories);
            XslCompiledTransform template;

            if (opts.template == null)
            {
                template = LoadTransform("defaulttemplate.xsl", sourceDirectories);
            }
            else
            {
                try {
                    XmlDocument templatexsl = new XmlDocument();
                    templatexsl.Load(opts.template);
                    template = new XslCompiledTransform(DebugOutput);
                    template.Load(templatexsl);
                } catch (Exception e) {
                    throw new ApplicationException("There was an error loading " + opts.template, e);
                }
            }

            XmlDocument overview = GetOverview(sourceDirectories);

            ArrayList extensions = GetExtensionMethods(overview);

            // Create the master page
            XsltArgumentList overviewargs = new XsltArgumentList();

            overviewargs.AddParam("Index", "", overview.CreateNavigator());

            var regenIndex = ShouldRegenIndexes(opts, overview, sourceDirectories);

            if (regenIndex)
            {
                overviewargs.AddParam("ext", "", opts.ext);
                overviewargs.AddParam("basepath", "", "./");
                Generate(overview, overviewxsl, overviewargs, opts.dest + "/index." + opts.ext, template, sourceDirectories);
                overviewargs.RemoveParam("basepath", "");
            }
            overviewargs.AddParam("basepath", "", "../");

            // Create the namespace & type pages

            XsltArgumentList typeargs = new XsltArgumentList();

            typeargs.AddParam("ext", "", opts.ext);
            typeargs.AddParam("basepath", "", "../");
            typeargs.AddParam("Index", "", overview.CreateNavigator());

            foreach (XmlElement ns in overview.SelectNodes("Overview/Types/Namespace"))
            {
                string nsname = ns.GetAttribute("Name");

                if (opts.onlytype != null && !opts.onlytype.StartsWith(nsname + "."))
                {
                    continue;
                }

                System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(opts.dest + "/" + nsname);
                if (!d.Exists)
                {
                    d.Create();
                }

                // Create the NS page
                string nsDest = opts.dest + "/" + nsname + "/index." + opts.ext;
                if (regenIndex)
                {
                    overviewargs.AddParam("namespace", "", nsname);
                    Generate(overview, overviewxsl, overviewargs, nsDest, template, sourceDirectories);
                    overviewargs.RemoveParam("namespace", "");
                }

                foreach (XmlElement ty in ns.SelectNodes("Type"))
                {
                    string typename, typefile, destfile;
                    GetTypePaths(opts, ty, out typename, out typefile, out destfile);

                    if (DestinationIsNewer(typefile, destfile))
                    {
                        // target already exists, and is newer.  why regenerate?
                        continue;
                    }

                    XmlDocument typexml = new XmlDocument();
                    typexml.Load(typefile);
                    PreserveMembersInVersions(typexml);
                    if (extensions != null)
                    {
                        DocLoader loader = CreateDocLoader(overview);
                        XmlDocUtils.AddExtensionMethods(typexml, extensions, loader);
                    }

                    Console.WriteLine(nsname + "." + typename);

                    Generate(typexml, stylesheet, typeargs, destfile, template, sourceDirectories);
                }
            }
        }
예제 #35
0
        public static Stream XslTransform(string resource, Stream input, params DictionaryEntry[] entries)
        {
            int t1 = Environment.TickCount;

            Stream s = Util.GetEmbeddedResourceStream(resource);

            int           t2 = Environment.TickCount;
            XPathDocument d  = new XPathDocument(s);

            Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "new XPathDocument(1) t={0}", Environment.TickCount - t2));

            int t3 = Environment.TickCount;
            XslCompiledTransform xslc = new XslCompiledTransform();

            // Using the Trusted Xslt is fine as the style sheet comes from our own assemblies.
            // This is similar to the prior this.GetType().Assembly/Evidence method that was used in the now depricated XslTransform.
            xslc.Load(d, XsltSettings.TrustedXslt, s_resolver);
            Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "XslCompiledTransform.Load t={0}", Environment.TickCount - t3));

            // Need to copy input stream because XmlReader will close it,
            // causing errors for later callers that access the same stream
            MemoryStream clonedInput = new MemoryStream();

            Util.CopyStream(input, clonedInput);

            int       t4  = Environment.TickCount;
            XmlReader xml = XmlReader.Create(clonedInput);

            Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "new XmlReader(2) t={0}", Environment.TickCount - t4));

            XsltArgumentList args = null;

            if (entries.Length > 0)
            {
                args = new XsltArgumentList();
                foreach (DictionaryEntry entry in entries)
                {
                    string key = entry.Key.ToString();
                    object val = entry.Value.ToString();
                    args.AddParam(key, "", val);
                    Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "arg: key='{0}' value='{1}'", key, val.ToString()));
                }
            }

            MemoryStream  m = new MemoryStream();
            XmlTextWriter w = new XmlTextWriter(m, Encoding.UTF8);

            w.WriteStartDocument();

            int t5 = Environment.TickCount;

            xslc.Transform(xml, args, w, s_resolver);
            Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "XslCompiledTransform.Transform t={0}", Environment.TickCount - t4));

            w.WriteEndDocument();
            w.Flush();
            m.Position = 0;

            Util.WriteLog(String.Format(CultureInfo.CurrentCulture, "XslCompiledTransform(\"{0}\") t={1}", resource, Environment.TickCount - t1));
            return(m);
        }
예제 #36
0
        private void BindJob()
        {
            using (Facade.IJob facJob = new Facade.Job())
            {
                LoadJob();

                using (Facade.IOrganisation facOrganisation = new Facade.Organisation())
                    m_organisation = facOrganisation.GetForIdentityId(m_job.IdentityId);

                XmlDocument          jobDocument = m_job.ToXml();
                XslCompiledTransform transformer = new XslCompiledTransform();
                transformer.Load(Server.MapPath(@"..\..\..\xsl\instructions.xsl"));
                XmlUrlResolver resolver  = new XmlUrlResolver();
                XPathNavigator navigator = jobDocument.CreateNavigator();

                // Populate the Collections.
                XsltArgumentList collectionArgs = new XsltArgumentList();
                if (m_job.JobType == eJobType.PalletReturn)
                {
                    collectionArgs.AddParam("InstructionTypeId", "", "5");
                }
                else
                {
                    collectionArgs.AddParam("InstructionTypeId", "", "1");
                }
                collectionArgs.AddParam("DocketText", "", m_organisation.DocketNumberText);
                collectionArgs.AddParam("webserver", "", Orchestrator.Globals.Configuration.WebServer);
                StringWriter sw = new StringWriter();
                transformer.Transform(navigator, collectionArgs, sw);
                lblCollections.Text = sw.GetStringBuilder().ToString();

                // Populate the Deliveries.
                sw = new StringWriter();
                XsltArgumentList deliveryArgs = new XsltArgumentList();
                deliveryArgs.AddParam("InstructionTypeId", "", "2,6,7");
                deliveryArgs.AddParam("DocketText", "", m_organisation.DocketNumberText);
                deliveryArgs.AddParam("webserver", "", Orchestrator.Globals.Configuration.WebServer);
                transformer.Transform(navigator, deliveryArgs, sw);
                lblDeliveries.Text = sw.GetStringBuilder().ToString();

                // Populate the Pallet Handling.
                sw = new StringWriter();
                XsltArgumentList leavePalletArgs = new XsltArgumentList();
                leavePalletArgs.AddParam("InstructionTypeId", "", "3");
                leavePalletArgs.AddParam("DocketText", "", m_organisation.DocketNumberText);
                leavePalletArgs.AddParam("webserver", "", Orchestrator.Globals.Configuration.WebServer);
                transformer.Transform(navigator, leavePalletArgs, sw);
                lblLeavePallets.Text = sw.GetStringBuilder().ToString();
                sw = new StringWriter();
                XsltArgumentList dehirePalletArgs = new XsltArgumentList();
                dehirePalletArgs.AddParam("InstructionTypeId", "", "4");
                dehirePalletArgs.AddParam("DocketText", "", m_organisation.DocketNumberText);
                dehirePalletArgs.AddParam("webserver", "", Orchestrator.Globals.Configuration.WebServer);
                transformer.Transform(navigator, dehirePalletArgs, sw);
                lblDeHirePallets.Text = sw.GetStringBuilder().ToString();

                if (lblLeavePallets.Text == lblDeHirePallets.Text)
                {
                    lblLeavePallets.Text  = "No Pallet Handling has been configured for this job.";
                    lblDeHirePallets.Text = String.Empty;
                }
            }

            LoadEmptyPallets();
        }
예제 #37
0
 public void AddParameterToXsltArgs(string paramName, string paramValue)
 {
     xsltArgs.AddParam(paramName,
                       "" /* i.e. Use the default namespace */,
                       paramValue);
 }
예제 #38
0
        internal void OnMenuHelp(object sender, EventArgs e)
        {
            Tuple <string, string> urls = GetHelpUrls();

            if (urls == null)
            {
                return;
            }

            string helpUrl = urls.Item1;

            if (!string.IsNullOrWhiteSpace(helpUrl))
            {
                try
                {
                    if (helpUrl.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase) &&
                        File.Exists(helpUrl))    //Check if it's an actual file too
                    {
                        //It's a local XML file, so transform it to HTML using the XSL
                        var    transform = new XslCompiledTransform(true);
                        string tempFile  = Path.Combine(Path.GetTempPath(),
                                                        string.Concat(Path.GetFileNameWithoutExtension(helpUrl), ".html"));

                        //The XSL is an embedded reasource
                        //Don't use two nested usings to avoid CA2202: Do not dispose objects multiple times
                        StringReader sr = null;
                        try
                        {
                            sr = new StringReader(CodeGenerationResource.xmldoc2html);
                            using (var xr = XmlReader.Create(sr))
                            {
                                sr = null;
                                transform.Load(xr);
                            }
                        }
                        finally
                        {
                            if (sr != null)
                            {
                                sr.Dispose();
                            }
                        }


                        var args = new XsltArgumentList();
                        if (!string.IsNullOrWhiteSpace(urls.Item2))
                        {
                            args.AddParam(XsltUrlParam, string.Empty, urls.Item2);
                        }

                        using (var stream = new FileStream(tempFile, FileMode.Create))
                            transform.Transform(helpUrl, args, stream);

                        helpUrl = tempFile;
                    }

                    var dte = this.ServiceProvider.GetService(typeof(SDTE)) as DTE;

                    if (dte != null)
                    {
                        dte.ItemOperations.Navigate(helpUrl);
                    }
                }
                catch (IOException ex) { Log.WriteError(ex); }
                catch (XmlException ex) { Log.WriteError(ex); }
                catch (XsltException ex) { Log.WriteError(ex); }
                catch (UriFormatException ex) { Log.WriteError(ex); }
                catch (System.Net.WebException ex) { Log.WriteError(ex); }
            }
        }
예제 #39
0
        public override bool transform()
        {
            //XmlUrlResolver resourceResolver = null;

            //try
            //{

            //    resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(),
            //        this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + "Powerpoint.oox2uof");
            //    MainTransform(TranslatorConstants.OOXToUOF_XSL, resourceResolver, originalFile, grpTmp, outputFile);

            //}
            //catch (Exception ex)
            //{
            //    logger.Warn(ex.Message);
            //}


            string numberRefTmp = Path.GetDirectoryName(originalFile) + "\\" + "numberRefTmp.xml";
            //  NumberRef(inputFile, numberRefTmp);
            //   deleteLayoutAnchors(inputFile);
            bool result = true;

            //  XmlTextWriter resultWriter = null;


            #region change the IDs in the UOF file to fix a bug
            //更改输出文件的ID值,以使从UOF转化为OPENXML时,Layout的id能正常转换
            //added by SYBASE 2009.07.08
            XmlDocument doc = new XmlDocument();
            //doc.Load(@"C:\Users\v-xipia\Desktop\test.xml");
            //  doc.Load(outputFile);
            doc.Load(inputFile);

            XmlTextWriter tw = null;

            // Create an XmlNamespaceManager to resolve the default namespace.
            XmlNamespaceManager nmgr = new XmlNamespaceManager(doc.NameTable);
            //nsmgr.AddNamespace("bk", "urn:newbooks-schema");
            nmgr.AddNamespace("字", TranslatorConstants.XMLNS_UOFWORDPROC);
            nmgr.AddNamespace("uof", TranslatorConstants.XMLNS_UOF);
            nmgr.AddNamespace("图", TranslatorConstants.XMLNS_UOFGRAPH);
            nmgr.AddNamespace("表", TranslatorConstants.XMLNS_UOFSPREADSHEET);
            nmgr.AddNamespace("演", TranslatorConstants.XMLNS_UOFPRESENTATION);
            nmgr.AddNamespace("a", TranslatorConstants.XMLNS_A);
            nmgr.AddNamespace("app", TranslatorConstants.XMLNS_APP);
            nmgr.AddNamespace("cp", TranslatorConstants.XMLNS_CP);
            nmgr.AddNamespace("dc", TranslatorConstants.XMLNS_DC);
            nmgr.AddNamespace("dcmitype", TranslatorConstants.XMLNS_DCMITYPE);
            nmgr.AddNamespace("dcterms", TranslatorConstants.XMLNS_DCTERMS);
            nmgr.AddNamespace("fo", TranslatorConstants.XMLNS_FO);
            nmgr.AddNamespace("p", TranslatorConstants.XMLNS_P);
            nmgr.AddNamespace("r", TranslatorConstants.XMLNS_R);
            nmgr.AddNamespace("rel", TranslatorConstants.XMLNS_REL);
            nmgr.AddNamespace("元", TranslatorConstants.XMLNS_METADATA);
            nmgr.AddNamespace("对象", TranslatorConstants.XMLNS_UOFOBJECTS);
            nmgr.AddNamespace("式样", TranslatorConstants.XMLNS_UOFSTYLES);
            nmgr.AddNamespace("pzip", "urn:u2o:xmlns:post-processings:special");
            nmgr.AddNamespace("图形", TranslatorConstants.XMLNS_UOFGRAPHICS);
            nmgr.AddNamespace("规则", TranslatorConstants.XMLNS_UOFRULES);
            //// Select and display all book titles.
            //XmlNodeList nodeList;
            XmlElement rootOutput = doc.DocumentElement;

            //2010-12-15 罗文甜,增加段落式样的标识符替换
            XmlNodeList paraStyleList = rootOutput.SelectNodes("//式样:段落式样_9912|//式样:段落式样_9905", nmgr);
            string      currentParaID = "";
            string      tempParaID    = "";
            int         inum          = 1;
            foreach (XmlNode paraStyle in paraStyleList)
            {
                currentParaID = paraStyle.Attributes.GetNamedItem("标识符_4100").Value;
                if (inum < 10)
                {
                    // tempParaID = "tyleAttrId" + "0000" + inum;
                    tempParaID = "tyleAttrId" + "0000" + inum;
                }
                else if (inum < 100)
                {
                    tempParaID = "tyleAttrId" + "000" + inum;
                }
                else if (inum < 1000)
                {
                    tempParaID = "tyleAttrId" + "00" + inum;
                }
                else if (inum < 10000)
                {
                    tempParaID = "tyleAttrId" + "0" + inum;
                }
                else if (inum < 100000)
                {
                    tempParaID = "tyleAttrId" + inum;
                }
                else
                {
                    throw new Exception("Too many paragraphs id");
                }
                paraStyle.Attributes.GetNamedItem("标识符_4100").Value = tempParaID;
                foreach (XmlNode paraStyleTwo in paraStyleList)
                {
                    if (((XmlElement)paraStyleTwo).HasAttribute("基式样引用_4104"))
                    {
                        if (paraStyleTwo.Attributes.GetNamedItem("基式样引用_4104").Value == currentParaID)
                        {
                            paraStyleTwo.Attributes.GetNamedItem("基式样引用_4104").Value = tempParaID;
                        }
                    }
                }

                XmlNodeList paraAttrs = rootOutput.SelectNodes("//字:段落属性_419B", nmgr);
                foreach (XmlNode paraAttr in paraAttrs)
                {
                    if (((XmlElement)paraAttr).HasAttribute("式样引用_419C") && paraAttr.Attributes.GetNamedItem("式样引用_419C").Value == currentParaID)
                    {
                        paraAttr.Attributes.GetNamedItem("式样引用_419C").Value = tempParaID;
                    }
                }

                inum++;
            }

            XmlNodeList animiationSequenceList = doc.SelectNodes("//演:序列_6B1B", nmgr);
            //2010-12-08 罗文甜:增加连接线始端和终端的图形引用
            XmlNodeList curveShapList = doc.SelectNodes("//图:连接线规则_8027", nmgr);

            XmlNodeList anchorNodeList;
            anchorNodeList = rootOutput.SelectNodes("//uof:锚点_C644", nmgr);

            //当前的GraphicsID
            string currentGraphicsID = "";
            //替换掉的GraphicsID
            //OBJ00003
            string tempGraphicsID = "";
            //tempGraphicsID = "OBJ";
            //对当前处理的图像编号计数
            int i = 1;

            foreach (XmlNode anchorNode in anchorNodeList)
            {
                //Console.WriteLine(anchorNode.Name);
                //存储当前GraphicsID,并替换掉
                currentGraphicsID = anchorNode.Attributes.GetNamedItem("图形引用_C62E").Value;
                //Console.WriteLine(currentGraphicsID + "\r\n");

                if (i < 10)
                {
                    tempGraphicsID = "Obj" + "000" + i;
                }
                else if (i < 100)
                {
                    tempGraphicsID = "Obj" + "00" + i;
                }
                else if (i < 1000)
                {
                    tempGraphicsID = "Obj" + "0" + i;
                }
                else if (i < 10000)
                {
                    tempGraphicsID = "Obj" + i;
                }
                else
                {
                    throw new Exception("Too many Graphics id");
                }


                anchorNode.Attributes.GetNamedItem("图形引用_C62E").Value = tempGraphicsID;
                //Console.WriteLine(tempGraphicsID);


                XmlNodeList graphicsNodeList;
                //XmlElement root = doc.DocumentElement;
                graphicsNodeList = rootOutput.SelectNodes("//图:图形_8062", nmgr);


                foreach (XmlNode graphicsNode in graphicsNodeList)
                {
                    if (graphicsNode.Attributes.GetNamedItem("标识符_804B").Value == currentGraphicsID)
                    {
                        //Console.WriteLine(graphicsNode.Name);
                        //Console.WriteLine(graphicsNode.Attributes.GetNamedItem("图:标识符").Value + "\r\n");
                        graphicsNode.Attributes.GetNamedItem("标识符_804B").Value = tempGraphicsID;
                        //Console.WriteLine(currentGraphicsID);
                        //Console.WriteLine();

                        // 动画引用
                        foreach (XmlNode animiationSequence in animiationSequenceList)
                        {
                            if (animiationSequence.Attributes.GetNamedItem("对象引用_6C28").Value == currentGraphicsID)
                            {
                                animiationSequence.Attributes.GetNamedItem("对象引用_6C28").Value = tempGraphicsID;
                            }
                            //2010-11-15 罗文甜:增加触发器的图形引用
                            XmlNode    tgtObject    = animiationSequence.SelectSingleNode("演:定时_6B2E", nmgr);
                            XmlElement tgtObjectEle = (XmlElement)tgtObject;

                            if (tgtObjectEle.HasAttribute("触发对象引用_6B34"))
                            {
                                if (tgtObjectEle.Attributes.GetNamedItem("触发对象引用_6B34").Value == currentGraphicsID)
                                {
                                    tgtObjectEle.Attributes.GetNamedItem("触发对象引用_6B34").Value = tempGraphicsID;
                                }
                            }
                        }
                        //2010-12-08 罗文甜:增加连接线始端和终端的图形引用
                        foreach (XmlNode curveShap in curveShapList)
                        {
                            if (curveShap.Attributes.GetNamedItem("连接线引用_8028").Value == currentGraphicsID)
                            {
                                curveShap.Attributes.GetNamedItem("连接线引用_8028").Value = tempGraphicsID;
                            }
                            if (((XmlElement)curveShap).HasAttribute("始端对象引用_8029") && curveShap.Attributes.GetNamedItem("始端对象引用_8029").Value == currentGraphicsID)
                            {
                                curveShap.Attributes.GetNamedItem("始端对象引用_8029").Value = tempGraphicsID;
                            }
                            if (((XmlElement)curveShap).HasAttribute("终端对象引用_802A") && curveShap.Attributes.GetNamedItem("终端对象引用_802A").Value == currentGraphicsID)
                            {
                                curveShap.Attributes.GetNamedItem("终端对象引用_802A").Value = tempGraphicsID;
                            }
                        }
                    }


                    //Console.WriteLine();
                }

                i++;
                //Console.WriteLine(nodeList1.Count);
            }


            XmlNodeList groupShapes = doc.SelectNodes("//pzip:archive//图形:图形集_7C00/图:图形_8062[@组合列表_8064]", nmgr);
            XmlNodeList shapes      = doc.SelectNodes("//pzip:archive//图形:图形集_7C00/图:图形_8062", nmgr);
            foreach (XmlNode shape in shapes)
            {
                currentGraphicsID = shape.Attributes.GetNamedItem("标识符_804B").Value;

                // only change group shapes
                if (!currentGraphicsID.Contains("Obj"))
                {
                    if (i < 10)
                    {
                        tempGraphicsID = "Obj" + "000" + i;
                    }
                    else if (i < 100)
                    {
                        tempGraphicsID = "Obj" + "00" + i;
                    }
                    else if (i < 1000)
                    {
                        tempGraphicsID = "Obj" + "0" + i;
                    }
                    else if (i < 10000)
                    {
                        tempGraphicsID = "Obj" + i;
                    }
                    else
                    {
                        throw new Exception("Too many Graphics id");
                    }

                    shape.Attributes.GetNamedItem("标识符_804B").Value = tempGraphicsID;

                    string newGroupIDString = string.Empty;

                    foreach (XmlNode groupShape in groupShapes)
                    {
                        string   groupID    = groupShape.Attributes.GetNamedItem("组合列表_8064").Value;
                        string[] graphicIDs = groupID.Split(new char[1] {
                            ' '
                        });

                        for (int j = 0; j < graphicIDs.Length; j++)
                        {
                            if (graphicIDs[j] == currentGraphicsID)
                            {
                                graphicIDs[j] = tempGraphicsID;
                            }
                        }

                        for (int k = 0; k < graphicIDs.Length; k++)
                        {
                            newGroupIDString += graphicIDs[k] + " ";
                        }
                        groupShape.Attributes.GetNamedItem("组合列表_8064").Value = newGroupIDString.Substring(0, newGroupIDString.Length - 1);
                        newGroupIDString = string.Empty;

                        /*
                         * if (groupID.Contains(currentGraphicsID))
                         * {
                         *  groupShape.Attributes.GetNamedItem("图:组合列表").Value = groupID.Replace(currentGraphicsID, tempGraphicsID);
                         * }
                         *
                         */
                    }

                    i++;
                }
            }



            int lastID = 0;

            XmlNodeList slideLayouts    = doc.SelectNodes("/pzip:archive/pzip:entry[@pzip:target='rules.xml']/规则:公用处理规则_B665/规则:演示文稿_B66D/规则:页面版式集_B651/规则:页面版式_B652", nmgr);
            XmlNodeList refSlideLayouts = doc.SelectNodes("/pzip:archive/pzip:entry[@pzip:target='content.xml']/演:演示文稿文档_6C10/演:幻灯片集_6C0E/演:幻灯片_6C0F", nmgr);
            //  XmlNodeList refSlideLayouts = doc.SelectNodes("uof:UOF/uof:演示文稿//@演:页面版式引用", nmgr);
            lastID = AddjustID(doc, slideLayouts, refSlideLayouts, "标识符_6B0D", "页面版式引用_6B27", "ID", 1);


            //<!--注销这部分内容李娟 2012 03,26·····································-->
            //String uofns = nmgr.LookupNamespace("uof");
            //XmlNode docroot = doc.SelectSingleNode("uof:UOF", nmgr);
            //XmlNode kzq = docroot.SelectSingleNode("/uof:UOF/uof:扩展区",nmgr);

            //if (kzq == null)
            //{
            //    kzq = doc.CreateElement("uof:扩展区",uofns);
            //    docroot.AppendChild(kzq);
            //}
            //XmlElement kz = doc.CreateElement("uof:扩展", uofns);
            //kz.SetAttribute("locID", "http://schemas.uof.org/cn/2003/uof", "u0051");

            //2010-11-19罗文甜:增加软件名称和软件版本
            //XmlElement rjmc = doc.CreateElement("uof:软件名称", uofns);
            //rjmc.SetAttribute("locID", "http://schemas.uof.org/cn/2003/uof", "u0052");
            //rjmc.InnerText = "EIOffice";
            //XmlElement rjbb = doc.CreateElement("uof:软件版本", uofns);
            //rjbb.SetAttribute("locID", "http://schemas.uof.org/cn/2003/uof", "u0053");
            //rjbb.InnerText = "v1.33";
            //XmlElement kznr = doc.CreateElement("uof:扩展内容", uofns);
            //kznr.SetAttribute("locID", "http://schemas.uof.org/cn/2003/uof", "u0054");

            //XmlElement path = doc.CreateElement("uof:路径", uofns);
            //XmlElement nr = doc.CreateElement("uof:内容", uofns);
            //path.SetAttribute("locID", "http://schemas.uof.org/cn/2003/uof", "u0065");
            //nr.SetAttribute("locID", "http://schemas.uof.org/cn/2003/uof", "u0056");
            //path.InnerText = "演示文稿";
            XmlNodeList masters = doc.SelectNodes("//演:母版_6C0D", nmgr);
            foreach (XmlNode master in masters)
            {
                XmlNodeList list = master.SelectNodes("uof:锚点_C644[uof:占位符_C626/@类型_C627='date' or uof:占位符_C626/@类型_C627='number' or uof:占位符_C626/@类型_C627='header' or uof:占位符_C626/@类型_C627='footer']", nmgr);
                foreach (XmlNode node in list)
                {
                    XmlElement jsx    = doc.CreateElement("uof:句属性", TranslatorConstants.XMLNS_UOF);
                    XmlElement ymyjlx = doc.CreateElement("uof:页眉页脚类型", TranslatorConstants.XMLNS_UOF);
                    XmlNode    para   = doc.SelectSingleNode("//图:图形_8062[@标识符_804B='" + node.Attributes["图形引用_C62E"].Value + "']/图:文本_803C/图:内容_8043/字:段落_416B", nmgr);
                    String     type   = string.Empty;
                    if (para != null)
                    {
                        String  refid     = para.Attributes["标识符_4169"].Value;
                        XmlNode childNode = node.SelectSingleNode("uof:占位符_C626", nmgr);
                        switch (childNode.Attributes["类型_C627"].Value)
                        {
                        case "date":
                            type = "datetime";
                            break;

                        case "number":
                            type = "slidenumber";
                            break;

                        case "header":
                            type = "header";
                            break;

                        case "footer":
                            type = "footer";
                            break;
                        }
                    }
                    //注销这块 李娟 2012.03.26····················································
                    //jsx.SetAttribute("locID", uofns, "w0027");
                    //jsx.SetAttribute("attrList", uofns, "引用 序号");
                    //String num;
                    //if (para.Attributes["序号"] == null)
                    //    num = "1";
                    //else
                    //    num = para.Attributes["序号"].Value;
                    //jsx.SetAttribute("序号", uofns, num);
                    //jsx.SetAttribute("引用", uofns, refid);
                    //ymyjlx.SetAttribute("locID", uofns, "w0031");
                    //ymyjlx.SetAttribute("attrList", uofns, "类型");
                    //ymyjlx.SetAttribute("类型", uofns, type);
                    //jsx.AppendChild(ymyjlx);
                    //nr.AppendChild(jsx);
                }
            }
            //注销这块 李娟2012.03.26
            //kznr.AppendChild(path);
            //kznr.AppendChild(nr);
            ////2010-11-19罗文甜
            //kz.AppendChild(rjmc);
            //kz.AppendChild(rjbb);

            //kz.AppendChild(kznr);
            //kzq.AppendChild(kz);
            //09.11.19 马有旭 添加↑
            //10.03.09 马有旭 添加 修改幻灯片段落ID 原:ID12E3C 改为:shp0graphc0
            //2010-11-24-罗文甜-修改
            XmlNodeList anchors = doc.SelectNodes("//pzip:archive/pzip:entry[@pzip:target='content.xml']/演:演示文稿文档_6C10/演:幻灯片集_6C0E/演:幻灯片_6C0F/uof:锚点_C644 | //pzip:archive/pzip:entry[@pzip:target='content.xml']/演:演示文稿文档_6C10/演:母版集_6C0C/演:母版_6C0D[@类型_6BEA='slide']/uof:锚点_C644[uof:占位符_C626/@类型_C627!='date' and uof:占位符_C626/@类型_C627!='footer' and uof:占位符_C626/@类型_C627!='number']", nmgr);
            //XmlNodeList anchors = doc.SelectNodes("/uof:UOF/uof:演示文稿/演:主体//uof:锚点", nmgr);
            int graphicCount = 0;
            int paraCount    = 0;
            foreach (XmlNode anchor in anchors)
            {
                XmlNode graphic = doc.SelectSingleNode("//pzip:archive/pzip:entry[@pzip:target='graphics.xml']/图形:图形集_7C00/图:图形_8062[@标识符_804B='" + anchor.Attributes["图形引用_C62E"].Value + "']", nmgr);
                if (graphic != null)
                {
                    ++graphicCount;
                    paraCount = 0;
                    String      newId      = "shp" + graphicCount + "graphc";
                    XmlNodeList paragraphs = graphic.SelectNodes("图:文本_803C/图:内容_8043/字:段落_416B", nmgr);
                    foreach (XmlNode para in paragraphs)
                    {
                        XmlAttribute attr = para.Attributes["标识符_4169"];
                        if (attr != null)
                        {
                            String oldId = attr.Value;
                            attr.Value = newId + paraCount;
                            XmlNodeList refs = doc.SelectNodes("//*[@段落引用_6C27='" + oldId + "']", nmgr);
                            foreach (XmlNode refNode in refs)
                            {
                                refNode.Attributes["段落引用_6C27"].Value = newId + paraCount;
                            }
                            ++paraCount;
                        }
                    }
                }
            }
            //注销这部分 李娟 ········································· 2012.03.36
            //删除@序号
            //XmlNodeList paraList = doc.SelectNodes("//字:段落[@序号]",nmgr);
            //foreach (XmlNode para in paraList)
            //{
            //    para.Attributes.Remove(para.Attributes["序号"]);
            //}
            try
            {
                string tmpAdjustID = Path.GetDirectoryName(inputFile) + Path.AltDirectorySeparatorChar + "tmpAdjustID.xml";
                tw = new XmlTextWriter(tmpAdjustID, Encoding.UTF8);
                doc.Save(tw);

                tw.Close();

                XPathDocument     xslDoc;
                XmlReaderSettings xrs              = new XmlReaderSettings();
                XmlReader         source           = null;
                XmlWriter         writer           = null;
                OoxZipResolver    zipResolver      = null;
                XmlUrlResolver    resourceResolver = null;
                try
                {
                    //xrs.ProhibitDtd = true;

                    resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(),
                                                            this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + "Powerpoint.oox2uof");

                    xslDoc          = new XPathDocument(((ResourceResolver)resourceResolver).GetInnerStream("post-processing.xslt"));
                    xrs.XmlResolver = resourceResolver;
                    source          = XmlReader.Create(tmpAdjustID);

                    XslCompiledTransform xslt     = new XslCompiledTransform();
                    XsltSettings         settings = new XsltSettings(true, false);
                    xslt.Load(xslDoc, settings, resourceResolver);

                    //if (!originalFile.Equals(string.Empty))
                    //{
                    //    zipResolver = new OoxZipResolver(originalFile, resourceResolver);
                    //}
                    XsltArgumentList parameters = new XsltArgumentList();
                    parameters.XsltMessageEncountered += new XsltMessageEncounteredEventHandler(MessageCallBack);

                    // zip format
                    parameters.AddParam("outputFile", "", outputFile);
                    // writer = new OoxZipWriter(inputFile);
                    writer = new UofZipWriter(outputFile);

                    if (zipResolver != null)
                    {
                        xslt.Transform(source, parameters, writer, zipResolver);
                    }
                    else
                    {
                        xslt.Transform(source, parameters, writer);
                    }
                }
                finally
                {
                    if (writer != null)
                    {
                        writer.Close();
                    }
                    if (source != null)
                    {
                        source.Close();
                    }
                }
            }
            catch
            {
                throw new Exception("Fail in ajust ids");
            }
            finally
            {
                if (tw != null)
                {
                    tw.Close();
                }
            }

            #endregion

            return(result);
        }
예제 #40
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int DBNId;
        string ResponseFormat, SDMXFormat, Indicator, Area, TimePeriod, Source, Language, DataResponse,Title, Footnote;
        XmlDocument QueryDocument, ResponseDocument;
        bool IsGroupBy=false;
        DBNId = 0;
        ResponseFormat = string.Empty;
        SDMXFormat = string.Empty;
        Indicator = string.Empty;
        Area = string.Empty;
        TimePeriod = string.Empty;
        Source = string.Empty;
        Language = string.Empty;
        DataResponse = string.Empty;
        Title = string.Empty;
        Footnote = string.Empty;
        QueryDocument = new XmlDocument();
        ResponseDocument = new XmlDocument();

        foreach (string QSComponent in Request.QueryString.Keys)
        {
            switch (QSComponent)
            {
                case Constants.WSQueryStrings.p:
                    if (this.Context.Request.QueryString[Constants.WSQueryStrings.p] != null && !string.IsNullOrEmpty(this.Context.Request.QueryString[Constants.WSQueryStrings.p]) && int.TryParse(this.Context.Request.QueryString[Constants.WSQueryStrings.p], out DBNId))
                    {
                        this.DIConnection = Global.GetDbConnection(DBNId);
                        this.DIQueries = new DIQueries(this.DIConnection.DIDataSetDefault(), this.DIConnection.DILanguageCodeDefault(this.DIConnection.DIDataSetDefault()));
                    }
                    else
                    {
                        Global.GetAppSetting();
                        DBNId = Convert.ToInt32(Global.GetDefaultDbNId());
                        this.DIConnection = Global.GetDbConnection(Convert.ToInt32(Global.GetDefaultDbNId()));
                        this.DIQueries = new DIQueries(this.DIConnection.DIDataSetDefault(), this.DIConnection.DILanguageCodeDefault(this.DIConnection.DIDataSetDefault()));
                    }
                    break;
                case Constants.WSQueryStrings.ResponseFormat:
                    if (Request.QueryString[Constants.WSQueryStrings.ResponseFormat] != null && !string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.ResponseFormat].ToString()))
                    {
                        ResponseFormat = Request.QueryString[Constants.WSQueryStrings.ResponseFormat].ToString();
                    }
                    else
                    {
                        ResponseFormat = Constants.WSQueryStrings.ResponseFormatTypes.SDMX;
                    }
                    break;
                case Constants.WSQueryStrings.SDMXFormat:
                    if (Request.QueryString[Constants.WSQueryStrings.SDMXFormat] != null && !string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.SDMXFormat].ToString()))
                    {
                        SDMXFormat = Request.QueryString[Constants.WSQueryStrings.SDMXFormat].ToString();
                    }
                    else
                    {
                        SDMXFormat = Constants.WSQueryStrings.SDMXFormatTypes.StructureSpecificTS;
                    }
                    break;
                case DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id:
                    if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id].ToString()))
                    {
                        Indicator = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.INDICATOR.Id].ToString();
                    }
                    break;
                case DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id:
                    if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id].ToString()))
                    {
                        Area = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.AREA.Id].ToString();
                    }
                    break;
                case DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id:
                    if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id].ToString()))
                    {
                        TimePeriod = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.TIME_PERIOD.Id].ToString();
                    }
                    break;
                case DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id:
                    if (Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id] != null && !string.IsNullOrEmpty(Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id].ToString()))
                    {
                        Source = Request.QueryString[DevInfo.Lib.DI_LibSDMX.Constants.Concept.SOURCE.Id].ToString();
                    }
                    break;
                case Constants.WSQueryStrings.Language:
                    if (Request.QueryString[Constants.WSQueryStrings.Language] != null && !string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.Language].ToString()))
                    {
                        Language = Request.QueryString[Constants.WSQueryStrings.Language].ToString();
                    }
                    break;
                case Constants.WSQueryStrings.GroupByIndicator:
                    if(!string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.GroupByIndicator]))
                    {
                        IsGroupBy = Convert.ToBoolean(Request.QueryString[Constants.WSQueryStrings.GroupByIndicator]);
                    }
                    break;
                case Constants.WSQueryStrings.Title:
                    if (!string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.Title]))
                    {
                        Title = Convert.ToString(Request.QueryString[Constants.WSQueryStrings.Title]);
                    }
                    break;
                case Constants.WSQueryStrings.FootNote:
                    if (!string.IsNullOrEmpty(Request.QueryString[Constants.WSQueryStrings.FootNote]))
                    {
                        Footnote = Convert.ToString(Request.QueryString[Constants.WSQueryStrings.FootNote]);
                    }
                    break;
                default:
                    break;
            }
        }

        if (!string.IsNullOrEmpty(ResponseFormat))
        {
            switch (ResponseFormat)
            {
                case Constants.WSQueryStrings.ResponseFormatTypes.SDMX:
                    QueryDocument = GetQueryXML(ResponseFormat, SDMXFormat, Indicator, Area, TimePeriod, Source, Language);

                    if (!string.IsNullOrEmpty(SDMXFormat))
                    {
                        switch (SDMXFormat)
                        {
                            case Constants.WSQueryStrings.SDMXFormatTypes.StructureSpecificTS:
                                ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecificTS, DIConnection, DIQueries);
                                break;
                            case Constants.WSQueryStrings.SDMXFormatTypes.StructureSpecific:
                                ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecific, DIConnection, DIQueries);
                                break;
                            case Constants.WSQueryStrings.SDMXFormatTypes.GenericTS:
                                ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.GenericTS, DIConnection, DIQueries);
                                break;
                            case Constants.WSQueryStrings.SDMXFormatTypes.Generic:
                                ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.Generic, DIConnection, DIQueries);
                                break;
                            default:
                                break;
                        }
                    }
                    else
                    {
                        ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecificTS, DIConnection, DIQueries);
                    }

                    Response.Write(ResponseDocument.OuterXml);
                    break;
                case Constants.WSQueryStrings.ResponseFormatTypes.JSON:
                    QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language);
                    Response.Write(DATAUtility.Get_Data(QueryDocument, DataTypes.JSON, DIConnection, DIQueries));
                    break;
                case Constants.WSQueryStrings.ResponseFormatTypes.XML:
                    QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language);
                    Response.Write(DATAUtility.Get_Data(QueryDocument, DataTypes.XML, DIConnection, DIQueries));
                    break;
                case Constants.WSQueryStrings.ResponseFormatTypes.TABLE:
                    string BaseUrl = HttpContext.Current.Request.Url.OriginalString.Split(new string[] { "?" }, StringSplitOptions.None)[0];
                    int index = BaseUrl.IndexOf("libraries");

                    string XsltUrl = string.Empty;
                    if (IsGroupBy)
                    {
                        XsltUrl = BaseUrl.Substring(0, index) + "stock/xslt/HTTPRequest_XMLResponse - INDGrp.xslt";
                        //XsltUrl = "../../stock/xslt/HTTPRequest_XMLResponse - INDGrp.xslt";
                    }
                    else
                    {
                        XsltUrl = BaseUrl.Substring(0, index) + "stock/xslt/HTTPRequest_XMLResponse.xslt";
                        //XsltUrl = "../../stock/xslt/HTTPRequest_XMLResponse.xslt";
                    }
                    BaseUrl = BaseUrl.Substring(0,index-1);
                    //string PItext = "type='application/xml' href='" + XsltUrl + "'";

                    QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language);

                    string XmlStr = DATAUtility.Get_Data(QueryDocument, DataTypes.XML, DIConnection, DIQueries);

                  //  DataTable DT = new DataTable();
                   // DT.ReadXml(new StringReader(XmlStr));
                    XsltArgumentList ArguList = new XsltArgumentList();
                    ArguList.AddParam("Title_Text","",Title);
                    ArguList.AddParam("Footnote_Text", "", Footnote);
                    ArguList.AddParam("BaseUrl", "", BaseUrl);
                    XmlStr = this.Transform(XmlStr, XsltUrl, ArguList);
                    XmlStr = XmlStr.Substring(XmlStr.IndexOf("<html>"));
                    //XmlDocument FormattedXml = new XmlDocument();
                    //FormattedXml.LoadXml(XmlStr);
                    //XmlProcessingInstruction XSLTTag = FormattedXml.CreateProcessingInstruction("xml-stylesheet", PItext);
                    //FormattedXml.InsertBefore(XSLTTag, FormattedXml.SelectSingleNode("Root"));
                    Response.ClearHeaders();
                    //Response.AddHeader("content-type", "application/xml");
                    //Response.Write(FormattedXml.InnerXml);
                    Response.Write(XmlStr);
                    break;
                default:
                    break;
            }
        }
        else
        {
            QueryDocument = GetQueryXML(ResponseFormat, null, Indicator, Area, TimePeriod, Source, Language);
            ResponseDocument = SDMXUtility.Get_Data(SDMXSchemaType.Two_One, QueryDocument, DataFormats.StructureSpecificTS, DIConnection, DIQueries);
        }
    }
예제 #41
0
    public static void Main(string[] args)
    {
        Opts opts = new Opts();
        opts.ProcessArgs(args);
        if (opts.RemainingArguments.Length != 2 && opts.RemainingArguments.Length != 3) {
            opts.DoHelp();
            return;
        }

        string datasource, rootentity, stylesheetfile;
        if (opts.RemainingArguments.Length == 2) {
            datasource = opts.RemainingArguments[0];
            rootentity = null;
            stylesheetfile = opts.RemainingArguments[1];
        } else {
            datasource = opts.RemainingArguments[0];
            rootentity = opts.RemainingArguments[1];
            stylesheetfile = opts.RemainingArguments[2];
        }

        XsltArgumentList xsltargs = new XsltArgumentList();

        if (opts.param != null)
        foreach (string p in opts.param) {
            int eq = p.IndexOf('=');
            if (eq == -1) {
                Console.Error.WriteLine("Param arguments must be name=value.");
                return;
            }
            string n = p.Substring(0, eq);
            string v = p.Substring(eq+1);
            xsltargs.AddParam(n, "", v);
        }

        XmlDocument sty = new XmlDocument();
        sty.PreserveWhitespace = true;
        sty.Load(stylesheetfile);

        XslTransform t = new XslTransform();
        t.Load(sty, null, null);

        NamespaceManager nsmgr = new NamespaceManager();

        // Scan xmlsn: attributes in the stylesheet node.
        // For all namespaces of the form assembly://assemblyname/TypeName, load in
        // the methods of that type as extension functions in that namespace.
        // And add xmlns declarations to nsmgr.
        foreach (XmlAttribute a in sty.DocumentElement.Attributes) {
            if (!a.Name.StartsWith("xmlns:")) continue;

            nsmgr.AddNamespace(a.Value, a.Name.Substring(6));

            System.Uri uri = new System.Uri(a.Value);
            if (uri.Scheme != "assembly") continue;
            System.Reflection.Assembly assembly = System.Reflection.Assembly.Load(uri.Host);
            System.Type ty = assembly.GetType(uri.AbsolutePath.Substring(1));
            if (ty == null) {
                Console.Error.WriteLine("Type not found: " + uri);
                return;
            }
            object obj = ty.GetConstructor(new Type[0]).Invoke(new Type[0]);
            xsltargs.AddExtensionObject(a.Value, obj);
        }

        StatementSource source = Store.CreateForInput(datasource);
        Store model;
        if (source is Store) model = (Store)source;
        else model = new MemoryStore(source);

        XPathNavigator nav;
        if (rootentity != null)
            nav = new XPathSemWebNavigator(rootentity, model, nsmgr);
        else
            nav = new XPathSemWebNavigator(model, nsmgr);

        t.Transform(nav, xsltargs, Console.Out, null);
    }
예제 #42
0
        private void DrawProfilesModule()
        {
            XsltArgumentList     args = new XsltArgumentList();
            XslCompiledTransform xslt = new XslCompiledTransform();
            SessionManagement    sm   = new SessionManagement();

            Profiles.Profile.Modules.CustomViewPersonGeneralInfo.DataIO data = new Profiles.Profile.Modules.CustomViewPersonGeneralInfo.DataIO();
            string email         = string.Empty;
            string imageemailurl = string.Empty;
            string audioemailurl = string.Empty;

            if (this.BaseData.SelectSingleNode("rdf:RDF[1]/rdf:Description[1]/prns:emailEncrypted", this.Namespaces) != null &&
                this.BaseData.SelectSingleNode("rdf:RDF[1]/rdf:Description[1]/vivo:email", this.Namespaces) == null)
            {
                email         = this.BaseData.SelectSingleNode("rdf:RDF[1]/rdf:Description[1]/prns:emailEncrypted", this.Namespaces).InnerText;
                imageemailurl = string.Format(Root.Domain + "/profile/modules/CustomViewPersonGeneralInfo/" + "EmailHandler.ashx?msg={0}", HttpUtility.UrlEncode(email));
                audioemailurl = string.Format(Root.Domain + "/profile/modules/CustomViewPersonGeneralInfo/" + "EmailAudioHandler.ashx?msg={0}", HttpUtility.UrlEncode(email));
            }

            args.AddParam("root", "", Root.Domain);
            if (email != string.Empty)
            {
                args.AddParam("email", "", imageemailurl);
                args.AddParam("emailAudio", "", audioemailurl);
                args.AddParam("emailAudioImg", "", Root.Domain + "/Framework/Images/listen.jpg");
            }
            args.AddParam("imgguid", "", Guid.NewGuid().ToString());



            if (base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[1]/vivo:orcidId", base.Namespaces) != null) // Only show ORCID if security settings allow it
            {
                args.AddParam("orcid", "", base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[1]/vivo:orcidId", base.Namespaces).InnerText);
                args.AddParam("orcidurl", "", Profiles.ORCID.Utilities.config.ORCID_URL + "/" + base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[1]/vivo:orcidId", base.Namespaces).InnerText);
                string infosite;
                if (Profiles.ORCID.Utilities.config.InfoSite == null)
                {
                    infosite = Root.Domain + "/about/default.aspx?tab=orcid";
                }
                else if (Profiles.ORCID.Utilities.config.InfoSite.Equals(""))
                {
                    infosite = Root.Domain + "/about/default.aspx?tab=orcid";
                }
                else
                {
                    infosite = Profiles.ORCID.Utilities.config.InfoSite;
                }
                args.AddParam("orcidinfosite", "", infosite);
                args.AddParam("orcidimage", "", Root.Domain + "/Framework/Images/orcid_16x16(1).gif");
                args.AddParam("orcidimageguid", "", Guid.NewGuid().ToString());
            }
            else if (Profiles.ORCID.Utilities.config.ShowNoORCIDMessage && Profiles.ORCID.Utilities.config.Enabled)
            {
                // Check for an ORCID
                string internalUsername = new Profiles.ORCID.Utilities.ProfilesRNSDLL.BLL.Profile.Data.Person().GetInternalUsername(Convert.ToInt64(Request.QueryString["Subject"]));
                Profiles.ORCID.Utilities.ProfilesRNSDLL.BO.ORCID.Person orcidPerson = new Profiles.ORCID.Utilities.ProfilesRNSDLL.BLL.ORCID.Person().GetByInternalUsername(internalUsername);
                if (!orcidPerson.Exists || orcidPerson.ORCIDIsNull)
                {
                    //args.AddParam("orcid", "", "No ORCID id has been created for this user");
                    args.AddParam("orcid", "", "Login to create your ORCID iD");
                    args.AddParam("orcidinfosite", "", Profiles.ORCID.Utilities.config.InfoSite);
                    string qs = HttpUtility.UrlEncode("predicateuri=http%3a%2f%2fvivoweb.org%2fontology%2fcore!orcidId&module=DisplayItemToEdit&ObjectType=Literal");
                    args.AddParam("orcidurl", "", Root.Domain + "/login/default.aspx?method=login&edit=true&editparams=" + qs);
                    args.AddParam("orcidimage", "", Root.Domain + "/Framework/Images/orcid_16x16(1).gif");
                    args.AddParam("orcidimageguid", "", Guid.NewGuid().ToString());
                }
            }
            args.AddParam("nodeid", "", Request.QueryString["Subject"]);
            litPersonalInfo.Text = XslHelper.TransformInMemory(Server.MapPath("~/Profile/Modules/CustomViewPersonGeneralInfo/CustomViewPersonGeneralInfo.xslt"), args, base.BaseData.OuterXml);

            try
            {
                string addressURI = base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[1]/vivo:mailingAddress", base.Namespaces).Attributes["rdf:resource"].Value;
                mapCountry = base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[@rdf:about=\"" + addressURI + "\"]/vivo:address3", base.Namespaces).InnerText;
                string mr = data.GetMapData(mapCountry);
                if (mr != "-1")
                {
                    mapRegion = "region: '" + mr + "',";
                }
            }
            catch (Exception) { }

            /*
             *          if (base.BaseData.SelectSingleNode("rdf:RDF/rdf:Description[1]/prns:mainImage/@rdf:resource", base.Namespaces) != null)
             *          {
             *              string imageurl = base.BaseData.SelectSingleNode("//rdf:RDF/rdf:Description[1]/prns:mainImage/@rdf:resource", base.Namespaces).Value;
             *              imgPhoto.ImageUrl = imageurl;// + "&cachekey=" + Guid.NewGuid().ToString();
             *          }
             *          else
             *          {
             *              imgPhoto.Visible = false;
             *          }
             */
            // OpenSocial.  Allows gadget developers to show test gadgets if you have them installed

            /*           string uri = this.BaseData.SelectSingleNode("rdf:RDF/rdf:Description/@rdf:about", base.Namespaces).Value;
             *         OpenSocialManager om = OpenSocialManager.GetOpenSocialManager(uri, Page);
             *         if (om.IsVisible() && om.GetUnrecognizedGadgets().Count > 0)
             *         {
             *             pnlSandboxGadgets.Visible = true;
             *             litSandboxGadgets.Visible = true;
             *             string sandboxDivs = "" ;
             *             foreach (PreparedGadget gadget in om.GetUnrecognizedGadgets())
             *             {
             *                 sandboxDivs += "<div id='" + gadget.GetChromeId() + "' class='gadgets-gadget-parent'></div>";
             *             }
             *             litSandboxGadgets.Text = sandboxDivs;
             *             om.LoadAssets();
             *             // Add this just in case it is needed.
             *             new ORNGProfileRPCService(Page, this.BaseData.SelectSingleNode("rdf:RDF/rdf:Description/foaf:firstName", base.Namespaces).InnerText, uri);
             *         }
             */
        }
예제 #43
0
    /// <summary>
    /// Transforms the <see cref="XmlDocument"/>.
    /// </summary>
    /// <param name="document">The document to be transformed.</param>
    /// <returns>Returns the resulting <see cref="XmlDocument"/>.</returns>
    public XmlDocument Transform(XmlDocument document)
    {
        XslTransform xslt = new XslTransform();
        XsltArgumentList args = new XsltArgumentList();
        if (HttpContext.Current == null)
        {
            xslt.Load(System.IO.Path.Combine(basePath,this.Type) + ".xslt");
        }
        else
        {
            xslt.Load(HttpContext.Current.Server.MapPath(this.Type + ".xslt"));

        foreach (string key in HttpContext.Current.Request.Params.AllKeys) {
            try {
                args.AddParam(key, String.Empty, HttpContext.Current.Request.Params[key]);
            } catch (Exception ex) { }
        }
        }
        MemoryStream ms = new MemoryStream();
        xslt.Transform(document, args, ms);
        XmlDocument output = new XmlDocument();
        output.LoadXml(System.Text.Encoding.ASCII.GetString(ms.ToArray()));
        return output;
    }
예제 #44
0
        public string GetDocument(Int64 id)
        {
            XElement xe = XElement.Parse($"<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                         $"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                                         $"<soap:Body>" +
                                         $"<PrivateAccessDocument xmlns=\"http://tempuri.org/\">" +
                                         $"<accessKey>{this.credentials}</accessKey>" +
                                         $"<db>0</db>" +
                                         $"<id>{id}</id>" +
                                         $"</PrivateAccessDocument>" +
                                         $"</soap:Body>" +
                                         $"</soap:Envelope>");
            WebClient wc = new WebClient();

            wc.BaseAddress = url;
            wc.Headers.Add(HttpRequestHeader.ContentType, "text/xml");
            var resultXML = System.Text.Encoding.UTF8.GetString(wc.UploadData("", System.Text.Encoding.UTF8.GetBytes(xe.ToString())));

            //return "Документец от сиела";


            var    data    = Regex.Match(resultXML, "<PrivateAccessDocumentResult>([^<]+)<").Groups[1].Value;
            string xmlData = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(data));

            MethodInfo method = typeof(XmlSerializer).GetMethod("set_Mode", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);

            method.Invoke(null, new object[] { 1 });

            var transform = new XslCompiledTransform();
            var settings  = new XsltSettings(false, true);

            using (TextReader textReader = new StringReader(this.xsl))
                using (XmlReader reader = new XmlTextReader(textReader))
                {
                    transform.Load(reader, settings, null);
                }



            XPathDocument docXPath;

            using (var reader = new StringReader(xmlData))
                using (var xml = XmlReader.Create(reader))
                    docXPath = new XPathDocument(xml, XmlSpace.Preserve);

            var xslArg = new XsltArgumentList();

            xslArg.AddParam("CurrentEdition", "", int.MaxValue);
            xslArg.AddParam("Repealed", "", false);
            xslArg.AddParam("LicenseLastEdition", "", int.MaxValue);
            xslArg.AddParam("LicenseExpiredText", "", string.Empty);
            xslArg.AddParam("DocumentDbId", "", string.Empty);
            xslArg.AddParam("Language", "", 1);

            var dbActualityDate = DateTime.Now;
            var currentDate     = (int)((dbActualityDate - DateTime.MinValue).TotalDays + 3);

            xslArg.AddParam("CurrentDate", "", currentDate.ToString());

            var writtenHtmlString = new StringBuilder();
            var stringWriter      = new StringWriter(writtenHtmlString);


            transform.Transform(docXPath, xslArg, stringWriter);

            return(writtenHtmlString.ToString());
        }
예제 #45
0
	private static void Main2() {
		if (opts.dumptemplate) {
			DumpTemplate();
			return;
		}
		
		if (opts.source == null || opts.source == "" || opts.dest == null || opts.dest == "")
			throw new ApplicationException("The source and dest options must be specified.");
		
		Directory.CreateDirectory(opts.dest);
		
		// Load the stylesheets, overview.xml, and resolver
		
		XslTransform overviewxsl = LoadTransform("overview.xsl");
		XslTransform stylesheet = LoadTransform("stylesheet.xsl");
		XslTransform template;
		if (opts.template == null) {
			template = LoadTransform("defaulttemplate.xsl");
		} else {
			try {
				XmlDocument templatexsl = new XmlDocument();
				templatexsl.Load(opts.template);
				template = new XslTransform();
				template.Load(templatexsl);
			} catch (Exception e) {
				throw new ApplicationException("There was an error loading " + opts.template, e);
			}
		}
		
		XmlDocument overview = new XmlDocument();
		overview.Load(opts.source + "/index.xml");

		ArrayList extensions = GetExtensionMethods (overview);
		
		// Create the master page
		XsltArgumentList overviewargs = new XsltArgumentList();
		overviewargs.AddParam("ext", "", opts.ext);
		overviewargs.AddParam("basepath", "", "./");
		Generate(overview, overviewxsl, overviewargs, opts.dest + "/index." + opts.ext, template);
		overviewargs.RemoveParam("basepath", "");
		overviewargs.AddParam("basepath", "", "../");
		
		// Create the namespace & type pages
		
		XsltArgumentList typeargs = new XsltArgumentList();
		typeargs.AddParam("ext", "", opts.ext);
		typeargs.AddParam("basepath", "", "../");
		
		foreach (XmlElement ns in overview.SelectNodes("Overview/Types/Namespace")) {
			string nsname = ns.GetAttribute("Name");

			if (opts.onlytype != null && !opts.onlytype.StartsWith(nsname + "."))
				continue;
				
			System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(opts.dest + "/" + nsname);
			if (!d.Exists) d.Create();
			
			// Create the NS page
			overviewargs.AddParam("namespace", "", nsname);
			Generate(overview, overviewxsl, overviewargs, opts.dest + "/" + nsname + "/index." + opts.ext, template);
			overviewargs.RemoveParam("namespace", "");
			
			foreach (XmlElement ty in ns.SelectNodes("Type")) {
				string typefilebase = ty.GetAttribute("Name");
				string typename = ty.GetAttribute("DisplayName");
				if (typename.Length == 0)
					typename = typefilebase;
				
				if (opts.onlytype != null && !(nsname + "." + typename).StartsWith(opts.onlytype))
					continue;

				string typefile = opts.source + "/" + nsname + "/" + typefilebase + ".xml";
				if (!File.Exists(typefile)) continue;

				XmlDocument typexml = new XmlDocument();
				typexml.Load(typefile);
				if (extensions != null) {
					DocLoader loader = CreateDocLoader (overview);
					XmlDocUtils.AddExtensionMethods (typexml, extensions, loader);
				}
				
				Console.WriteLine(nsname + "." + typename);
				
				Generate(typexml, stylesheet, typeargs, opts.dest + "/" + nsname + "/" + typefilebase + "." + opts.ext, template);
			}
		}
	}