/// <summary>
    /// Transformes CAML xml fragment trough XSL stylesheet.
    /// </summary>
    /// <param name="caml">Source xml = CAML fragment</param>
    /// <param name="ti">Transformation</param>
    /// <returns>Transformed text</returns>
    public static string TransformCAML(XmlNode caml, TransformationInfo ti)
    {
        XslCompiledTransform xslTransform = new XslCompiledTransform();

        // Read stylesheet code from transformation
        StringReader stream = new StringReader(ti.TransformationCode);
        XmlTextReader xmlReader = new XmlTextReader(stream);
        xslTransform.Load(xmlReader);

        // Create XMLDocument from CAML fragment
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(caml.InnerXml);

        StringWriter transformed = new StringWriter();
        xslTransform.Transform(xmlDoc, null, transformed);

        return transformed.ToString();
    }
Example #2
0
    public static string Transform(string xsltFile, string xml, XsltArgumentList xslArg)
    {
        string result = "";
        try {

        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(xsltFile);
        // XmlWriterSettings.OmitXmlDeclaration

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(new StringReader(xml));

        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        settings.NewLineOnAttributes = true;

        using (StringWriter sw = new StringWriter()) {
        using (XmlWriter writer = XmlWriter.Create(sw, settings)) {
            xslt.Transform(xmlDoc, xslArg, writer);
        }
        sw.Flush();
        result = sw.ToString();
          }
        } catch (Exception ex) {
        Console.WriteLine(ex.ToString());
        }
        return result;
    }
Example #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;
        }
    }
Example #4
0
 static void Main()
 {
     XslCompiledTransform xslt =
       new XslCompiledTransform();
     xslt.Load("../../../MusicCatalogue.xslt");
     xslt.Transform("../../../MusicCatalogue.xml", "../../../14.MusicCatalogue.html");
     Console.WriteLine("Successfully transformed!");
 }
    static void Main()
    {
        var xslt = new XslCompiledTransform();
        xslt.Load(stylesheet);
        xslt.Transform(inputFile, outputFile);

        Console.WriteLine("HTML file saved to {0}", outputFile);
    }
Example #6
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();
            }
        }
    }
    static void Main()
    {
        string originPathXslt = "../../../xml/catalogue.xslt";
        string originPathXml = "../../../xml/catalogue.xml";
        string destinationPath = "../../../xml/catalogue.html";

        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(originPathXslt);
        xslt.Transform(originPathXml, destinationPath);
    }
Example #8
0
 protected void ToExcel_Click(object sender, EventArgs e)
 {
     string json = ExcelGridData.Value.ToString();
     StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null);
     XmlNode xml = eSubmit.Xml;
     this.Response.Clear();
     this.Response.ContentType = "application/vnd.ms-excel";
     this.Response.AddHeader("Content-Disposition", "attachment; filename=SaleRank.xls");
     XslCompiledTransform xtExcel = new XslCompiledTransform();
     xtExcel.Load(Server.MapPath("./Styles/Excel.xsl"));
     xtExcel.Transform(xml, null, this.Response.OutputStream);
     this.Response.End();
 }
Example #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";

        string xsltFile = Server.MapPath("books.xslt");
        string xmlFile = Server.MapPath("books.xml");

        XslCompiledTransform xslt = new XslCompiledTransform(true); //Pass in true to enable XSLT Debugging
        xslt.Load(xsltFile);

        XPathDocument doc = new XPathDocument(xmlFile);
        xslt.Transform(doc, new XmlTextWriter(Response.Output));
    }
    static void Main()
    {
        string decorationLine = new string('-', Console.WindowWidth);
        Console.Write(decorationLine);
        Console.WriteLine("***Transforming the XML document 'albums-catalogue.xml' to a HTML");
        Console.WriteLine("file using 'albums-catalogue.xsl' stylesheet file with XSLT***");
        Console.Write(decorationLine);

        XslCompiledTransform xslTransformer = new XslCompiledTransform();
        xslTransformer.Load("../../albums-catalogue.xsl");
        xslTransformer.Transform("../../albums-catalogue.xml", "../../albums-catalogue.html");
        
        Console.WriteLine("Completed! You can see the HTML file in project's directory!");
    }
    public CsvLoader(DirectoryInfo baseDir)
    {
        CsvDir = new DirectoryInfo(baseDir.FullName + '\\' + InputCsvDirName);
        if(!CsvDir.Exists){
            throw new Exception(string.Format("Directory not found: {0}", CsvDir.FullName));
        }
        OutputXmlDir = new DirectoryInfo(baseDir.FullName + '\\' + OutputXmlDirName);
        OutputHtmlDir = new DirectoryInfo(baseDir.FullName + '\\' + OutputHtmlDirName);
        InputXsltDir = new DirectoryInfo(baseDir.FullName + '\\' + InputXsltDirName);

        foreach(string s in XsltFileNames){
            var xslt = new XslCompiledTransform();
            FileInfo xsltFile = GetFileInfo(InputXsltDir, s + ".xsl");
            xslt.Load(xsltFile.FullName);
            xslts.Add(s, xslt);
        }
    }
    public static void Transform(string sXmlPath, string sXslPath)
    {
        try {
        XPathDocument myXPathDoc = new XPathDocument(sXmlPath);
        XslCompiledTransform myXslTrans = new XslCompiledTransform();
        myXslTrans.Load(sXslPath);
        XsltArgumentList xslArgs = new XsltArgumentList();
        Utils classPtr = new Utils();
        xslArgs.AddExtensionObject("urn:util", classPtr);
        XmlTextWriter myWriter = new XmlTextWriter("result.xml", null);
        myXslTrans.Transform(myXPathDoc, xslArgs, myWriter);
        myWriter.Close();
        } catch (Exception e) {

        Console.WriteLine("Exception: {0}", e.ToString());
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        string m = "<?xml version=\"1.0\"?>";
        m += "<address>";
        m += "<addressline1>" + "Veerannapet" + "</addressline1>";
        m += "<addressline2>" + "Veerannapet2" + "</addressline2>";
        m += "<city>" + "Mahabubnagar" + "</city>";
        m += "<postcode>" + "509001" + "</postcode>";
        m += "</address>";

        string result1 = m.Replace("<?xml version=\"1.0\"?>", "");

        XmlDocument docs = new XmlDocument();
        docs.LoadXml(result1);
        string json = Newtonsoft.Json.JsonConvert.SerializeXmlNode(docs);

        XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json, "Report");

        XslCompiledTransform xsl = new XslCompiledTransform();
        StringWriter result = new StringWriter();

        xsl.Load(Server.MapPath("Focus.xslt"));

        XmlTextWriter tx = new XmlTextWriter(result);

        XmlDeclaration xmldecl;
        xmldecl = doc.CreateXmlDeclaration("1.0", null, null);

        XmlElement root = doc.DocumentElement;
        doc.InsertBefore(xmldecl, root);

        //string strs = doc.InnerXml.ToString();
        doc.WriteTo(tx);
        xsl.Transform(doc, null, tx);

        result.Close();
        result.Flush();

        string str = result.ToString();
        // ... And the result you'll send back will be usable in a report:
        Response.ContentType = "text/xml";
        Response.Write(str.ToString());

        Response.Flush();
        Response.Close();
    }
Example #14
0
    //read in the blog posts from an RSS feed, using an XSLT stylesheet
    protected void LoadLatestBlogPosts()
    {
        try
        {
            string LatestBlogPostsRssUrl = System.Configuration.ConfigurationManager.AppSettings["LatestBlogPostsRssUrl"];
            string LatestBlogPostsXslUrl = Server.MapPath(string.Format("xsl/{0}", ConfigurationManager.AppSettings["LatestBlogPostsXslFile"]));
            XmlDocument latestBlogPostsDoc = new XmlDocument();
            XslCompiledTransform latestBlogPostsXsl = new XslCompiledTransform();
            StringBuilder latestBlogPostsStringBuilder = new StringBuilder();
            StringWriter latestBlogPostsStringWriter = new StringWriter(latestBlogPostsStringBuilder);

            latestBlogPostsDoc.Load(LatestBlogPostsRssUrl);
            latestBlogPostsXsl.Load(LatestBlogPostsXslUrl);
            latestBlogPostsXsl.Transform(latestBlogPostsDoc, null, latestBlogPostsStringWriter);
            //latestBlogPostsStringBuilder.Append("Cached at " + DateTime.Now.ToString());
            LatestBlogPostsLiteral.Text = latestBlogPostsStringBuilder.ToString();
        }
        catch (Exception ex)
        {
            //no op; since the .text assignment is the last line, then the section will simply not display if there are errors
        }
    }
Example #15
0
    public void Consume(string contentFolder, string siteFolder, string filename, string ext)
    {
        string contentFile = contentFolder + "/" + filename;
        string templateFile = GetTemplateFilename(filename, ext);
        SiteFile = siteFolder + "/index.html";

        try {
                //XsltArgumentList xslArg = BuildXsltArgumentList();
        XslCompiledTransform xslt = new XslCompiledTransform();
        xslt.Load(templateFile);

        using (StringWriter sw = new StringWriter()) {
              using (XmlWriter writer = XmlWriter.Create(sw)) {
          	xslt.Transform(contentFile, XslArgs, writer);
              }
              sw.Flush();
              Content = sw.ToString();
            }
        } catch (Exception ex) {
            ReportError(templateFile, contentFile, ex);
        }
    }
            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);
            }
Example #17
0
        private static void GenerateEmail(int eventID)
        {
            SystemInfoDataContext        systemInfo;
            MeterInfoDataContext         meterInfo;
            FaultLocationInfoDataContext faultInfo;
            EventTableAdapter            eventAdapter;
            EventTypeTableAdapter        eventTypeAdapter;

            int    faultTypeID;
            string eventDetail;

            MeterData.EventRow eventRow;
            List <int>         faultedMeters;
            List <int>         meterGroups;
            List <Recipient>   recipients;

            XslCompiledTransform transform;
            XDocument            htmlDocument;

            List <Attachment> attachments;
            string            subject;
            string            html;

            systemInfo       = s_dbAdapterContainer.GetAdapter <SystemInfoDataContext>();
            meterInfo        = s_dbAdapterContainer.GetAdapter <MeterInfoDataContext>();
            faultInfo        = s_dbAdapterContainer.GetAdapter <FaultLocationInfoDataContext>();
            eventAdapter     = s_dbAdapterContainer.GetAdapter <EventTableAdapter>();
            eventTypeAdapter = s_dbAdapterContainer.GetAdapter <EventTypeTableAdapter>();

            faultTypeID = eventTypeAdapter.GetData()
                          .Where(eventType => eventType.Name == "Fault")
                          .Select(eventType => eventType.ID)
                          .FirstOrDefault();

            eventDetail = eventAdapter.GetEventDetail(eventID);
            eventRow    = eventAdapter.GetDataByID(eventID)[0];

            faultedMeters = eventAdapter.GetSystemEvent(eventRow.StartTime, eventRow.EndTime, s_timeTolerance)
                            .Where(evt => evt.LineID == eventRow.LineID)
                            .Where(evt => evt.EventTypeID == faultTypeID)
                            .Select(evt => evt.MeterID)
                            .ToList();

            meterGroups = meterInfo.GroupMeters
                          .Where(groupMeter => faultedMeters.Contains(groupMeter.MeterID))
                          .Select(groupMeter => groupMeter.GroupID)
                          .ToList();

            foreach (FaultEmailTemplate template in faultInfo.FaultEmailTemplates.ToList())
            {
                recipients = template.GetRecipients(systemInfo.Recipients, meterGroups);

                if (recipients.Count == 0)
                {
                    continue;
                }

                using (StringReader templateReader = new StringReader(template.Template))
                    using (StringReader dataReader = new StringReader(eventDetail))
                        using (XmlReader xmlTemplateReader = XmlReader.Create(templateReader))
                            using (XmlReader xmlDataReader = XmlReader.Create(dataReader))
                                using (StringWriter transformWriter = new StringWriter())
                                {
                                    transform = new XslCompiledTransform();
                                    transform.Load(xmlTemplateReader);
                                    transform.Transform(xmlDataReader, null, transformWriter);
                                    htmlDocument = XDocument.Parse(transformWriter.ToString(), LoadOptions.PreserveWhitespace);
                                }

                htmlDocument.TransformAll("format", element => element.Format());
                attachments = new List <Attachment>();

                try
                {
                    htmlDocument.TransformAll("chart", (element, index) =>
                    {
                        string cid = $"chart{index:00}.png";

                        Stream image          = ChartGenerator.ConvertToChartImageStream(s_dbAdapterContainer, element);
                        Attachment attachment = new Attachment(image, cid);
                        attachment.ContentId  = attachment.Name;
                        attachments.Add(attachment);

                        return(new XElement("img", new XAttribute("src", $"cid:{cid}")));
                    });

                    subject = (string)htmlDocument.Descendants("title").FirstOrDefault() ?? "Fault detected by openXDA";
                    html    = htmlDocument.ToString(SaveOptions.DisableFormatting).Replace("&amp;", "&");
                    SendEmail(recipients, subject, html, attachments);
                    LoadEmail(eventID, recipients, subject, html);
                }
                finally
                {
                    foreach (Attachment attachment in attachments)
                    {
                        attachment.Dispose();
                    }
                }
            }
        }
Example #18
0
        /// <summary>
        /// POST requests handler
        /// </summary>
        /// <param name="p"></param>
        public override void HandleGETRequest(HttpProcessor processor)
        {
            Log.WriteLine("HTTP GET request from {0}: {1}", ((System.Net.IPEndPoint)processor.Socket.Client.RemoteEndPoint).Address, processor.HttpUrl);
            try
            {
                // Parse request
                string xml     = string.Empty;
                string request = processor.HttpUrl;

                // Check for www request
                bool isWWWRequest = request.StartsWith("/" + TinyOPDS.Properties.Settings.Default.HttpPrefix) && !request.StartsWith("/" + TinyOPDS.Properties.Settings.Default.RootPrefix) ? true : false;

                // Remove prefix if any
                if (!request.Contains("opds-opensearch.xml") && !string.IsNullOrEmpty(TinyOPDS.Properties.Settings.Default.RootPrefix))
                {
                    request = request.Replace(TinyOPDS.Properties.Settings.Default.RootPrefix, "/");
                }
                if (!string.IsNullOrEmpty(TinyOPDS.Properties.Settings.Default.HttpPrefix))
                {
                    request = request.Replace(TinyOPDS.Properties.Settings.Default.HttpPrefix, "/");
                }

                while (request.IndexOf("//") >= 0)
                {
                    request = request.Replace("//", "/");
                }

                // Remove any parameters from request except TinyOPDS params
                int paramPos = request.IndexOf('?');
                if (paramPos >= 0)
                {
                    int ourParamPos = request.IndexOf("pageNumber") + request.IndexOf("searchTerm");
                    if (ourParamPos >= 0)
                    {
                        ourParamPos = request.IndexOf('&', ourParamPos + 10);
                        if (ourParamPos >= 0)
                        {
                            request = request.Substring(0, ourParamPos);
                        }
                    }
                    else
                    {
                        request = request.Substring(0, paramPos);
                    }
                }

                string ext = Path.GetExtension(request).ToLower();
                if (!_extensions.Contains(ext))
                {
                    ext = string.Empty;
                }

                string[] http_params = request.Split(new Char[] { '?', '=', '&' });

                // User-agent check: some e-book readers can handle fb2 files (no conversion is  needed)
                string userAgent = processor.HttpHeaders["User-Agent"] as string;
                bool   acceptFB2 = Utils.DetectFB2Reader(userAgent) || isWWWRequest;
                int    threshold = (int)(isWWWRequest ? TinyOPDS.Properties.Settings.Default.ItemsPerWebPage : TinyOPDS.Properties.Settings.Default.ItemsPerOPDSPage);

                // Is it OPDS request?
                if (string.IsNullOrEmpty(ext))
                {
                    try
                    {
                        // Is it root node requested?
                        if (request.Equals("/"))
                        {
                            xml = new RootCatalog().GetCatalog().ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/newdate"))
                        {
                            xml = new NewBooksCatalog().GetCatalog(request.Substring(8), true, acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/newtitle"))
                        {
                            xml = new NewBooksCatalog().GetCatalog(request.Substring(9), false, acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/authorsindex"))
                        {
                            int numChars = request.StartsWith("/authorsindex/") ? 14 : 13;
                            xml = new AuthorsCatalog().GetCatalog(request.Substring(numChars), false, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/author/"))
                        {
                            xml = new BooksCatalog().GetCatalogByAuthor(request.Substring(8), acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/sequencesindex"))
                        {
                            int numChars = request.StartsWith("/sequencesindex/") ? 16 : 15;
                            xml = new SequencesCatalog().GetCatalog(request.Substring(numChars), threshold).ToStringWithDeclaration();
                        }
                        else if (request.Contains("/sequence/"))
                        {
                            xml = new BooksCatalog().GetCatalogBySequence(request.Substring(10), acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/genres"))
                        {
                            int numChars = request.Contains("/genres/") ? 8 : 7;
                            xml = new GenresCatalog().GetCatalog(request.Substring(numChars)).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/genre/"))
                        {
                            xml = new BooksCatalog().GetCatalogByGenre(request.Substring(7), acceptFB2, threshold).ToStringWithDeclaration();
                        }
                        else if (request.StartsWith("/search"))
                        {
                            if (http_params.Length > 1 && http_params[1].Equals("searchTerm"))
                            {
                                xml = new OpenSearch().Search(http_params[2], "", acceptFB2).ToStringWithDeclaration();
                            }
                            else if (http_params[1].Equals("searchType"))
                            {
                                int pageNumber = 0;
                                if (http_params.Length > 6 && http_params[5].Equals("pageNumber"))
                                {
                                    int.TryParse(http_params[6], out pageNumber);
                                }
                                xml = new OpenSearch().Search(http_params[4], http_params[2], acceptFB2, pageNumber).ToStringWithDeclaration();
                            }
                        }

                        if (string.IsNullOrEmpty(xml))
                        {
                            processor.WriteFailure();
                            return;
                        }

                        // Fix for the root namespace
                        // TODO: fix with standard way (how?)
                        xml = xml.Insert(xml.IndexOf("<feed ") + 5, " xmlns=\"http://www.w3.org/2005/Atom\"");

                        if (TinyOPDS.Properties.Settings.Default.UseAbsoluteUri)
                        {
                            try
                            {
                                string host = processor.HttpHeaders["Host"].ToString();
                                xml = xml.Replace("href=\"", "href=\"http://" + (isWWWRequest ? host.UrlCombine(TinyOPDS.Properties.Settings.Default.HttpPrefix) : host.UrlCombine(TinyOPDS.Properties.Settings.Default.RootPrefix)));
                            }
                            catch { }
                        }
                        else
                        {
                            string prefix = isWWWRequest ? TinyOPDS.Properties.Settings.Default.HttpPrefix : TinyOPDS.Properties.Settings.Default.RootPrefix;
                            if (!string.IsNullOrEmpty(prefix))
                            {
                                prefix = "/" + prefix;
                            }
                            xml = xml.Replace("href=\"", "href=\"" + prefix);
                            // Fix open search link
                            xml = xml.Replace(prefix + "/opds-opensearch.xml", "/opds-opensearch.xml");
                        }

                        // Apply xsl transform
                        if (isWWWRequest)
                        {
                            string html = string.Empty;

                            MemoryStream htmlStream = new MemoryStream();
                            using (StringReader stream = new StringReader(xml))
                            {
                                XPathDocument myXPathDoc = new XPathDocument(stream);

// for easy debug of xsl transform, we'll reload external file in DEBUG build
#if DEBUG
                                string xslFileName = Path.Combine(Utils.ServiceFilesLocation, "xml2html.xsl");
                                _xslTransform = new XslCompiledTransform();
                                if (File.Exists(xslFileName))
                                {
                                    _xslTransform.Load(xslFileName);
                                }
                                else
                                {
                                    using (Stream resStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".xml2html.xsl"))
                                    {
                                        using (XmlReader reader = XmlReader.Create(resStream))
                                            _xslTransform.Load(reader);
                                    }
                                }
#endif
                                XmlTextWriter myWriter = new XmlTextWriter(htmlStream, null);
                                _xslTransform.Transform(myXPathDoc, null, myWriter);
                                htmlStream.Position = 0;
                                using (StreamReader sr = new StreamReader(htmlStream)) html = sr.ReadToEnd();
                            }

                            processor.WriteSuccess("text/html");
                            processor.OutputStream.Write(html);
                        }
                        else
                        {
                            processor.WriteSuccess("application/atom+xml;charset=utf-8");
                            processor.OutputStream.Write(xml);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.WriteLine(LogLevel.Error, "OPDS catalog exception {0}", e.Message);
                    }
                    return;
                }
                else if (request.Contains("opds-opensearch.xml"))
                {
                    xml = new OpenSearch().OpenSearchDescription().ToStringWithDeclaration();
                    xml = xml.Insert(xml.IndexOf("<OpenSearchDescription") + 22, " xmlns=\"http://a9.com/-/spec/opensearch/1.1/\"");

                    if (TinyOPDS.Properties.Settings.Default.UseAbsoluteUri)
                    {
                        try
                        {
                            string host = processor.HttpHeaders["Host"].ToString();
                            xml = xml.Replace("href=\"", "href=\"http://" + host.UrlCombine(TinyOPDS.Properties.Settings.Default.RootPrefix));
                        }
                        catch { }
                    }

                    processor.WriteSuccess("application/atom+xml;charset=utf-8");
                    processor.OutputStream.Write(xml);
                    return;
                }

                // fb2.zip book request
                else if ((request.Contains(".fb2.zip") && ext.Equals(".zip")) || ext.Equals(".epub"))
                {
                    string bookID = request.Substring(1, request.IndexOf('/', 1) - 1).Replace("%7B", "{").Replace("%7D", "}");
                    Book   book   = Library.GetBook(bookID);

                    if (book != null)
                    {
                        MemoryStream memStream = null;
                        memStream = new MemoryStream();

                        if (request.Contains(".fb2.zip"))
                        {
                            try
                            {
                                if (book.FilePath.ToLower().Contains(".zip@"))
                                {
                                    string[] pathParts = book.FilePath.Split('@');
                                    using (ZipFile zipFile = new ZipFile(pathParts[0]))
                                    {
                                        ZipEntry entry = zipFile.Entries.First(e => e.FileName.Contains(pathParts[1]));
                                        if (entry != null)
                                        {
                                            entry.Extract(memStream);
                                        }
                                    }
                                }
                                else
                                {
                                    using (FileStream stream = new FileStream(book.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                        stream.CopyTo(memStream);
                                }
                                memStream.Position = 0;

                                // Compress fb2 document to zip
                                using (ZipFile zip = new ZipFile())
                                {
                                    zip.AddEntry(Transliteration.Front(string.Format("{0}_{1}.fb2", book.Authors.First(), book.Title)), memStream);
                                    using (MemoryStream outputStream = new MemoryStream())
                                    {
                                        zip.Save(outputStream);
                                        outputStream.Position = 0;
                                        processor.WriteSuccess("application/fb2+zip");
                                        outputStream.CopyTo(processor.OutputStream.BaseStream);
                                    }
                                }
                                HttpServer.ServerStatistics.BooksSent++;
                            }
                            catch (Exception e)
                            {
                                Log.WriteLine(LogLevel.Error, "FB2 file exception {0}", e.Message);
                            }
                        }
                        else if (ext.Equals(".epub"))
                        {
                            try
                            {
                                if (book.FilePath.ToLower().Contains(".zip@"))
                                {
                                    string[] pathParts = book.FilePath.Split('@');
                                    using (ZipFile zipFile = new ZipFile(pathParts[0]))
                                    {
                                        ZipEntry entry = zipFile.Entries.First(e => e.FileName.Contains(pathParts[1]));
                                        if (entry != null)
                                        {
                                            entry.Extract(memStream);
                                        }
                                        entry = null;
                                    }
                                }
                                else
                                {
                                    using (FileStream stream = new FileStream(book.FilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                                        stream.CopyTo(memStream);
                                }
                                memStream.Position = 0;
                                // At this moment, memStream has a copy of requested book
                                // For fb2, we need convert book to epub
                                if (book.BookType == BookType.FB2)
                                {
                                    // No convertor found, return an error
                                    if (string.IsNullOrEmpty(TinyOPDS.Properties.Settings.Default.ConvertorPath))
                                    {
                                        Log.WriteLine(LogLevel.Error, "No FB2 to EPUB convertor found, file request can not be completed!");
                                        processor.WriteFailure();
                                        return;
                                    }

                                    // Save fb2 book to the temp folder
                                    string inFileName = Path.Combine(Path.GetTempPath(), book.ID + ".fb2");
                                    using (FileStream stream = new FileStream(inFileName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite))
                                        memStream.CopyTo(stream);

                                    // Run converter
                                    string outFileName = Path.Combine(Path.GetTempPath(), book.ID + ".epub");
                                    string command     = Path.Combine(TinyOPDS.Properties.Settings.Default.ConvertorPath, Utils.IsLinux ? "fb2toepub" : "Fb2ePub.exe");
                                    string arguments   = string.Format(Utils.IsLinux ? "{0} {1}" : "\"{0}\" \"{1}\"", inFileName, outFileName);

                                    using (ProcessHelper converter = new ProcessHelper(command, arguments))
                                    {
                                        converter.Run();

                                        if (File.Exists(outFileName))
                                        {
                                            memStream = new MemoryStream();
                                            using (FileStream fileStream = new FileStream(outFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                                                fileStream.CopyTo(memStream);

                                            // Cleanup temp folder
                                            try { File.Delete(inFileName); }
                                            catch { }
                                            try { File.Delete(outFileName); }
                                            catch { }
                                        }
                                        else
                                        {
                                            string converterError = string.Empty;
                                            foreach (string s in converter.ProcessOutput)
                                            {
                                                converterError += s + " ";
                                            }
                                            Log.WriteLine(LogLevel.Error, "EPUB conversion error on file {0}. Error description: {1}", inFileName, converterError);
                                            processor.WriteFailure();
                                            return;
                                        }
                                    }
                                }

                                // At this moment, memStream has a copy of epub
                                processor.WriteSuccess("application/epub+zip");
                                memStream.Position = 0;
                                memStream.CopyTo(processor.OutputStream.BaseStream);
                                HttpServer.ServerStatistics.BooksSent++;
                            }

                            catch (Exception e)
                            {
                                Log.WriteLine(LogLevel.Error, "EPUB file exception {0}", e.Message);
                            }
                        }

                        processor.OutputStream.BaseStream.Flush();
                        if (memStream != null)
                        {
                            memStream.Dispose();
                        }
                    }
                    else
                    {
                        Log.WriteLine(LogLevel.Error, "Book {0} not found in library.", bookID);
                    }
                }
                // Cover image or thumbnail request
                else if (ext.Contains(".jpeg"))
                {
                    bool   getCover = true;
                    string bookID   = string.Empty;
                    if (request.Contains("/cover/"))
                    {
                        bookID = Path.GetFileNameWithoutExtension(request.Substring(request.IndexOf("/cover/") + 7));
                    }
                    else if (request.Contains("/thumbnail/"))
                    {
                        bookID   = Path.GetFileNameWithoutExtension(request.Substring(request.IndexOf("/thumbnail/") + 11));
                        getCover = false;
                    }

                    bookID = bookID.Replace("%7B", "{").Replace("%7D", "}");

                    if (!string.IsNullOrEmpty(bookID))
                    {
                        CoverImage image = null;
                        Book       book  = Library.GetBook(bookID);

                        if (book != null)
                        {
                            if (ImagesCache.HasImage(bookID))
                            {
                                image = ImagesCache.GetImage(bookID);
                            }
                            else
                            {
                                image = new CoverImage(book);
                                if (image != null && image.HasImages)
                                {
                                    ImagesCache.Add(image);
                                }
                            }

                            if (image != null && image.HasImages)
                            {
                                processor.WriteSuccess("image/jpeg");
                                (getCover ? image.CoverImageStream : image.ThumbnailImageStream).CopyTo(processor.OutputStream.BaseStream);
                                processor.OutputStream.BaseStream.Flush();
                                HttpServer.ServerStatistics.ImagesSent++;
                                return;
                            }
                        }
                    }
                }
                // favicon.ico request
                else if (ext.Contains(".ico"))
                {
                    string icon   = Path.GetFileName(request);
                    Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + ".Icons." + icon);
                    if (stream != null && stream.Length > 0)
                    {
                        processor.WriteSuccess("image/x-icon");
                        stream.CopyTo(processor.OutputStream.BaseStream);
                        processor.OutputStream.BaseStream.Flush();
                        return;
                    }
                }
                processor.WriteFailure();
            }
            catch (Exception e)
            {
                Log.WriteLine(LogLevel.Error, ".HandleGETRequest() exception {0}", e.Message);
                processor.WriteFailure();
            }
        }
Example #19
0
        /// <summary>
        /// Builds the outline asynchronous.
        /// </summary>
        /// <param name="coverIncluded">if set to <c>true</c> indicates a cover is included in the PDF.</param>
        /// <param name="tableOfContentsIncluded">if set to <c>true</c> indicates a table of contents is included in the PDF.</param>
        /// <param name="outputDottedLinesInTableOfContents">if set to <c>true</c> outputs dotted lines in the table of contents.</param>
        /// <param name="htmlToPdfFiles">The HTML to PDF files.</param>
        /// <param name="outlineBuilder">The outline builder.</param>
        /// <param name="defaultTableOfContentsStyleSheetBuilder">The default table of contents style sheet builder.</param>
        /// <param name="pdfPrinter">The PDF printer.</param>
        /// <param name="htmlToPdfOptions">The HTML to PDF options.</param>
        /// <param name="variables">The variables.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        internal static async Task BuildOutlineAsync(
            bool coverIncluded,
            bool tableOfContentsIncluded,
            bool outputDottedLinesInTableOfContents,
            ConcurrentBag <HtmlToPdfFile> htmlToPdfFiles,
            Action <XmlWriter, IReadOnlyCollection <HtmlToPdfFile>, bool> outlineBuilder,
            Func <bool, string> defaultTableOfContentsStyleSheetBuilder,
            PdfPrinter pdfPrinter,
            HtmlToPdfOptions htmlToPdfOptions,
            Dictionary <string, string> variables)
        {
            int tocIndex      = coverIncluded ? 1 : 0;
            int tocPageNumber = htmlToPdfFiles.Where(x => x.Index < tocIndex).Sum(x => x.NumberOfPages) + 1;

            foreach (HtmlToPdfFile htmlToPdfFile in htmlToPdfFiles.Where(x => x.Index >= tocIndex))
            {
                htmlToPdfFile.Index += 1;
            }

            HtmlToPdfFile tocHtmlToPdfFile = new HtmlToPdfFile
            {
                Index = tocIndex,

                // TODO: extract wkhtmltopdf specific details
                Input = Path.Combine(Path.GetTempPath(), "__WKANCHOR_2").ToLower(),

                // TODO: localization
                Title            = "Table of Contents",
                TitleAndHeadings = new List <HtmlHeading>
                {
                    new HtmlHeading
                    {
                        Level = 0,
                        Page  = 0,
                        Text  = "Table of Contents",
                    },
                    new HtmlHeading
                    {
                        Level = 1,
                        Page  = tocPageNumber,
                        Text  = "Table of Contents",
                    },
                },
            };

            htmlToPdfFiles.Add(tocHtmlToPdfFile);

            using (TempHtmlFile tempHtmlFile = new TempHtmlFile())
            {
                string defaultTocXsl = defaultTableOfContentsStyleSheetBuilder(outputDottedLinesInTableOfContents);
                using (StringReader stringReader = new StringReader(defaultTocXsl))
                {
                    using (XmlReader tocXslXmlReader = XmlReader.Create(stringReader))
                    {
                        XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();
                        xslCompiledTransform.Load(tocXslXmlReader);

                        using (MemoryStream memoryStream = new MemoryStream())
                        {
                            using (XmlWriter xmlWriter = XmlWriter.Create(memoryStream))
                            {
                                outlineBuilder(xmlWriter, htmlToPdfFiles, tableOfContentsIncluded);
                            }

                            // Reset stream position to read from the beginning
                            memoryStream.Seek(0, SeekOrigin.Begin);

                            using (XmlReader xmlReader = XmlReader.Create(memoryStream))
                            {
                                using (XmlWriter xmlWriter = XmlWriter.Create(tempHtmlFile.FilePath))
                                {
                                    xslCompiledTransform.Transform(xmlReader, xmlWriter);
                                }
                            }
                        }
                    }
                }

                // print as pdf
                string pdfFile = await pdfPrinter.PrintAsPdfAsync(
                    tempHtmlFile.FilePath,
                    htmlToPdfOptions,
                    variables,
                    false);

                int numberOfPages = PdfDocument.CountNumberOfPages(pdfFile);

                tocHtmlToPdfFile.PdfFilePath   = pdfFile;
                tocHtmlToPdfFile.NumberOfPages = numberOfPages;
            }
        }
Example #20
0
        /// <summary>
        /// Applies the XSLT transformation to the document, writing the output
        /// directly to the HTTP response.
        /// </summary>
        /// <param name="context">HTTP execution context.</param>
        /// <param name="document">Input document.</param>
        /// <param name="xsltUri">XSLT transformation.</param>
        private static void RenderDocument(HttpContext context, XDocument document, string xsltUri)
        {
            #region Validations

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (xsltUri == null)
            {
                throw new ArgumentNullException(nameof(xsltUri));
            }

            #endregion


            /*
             * Load
             */
            UrlResolver r = new UrlResolver(false);

            XmlReaderSettings xrs = new XmlReaderSettings();
            xrs.XmlResolver = r;

            XsltSettings xs = new XsltSettings();
            xs.EnableDocumentFunction = false;
            xs.EnableScript           = false;

            XslCompiledTransform xslt = new XslCompiledTransform();

            using (XmlReader xr = XmlReader.Create(xsltUri, xrs))
            {
                xslt.Load(xr, xs, r);
            }


            /*
             *
             */
            context.Response.StatusCode = 200;

            if (xslt.OutputSettings.OutputMethod == XmlOutputMethod.Html)
            {
                context.Response.ContentType = "text/html";
            }
            else if (xslt.OutputSettings.OutputMethod == XmlOutputMethod.Text)
            {
                context.Response.ContentType = "text/plain";
            }
            else
            {
                context.Response.ContentType = "text/xml";
            }


            /*
             * Apply
             */
            XmlWriterSettings xws = xslt.OutputSettings.Clone();
            xws.Indent = false;

            XsltArgumentList args = new XsltArgumentList();
            args.AddParam("ApplicationPath", "", ToApplicationPath(context.Request));

            using (XmlWriter xw = XmlWriter.Create(context.Response.OutputStream, xws))
            {
                xslt.Transform(document.CreateNavigator(), args, xw);
            }

            context.Response.End();
        }
Example #21
0
        protected void TransformData()
        {
            MemoryStream         xslt_stream, xml_stream;
            XmlTextReader        xml_reader;
            XsltSettings         xslt_settings;
            XPathDocument        doc;
            DataTable            DataSource = null;
            XslCompiledTransform xslt;
            XsltArgumentList     arg_list = null;
            string template_path          = null;

            try
            {
                CreateResultsTable();

                xslt          = new XslCompiledTransform();
                xslt_settings = new XsltSettings(true, true);
                xslt_stream   = new MemoryStream();
                xml_stream    = new MemoryStream();

                if (HasTemplate)
                {
                    Logger.WriteLine("XsltWriter.TransformData", "", System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);

                    // Determine if we are using an XSLT template on disk or if we are getting it from another module.
                    if (!string.IsNullOrEmpty(TemplateName))
                    {
                        // Parse the templates path.
                        template_path = TextParser.Parse(TemplateName, DrivingData, SharedData, ModuleCommands);

                        // Check for the file expecting relative path.
                        if (System.IO.File.Exists(System.IO.Path.GetFullPath(template_path)))
                        {
                            TemplateName = System.IO.Path.GetFullPath(template_path);
                        }
                        // Check for the file from absolute path.
                        else if (System.IO.File.Exists(template_path))
                        {
                            TemplateName = template_path;
                        }
                        // Check for the file two layers up incase we are in the bin/debug|release folder.
                        else if (System.IO.File.Exists(@"..\..\" + template_path))
                        {
                            TemplateName = System.IO.Path.GetFullPath(@"..\..\" + template_path);
                        }
                        else
                        {
                            throw new Exception(string.Format("The XSLT template file '{0}' was not found.", template_path));
                        }

                        Logger.WriteLine("XsltWriter.TransformData", "PHYSICAL STYLE SHEET: ", System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);

                        // Load the style sheet from the referenced path.
                        xslt.Load(TextParser.Parse(TemplateName, DrivingData, SharedData, ModuleCommands), xslt_settings, null);
                    }
                    else
                    {
                        Logger.WriteLine("XsltWriter.TransformData", " DYNAMIC STYLE SHEET: ", System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);

                        // Load the style sheet from the referenced module.
                        xslt.Load(new XmlTextReader(new StringReader(TextParser.Parse(TemplateBody, DrivingData, SharedData, ModuleCommands))), xslt_settings, null);
                    }

                    if (SourceDataTable != null)
                    {
                        Logger.WriteLine("XsltWriter.TransformData", "          DATASOURCE: " + TextParser.Parse(SourceDataTable.Name, DrivingData, SharedData, ModuleCommands), System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);
                        //Logger.WriteLine("XsltWriter.TransformData", "              FILTER: " + SourceDataTable.FilterExpression, System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);

                        // Get the data source table.
                        DataSource = SourceDataTable.Process(DestinationDataTable.CacheTableCollection);
                    }

                    // Check to see if the XSLT writer has any arguments defined.
                    if (ArgumentContainer != null && ArgumentContainer.Count > 0)
                    {
                        Logger.WriteLine("XsltWriter.TransformData", "", System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);
                        Logger.WriteLine("XsltWriter.TransformData", "      ARGUMENT COUNT: " + ArgumentContainer.Count, System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);

                        arg_list = new XsltArgumentList();

                        // Load the argument list.
                        foreach (Argument arg in ArgumentContainer.Arguments)
                        {
                            Logger.WriteLine("XsltWriter.TransformData", "", System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);
                            Logger.WriteLine("XsltWriter.TransformData", "       ARGUMENT NAME: " + arg.Name, System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);
                            Logger.WriteLine("XsltWriter.TransformData", "               VALUE: " + TextParser.Parse(arg.Value, DrivingData, SharedData, ModuleCommands), System.Diagnostics.TraceEventType.Information, 2, 0, SharedData.LogCategory);

                            arg_list.AddParam(arg.Name, "", TextParser.Parse(arg.Value, DrivingData, SharedData, ModuleCommands));
                        }
                    }

                    if ((DataSource != null && DataSource.Rows.Count > 0) || AllowEmptyReport)
                    {
                        if (DataSource == null)
                        {
                            DataSource = new DataTable("NOT_USED");
                        }

                        if (AllowEmptyReport && !string.IsNullOrEmpty(EmptyMessage) && DataSource.Rows.Count == 0)
                        {
                            DataSource.Columns.Add(new DataColumn("Message", typeof(string)));

                            var row = DataSource.NewRow();
                            row["Message"] = EmptyMessage;
                            DataSource.Rows.Add(row);
                        }

                        // Get the data from the source table in XML form.
                        DataSource.WriteXml(xml_stream);

                        // Make sure we are looking at the begining of our data stream.
                        xml_stream.Position = 0;

                        // Load the xml from our xml stream into our xml reader.
                        xml_reader = new XmlTextReader(xml_stream);

                        // Create an xml document from the xml reader.
                        doc = new XPathDocument(xml_reader);

                        // Transform the xml document with the xslt template and load it into our xslt_stream.
                        xslt.Transform(doc, arg_list, xslt_stream);

                        xslt_stream.Flush();
                        xslt_stream.Position = 0;

                        Logger.WriteLine("XsltWriter.TransformData", "", TraceEventType.Information, 2, 0, SharedData.LogCategory);
                        Logger.WriteLine("XsltWriter.TransformData", "    CREATE TRANSFORM: SUCCESSFULL", TraceEventType.Information, 2, 0, SharedData.LogCategory);

                        Save(xslt_stream);
                    }
                    else
                    {
                        Logger.WriteLine("XsltWriter.TransformData", "", TraceEventType.Information, 2, 0, SharedData.LogCategory);
                        Logger.WriteLine("XsltWriter.TransformData", "DISCARDING TRANSFORM: NO DATA", TraceEventType.Information, 2, 0, SharedData.LogCategory);
                    }
                }
                else
                {
                    throw new Exception("XSLT writer must have a template defined.");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private dynamic XsltTransform(string xmlpage, string xsltname, string contentType = "")
        {
            string output = "", myXmlFileMoreSpecific, myXmlFileLessSpecific, myXmlFile;
            var    namespaces = this.GetType().FullName.Split('.').AsEnumerable();

            namespaces = namespaces.Except(new string[] { this.GetType().Name });
            namespaces = namespaces.Except(new string[] { namespaces.Last() });
            var area = string.Join(".", namespaces);

            // se esiste un xslt chiamato {ContentType}.{FieldName}.xslt ha priorità rispetto agli altri
            myXmlFile             = myXmlFileLessSpecific = HostingEnvironment.MapPath("~/") + @"App_Data\Sites\" + _shellSetting.Name + @"\Xslt\" + xsltname + ".xslt";
            myXmlFileMoreSpecific = HostingEnvironment.MapPath("~/") + @"App_Data\Sites\" + _shellSetting.Name + @"\Xslt\" + contentType + "." + xsltname + ".xslt";
            if (File.Exists(myXmlFileMoreSpecific))
            {
                myXmlFile = myXmlFileMoreSpecific;
            }

            if (File.Exists(myXmlFile))
            {
                XmlReader myXPathDoc = XmlReader.Create(new StringReader(xmlpage));
                myXPathDoc.Read();
                XsltArgumentList argsList = new XsltArgumentList();

                argsList.AddExtensionObject("my:HttpUtility", new ExtensionObject());

                string cult = _workContext.GetContext().CurrentCulture;
                if (String.IsNullOrEmpty(cult))
                {
                    cult = "it";
                }
                else
                {
                    cult = cult.Substring(0, 2);
                }

                argsList.AddParam("LinguaParameter", "", cult);

                var allrequest = _workContext.GetContext().HttpContext.Request.QueryString.Keys;

                for (var i = 0; i < allrequest.Count; i++)
                {
                    string _key   = allrequest[i];
                    string _value = _workContext.GetContext().HttpContext.Request.QueryString[_key].ToString();
                    argsList.AddParam(_key.ToLower().Trim(), "", _value);
                }

                XsltSettings settings = new XsltSettings();
                settings.EnableScript = true;

                XslCompiledTransform myXslTrans;
                var enableXsltDebug = false;
#if DEBUG
                enableXsltDebug = true;
#endif
                myXslTrans = new XslCompiledTransform(enableXsltDebug);
                myXslTrans.Load(myXmlFile, settings, new XmlUrlResolver());

                StringWriter sw        = new StringWriter();
                XmlWriter    xmlWriter = new XmlTextWriter(sw);
                myXslTrans.Transform(myXPathDoc, argsList, xmlWriter);

                output = sw.ToString();
            }
            else
            {
                output = xmlpage;
            }
            string      xml = RemoveAllNamespaces(output);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNode newNode  = doc.DocumentElement;
            string  JsonData = JsonConvert.SerializeXmlNode(newNode);
            JsonData = JsonData.Replace(",\"\"]}", "]}"); // aggiunto perchè nella nuova versione di newtonjson i nodi xml vuoti non vengono piu tradotti in "" ma in null
            JsonData = JsonData.Replace("\":lasernumeric", "");
            JsonData = JsonData.Replace("lasernumeric:\"", "");
            JsonData = JsonData.Replace("\":laserboolean", "");
            JsonData = JsonData.Replace("laserboolean:\"", "");
            JsonData = JsonData.Replace(@"\r\n", "");
            JsonData = JsonData.Replace("\":laserDate", "\"\\/Date(");
            JsonData = JsonData.Replace("laserDate:\"", ")\\/\"");
            JavaScriptSerializer ser = new JavaScriptSerializer();
            ser.MaxJsonLength = Int32.MaxValue;
            dynamic dynamiccontent_tmp = ser.Deserialize(JsonData, typeof(object));
            dynamic dynamiccontent     = new DynamicJsonObject(dynamiccontent_tmp);

            return(dynamiccontent);
        }
        /// <summary>
        /// Transforms an XML document content to an XML document content in another format by specifying an XSLT path
        /// </summary>
        /// <param name="xmlString">Original XML document content</param>
        /// <param name="xsltFilePath">XSLT path</param>
        /// <param name="parameters">A generic dictionary containing the XSLT parameters for XSLT transformation(optional)</param>
        /// <param name="extensionObjects">A generic dictionary containing the XSLT extended objects for XSLT transformation(optional)</param>
        /// <param name="outputEncodingName">The encoding name indicating the encoding of the output content. A table listing all available encoding names and their relative code page numbers can be found at :  http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx </param>
        /// <returns>Transformed XML document content</returns>
        public string GetTransformedXmlStringByXsltDocument(string xmlString, string xsltFilePath, IDictionary <string, object> parameters, IDictionary <string, object> extensionObjects, string outputEncodingName)
        {
            string returnValue = xmlString;

            if (this.EnableTracing)
            {
                TracingHelper.Trace(new object[] { xmlString, xsltFilePath, parameters, extensionObjects, outputEncodingName }, this.TraceSourceName);
            }

            XmlDocument document = new XmlDocument();

            document.LoadXml(xmlString);

            XslCompiledTransform transform = new XslCompiledTransform();

            transform.Load(xsltFilePath);

            //StringWriter stringWriter = new StringWriter();

            XsltArgumentList xsltArgumentList = null;

            if (parameters != null)
            {
                if (parameters.Count > 0)
                {
                    if (xsltArgumentList == null)
                    {
                        xsltArgumentList = new XsltArgumentList();
                    }

                    foreach (string key in parameters.Keys)
                    {
                        xsltArgumentList.AddParam(key, String.Empty, parameters[key]);
                    }
                }
            }

            if (extensionObjects != null)
            {
                if (extensionObjects.Count > 0)
                {
                    if (xsltArgumentList == null)
                    {
                        xsltArgumentList = new XsltArgumentList();
                    }

                    foreach (string key in extensionObjects.Keys)
                    {
                        xsltArgumentList.AddExtensionObject(key, extensionObjects[key]);
                    }
                }
            }

            //transform.Transform(document, xsltArgumentList, stringWriter);

            //stringWriter.Flush();
            //stringWriter.Close();

            //returnValue = stringWriter.ToString();

            MemoryStream stream = new MemoryStream();

            transform.Transform(document, xsltArgumentList, stream);

            stream.Flush();

            //byte[] outputBytes = stream.GetBuffer();

            //Encoding outputEncoding = String.IsNullOrEmpty(outputEncodingName) ? Encoding.Default : Encoding.GetEncoding(outputEncodingName);

            //returnValue = outputEncoding.GetString(outputBytes);

            byte[] bytes = new byte[stream.Length];
            stream.Seek(0, SeekOrigin.Begin);
            stream.Read(bytes, 0, bytes.Length);

            Encoding outputEncoding = String.IsNullOrEmpty(outputEncodingName) ? Encoding.Default : Encoding.GetEncoding(outputEncodingName);

            returnValue = outputEncoding.GetString(bytes);

            stream.Close();

            if (this.EnableTracing)
            {
                TracingHelper.Trace(new object[] { document.InnerXml, transform, outputEncoding.BodyName, returnValue }, this.TraceSourceName);
            }

            return(returnValue);
        }
Example #24
0
        public XML(BaseDatos baseDatos)
        {
            _baseDatos            = baseDatos;
            _selloDigital         = new SelloDigital();
            _ws                   = new WSCFDBuilderPlus();
            _xslCompiledTransform = new XslCompiledTransform();

            _facturaRutaCer = ObtenerConfiguracionSistema("FacturaRutaCer");
            if (string.IsNullOrWhiteSpace(_facturaRutaCer))
            {
                throw new ArgumentNullException("FacturaRutaCer, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaRutaKey = ObtenerConfiguracionSistema("FacturaRutaKey");
            if (string.IsNullOrWhiteSpace(_facturaRutaKey))
            {
                throw new ArgumentNullException("FacturaRutaKey, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaFiel = ObtenerConfiguracionSistema("FacturaRutaFiel");
            if (string.IsNullOrWhiteSpace(_facturaFiel))
            {
                throw new ArgumentNullException("FacturaRutaFiel, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaRutaXslt = ObtenerConfiguracionSistema("FacturaRutaXslt");
            if (string.IsNullOrWhiteSpace(_facturaRutaXslt))
            {
                throw new ArgumentNullException("FacturaRutaXslt, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaRutaTimbrado = ObtenerConfiguracionSistema("FacturaRutaTimbrado");
            if (string.IsNullOrWhiteSpace(_facturaRutaTimbrado))
            {
                throw new ArgumentNullException("FacturaRutaTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _wsUrlTimbrado = ObtenerConfiguracionSistema("WsUrlTimbrado");
            if (string.IsNullOrWhiteSpace(_wsUrlTimbrado))
            {
                throw new ArgumentNullException("WsUrlTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _wsUsuarioTimbrado = ObtenerConfiguracionSistema("WsUsuarioTimbrado");
            if (string.IsNullOrWhiteSpace(_wsUsuarioTimbrado))
            {
                throw new ArgumentNullException("WsUsuarioTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _wsContraseñaTimbrado = ObtenerConfiguracionSistema("WsContraseñaTimbrado");
            if (string.IsNullOrWhiteSpace(_wsContraseñaTimbrado))
            {
                throw new ArgumentNullException("WsContraseñaTimbrado, no está definido en Tabla ConfiguracionSistema.");
            }

            _facturaCertificado = ObtenerCertificado();
            if (string.IsNullOrWhiteSpace(_facturaCertificado))
            {
                throw new ArgumentNullException("FacturaCertificado, no se encontró archivo .cer en la ruta " + _facturaRutaCer);
            }

            _facturaArchivoKey = ObtenerFacturaArchivoKey();
            if (_facturaArchivoKey == null)
            {
                throw new ArgumentNullException("FacturaArchivoKey,  no se encontró archivo .key en la ruta " + _facturaRutaKey);
            }

            if (!File.Exists(_facturaRutaXslt))
            {
                throw new ArgumentNullException("FacturaRutaXslt,  no se encontró archivo .xslt en la ruta " + _facturaRutaXslt);
            }

            _xslCompiledTransform.Load(_facturaRutaXslt);
        }
Example #25
0
        private void Transform()
        {
            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Transforming: {0}", this.XmlFile));
            XDocument xslDoc;

            if (!string.IsNullOrEmpty(this.XslTransformFile) && !File.Exists(this.XslTransformFile))
            {
                this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "XslTransformFile not found: {0}", this.XslTransformFile));
                return;
            }

            if (!string.IsNullOrEmpty(this.XslTransformFile))
            {
                // Load the XslTransformFile
                this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Loading XslTransformFile: {0}", this.XslTransformFile));
                xslDoc = XDocument.Load(this.XslTransformFile);
            }
            else if (!string.IsNullOrEmpty(this.XslTransform))
            {
                // Load the XslTransform
                this.LogTaskMessage(MessageImportance.Low, "Loading XslTransform");
                using (StringReader sr = new StringReader(this.XslTransform))
                {
                    xslDoc = XDocument.Load(sr);
                }
            }
            else
            {
                this.Log.LogError("XslTransform or XslTransformFile must be specified");
                return;
            }

            // Load the style sheet.
            XslCompiledTransform xslt     = new XslCompiledTransform();
            XsltSettings         settings = new XsltSettings {
                EnableScript = true
            };

            using (StringReader sr = new StringReader(xslDoc.ToString()))
            {
                xslt.Load(XmlReader.Create(sr), settings, null);
                StringBuilder builder = new StringBuilder();
                using (XmlWriter writer = XmlWriter.Create(builder, xslt.OutputSettings))
                {
                    this.LogTaskMessage(MessageImportance.Low, "Running XslTransform");

                    // Execute the transform and output the results to a writer.
                    xslt.Transform(this.xmlDoc.CreateReader(), writer);
                }

                this.Output = builder.ToString();
            }

            if (!string.IsNullOrEmpty(this.OutputFile))
            {
                if (xslt.OutputSettings.OutputMethod == XmlOutputMethod.Text)
                {
                    this.LogTaskMessage(MessageImportance.Low, "Writing using text method");
                    using (FileStream stream = new FileStream(this.OutputFile, FileMode.Create))
                    {
                        StreamWriter streamWriter = null;

                        try
                        {
                            streamWriter = new StreamWriter(stream, Encoding.Default);

                            // Output the results to a writer.
                            streamWriter.Write(this.Output);
                        }
                        finally
                        {
                            if (streamWriter != null)
                            {
                                streamWriter.Close();
                            }
                        }
                    }
                }
                else
                {
                    this.LogTaskMessage(MessageImportance.Low, "Writing using XML method");
                    using (StringReader sr = new StringReader(this.Output))
                    {
                        XDocument newxmlDoc = XDocument.Load(sr);
                        if (!string.IsNullOrEmpty(this.OutputFile))
                        {
                            XmlWriterSettings writerSettings = new XmlWriterSettings {
                                ConformanceLevel = this.conformanceLevel, Encoding = this.fileEncoding, Indent = this.Indent, OmitXmlDeclaration = this.OmitXmlDeclaration, CloseOutput = true
                            };
                            using (XmlWriter xw = XmlWriter.Create(this.OutputFile, writerSettings))
                            {
                                newxmlDoc.WriteTo(xw);
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Transforms to HTML.
        /// </summary>
        /// <param name="xmlReportData">The XML report data.</param>
        /// <param name="xsltFilePath">The XSLT file path. If not passed the default XSLT template will be used.</param>
        /// <returns>String that results after the XSLT applied on the XML string</returns>
        public static string TransformToHTML(string xmlReportData, CancellationToken cancellationToken, string xsltFilePath = null)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(string.Empty);
            }

            if (string.IsNullOrWhiteSpace(xsltFilePath))
            {
                xsltFilePath = GetDefaultXsltPath();
            }

            string finalReportString = String.Empty;

            using (StringReader xsltStringFromFileReader = new StringReader(File.ReadAllText(xsltFilePath)))
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return(string.Empty);
                }

                // xslInput is a string that contains xsl
                using (StringReader xmlReportStringReader = new StringReader(xmlReportData)) // xmlInput is a string that contains xml
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return(string.Empty);
                    }

                    using (XmlReader xsltFileXmlReader = XmlReader.Create(xsltStringFromFileReader))
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            return(string.Empty);
                        }

                        XslCompiledTransform xsltCompiledTransformation = new XslCompiledTransform();
                        xsltCompiledTransformation.Load(xsltFileXmlReader);

                        using (XmlReader xmlReportXmlReader = XmlReader.Create(xmlReportStringReader))
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                return(string.Empty);
                            }

                            using (StringWriter outputStringWriter = new StringWriter())
                            {
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    return(string.Empty);
                                }

                                using (XmlWriter xsltXmlWriter = XmlWriter.Create(outputStringWriter, xsltCompiledTransformation.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
                                {
                                    if (cancellationToken.IsCancellationRequested)
                                    {
                                        return(string.Empty);
                                    }

                                    xsltCompiledTransformation.Transform(xmlReportXmlReader, xsltXmlWriter);
                                    finalReportString = outputStringWriter.ToString();
                                }
                            }
                        }
                    }
                }
            }

            return(finalReportString);
        }
Example #27
0
        public override void Run()
        {
            IViewContent viewContent = WorkbenchSingleton.Workbench.ActiveViewContent;

            if (viewContent == null || !(viewContent is ITextEditorControlProvider))
            {
                return;
            }
            TextEditorControl textAreaControl = ((ITextEditorControlProvider)viewContent).TextEditorControl;

            int startLine = textAreaControl.Document.GetLineNumberForOffset(textAreaControl.ActiveTextAreaControl.Caret.Offset);
            int endLine   = startLine;

            LineSegment line    = textAreaControl.Document.GetLineSegment(startLine);
            string      curLine = textAreaControl.Document.GetText(line.Offset, line.Length).Trim();

            if (!curLine.StartsWith("///") && !curLine.StartsWith("'''"))
            {
                return;
            }

            while (startLine > 0)
            {
                line    = textAreaControl.Document.GetLineSegment(startLine);
                curLine = textAreaControl.Document.GetText(line.Offset, line.Length).Trim();
                if (curLine.StartsWith("///") || curLine.StartsWith("'''"))
                {
                    --startLine;
                }
                else
                {
                    break;
                }
            }

            while (endLine < textAreaControl.Document.TotalNumberOfLines - 1)
            {
                line    = textAreaControl.Document.GetLineSegment(endLine);
                curLine = textAreaControl.Document.GetText(line.Offset, line.Length).Trim();
                if (curLine.StartsWith("///") || curLine.StartsWith("'''"))
                {
                    ++endLine;
                }
                else
                {
                    break;
                }
            }

            StringBuilder documentation = new StringBuilder();

            for (int lineNr = startLine + 1; lineNr < endLine; ++lineNr)
            {
                line    = textAreaControl.Document.GetLineSegment(lineNr);
                curLine = textAreaControl.Document.GetText(line.Offset, line.Length).Trim();
                if (curLine.StartsWith("///"))
                {
                    documentation.Append(curLine.Substring(3));
                }
                else
                {
                    documentation.Append(curLine.Substring(2));
                }
                documentation.Append('\n');
            }
            string xml  = "<member>" + documentation.ToString() + "</member>";
            string html = String.Empty;

            try
            {
                XslCompiledTransform t = new XslCompiledTransform();
                t.Load(Path.Combine(Path.Combine(PropertyService.DataDirectory, "ConversionStyleSheets"), "ShowXmlDocumentation.xsl"));
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xml);
                StringBuilder sb         = new StringBuilder();
                TextWriter    textWriter = new StringWriter(sb);
                XmlWriter     writer     = new XmlTextWriter(textWriter);
                t.Transform(doc, writer);
                html = sb.ToString();
                textWriter.Close();
                writer.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            new ToolWindowForm(textAreaControl, html).Show();
        }
Example #28
0
        // --------------------------------------------------------------------------------------------------------------
        //  LoadXSL_Resolver
        //  -------------------------------------------------------------------------------------------------------------
        public int LoadXSL_Resolver(String _strXslFile, XmlResolver xr)
        {
            _strXslFile = FullFilePath(_strXslFile);
            xslt        = new XslCompiledTransform();
            XmlReaderSettings xrs = null;

            switch (_nInputXsl)
            {
            case XslInputType.URI:
                _output.WriteLine("Loading style sheet as URI " + _strXslFile);
                xslt.Load(_strXslFile, XsltSettings.TrustedXslt, xr);
                break;

            case XslInputType.Reader:
                switch (_readerType)
                {
                case ReaderType.XmlTextReader:
                    XmlTextReader trTemp = new XmlTextReader(_strXslFile);
                    try
                    {
                        _output.WriteLine("Loading style sheet as XmlTextReader " + _strXslFile);
                        xslt.Load(trTemp, XsltSettings.TrustedXslt, xr);
                    }
                    finally
                    {
                        if (trTemp != null)
                        {
                            trTemp.Dispose();
                        }
                    }
                    break;

                case ReaderType.XmlNodeReader:
                    XmlDocument docTemp = new XmlDocument();
                    docTemp.Load(_strXslFile);
                    XmlNodeReader nrTemp = new XmlNodeReader(docTemp);
                    try
                    {
                        _output.WriteLine("Loading style sheet as XmlNodeReader " + _strXslFile);
                        xslt.Load(nrTemp, XsltSettings.TrustedXslt, xr);
                    }
                    finally
                    {
                        if (nrTemp != null)
                        {
                            nrTemp.Dispose();
                        }
                    }
                    break;

                case ReaderType.XmlValidatingReader:
                default:
                    xrs = new XmlReaderSettings();
#pragma warning disable 0618
                    xrs.ProhibitDtd = false;
#pragma warning restore 0618
                    XmlReader vrTemp = XmlReader.Create(_strXslFile, xrs);
                    try
                    {
                        _output.WriteLine("Loading style sheet as XmlValidatingReader " + _strXslFile);
                        xslt.Load(vrTemp, XsltSettings.TrustedXslt, xr);
                    }
                    finally
                    {
                        if (vrTemp != null)
                        {
                            vrTemp.Dispose();
                        }
                    }
                    break;
                }
                break;

            case XslInputType.Navigator:
                xrs = new XmlReaderSettings();
#pragma warning disable 0618
                xrs.ProhibitDtd = false;
#pragma warning restore 0618
                XmlReader xrLoad = XmlReader.Create(_strXslFile, xrs);

                XPathDocument xdTemp = new XPathDocument(xrLoad, XmlSpace.Preserve);
                xrLoad.Dispose();
                _output.WriteLine("Loading style sheet as Navigator " + _strXslFile);
                xslt.Load(xdTemp, XsltSettings.TrustedXslt, xr);
                break;
            }
            return(1);
        }
Example #29
0
        /// <summary>
        /// Run the generated XML file through the XSL transformation engine to create the file output.
        /// </summary>
        private void AsyncGenerateOutput(object sender, DoWorkEventArgs e)
        {
            _blnQueueOutputGeneratorRun = false;
            string strXslPath = Path.Combine(Utils.GetStartupPath, "sheets", _strSelectedSheet + ".xsl");

            if (!File.Exists(strXslPath))
            {
                string strReturn = "File not found when attempting to load " + _strSelectedSheet + Environment.NewLine;
                Log.Debug(strReturn);
                Program.MainForm.ShowMessageBox(this, strReturn);
                return;
            }
#if DEBUG
            XslCompiledTransform objXslTransform = new XslCompiledTransform(true);
#else
            XslCompiledTransform objXslTransform = new XslCompiledTransform();
#endif
            try
            {
                objXslTransform.Load(strXslPath);
            }
            catch (Exception ex)
            {
                string strReturn = "Error attempting to load " + _strSelectedSheet + Environment.NewLine;
                Log.Debug(strReturn);
                Log.Error("ERROR Message = " + ex.Message);
                strReturn += ex.Message;
                Program.MainForm.ShowMessageBox(this, strReturn);
                return;
            }

            if (_workerOutputGenerator.CancellationPending)
            {
                e.Cancel = true;
                return;
            }

            using (MemoryStream objStream = new MemoryStream())
            {
                using (XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8))
                {
                    objXslTransform.Transform(_objCharacterXml, objWriter);
                    if (_workerOutputGenerator.CancellationPending)
                    {
                        e.Cancel = true;
                        return;
                    }

                    objStream.Position = 0;

                    // This reads from a static file, outputs to an HTML file, then has the browser read from that file. For debugging purposes.
                    //objXSLTransform.Transform("D:\\temp\\print.xml", "D:\\temp\\output.htm");
                    //webBrowser1.Navigate("D:\\temp\\output.htm");

                    if (!GlobalOptions.PrintToFileFirst)
                    {
                        // Populate the browser using DocumentText (DocumentStream would cause issues due to stream disposal).
                        using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8, true))
                        {
                            webViewer.DocumentText = objReader.ReadToEnd();
                        }
                    }
                    else
                    {
                        // The DocumentStream method fails when using Wine, so we'll instead dump everything out a temporary HTML file, have the WebBrowser load that, then delete the temporary file.
                        // Read in the resulting code and pass it to the browser.

                        using (StreamReader objReader = new StreamReader(objStream, Encoding.UTF8, true))
                        {
                            string strOutput = objReader.ReadToEnd();
                            File.WriteAllText(_strFilePathName, strOutput);
                        }

                        webViewer.Url = new Uri("file:///" + _strFilePathName);
                    }
                }
            }
        }
Example #30
0
        private void Transform_click(object sender, RoutedEventArgs e)
        {
            tbox.Clear();
            if (xml_path == null || xml_path.Length == 0)
            {
                tbox.AppendText("Check the name for input XML file");
                return;
            }
            else if (xsd_path == null || xsd_path.Length == 0)
            {
                tbox.AppendText("Check the name for input XSD file");
                return;
            }
            else if (xslt_path == null || xslt_path.Length == 0)
            {
                tbox.AppendText("\nCheck the name for XSLT file!\n");
                return;
            }
            else if (out_xsd_path == null || out_xsd_path.Length == 0)
            {
                tbox.AppendText("\nCheck the name for output XSD file!\n");
                return;
            }

            #region Initial validation
            tbox.AppendText("Starting initial validation...\n");
            if (Validate(xml_path, xsd_path))
            {
                tbox.AppendText("Initial validation successfull.\n");
            }
            else
            {
                tbox.AppendText("\nValidation failed\n");
                return;
            }
            #endregion

            #region TRANSFORM

            XDocument newTree = new XDocument();
            using (XmlWriter writer = XmlWriter.Create(newTree.CreateWriter()))
            {
                XslCompiledTransform xslt = new XslCompiledTransform();
                tbox.AppendText("\nStarting transformation...\n");
                try
                {
                    xslt.Load(xslt_path);
                    xslt.Transform(xml_path, writer);
                }
                catch (Exception ex)
                { tbox.AppendText("Transformation error: " + ex.Message + " Check XSLT file!\n"); return; }
                tbox.AppendText("Transformation complete\n");
            }

            #endregion

            #region Final validation
            tbox.AppendText("\nStarting final validation...\n");
            if (Validate(newTree.ToString(), out_xsd_path))
            {
                tbox.AppendText("Final validation successfull\n");
            }
            else
            {
                tbox.AppendText("Validation error\n");
                return;
            }
            #endregion

            #region File save
            tbox.AppendText("\nSaving output XML file...\n");
            if (output_textBox.Text.Length > 0)
            {
                out_xml = output_textBox.Text;
            }
            else
            {
                out_xml = "out.xml";
            }
            try
            {
                File.WriteAllText(new Uri(Directory.GetCurrentDirectory() + "\\" + out_xml, UriKind.Absolute).LocalPath, newTree.ToString());
                tbox.AppendText("File saved: " + (new Uri(Directory.GetCurrentDirectory())).ToString() + "/" + out_xml);
            }
            catch (Exception ex)
            {
                tbox.AppendText("Can't save file!\nError: " + ex.Message + "\nUnable to save file " + out_xml);
                return;
            }
            #endregion
        }
Example #31
0
        private void Display()
        {
            try
            {
                XslCompiledTransform xsl = new XslCompiledTransform();
                if (File.Exists(ApplicationSettings.Instance.LocalDataPath + @"\theme\sms.xslt") &&
                    ApplicationSettings.Instance.Active)
                {
                    xsl.Load(ApplicationSettings.Instance.LocalDataPath + @"\theme\sms.xslt");
                }
                else
                {
                    xsl.Load(ApplicationSettings.Instance.AppPath + @"\sms.xslt");
                }

                XsltArgumentList argList = new XsltArgumentList();

                argList.AddParam("systemPath", "", ApplicationSettings.Instance.AppPath);
                argList.AddParam("dataPath", "", ApplicationSettings.Instance.LocalDataPath);
                if (File.Exists(ApplicationSettings.Instance.LocalDataPath + @"\theme"))
                {
                    argList.AddParam("themePath", "", ApplicationSettings.Instance.LocalDataPath + @"\theme");
                }
                if (ApplicationSettings.Instance.SmsShowImages)
                {
                    argList.AddParam("showImages", "", "true");
                }
                else
                {
                    argList.AddParam("showImages", "", "false");
                }

                if (File.Exists(ApplicationSettings.Instance.LocalDataPath + @"\me.png"))
                {
                    argList.AddParam("meImage", "", ApplicationSettings.Instance.LocalDataPath + @"\me.png");
                }
                else if (File.Exists(ApplicationSettings.Instance.LocalDataPath + @"\me.gif"))
                {
                    argList.AddParam("meImage", "", ApplicationSettings.Instance.LocalDataPath + @"\me.gif");
                }
                else if (File.Exists(ApplicationSettings.Instance.LocalDataPath + @"\me.jpg"))
                {
                    argList.AddParam("meImage", "", ApplicationSettings.Instance.LocalDataPath + @"\me.jpg");
                }
                else if (File.Exists(ApplicationSettings.Instance.LocalDataPath + @"\me.jpeg"))
                {
                    argList.AddParam("meImage", "", ApplicationSettings.Instance.LocalDataPath + @"\me.jpeg");
                }
                else
                {
                    argList.AddParam("meImage", "", ApplicationSettings.Instance.AppPath + @"\me.gif");
                }

                argList.AddParam("bgColor", "", ApplicationSettings.Instance.SmsBackgroundColor);
                argList.AddParam("fontColor", "", ApplicationSettings.Instance.SmsTextColor);

                XmlDocument outputDocument = new XmlDocument();
                System.Xml.XPath.XPathNavigator outputNavigator = outputDocument.CreateNavigator();
                using (XmlWriter writer = outputNavigator.AppendChild())
                {
                    xsl.Transform(m_smsXmlDoc, argList, writer);
                }

                webBrowser.DocumentText = outputDocument.OuterXml;
            }
            catch (Exception)
            {
            }
        }
        /// <inheritdoc />
        /// <devdoc>
        /// This will delete a pre-existing _files folder. Be sure the user has at least seen an
        /// overwrite prompt for the web page by now!
        /// </devdoc>
        public override void WriteReport(CoverageExport dataset, ReportConfigurationModel configuration)
        {
            EnsureJQueryIsCached();

            // Note (Windows-specific):
            // when a web page ("Page.html") is accompanied by a folder named like "Page_files",
            // windows will try to keep the folder with the html page when moved, and warn if one of
            // these are renamed (since the other will not be, and any links in the page will not work).
            string filesDirName = Path.GetFileNameWithoutExtension(configuration.DestinationPath) + "_files";
            string filesDirPath = Path.Combine(Path.GetDirectoryName(configuration.DestinationPath), filesDirName);


            // make sure we're working with a fresh files folder.
            var filesDir = new DirectoryInfo(filesDirPath);

            if (filesDir.Exists)
            {
                filesDir.Delete(recursive: true);
            }
            filesDir.Create();


            string jQueryFullPath = Path.Combine(filesDirPath, ReportConstants.JQueryFileName);

            File.Copy(JQueryCachedPath, jQueryFullPath);


            using (var tempFile = WriteToTempFile(dataset))
            {
                var transform = new XslCompiledTransform();
                using (var xslReader = XmlReader.Create(new StringReader(Resources.HTMLTransform)))
                {
                    transform.Load(xslReader);
                }

                var args = new XsltArgumentList();

                args.AddParam(ReportConstants.HtmlGenDate, "",
                              DateTime.Now.ToString("dd MMM yyyy HH:mm:ss"));

                args.AddParam(ReportConstants.HtmlTotalLines, "",
                              dataset.LinesCovered + dataset.LinesPartiallyCovered + dataset.LinesNotCovered);

                args.AddParam(ReportConstants.HtmlTotalBlocks, "",
                              dataset.BlocksCovered + dataset.BlocksNotCovered);

                args.AddParam(ReportConstants.HtmlExpansionDepth, "",
                              (int)configuration.DefaultExpansion);

                args.AddParam("jQuerySource", "",
                              Path.Combine(filesDirName, ReportConstants.JQueryFileName));


                using (var outputFile = new FileStream(configuration.DestinationPath, FileMode.Create, FileAccess.Write))
                {
                    using (var tempReader = XmlReader.Create(tempFile.Stream))
                    {
                        transform.Transform(tempReader, args, outputFile);
                    }
                }
            }
        }
Example #33
0
        public override bool transform()
        {
            // pretreat to the input .uof file of Presentation
            //preMethod(inputFile);

            FileStream fs = null;
            // XmlUrlResolver resourceResolver = null;
            XmlReader xr = null;

            string extractPath = Path.GetDirectoryName(outputFile) + Path.AltDirectorySeparatorChar;
            string prefix      = this.GetType().Namespace + "." + TranslatorConstants.RESOURCE_LOCATION + "." + TranslatorConstants.UOFToOOX_POWERPOINT_LOCATION;
            string uof2ooxpre  = extractPath + "uof2ooxpre.xml"; //  调用此部分出异常 所以改为下面语句
            string picture_xml = "data";

            // string uof2ooxpre = extractPath + "tmpDoc1.xml";

            try
            {
                // copy XSLT templates
                Assembly asm = Assembly.GetExecutingAssembly();
                foreach (string name in asm.GetManifestResourceNames())
                {
                    if (name.StartsWith(prefix))
                    {
                        string     filename   = name.Substring(prefix.Length + 1);
                        FileStream writer     = new FileStream(extractPath + filename, FileMode.Create);
                        Stream     baseStream = asm.GetManifestResourceStream(name);
                        int        Length     = 10240;
                        Byte[]     buffer     = new Byte[Length];
                        int        bytesRead  = baseStream.Read(buffer, 0, Length);
                        while (bytesRead > 0)
                        {
                            writer.Write(buffer, 0, bytesRead);
                            bytesRead = baseStream.Read(buffer, 0, Length);
                        }
                        baseStream.Close();
                        writer.Close();
                    }
                }

                //resourceResolver = new ResourceResolver(Assembly.GetExecutingAssembly(), prefix);
                //xr = XmlReader.Create(((ResourceResolver)resourceResolver).GetInnerStream("uof2oopre.xslt"));
                xr = XmlReader.Create(extractPath + "uof2ooxpre.xslt");

                XPathDocument        doc       = new XPathDocument(extractPath + @"content.xml");
                XslCompiledTransform transFrom = new XslCompiledTransform();
                XsltSettings         setting   = new XsltSettings(true, false);
                XmlUrlResolver       xur       = new XmlUrlResolver();
                transFrom.Load(xr, setting, xur);
                XPathNavigator nav = ((IXPathNavigable)doc).CreateNavigator();
                // fs = new FileStream(outputFile, FileMode.Create);
                fs = new FileStream(uof2ooxpre, FileMode.Create);
                transFrom.Transform(nav, null, fs);
                fs.Close();

                preMethod(uof2ooxpre);

                if (Directory.Exists(extractPath + "drawings") && Directory.Exists(extractPath + "embeddings"))
                {
                    string      tmpOle = extractPath + Path.AltDirectorySeparatorChar + "tmpOle.xml";
                    XmlDocument xdoc   = new XmlDocument();
                    xdoc.Load(outputFile);
                    XmlNameTable        nt = xdoc.NameTable;
                    XmlNamespaceManager nm = new XmlNamespaceManager(nt);
                    nm.AddNamespace("w", TranslatorConstants.XMLNS_W);
                    nm.AddNamespace("uof", TranslatorConstants.XMLNS_UOF);

                    xdoc = OlePretreatment(xdoc, "uof:UOF", extractPath, nm);
                    xdoc.Save(tmpOle);
                    // OutputFilename = tmpPic;
                    outputFile = tmpOle;
                }


                if (Directory.Exists(extractPath + picture_xml))
                {
                    string      tmpPic = extractPath + Path.AltDirectorySeparatorChar + "tmpPic.xml";
                    XmlDocument xdoc   = new XmlDocument();
                    xdoc.Load(outputFile);
                    XmlNameTable        nt = xdoc.NameTable;
                    XmlNamespaceManager nm = new XmlNamespaceManager(nt);
                    nm.AddNamespace("w", TranslatorConstants.XMLNS_W);
                    nm.AddNamespace("uof", TranslatorConstants.XMLNS_UOF);

                    xdoc = PicPretreatment(xdoc, "uof:UOF", extractPath + picture_xml, nm);
                    xdoc.Save(tmpPic);
                    // OutputFilename = tmpPic;
                    outputFile = tmpPic;
                }

                // 公式
                if (File.Exists(extractPath + "equations.xml"))
                {
                    string tmpEqu = extractPath + Path.AltDirectorySeparatorChar + "tmpEqu.xml";

                    string      equXML = extractPath + "equations.xml";
                    XmlDocument equDoc = new XmlDocument();
                    equDoc.Load(equXML);

                    XmlDocument xdoc = new XmlDocument();
                    xdoc.Load(outputFile);

                    XmlNode equ = xdoc.ImportNode(equDoc.LastChild, true);
                    xdoc.LastChild.AppendChild(equ);
                    xdoc.Save(tmpEqu);

                    outputFile = tmpEqu;
                }
                return(true);
            }

            catch (Exception ex)
            {
                logger.Error("Fail in Uof2.0 to OOX pretreatment1: " + ex.Message);
                logger.Error(ex.StackTrace);
                throw new Exception("Fail in Uof2.0 to OOX pretreatment1 of Presentation");
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                }
            }
        }
Example #34
0
 private static int[] selectedDropBlock = new int[3]; // przechowuje rodzaj i nr indeksu elementu na którym zwolniono przycisk myszy
 //private int pom1; // pomocnicza
 /// <summary>
 /// Odpowiada za wyświetlenie informacji o klikanym bloku schematu
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 static public void OnMouseClick(object sender, MouseEventArgs e)
 {
     if (Data.comunicationNet1.Channels.Rows.Count > 0) // zapobiega próbom wywołania przed wczytaniem bazy
     {
         int[] containInfo = new int[2];
         containInfo = Map.MapContainTest(e);
         if (containInfo[0] != 0) // jeśli containInfo[0]=0 to wskaznik myszy nie wskazuje żadnego elementu schematu
         {
             Program.f1.webBrowser1.Document.OpenNew(false);
             if (containInfo[0] == (int)itemType.server) // ikona servera
             {
                 Array.Clear(GraphGUIMainForm.activeItem, 0, GraphGUIMainForm.activeItem.Length);
                 GraphGUIMainForm.activeItem[0, 0] = true;
                 // Informacja o pliku:
                 FileInfo fi      = new FileInfo(GraphGUIMainForm.configFile);
                 string   stronka = (string)GraphGUIMainForm.resources.GetObject("FileInfoTable");
                 // wypełniam odpowiednie pola informacjami
                 stronka = stronka.Replace("XXXparam1", fi.Name.ToString());
                 stronka = stronka.Replace("XXXparam2", fi.CreationTime.ToString());
                 stronka = stronka.Replace("XXXparam3", fi.Length.ToString() + " bytes");
                 stronka = stronka.Replace("XXXparam4", fi.Attributes.ToString());
                 Program.f1.webBrowser1.Document.Write(stronka);
             }
             else
             {
                 bool flag = false;
                 XslCompiledTransform xstl  = new XslCompiledTransform();
                 XPathDocument        xpdoc = new XPathDocument(GraphGUIMainForm.configFile);
                 XsltArgumentList     args  = new XsltArgumentList();
                 StringWriter         sw    = new StringWriter();
                 TextReader           tr;
                 XmlReader            xmlr;
                 string xslFile = "";
                 Array.Clear(GraphGUIMainForm.activeItem, 0, GraphGUIMainForm.activeItem.Length);
                 if (containInfo[0] == (int)itemType.channelLabel)
                 {
                     GraphGUIMainForm.activeItem[3, containInfo[1]] = true;
                     xslFile = (string)GraphGUIMainForm.resources.GetObject("ChannelInfoTable");
                     args.AddParam("id", string.Empty, Data.comunicationNet1.Channels.Rows[containInfo[1]]["ChannelID"].ToString());
                     flag = true;
                 }
                 else if (containInfo[0] == (int)itemType.protocol)
                 {
                     GraphGUIMainForm.activeItem[4, containInfo[1]] = true;
                     xslFile = (string)GraphGUIMainForm.resources.GetObject("ProtocolInfoTable");
                     args.AddParam("id", string.Empty, Data.comunicationNet1.Protocol.Rows[containInfo[1]]["ProtocolID"].ToString());
                     flag = true;
                 }
                 else if (containInfo[0] == (int)itemType.segment)
                 {
                     GraphGUIMainForm.activeItem[5, containInfo[1]] = true;
                     xslFile = (string)GraphGUIMainForm.resources.GetObject("SegmentInfoTable");
                     args.AddParam("id", string.Empty, Data.comunicationNet1.Segments.Rows[containInfo[1]]["SegmentID"].ToString());
                     flag = true;
                 }
                 else if (containInfo[0] == (int)itemType.station)
                 {
                     GraphGUIMainForm.activeItem[6, containInfo[1]] = true;
                     xslFile = (string)GraphGUIMainForm.resources.GetObject("StationInfoTable");
                     args.AddParam("id", string.Empty, Data.comunicationNet1.Station.Rows[containInfo[1]]["StationID"].ToString());
                     flag = true;
                 }
                 else if (containInfo[0] == (int)itemType.line & GraphGUIMainForm.line[containInfo[1]].type == lineType.segm_stat) // linia segment-station
                 {
                     GraphGUIMainForm.activeItem[7, containInfo[1] - Data.comunicationNet1.Protocol.Rows.Count - Data.comunicationNet1.Segments.Rows.Count] = true;
                     xslFile = (string)GraphGUIMainForm.resources.GetObject("InterfaceInfoTable");
                     args.AddParam("id", string.Empty, Data.comunicationNet1.Interfaces.Rows[containInfo[1] - Data.comunicationNet1.Protocol.Rows.Count - Data.comunicationNet1.Segments.Rows.Count]["Name"].ToString());
                     flag = true;
                 }
                 if (flag)
                 {
                     tr   = new StringReader(xslFile);
                     xmlr = new XmlTextReader(tr);
                     xstl.Load(xmlr);
                     xstl.Transform(xpdoc, args, sw);
                     string doc = sw.ToString();
                     Program.f1.webBrowser1.Document.Write(doc);
                 }
             }
             Program.f1.GenerateSchema(false); // odświeżenie widoku
         }
         else // czyści okienko informacyjne farmularza
         {
             Array.Clear(GraphGUIMainForm.activeItem, 0, GraphGUIMainForm.activeItem.Length);
             string blank = (string)GraphGUIMainForm.resources.GetObject("Blank");
             Program.f1.webBrowser1.Document.Write(blank);
             Program.f1.webBrowser1.Refresh();
         }
     } // if
 }     // OnMouseClick
Example #35
0
        /// <summary>
        /// This method generates the HTML from the passed-in XML
        /// </summary>
        /// <param name="sender">The object raising the event</param>
        /// <param name="e">The event arguments</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            const string METHOD_NAME = "Page_Load";

            try
            {
                //Get the current URL (without querystring) and replace the .ASPX with .SVC
                string currentUrl = Request.Url.GetLeftPart(UriPartial.Path);
                currentUrl = currentUrl.ToLowerInvariant().Replace(".aspx", ".svc");

                //Load in the XML WSDL document for the web service
                WebClient   webClient = new WebClient();
                string      wsdl      = webClient.DownloadString(currentUrl + "?wsdl");
                XmlDocument xmlDoc    = new XmlDocument();
                xmlDoc.LoadXml(wsdl);

                //Now load in the appropriate XSLT stylesheet based on the passed-in querystring
                if (!String.IsNullOrEmpty(Request.QueryString["operation"]))
                {
                    //Viewing operation details
                    string           operationName = Request.QueryString["operation"].Trim();
                    XsltArgumentList argsList      = new XsltArgumentList();
                    argsList.AddParam("operationName", "", operationName);
                    argsList.AddParam("productName", "", "Library Information System");

                    XslCompiledTransform xslt = new XslCompiledTransform();
                    xslt.Load(Server.MapPath("~/Transforms/OperationDetails.xslt"));

                    //Write out the transformed file to the Response stream
                    MemoryStream memoryStream = new MemoryStream();
                    XHTMLWriter  writer       = new XHTMLWriter(memoryStream, System.Text.Encoding.UTF8);
                    xslt.Transform(xmlDoc, argsList, Response.Output);
                }
                else if (!String.IsNullOrEmpty(Request.QueryString["datacontract"]))
                {
                    //Viewing data-contract details
                    string           datacontractName = Request.QueryString["datacontract"].Trim();
                    XsltArgumentList argsList         = new XsltArgumentList();
                    argsList.AddParam("datacontractName", "", datacontractName);
                    argsList.AddParam("productName", "", "Library Information System");

                    string dataContractName   = Request.QueryString["datacontract"].Trim();
                    XslCompiledTransform xslt = new XslCompiledTransform();
                    xslt.Load(Server.MapPath("~/Transforms/DataContractDetails.xslt"));

                    //Write out the transformed file to the Response stream
                    MemoryStream memoryStream = new MemoryStream();
                    XHTMLWriter  writer       = new XHTMLWriter(memoryStream, System.Text.Encoding.UTF8);
                    xslt.Transform(xmlDoc, argsList, Response.Output);
                }
                else
                {
                    //Viewing the list of operations
                    XslCompiledTransform xslt = new XslCompiledTransform();
                    xslt.Load(Server.MapPath("~/Transforms/ServiceOperations.xslt"));

                    //Pass the product name
                    XsltArgumentList argsList = new XsltArgumentList();
                    argsList.AddParam("productName", "", "Library Information System");

                    //Write out the transformed file to the Response stream
                    MemoryStream memoryStream = new MemoryStream();
                    XHTMLWriter  writer       = new XHTMLWriter(memoryStream, System.Text.Encoding.UTF8);
                    xslt.Transform(xmlDoc, argsList, Response.Output);
                }
            }
            catch (System.Exception exception)
            {
                Response.Write("Documentation Unavailable (" + exception.Message + ")!");
                Logger.LogErrorEvent(CLASS_NAME + METHOD_NAME, exception);
            }
        }
 public void LoadStyleSheet()
 {
     transform = new XslCompiledTransform(true);
     transform.Load(new SystemPath(Stylesheet).ToString());
 }
Example #37
0
 private void loadXslt()
 {
     myXslTransform = new XslCompiledTransform();
     myXslTransform.Load(_filename);
 }
Example #38
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string username = Convert.ToString(Session["username"]);
            Label1.Text = "Welcome" + " " + " " + username;
            if (!IsPostBack)
            {
                // The page is being loaded and accessed for the first time.
                // Retrieve user input from the form.
                if (Request.QueryString["s"] == null)
                    // Set the default stock symbol to YHOO.
                    m_symbol = "YHOO";
                else
                    // Get the user's input.
                    m_symbol = Request.QueryString["s"].ToString().ToUpper();
                // Update the textbox value.
                txtSymbol.Value = m_symbol;
                // This DIV that contains text and DIVs that displays stock quotes and chart from Yahoo.
                // Set the innerHTML property to replaces the existing content of the DIV.
                divService.InnerHtml = "<br />";
                if (m_symbol.Trim() != "")
                {
                    try
                    {
                        // Return the stock quote data in XML format.
                        String arg = GetQuote(m_symbol.Trim());
                        if (arg == null)
                            return;

                        // Read XML.
                        // Declare an XmlDocument object to represents an XML document.
                        XmlDocument xd = new XmlDocument();
                        // Loads the XML data from a stream.
                        xd.LoadXml(arg);

                        // Read XSLT
                        // Declare an XslCompiledTransform object to transform XML data using an XSLT style sheet.
                        XslCompiledTransform xslt = new XslCompiledTransform();
                        // Use the Load method to load the Xsl transform object.
                        xslt.Load(Server.MapPath("stock.xsl"));

                        // Transform the XML document into HTML.
                        StringWriter fs = new StringWriter();
                        xslt.Transform(xd.CreateNavigator(), null, fs);
                        string result = fs.ToString();

                        // Replace the characters "&gt;" and "&lt;" back to "<" and ">".
                        divService.InnerHtml = "<br />" + result.Replace("&lt;", "<").Replace("&gt;", ">") + "<br />";

                        // Display stock charts.
                        String[] symbols = m_symbol.Replace(",", " ").Split(' ');
                        // Loop through each stock
                        for (int i = 0; i < symbols.Length; ++i)
                        {
                            if (symbols[i].Trim() == "")
                                continue;
                            int index = divService.InnerHtml.ToLower().IndexOf(symbols[i].Trim().ToLower() + " is invalid.");
                            // If index = -1, the stock symbol is valid.
                            if (index == -1)
                            {
                                // Use a random number to defeat cache.
                                Random random = new Random();
                                divService.InnerHtml += "<img id='imgChart_" + i.ToString() + "' src='http://ichart.finance.yahoo.com/b?s=" + symbols[i].Trim().ToUpper() + "& " + random.Next() + "' border=0><br />";
                                // 1 days
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(0," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div1d_" + i.ToString() + "'><b>1d</b></span></a>&nbsp;&nbsp;";
                                // 5 days
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(1," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div5d_" + i.ToString() + "'>5d</span></a>&nbsp;&nbsp;";
                                // 3 months
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(2," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div3m_" + i.ToString() + "'>3m</span></a>&nbsp;&nbsp;";
                                // 6 months
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(3," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div6m_" + i.ToString() + "'>6m</span></a>&nbsp;&nbsp;";
                                // 1 yeas
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(4," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div1y_" + i.ToString() + "'>1y</span></a>&nbsp;&nbsp;";
                                // 2 years
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(5," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div2y_" + i.ToString() + "'>2y</span></a>&nbsp;&nbsp;";
                                // 5 years
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(6," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div5y_" + i.ToString() + "'>5y</span></a>&nbsp;&nbsp;";
                                // Max
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(7," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='divMax_" + i.ToString() + "'>Max</span></a><br><br /><br />&nbsp;&nbsp;";
                            }
                        }
                    }
                    catch
                    {
                        // Handle exceptions
                    }
                }
            }
    }
Example #39
0
        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);
            }
        }
		// Function  : Export_with_XSLT_Web 
		// Arguments : dsExport, sHeaders, sFileds, FormatType, FileName
		// Purpose   : Exports dataset into CSV / Excel format

		private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)
		{
			try
			{				
				// Appending Headers
				response.Clear();
				response.Buffer= true;
				
				if(FormatType == ExportFormat.CSV)
				{
					response.ContentType = "text/csv";
					response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
				}		
				else
				{
					response.ContentType = "application/vnd.ms-excel";
					response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
				}

				// XSLT to use for transforming this dataset.						
				MemoryStream stream = new MemoryStream( );
				XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
				CreateStylesheet(writer, sHeaders, sFileds, FormatType);
				writer.Flush( ); 
				stream.Seek( 0, SeekOrigin.Begin);
                XmlDocument xsl = new XmlDocument();
                xsl.Load(stream);

                //XslTransform xslTran = new XslTransform();				
                //xslTran.Load(new XmlTextReader(stream), null, null);				
                //System.IO.StringWriter  sw = new System.IO.StringWriter();			
                //xslTran.Transform(xmlDoc, null, sw, null);

                XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);

                StringWriter sw = new StringWriter();
                XmlTextWriter xtw = new XmlTextWriter(sw);
                XslCompiledTransform t = new XslCompiledTransform();
                t.Load((IXPathNavigable)xsl, null, null);
                t.Transform((IXPathNavigable)xmlDoc, xtw);
					
				//Writeout the Content				
				response.Write(sw.ToString());			
				sw.Close();
                xtw.Close();
				writer.Close();
				stream.Close();			
				response.End();
                sw.Dispose();
                stream.Dispose();
			}
			catch(ThreadAbortException Ex)
			{
				string ErrMsg = Ex.Message;
			}
			catch(Exception Ex)
			{
				throw Ex;
			}
		}		
Example #41
0
        static void Main(string[] args)
        {
            if (CreateOutputFolders() == false)
            {
                Console.ReadKey();
                Environment.Exit(99);
            }
            const string xsltFilePath = "xs3p.xsl";

            // Load XSLT
            XsltSettings         settings    = new XsltSettings(true, true);
            XslCompiledTransform transformer = new XslCompiledTransform();

            transformer.Load(xsltFilePath, settings, new XmlUrlResolver());

            string schemaProjectDirectory = System.Environment.CurrentDirectory + "\\XSD";

            // Look in the project output directory for all xsd files
            string[] files = Directory.GetFiles(schemaProjectDirectory, "*.xsd");

            // Create the output directories for the generated HTML files, and code example files
            //string outputDirectory = Path.Combine(Environment.CurrentDirectory, "Generated HTML Docs");
            //if (!Directory.Exists(outputDirectory))
            //    Directory.CreateDirectory(outputDirectory);

            //string exampleDirectory = Path.Combine(Environment.CurrentDirectory, "Generated Examples");
            //if (!Directory.Exists(exampleDirectory))
            //    Directory.CreateDirectory(exampleDirectory);

            // For each XSD file, create the HTML documentation, and examples (.cs, .vb, .xml, json)
            Console.WriteLine("Generating Files.....");
            foreach (string xsdFilePath in files)
            {
                //Don't create HTML documentation or XML samples for base schema
                if (xsdFilePath == schemaProjectDirectory + "\\Common.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\ISOCountryCodeType-V2006.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\ISOCurrencyCodeType.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\MessageContext.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\Meta.xsd")
                {
                    continue;
                }


                #region Generate the HTML documentation
                string outHtmlFileName = Path.Combine(sGeneratedPath + "\\HTML\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".html";
                using (StreamWriter outHtmlfile = new StreamWriter(outHtmlFileName))
                {
                    string documentTitle = Path.GetFileNameWithoutExtension(xsdFilePath);
                    documentTitle = documentTitle.Replace("CUFX_", "");
                    documentTitle = documentTitle.Replace("_", " ");

                    XsltArgumentList argsList = new XsltArgumentList();
                    argsList.AddParam("title", "", documentTitle);
                    argsList.AddParam("currentDateTime", "", DateTime.Now.ToString("d"));

                    using (XmlTextReader xsdReader = new XmlTextReader(xsdFilePath))
                    {
                        XPathNavigator nav = new XPathDocument(xsdReader).CreateNavigator();

                        try
                        {
                            transformer.Transform(nav, argsList, outHtmlfile);
                        }
                        catch (XsltException xsltEx)
                        {
                            Console.WriteLine("Could not transform the XSD file [{0}]. Message: [{1}] line: [{2}], position: [{3}]", xsdFilePath, xsltEx.Message, xsltEx.LineNumber, xsltEx.LinePosition);
                            Console.ReadKey();
                        }
                        xsdReader.Close();
                    }
                    outHtmlfile.Close();
                    //Console.WriteLine("HTML Files Created");
                }
                #endregion

                #region Generate the XML/JSON examples
                string outXmlFileName = Path.Combine(sGeneratedPath + "\\XML\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".xml";
                using (XmlTextWriter outXmlFile = new XmlTextWriter(outXmlFileName, null))
                {
                    outXmlFile.Formatting = System.Xml.Formatting.Indented;
                    XmlQualifiedName qname = new XmlQualifiedName("AccountList",
                                                                  "http://cufxstandards.com/v2/Account.xsd");
                    XmlSampleGenerator generator = new XmlSampleGenerator(xsdFilePath, qname);
                    generator.WriteXml(outXmlFile);
                    //Console.WriteLine("XML Files Created");
                }

                string outJSONFileName = Path.Combine(sGeneratedPath + "\\JSON\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".json";
                JsonGenerator.GenerateJsonFromXml(outXmlFileName, outJSONFileName);
                #endregion

                // Generate one .cs for all the types and place it in the Schemas project
                //string cufxCsFile = Path.Combine(schemaProjectDirectory, "CUFX.cs");
                //string cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".cs";
                //string cufxVbFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".vb";
                //CodeGenerator.GenerateCodeFromXsd(xsdFilePath, cufxCsFile, cufxVbFile);
                //CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile);
                //JsonGenerator.GenerateJsonFromCs(cufxCsFile, Path.Combine(sGeneratedPath + "\\JSON\\", Path.GetFileNameWithoutExtension(cufxCsFile)) + ".json");

                //#region Generate the WCF examples
                //cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".cs";
                //string cufxVbFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".vb";
                //CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile);
                //CodeGenerator.GenerateCodeFromXsd(xsdFilePath, cufxCsFile, cufxVbFile);
                //Now Generate the WCF Files
                //Converter converter = new Converter(xsdFilePath);
                //bool wasSuccessful = converter.Convert(cufxCsFile);
                //#endregion
            }
            Console.WriteLine("HTML & XML Files Created.....");

            #region Generate the WCF examples
            // Generate one .cs for all the types and place it in the Schemas project
            string cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", "CUFX.cs");
            //CodeGeneratorV1.GenerateCodeFromXsds(files, sGeneratedPath + "\\WCF\\CUFX.vb", sGeneratedPath + "\\WCF\\CUFX.cs");

            //Working Single WCF Generator
            CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile);

            //Now Generate the WCF File
            //Converter converter = new Converter(sGeneratedPath + "\\WCF\\CUFXTemp.cs");
            //bool wasSuccessful = converter.Convert(sGeneratedPath + "\\WCF\\CUFX.cs");
            //System.IO.File.Delete(sGeneratedPath + "\\WCF\\CUFXTemp.cs");

            //if (wasSuccessful)
            //{
            Console.WriteLine("WCF File Created");
            //}
            #endregion



            Console.WriteLine("JSON File Created");
            Console.WriteLine("Press any key to close");
            Console.ReadLine();
        }
Example #42
0
        public static string TransformNET(string document, string xslt, string tmpDir)
        {
            XslCompiledTransform t = new XslCompiledTransform(true);
            //StringReader xsltStringReader = new StringReader(tbXslt.Text);

            // XmlReader stylesheetReader = XmlReader.Create(xsltStringReader);
            XsltSettings      settings           = new XsltSettings();
            const XmlResolver stylesheetResolver = null;

            //t.Load(stylesheetReader, settings, stylesheetResolver);
            if (!Directory.Exists(tmpDir))
            {
                tmpDir = Path.GetTempPath();
            }

            string tmpFile = tmpDir + "tmp.xslt";

            File.WriteAllText(tmpFile, xslt);

            t.Load(@"file://" + tmpFile, settings, stylesheetResolver);

            // HACK: EVOLUTION strip namespace and schema instance
            int    si   = document.IndexOf("xmlns:xsi=\"");
            int    ei   = document.IndexOf("\"", si + "xmlns:xsi=\"".Length) + 1;
            string text = document.Remove(si, ei - si);

            si   = text.IndexOf("xmlns=\"");
            ei   = text.IndexOf("\"", si + "xmlns=\"".Length) + 1;
            text = text.Remove(si, ei - si);
            StringReader documentStringReader = new StringReader(text);
            XmlReader    documentReader       = XmlReader.Create(documentStringReader);

            StringBuilder     outputBuilder        = new StringBuilder();
            XmlWriterSettings outputWriterSettings = new XmlWriterSettings
            {
                Indent              = true,
                CheckCharacters     = false,
                NewLineOnAttributes = true
            };
            XmlWriter outputWriter = XmlWriter.Create(outputBuilder, outputWriterSettings);

            Debug.Assert(outputWriter != null);
            XsltArgumentList xsltArgumentList = new XsltArgumentList();

            try
            {
                DoTransform(t, outputWriter, documentReader, xsltArgumentList);
                outputWriter.Flush();
                outputBuilder.Insert(outputBuilder.ToString().IndexOf(">", outputBuilder.ToString().IndexOf("?>") + 2),
                                     Environment.NewLine +
                                     "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://kocour.ms.mff.cuni.cz/xcase/company/\"");

                StringReader outputReader = new StringReader(outputBuilder.ToString());
                XDocument    d            = XDocument.Load(outputReader);
                outputReader.Close();
                return(d.PrettyPrintXML());
            }
            finally
            {
                outputWriter.Close();

                //stylesheetReader.Close();
                //xsltStringReader.Close();
                //xsltStringReader.Dispose();

                documentReader.Close();
                documentStringReader.Close();
                documentStringReader.Dispose();
            }
        }
Example #43
0
 public static void ConverXmlToHtml()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load(@"..\..\..\XML_export\test.xsl");
     xslt.Transform(@"..\..\..\XML_export\test.xml", @"..\..\..\XML_export\students.html");
 }
Example #44
0
        public Tuple <Stream, string> Format(IEnumerable <Match> matches, Observer observer, string template)
        {
            IEnumerable <IGrouping <Search, Match> > indexedBySearch = matches.GroupBy(m => m.Search);

            XslCompiledTransform transform = new XslCompiledTransform();

            transform.Load(XmlReader.Create(new StringReader(template)));

            XmlDocument source = new XmlDocument();
            var         root   = source.DocumentElement.AppendChild(source.CreateElement("notification"));

            foreach (IGrouping <Search, Match> groupedSearch in indexedBySearch)
            {
                var xmlSearch = source.CreateElement("search");
                root.AppendChild(xmlSearch);

                xmlSearch.SetAttribute("id", groupedSearch.Key.Id.ToString());
                xmlSearch.AppendChild(source.CreateElement("name", groupedSearch.Key.Name));
                xmlSearch.AppendChild(source.CreateElement("phrase", groupedSearch.Key.Phrase));

                foreach (Match match in groupedSearch)
                {
                    var xmlMatch = xmlSearch.AppendChild(source.CreateElement("meeting")) as XmlElement;
                    xmlMatch.SetAttribute("id", match.Meeting.Id.ToString());
                    xmlMatch.SetAttribute("meetingId", match.Meeting.MeetingId.ToString());
                    xmlMatch.AppendChild(source.CreateElement("title")).InnerText     = match.Meeting.Title;
                    xmlMatch.AppendChild(source.CreateElement("url")).InnerText       = match.Meeting.Url.ToString();
                    xmlMatch.AppendChild(source.CreateElement("date")).InnerText      = match.Meeting.Date.ToString();
                    xmlMatch.AppendChild(source.CreateElement("boardName")).InnerText = match.Meeting.BoardName;

                    var xmlSource = xmlMatch.AppendChild(source.CreateElement("source")) as XmlElement;
                    xmlSource.SetAttribute("id", match.Meeting.Source.Id.ToString());
                    xmlSource.AppendChild(source.CreateElement("name")).InnerText = match.Meeting.Source.Name;
                }
            }

            MemoryStream output       = new MemoryStream();
            XmlWriter    resultWriter = XmlWriter.Create(output);

            transform.Transform(source, resultWriter);

            output.Seek(0, SeekOrigin.Begin);

            XmlDocument resultDoc = new XmlDocument();

            resultDoc.Load(XmlReader.Create(output));

            string contentType = "text/xml";

            // Inspect result to determine content-type.
            switch (resultDoc.DocumentElement.NamespaceURI)
            {
            //case "http://www.w3.org/1999/XSL/Format":
            //    // run through FO.NET to produce PDF.
            //    contentType = "application/pdf";
            //    break;
            case "http://www.w3.org/1999/xhtml":
                contentType = "text/html";
                break;

            default:
                break;
            }

            output.Seek(0, SeekOrigin.Begin);

            return(new Tuple <Stream, string>(output, contentType));
        }
		// Function  : Export_with_XSLT_Windows 
		// Arguments : dsExport, sHeaders, sFileds, FormatType, FileName
		// Purpose   : Exports dataset into CSV / Excel format

		private void Export_with_XSLT_Windows(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)
		{
			
			try
			{				
				// XSLT to use for transforming this dataset.						
				MemoryStream stream = new MemoryStream( );
				XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);				
				CreateStylesheet(writer, sHeaders, sFileds, FormatType);
				writer.Flush( ); 
				stream.Seek( 0, SeekOrigin.Begin);
                XmlDocument xsl = new XmlDocument();
                xsl.Load(stream);

                //XslTransform xslTran = new XslTransform();				
                //xslTran.Load(new XmlTextReader(stream), null, null);				
                //System.IO.StringWriter  sw = new System.IO.StringWriter();			
                //xslTran.Transform(xmlDoc, null, sw, null);

                XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);

                StringWriter sw = new StringWriter();
                XmlTextWriter xtw = new XmlTextWriter(sw);
                XslCompiledTransform t = new XslCompiledTransform();
                t.Load((IXPathNavigable)xsl, null, null);
                t.Transform((IXPathNavigable)xmlDoc, xtw);

                //Writeout the Content				
                File.WriteAllText(FileName, sw.ToString());
                sw.Close();
                xtw.Close();
                writer.Close();
                stream.Close();
                sw.Dispose();
                stream.Dispose();
            }			
			catch(Exception Ex)
			{
				throw Ex;
			}
		}		
Example #46
0
        static void Main()
        {
            MessageBox.Show(RuleControl.ParseConstValue(""));
            MessageBox.Show(RuleControl.ParseConstValue("asdfaf"));
            MessageBox.Show(RuleControl.ParseConstValue("a''sdf'af"));
            MessageBox.Show(RuleControl.ParseConstValue("{SQ"));
            MessageBox.Show(RuleControl.ParseConstValue("{SQLasdfasdfaf"));
            MessageBox.Show(RuleControl.ParseConstValue("SQL}asdfasdfaf"));
            MessageBox.Show(RuleControl.ParseConstValue("{SQL}asdfasdfaf"));
            MessageBox.Show(RuleControl.ParseConstValue("{SQL}asdfa'af"));
            MessageBox.Show(RuleControl.ParseConstValue(@"\{SQL}asdfasdfaf"));
            MessageBox.Show(RuleControl.ParseConstValue(@"\\{SQL}asdfasdfaf"));
            MessageBox.Show(RuleControl.ParseConstValue(@"\{SQL}"));
            MessageBox.Show(RuleControl.ParseConstValue(@"{SQL}"));


            //Form frm = new Form();
            //TextBox b = new TextBox();
            //b.Multiline = true;
            //b.Dock = DockStyle.Fill;
            //frm.Controls.Add(b);
            //frm.ShowDialog();

            //MessageBox.Show(string.Format(b.Text, 1, 2));
            //return;

            //MessageBox.Show("wait a minute.");

            //DLogMgt.OnError += new EventHandler(DLogMgt_OnError);
            //DLogMgt.OnLog += new DLogHandler(DLogMgt_OnLog);

            //DElement e1 = new DElement(0x0010, 0x0010, DVR.PN, "Bill^Gates");
            //MessageBox.Show(e1.Value);

            //DElement e2 = new DElement(0x0007, 0x0007, DVR.LO, "Hello world ÖíÍ·");
            //MessageBox.Show(e2.Value);

            ////DHelper.CharacterSetName = "ISO 2022 IR 13";
            ////DHelper.CharacterSetName = "ISO 2022 IR 87";
            //DElementList eleList = DElementList.OpenFile(@"D:\Standard\DICOM\DicomFile_Japan\SCSH31.dcm");
            ////DElementList eleList = DElementList.OpenFile(@"D:\Standard\DICOM\DicomFile_Japan\SCSH32.dcm");
            ////DElementList eleList = DElementList.OpenFile(@"D:\Standard\DICOM\DicomFile\001.dcm");
            //DElement eleCS = eleList.GetElement(0x00080005);
            //if (eleCS != null)
            //{
            //    MessageBox.Show(eleCS.Value);
            //    //eleCS.Value = DHelper.CharacterSetName;
            //    //MessageBox.Show(eleCS.Value);
            //}
            //DElement elePN = eleList.GetElement(0x00100010);
            //MessageBox.Show(elePN.Value);

            //using (StreamWriter sw = File.CreateText("File.txt"))
            //{
            //    sw.Write(eleList.ToXMLString());
            //}

            //return;

            //MessageBox.Show(((int)' ').ToString());
            //return;

            XmlDocument doc = new XmlDocument();

            doc.Load(@"../../XMLBlank\test.xml");
            XmlNode nodeR = doc.GetElementsByTagName("r")[0];
            XmlNode nodeA = nodeR.ChildNodes[0];
            XmlNode nodeB = nodeR.ChildNodes[1];
            XmlNode nodeC = nodeR.ChildNodes[2];
            XmlNode nodeD = nodeR.ChildNodes[3];

            MessageBox.Show("a:" + nodeA.InnerText + ";\r\n"
                            + "b:" + nodeB.InnerText + ";\r\n"
                            + "c:" + nodeC.InnerText + ";\r\n"
                            + "d:" + nodeD.InnerText + ";\r\n");

            XPathDocument myXPathDoc = new XPathDocument(@"../../XMLBlank\test.xml");

            using (XmlTextWriter myWriter = new XmlTextWriter(@"../../XMLBlank\result" + DateTime.Now.Ticks + ".xml", null))
            {
                XslCompiledTransform myXslTrans = new XslCompiledTransform();
                myXslTrans.Load(@"../../XMLBlank\transfrom.xsl");
                myXslTrans.Transform(myXPathDoc, null, myWriter);
            }

            //return;


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain());
        }
Example #47
0
 protected void BtnSaveToExcel(object sender, EventArgs e)
 {
     string json = ExcelGridData.Value.ToString();
     json = json.Replace("retailid", "单据号");
     json = json.Replace("setdate", "销售日期");
     json = json.Replace("znums", "数量");
     json = json.Replace("zxsums", "现价金额");
     json = json.Replace("zssums", "结算金额");
     json = json.Replace("FCalcSums", "实销金额");
     json = json.Replace("yhsum", "优惠金额");
     json = json.Replace("s_sums", "实收金额");
     json = json.Replace("vipcode", "VIP卡号");
     json = json.Replace("s_name", "营业员");
     json = json.Replace("x_name", "班组");
     json = json.Replace("crdate", "制单日期");
     json = json.Replace("cr_name", "制单人");
     json = json.Replace("comment", "备注");
     StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null);
     XmlNode xml = eSubmit.Xml;
     this.Response.Clear();
     this.Response.ContentType = "application/vnd.ms-excel";
     this.Response.AddHeader("Content-Disposition", "attachment; filename=Retail" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
     XslCompiledTransform xtExcel = new XslCompiledTransform();
     xtExcel.Load(Server.MapPath("ExcelTemp/Excel.xsl"));
     xtExcel.Transform(xml, null, this.Response.OutputStream);
     this.Response.End();
 }
Example #48
0
        } // get Data

        static void Main(string[] args)
        {
            // Dictionary<string, string> articleStrFields = new Dictionary<string, string>();
            string codeBase       = AppDomain.CurrentDomain.BaseDirectory;
            string documents      = string.Format(@"{0}..\..\..\documents", codeBase);
            string temp           = string.Format(@"{0}..\..\..\temp", codeBase);
            string articleXML     = "";
            string articleSaxoXML = "";
            int    count          = 0;
            string saxohost       = ConfigurationManager.AppSettings["saxohost"].ToString();

            string[] keys               = { "article_uid", "siteid", "origsite", "anchor", "seodescription", "relatedarticles", "heading", "summary", "body", "byline", "category" };
            string   siteid             = args[0];
            string   destination_siteid = args[1];
            DateTime startdate          = DateTime.ParseExact(args[2], "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);
            DateTime stopdate           = DateTime.ParseExact(args[3], "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

            LogFileName = args[4];
            string myarticle_uid = "";

            if (args.Length == 6)
            {
                myarticle_uid = args[5];
            }

            string query = string.Format("select * from article where startdate >= '{0}' and startdate <= '{1}' and siteid = {2} order by startdate", startdate.ToShortDateString(), stopdate.ToShortDateString(), siteid);

            if (myarticle_uid.Length > 0)
            {
                query = string.Format("select * from article where article_uid = '{0}'", myarticle_uid);
            }


            DataSet ds = BusinessRule.BusinessRule.BusGetDataset(query);

            Console.WriteLine("Total: {0}", ds.Tables[0].Rows.Count);
            foreach (DataRow articleRow in ds.Tables[0].Rows)
            {
                XmlDocument x = new XmlDocument();
                x.Load(string.Format(@"{0}\xmldocument.xml", documents));
                x.GetElementsByTagName("siteuri").Item(0).InnerText = string.Format("{0}/{1}", saxohost, destination_siteid);
                x.GetElementsByTagName("site").Item(0).InnerText    = destination_siteid;

                string article_uid = articleRow["article_uid"].ToString();
                int    imagecount  = Convert.ToInt32(articleRow["imagecount"]);

                startdate = Convert.IsDBNull(articleRow["startdate"]) ? DateTime.Now : (DateTime)articleRow["startdate"];
                DateTime enddate = Convert.IsDBNull(articleRow["enddate"]) ? DateTime.Now.AddYears(100) : (DateTime)articleRow["enddate"];
                x.GetElementsByTagName("startdate").Item(0).InnerXml = startdate.ToString("yyyyMMdd");
                x.GetElementsByTagName("enddate").Item(0).InnerXml   = enddate.ToString("yyyyMMdd");
                if (imagecount > 0)
                {
                    query = string.Format("select si.url, i.caption from image i, saxo_image si where i.asset_uid = si.asset_uid and  si.destination_siteid ='{0}' and  i.asset_uid in (select asset_uid from asset where article_uid = '{1}')", destination_siteid, article_uid);
                    DataSet dsImage = BusinessRule.BusinessRule.BusGetDataset(query);
                    if (dsImage.Tables[0].Rows.Count == 1)
                    {
                        x.GetElementsByTagName("image").Item(0).InnerText        = dsImage.Tables[0].Rows[0][0].ToString();
                        x.GetElementsByTagName("imageCaption").Item(0).InnerText = Convert.IsDBNull(dsImage.Tables[0].Rows[0][1]) ? "" : dsImage.Tables[0].Rows[0][1].ToString();
                    }
                    else
                    {
                        query = string.Format("select gallery_uid from saxo_gallery where article_uid = '{0}' and destination_siteid ='{1}' ", article_uid, destination_siteid);
                        DataSet dsGallery = BusinessRule.BusinessRule.BusGetDataset(query);
                        if (dsGallery.Tables[0].Rows.Count == 1)
                        {
                            string galleryuid = dsImage.Tables[0].Rows[0][0].ToString();
                            x.GetElementsByTagName("gallerypathuid").Item(0).InnerXml = galleryuid;
                            Uri uri = new Uri(galleryuid);
                            x.GetElementsByTagName("galleryuid").Item(0).InnerXml = Path.GetFileName(uri.LocalPath);
                        }
                    } // end else
                }     // end imagecount >0

                foreach (string k in keys)
                {
                    string value = Convert.IsDBNull(articleRow[k]) ? "" : articleRow[k].ToString();
                    switch (k)
                    {
                    case "category":
                        x.GetElementsByTagName("category").Item(0).InnerXml      = cdata(value);
                        x.GetElementsByTagName("category_saxo").Item(0).InnerXml = cdata(GetSaxoValue("saxo_category", value));
                        x.GetElementsByTagName("taxonomyword").Item(0).InnerXml  = cdata(GetSaxoValue("taxonomyword", value));
                        break;

                    case "article_uid":
                        x.GetElementsByTagName("contentid").Item(0).InnerText = string.Format("ci_{0}", article_uid);
                        break;

                    case "keyword":
                        XmlNode      xn      = x.GetElementsByTagName("keywords").Item(0);
                        RegexOptions options = RegexOptions.None;
                        Regex        regex   = new Regex(@"[ ]{2,}", options);
                        value = regex.Replace(value, @" ");
                        value = value.Trim();
                        if (value.Length > 0)
                        {
                            string[] keywords = value.Split(' ');
                            foreach (string kvalue in keywords)
                            {
                                XmlNode xk = x.CreateNode(XmlNodeType.Element, "keyword", "");
                                xk.InnerText = kvalue;
                                xn.AppendChild(xk);
                            }
                        }
                        break;

                    default:
                        x.GetElementsByTagName(k).Item(0).InnerXml = cdata(value);
                        break;
                    }
                } // foreach k

                articleXML     = string.Format(@"{0}\{1}.xml", temp, article_uid);
                articleSaxoXML = string.Format(@"{0}\{1}_saxo.xml", temp, article_uid);
                x.Save(articleXML);
                XslCompiledTransform xslt = new XslCompiledTransform();
                xslt.Load(string.Format(@"{0}\article.xslt", documents));
                xslt.Transform(articleXML, articleSaxoXML);
                string saxoarticlexml = getData(articleSaxoXML); // saxotech xml format this is posted to OWS
                string message        = "";
                try
                {
                    count += 1;
                    XmlDocument sx = new XmlDocument();
                    sx.LoadXml(saxoarticlexml);
                    DataDb.spExecute("LoadSaxoArticle", ref message, "@article_uid", article_uid, "@siteid", siteid, "@destination_siteid", destination_siteid, "@xmldata", saxoarticlexml);
                    if (message.Length > 0)
                    {
                        writetolog(string.Format("Article uid: {0} {1}", article_uid, message));
                    }
                    else
                    {
                        Console.WriteLine("{0} Article: {1}  Saxoxml  ", count, article_uid);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Article Exception {0} ", article_uid, ex.Message);
                }
                finally
                {
                    string[] tempFiles = { articleXML, articleSaxoXML };
                    foreach (string tempFile in tempFiles)
                    {
                        if (tempFile.Length > 0 && File.Exists(tempFile))
                        {
                            File.Delete(tempFile);
                        }
                    }
                }
            } // for each articleRow
        }
Example #49
0
        public static string relay(XSLRequestConfig xslConf, bool usePivote)
        {
            HttpWebRequest  request;
            HttpWebResponse response      = null;
            Stream          resStream     = null;
            StreamReader    streamReader  = null;
            StringBuilder   stringBuilder = new StringBuilder();

            try
            {
                string appendChar = "?";
                if (xslConf.getURL().IndexOf(appendChar) > -1)
                {
                    appendChar = "&";
                }

                //send HTTP request
                request = (HttpWebRequest)WebRequest.Create(xslConf.getURL()
                                                            + appendChar + xslConf.getQueryString().ConstructQueryString());

                //another way...
                //request = (HttpWebRequest)WebRequest.Create(
                //    xslConf.getQueryString().WriteLocalPathWithQuery(new Uri(xslConf.getURL())));


                if (request != null)
                {
                    response     = (HttpWebResponse)request.GetResponse();
                    resStream    = response.GetResponseStream();
                    streamReader = new StreamReader(resStream, xslConf.getEncoding());

                    if (usePivote)
                    {
                        //is a call to pivote: do nothing to response text
                        stringBuilder = new StringBuilder(streamReader.ReadToEnd());
                    }
                    else
                    {
                        //is openLabyrinth: must XSLT
                        XslCompiledTransform xslCompiledTransform = new XslCompiledTransform();

                        if (System.Environment.MachineName.ToLower().IndexOf("vptest") == -1)
                        {
                            xslConf.setApproot(@"C:\dev\nosm-verse\src");
                            xslConf.setAppDir(@"sl_dispatch");
                        }

                        xslCompiledTransform.Load(xslConf.getApproot() + "\\" + xslConf.getAppDir() + "\\" + xslConf.getStylesheetPath());
                        StringWriter  stringWriter  = new StringWriter(stringBuilder);
                        XmlTextReader xmlTextReader = new XmlTextReader(streamReader);

                        if (System.Environment.MachineName.ToLower().IndexOf("vptest") > -1)
                        {
                            xslCompiledTransform.Transform(xmlTextReader, null, stringWriter);
                        }
                        else
                        {
                            xslCompiledTransform.Transform(@"C:\dev\nosm-verse\src\sl_dispatch\ol-mnode1.xml", null, stringWriter);
                        }
                        stringWriter.Close();
                    }
                }
            }
            catch (WebException exception)
            {
                if ((exception.Status == WebExceptionStatus.ProtocolError) || (response.StatusCode != System.Net.HttpStatusCode.OK))
                { //get the response object from the WebException
                    response = exception.Response as HttpWebResponse;
                    if (response == null)
                    {
                        return("<Error>" + exception.StackTrace + "</Error>");
                    }
                }
            }

            finally
            {
                if (response != null)
                {
                    response.Close();
                }
                if (resStream != null)
                {
                    resStream.Close();
                }
                if (streamReader != null)
                {
                    streamReader.Close();
                }
            }

            return(stringBuilder.ToString());
        }
Example #50
0
        /// <summary>
        /// Loads an HTML document from an Internet resource and saves it to the specified XmlTextWriter, after an XSLT transformation.
        /// </summary>
        /// <param name="htmlUrl">The requested URL, such as "http://Myserver/Mypath/Myfile.asp". May not be null.</param>
        /// <param name="xsltUrl">The URL that specifies the XSLT stylesheet to load.</param>
        /// <param name="xsltArgs">An XsltArgumentList containing the namespace-qualified arguments used as input to the transform.</param>
        /// <param name="writer">The XmlTextWriter to which you want to save.</param>
        /// <param name="xmlPath">A file path where the temporary XML before transformation will be saved. Mostly used for debugging purposes.</param>
        public void LoadHtmlAsXml(string htmlUrl, string xsltUrl, XsltArgumentList xsltArgs, XmlTextWriter writer,
                                  string xmlPath)
        {
            if (htmlUrl == null)
            {
                throw new ArgumentNullException("htmlUrl");
            }

            HtmlDocument doc = Load(htmlUrl);

            if (xmlPath != null)
            {
                XmlTextWriter w = new XmlTextWriter(xmlPath, doc.Encoding);
                doc.Save(w);
                w.Close();
            }
            if (xsltArgs == null)
            {
                xsltArgs = new XsltArgumentList();
            }

            // add some useful variables to the xslt doc
            xsltArgs.AddParam("url", "", htmlUrl);
            xsltArgs.AddParam("requestDuration", "", RequestDuration);
            xsltArgs.AddParam("fromCache", "", FromCache);

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(xsltUrl);
            xslt.Transform(doc, xsltArgs, writer);
        }
Example #51
0
 static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load(@"../../students.xsl");
     xslt.Transform(@"../../StudentSystem.xml", "../../students.html");
 }
Example #52
0
        private static void RenderXmlInternal(HtmlHelper htmlHelper, XmlDocument xmlDocument, XPathNavigator xpathNavigator, string documentSource, XslCompiledTransform transform, string transformSource, XsltArgumentList transformArgumentList)
        {
            XPathDocument xpathDocument = null;

            //Checking if we have been given XmlDocument or XPathNavigator directly, or do we have path for document
            if ((xmlDocument == null) && (xpathNavigator == null) && (!String.IsNullOrEmpty(documentSource) && (documentSource.Trim().Length != 0)))
            {
                //Checking if path is absolute or relative
                if (!Path.IsPathRooted(documentSource))
                {
                    //Mapping the relative path
                    documentSource = htmlHelper.ViewContext.HttpContext.Server.MapPath(documentSource);
                }

                //Loading XML from file into XPathDocument
                using (FileStream documentStream = new FileStream(documentSource, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlTextReader documentReader = new XmlTextReader(documentStream);
                    xpathDocument = new XPathDocument(documentReader);
                }
            }

            //Checking if we have been given XslCompiledTransform directly, or do we have path for transform
            if ((transform == null) && (!String.IsNullOrEmpty(transformSource) && (transformSource.Trim().Length != 0)))
            {
                //Checking if path is absolute or relative
                if (!Path.IsPathRooted(transformSource))
                {
                    //Mapping the relative path
                    transformSource = htmlHelper.ViewContext.HttpContext.Server.MapPath(transformSource);
                }

                //Loading XSLT from file into XslCompiledTransform
                using (FileStream transformStream = new FileStream(transformSource, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    XmlTextReader tranformReader = new XmlTextReader(transformStream);
                    transform = new XslCompiledTransform();
                    transform.Load(tranformReader);
                }
            }

            //Checking if we have XML in any form
            if (((xmlDocument != null) || (xpathDocument != null)) || (xpathNavigator != null))
            {
                //Checking if we have XSLT
                if (transform == null)
                {
                    //If not, let's use transparent one
                    transform = _transparentTransform;
                }

                //Perform transformation based on form in which we have our XML
                if (xmlDocument != null)
                {
                    transform.Transform((IXPathNavigable)xmlDocument, transformArgumentList, htmlHelper.ViewContext.Writer);
                }
                else if (xpathNavigator != null)
                {
                    transform.Transform(xpathNavigator, transformArgumentList, htmlHelper.ViewContext.Writer);
                }
                else
                {
                    transform.Transform((IXPathNavigable)xpathDocument, transformArgumentList, htmlHelper.ViewContext.Writer);
                }
            }
        }
Example #53
0
 static void Main()
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load("../../catalog.xsl");
     xslt.Transform("../../catalog.xml", "../../catalog.html");
 }
Example #54
0
    /// <summary>
    /// Generate the order receipt using XSL Transformation
    /// </summary>
    public void GenerateReceipt()
    {
        string templatePath = Server.MapPath(ZNodeConfigManager.EnvironmentConfig.ConfigPath + "Receipt.xsl");

        XmlDocument xmlDoc = new XmlDocument();
        XmlElement rootElement = GetElement(xmlDoc, "Order", "");

        rootElement.AppendChild(GetElement(xmlDoc, "SiteName", ZNodeConfigManager.SiteConfig.CompanyName));
        rootElement.AppendChild(GetElement(xmlDoc, "AccountId", _Order.AccountID.ToString()));
        rootElement.AppendChild(GetElement(xmlDoc, "ReceiptText", ZNodeConfigManager.MessageConfig.GetMessage("OrderReceiptConfirmationIntroText")));
        rootElement.AppendChild(GetElement(xmlDoc, "CustomerServiceEmail", ZNodeConfigManager.SiteConfig.CustomerServiceEmail));
        rootElement.AppendChild(GetElement(xmlDoc, "CustomerServicePhoneNumber", ZNodeConfigManager.SiteConfig.CustomerServicePhoneNumber));
        rootElement.AppendChild(GetElement(xmlDoc, "FeedBack", FeedBackUrl));

        if (_Order.CardTransactionID != null)
        {
            rootElement.AppendChild(GetElement(xmlDoc, "TransactionID", _Order.CardTransactionID));
        }
        rootElement.AppendChild(GetElement(xmlDoc, "PromotionCode", _Order.CouponCode));
        rootElement.AppendChild(GetElement(xmlDoc, "PONumber", _Order.PurchaseOrderNumber));
        rootElement.AppendChild(GetElement(xmlDoc, "OrderId", _Order.OrderID.ToString()));
        rootElement.AppendChild(GetElement(xmlDoc, "OrderDate", _Order.OrderDate.ToString()));

        rootElement.AppendChild(GetElement(xmlDoc, "ShippingName", _shoppingCart.Shipping.ShippingName));
        rootElement.AppendChild(GetElement(xmlDoc, "PaymentName", _shoppingCart.Payment.PaymentName));

        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressCompanyName", _Order.ShippingAddress.CompanyName));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressFirstName", _Order.ShippingAddress.FirstName));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressLastName", _Order.ShippingAddress.LastName));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressStreet1", _Order.ShippingAddress.Street1));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressStreet2", _Order.ShippingAddress.Street2));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressCity", _Order.ShippingAddress.City));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressStateCode", _Order.ShippingAddress.StateCode));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressPostalCode", _Order.ShippingAddress.PostalCode));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressCountryCode", _Order.ShippingAddress.CountryCode));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingAddressPhoneNumber", _Order.ShippingAddress.PhoneNumber));

        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressCompanyName", _Order.BillingAddress.CompanyName));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressFirstName", _Order.BillingAddress.FirstName));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressLastName", _Order.BillingAddress.LastName));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressStreet1", _Order.BillingAddress.Street1));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressStreet2", _Order.BillingAddress.Street2));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressCity", _Order.BillingAddress.City));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressStateCode", _Order.BillingAddress.StateCode));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressPostalCode", _Order.BillingAddress.PostalCode));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressCountryCode", _Order.BillingAddress.CountryCode));
        rootElement.AppendChild(GetElement(xmlDoc, "BillingAddressPhoneNumber", _Order.BillingAddress.PhoneNumber));

        XmlElement items = xmlDoc.CreateElement("Items");

        foreach (ZNodeShoppingCartItem shoppingCartItem in _shoppingCart.ShoppingCartItems)
        {
            XmlElement item = xmlDoc.CreateElement("Item");
            item.AppendChild(GetElement(xmlDoc, "Quantity", shoppingCartItem.Quantity.ToString()));

            ZNodeGenericCollection<ZNodeDigitalAsset> assetCollection = shoppingCartItem.Product.ZNodeDigitalAssetCollection;
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(shoppingCartItem.Product.Name + "<br />");

            if (assetCollection.Count > 0)
            {
                sb.Append("DownloadLink : <a href='" + shoppingCartItem.Product.DownloadLink + "' target='_blank'>" + shoppingCartItem.Product.DownloadLink + "</a><br />");

                foreach (ZNodeDigitalAsset digitalAsset in assetCollection)
                {
                    sb.Append(digitalAsset.DigitalAsset + "<br />");
                }
            }

            item.AppendChild(GetElement(xmlDoc, "Name", sb.ToString()));
            item.AppendChild(GetElement(xmlDoc, "SKU", shoppingCartItem.Product.SKU));
            item.AppendChild(GetElement(xmlDoc, "Description", shoppingCartItem.Product.ShoppingCartDescription));
            item.AppendChild(GetElement(xmlDoc, "Note", ""));
            item.AppendChild(GetElement(xmlDoc, "Price", shoppingCartItem.UnitPrice.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
            item.AppendChild(GetElement(xmlDoc, "Extended", shoppingCartItem.ExtendedPrice.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));

            items.AppendChild(item);
        }

        rootElement.AppendChild(GetElement(xmlDoc, "TaxCostValue", _Order.TaxCost.ToString()));
        rootElement.AppendChild(GetElement(xmlDoc, "SalesTaxValue", _Order.SalesTax.ToString()));
        rootElement.AppendChild(GetElement(xmlDoc, "VATCostValue", _Order.VAT.ToString()));
        rootElement.AppendChild(GetElement(xmlDoc, "HSTCostValue", _Order.HST.ToString()));
        rootElement.AppendChild(GetElement(xmlDoc, "PSTCostValue", _Order.PST.ToString()));
        rootElement.AppendChild(GetElement(xmlDoc, "GSTCostValue", _Order.GST.ToString()));

        rootElement.AppendChild(GetElement(xmlDoc, "SubTotal", _Order.SubTotal.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "TaxCost", _Order.TaxCost.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "SalesTax", _Order.SalesTax.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "VAT", _Order.VAT.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "HST", _Order.HST.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "PST", _Order.PST.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "GST", _Order.GST.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));

        //
        rootElement.AppendChild(GetElement(xmlDoc, "DiscountAmount", "-" + _Order.DiscountAmount.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingName", _shoppingCart.Shipping.ShippingName));
        rootElement.AppendChild(GetElement(xmlDoc, "ShippingCost", _Order.ShippingCost.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));
        rootElement.AppendChild(GetElement(xmlDoc, "TotalCost", _Order.Total.ToString("c") + ZNodeCurrencyManager.GetCurrencySuffix()));

        rootElement.AppendChild(GetElement(xmlDoc, "AdditionalInstructions", _Order.AdditionalInstructions));

        rootElement.AppendChild(items);
        xmlDoc.AppendChild(rootElement);

        // Use a memorystream to store the result into the memory
        MemoryStream ms = new MemoryStream();

        XslCompiledTransform xsl = new XslCompiledTransform();

        xsl.Load(templatePath);

        xsl.Transform(xmlDoc, null, ms);

        // Move to the begining
        ms.Seek(0, SeekOrigin.Begin);

        // Pass the memorystream to a streamreader
        StreamReader sr = new StreamReader(ms);

        _receiptTemplate = sr.ReadToEnd();
    }
Example #55
0
        public XmlDocument GeneraFacturaXml(string certificado, string llave,
                                            bool incluirDetallista, bool incluirAddenda, bool incluirAlsuper,
                                            bool incluirEdifact, bool incluirComercExt, out string cadenaOriginal, out string sello)
        {
            // tipoComplemento: detallista, addenda, alsuper, edifact, comercext
            string tipoComplemento = string.Empty;

            // Generamos el comprobante y agregamos el certificado
            GeneraComprobante();
            _comprobante.certificado = certificado;

            #region Agregamos el nodo detallista

            if (incluirDetallista)
            {
                tipoComplemento = "detallista";

                ComplementoFE complemento  = new ComplementoFE(_iniAdd);
                XmlDocument   tempDocument = complemento.GeneraComplementoXml(tipoComplemento);

                _comprobante.Complemento = new Schemasv32.ComprobanteComplemento
                {
                    Any = new[] { tempDocument["detallista:detallista"] }
                };
            }

            #endregion

            #region Agrega Complemento Comercio Exterior
            if (incluirComercExt)
            {
                tipoComplemento = "comercExterior";

                ComplementoFE complemento  = new ComplementoFE(_iniAdd);
                XmlDocument   tempDocument = complemento.GeneraComplementoXml(tipoComplemento);

                _comprobante.Complemento = new Schemasv32.ComprobanteComplemento
                {
                    Any = new[] { tempDocument["cce:ComercioExterior"] }
                };
            }

            #endregion

            #region Generamos un documento XML usando la información actual de comprobante y detallista

            XmlDocument doc = new XmlDocument();
            using (MemoryStream tempStream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Schemasv32.Comprobante));

                serializer.Serialize(tempStream, _comprobante);
                tempStream.Seek(0, SeekOrigin.Begin);
                doc.Load(tempStream);
            }

            #endregion

            #region Generamos la cadena original

            using (MemoryStream tempStream = new MemoryStream())
            {
                using (
                    XmlTextWriter xmlWriter = new XmlTextWriter(tempStream, Encoding.UTF8))
                {
                    doc.WriteContentTo(xmlWriter);
                    xmlWriter.Flush();
                    tempStream.Seek(0, SeekOrigin.Begin);
                    XPathDocument xpathFactura = new XPathDocument(tempStream);
                    xmlWriter.Close();

                    // Generamos la cadena original usando el archivo XSLT del SAT Ver32
                    // Archivo cadenaoriginal_3_2 incluye datos del complemento comerc ext
                    XslCompiledTransform xslCadena = new XslCompiledTransform();
                    //xslCadena.Load("cadenaoriginal32.xslt");
                    if (incluirComercExt)
                    {
                        xslCadena.Load("cadenaoriginal_3_2.xslt");
                    }
                    else
                    {
                        xslCadena.Load("cadenaoriginal32_local.xslt");
                    }

                    using (MemoryStream cadenaStream = new MemoryStream())
                    {
                        xslCadena.Transform(xpathFactura, null, cadenaStream);
                        cadenaOriginal = cadenaStream.GetString();
                    }
                }
            }

            // Elimina saltos de linea y espacios en blanco entre los campos de la cadena original
            char[]   crlf         = new char[] { '\n', '\r' };
            string[] cadenaLineas = cadenaOriginal.Split(crlf);
            cadenaOriginal = null;
            for (int i = 0; i < cadenaLineas.Length; i++)
            {
                if ((cadenaLineas[i].Length >= 2) || (cadenaLineas[i].StartsWith("-")))
                {
                    cadenaOriginal += cadenaLineas[i].Substring(2).Trim();
                }
            }

            #endregion

            #region Generamos el sello de la factura

            // La encriptación de la versión 3 debe ser en SHA-1
            RSACryptoServiceProvider provider = OpenSSL.GetRsaProviderFromPem(llave);
            if (provider == null)
            {
                throw new Exception(
                          "No se pudo crear el proveedor de seguridad a partir del archivo fel");
            }
            byte[] selloBytes = provider.SignData(
                Encoding.UTF8.GetBytes(cadenaOriginal), "SHA1");
            sello = Convert.ToBase64String(selloBytes);

            // Actualizamos el documento original con el sello
            _comprobante.sello = sello;

            #endregion

            #region Agregamos la addenda

            if (incluirAddenda)
            {
                tipoComplemento = "addenda";

                ComplementoFE complemento  = new ComplementoFE(_iniAdd);
                XmlDocument   tempDocument = complemento.GeneraComplementoXml(tipoComplemento, cadenaOriginal);

                _comprobante.Addenda = new Schemasv32.ComprobanteAddenda
                {
                    Any = new[]
                    {
                        tempDocument["Addenda"]["requestForPayment"]
                    }
                };
            }

            #endregion

            #region Agrega addenda Alsuper
            if (incluirAlsuper)
            {
                tipoComplemento = "alsuper";

                ComplementoFE complemento  = new ComplementoFE(_iniAdd);
                XmlDocument   tempDocument = complemento.GeneraComplementoXml(tipoComplemento);

                _comprobante.Addenda = new Schemasv32.ComprobanteAddenda
                {
                    Any = new[]
                    {
                        tempDocument["alsuper:Alsuper"]
                    }
                };
            }
            #endregion

            #region Agrega addenda EDIFACT
            if (incluirEdifact)
            {
                tipoComplemento = "edifact";
                ComplementoFE complemento  = new ComplementoFE(_iniAdd);
                XmlDocument   tempDocument = complemento.GeneraComplementoXml(tipoComplemento, cadenaOriginal, sello);

                _comprobante.Addenda = new Schemasv32.ComprobanteAddenda
                {
                    Any = new[]
                    {
                        tempDocument["lev1add:EDCINVOICE"]
                    }
                };
            }
            #endregion

            #region Generamos el documento final

            using (MemoryStream tempStream = new MemoryStream())
            {
                doc = new XmlDocument();
                XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
                namespaces.Add("cfdi", "http://www.sat.gob.mx/cfd/3");
                namespaces.Add("cce", "http://www.sat.gob.mx/ComercioExterior");
                //namespaces.Add("cce11", "http://www.sat.gob.mx/ComercioExterior11");
                XmlSerializer serializer = new XmlSerializer(typeof(Schemasv32.Comprobante));

                serializer.Serialize(tempStream, _comprobante, namespaces);
                tempStream.Seek(0, SeekOrigin.Begin);
                doc.Load(tempStream);
            }
            #endregion

            #region Agregamos otros atributos del documento
            XmlAttribute xsiAttrib     = doc.CreateAttribute("xsi:schemaLocation", "http://www.w3.org/2001/XMLSchema-instance");
            string       textoAtributo = "http://www.sat.gob.mx/cfd/3 " +
                                         "http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd " +
                                         "http://www.sat.gob.mx/detallista " +
                                         "http://www.sat.gob.mx/sitio_internet/cfd/detallista/detallista.xsd";
            if (incluirAlsuper)
            {
                textoAtributo = textoAtributo + " http://proveedores.alsuper.com/CFD " +
                                "http://proveedores.alsuper.com/addenda/1.xsd";
            }
            if (incluirComercExt)
            {
                /*textoAtributo = textoAtributo + " http://www.sat.gob.mx/ComercioExterior11 " +
                 *  "http://www.sat.gob.mx/sitio_internet/cfd/ComercioExterior11/ComercioExterior11.xsd";*/
                textoAtributo = textoAtributo + " http://www.sat.gob.mx/ComercioExterior " +
                                "http://www.sat.gob.mx/sitio_internet/cfd/ComercioExterior/ComercioExterior10.xsd";
            }

            xsiAttrib.InnerText = textoAtributo;
            doc["cfdi:Comprobante"].Attributes.Append(xsiAttrib);
            #endregion

            return(doc);
        }
Example #56
0
    private string Transform(string xml, string xsl, XsltArgumentList argsList)
    {
        XDocument selectedXml = XDocument.Parse(xml);
        XslCompiledTransform xmlTransform = new XslCompiledTransform();

        StringBuilder htmlOutput = new StringBuilder();
        XmlWriter writer = XmlWriter.Create(htmlOutput);

        xmlTransform.Load(xsl);
        xmlTransform.Transform(selectedXml.CreateReader(), argsList, writer);

        return htmlOutput.ToString();
    }
    private static String ParseResponse(string response)
    {
        
        XmlDocument doc = null;
        XslCompiledTransform myXslTransform = null;
        TextWriter sw = null;
        string result;
        try
        {
            doc = new XmlDocument(); ;
            myXslTransform = new XslCompiledTransform();
            sw = new StringWriter();

            doc.LoadXml(response);

            myXslTransform.Load(new XmlTextReader(new StringReader(Resources.Resource.xml2json)));

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            myXslTransform.Transform(doc, null, sw);

            result = sw.ToString();
        } 
        catch
        {
            result = System.Web.Configuration.WebConfigurationManager.AppSettings["errorParsingOrLoading"];
            logger.Error(result);
        }
        finally
        {
            sw.Close();   
        }
        return result;
    }
Example #58
0
 static void Main(string[] args)
 {
     XslCompiledTransform xslt = new XslCompiledTransform();
     xslt.Load("../../students.xsl");
     xslt.Transform("../../students.xml", "../../students.html");
 }
Example #59
-1
    public void renderLoginControls()
    {
        try
        {
            string XmlPath = Server.MapPath("xml/UserLogin.xml");
            string XsltPath = Server.MapPath("xslt/UserLogin.xslt");

            XPathDocument xdoc = new XPathDocument(XmlPath);

            XslCompiledTransform transform = new XslCompiledTransform();
            transform.Load(XsltPath);

            StringWriter sw = new StringWriter();

            //Transform
            transform.Transform(xdoc, null, sw);
            string result = sw.ToString();

            //Remove Namespace
            result = result.Replace("xmlns:asp=\"remove\"", "");
            result = result.Replace("xmlns:cc1=\"remove\"", "");

            //Parse Control
            Control ctrl = Page.ParseControl(result);
            phLogin.Controls.Add(ctrl);
        }
        catch (Exception ex)
        {
            objNLog.Error("Error : " + ex.Message);
        }
    }
Example #60
-1
	protected void ShowStyledPage()
	{
		if (Request["clear_templates"] == "1")
		{
			transformer = null;
		}
		if (Request["checkconfig"] == "1")
		{
			if (Request["config"] == null || Request["config"].Length == 0)
			{
				Response.Write("No config supplied");
			}

			string wrappedConfig = "<newconfig>" + Request["config"] + "</newconfig>";

			XmlDocument newconfig = new XmlDocument();
			try
			{
				newconfig.LoadXml(wrappedConfig);
			}
			catch (Exception ex)
			{
				Response.Write(ex.Message);
				return;
			}
			Response.Write("Config is OK");

		}
		else
		{
			string sourcefile = Request["source"];
			string stylesheet = Server.MapPath(@"\skins\acs\HTMLOutput.xsl");
			sourcefile = @"App_Data/" + sourcefile;
			XmlDocument source = new XmlDocument();
			source.Load(Server.MapPath(sourcefile));

			RewriteConfig(ref source);

			lock (locker)
			{
				if (transformer == null)
				{
					transformer = new XslCompiledTransform();
					// this stuff is necessary to cope with our stylesheets having DTDs
					// Without all this settings and resolver stuff, you can't use the Load method
					// and tell it to allow DTDs
					XmlReaderSettings xset = new XmlReaderSettings();
                    xset.DtdProcessing = DtdProcessing.Parse;

					using (XmlReader xread = XmlReader.Create(stylesheet, xset))
					{
						try
						{
							transformer.Load(xread, XsltSettings.TrustedXslt, new XmlUrlResolver());
						}
						catch (Exception e)
						{
							throw new XsltException("Couldn't load xslt file: " + stylesheet, e);
						}
					}
				}
			}


			StringWriter sw = new StringWriter();
			transformer.Transform(source, null, sw);
			string output = sw.ToString();
			Response.Write(output);
		}
	}