private string getHTML(Panel Pnl)
 {
     StringBuilder sb = new StringBuilder();
     StringWriter textwriter = new StringWriter(sb);
     HtmlTextWriter htmlwriter = new HtmlTextWriter(textwriter);
     Pnl.RenderControl(htmlwriter);
     htmlwriter.Flush();
     textwriter.Flush();
     htmlwriter.Dispose();
     textwriter.Dispose();
     return sb.ToString();
 }
Example #2
0
        public static void LogToFileAsXML(TFSExceptionReport ex, DateTime now)
        {
            try
            {
                //Get exception logger
                var log = LogManager.GetLogger(repo.Name, XMLReporterLogger);
                ex.ExceptionEntity.Comment =
                    $"{now.ToString("G", CultureInfo.InvariantCulture)}: {ex.ExceptionEntity.Comment}";
                var          ser    = new XmlSerializer(typeof(ExceptionEntity));
                var          outStr = new StringBuilder();
                StringWriter mem    = null;
                try
                {
                    mem = new StringWriter(outStr);
                    using (var writer = new XmlTextWriter(mem))
                    {
                        mem = null;
                        writer.Formatting = Formatting.Indented;
                        ser.Serialize(writer, ex.ExceptionEntity);
                    }
                }
                finally
                {
                    mem?.Dispose();
                }

                log.Info(outStr.ToString());
                StoreAsFile(outStr.ToString(), "xml", ex.ExceptionEntity.StackTrace, now);
            }
            catch
            {
                //No more falback solutions.
                //need to catch to avoid circular exception
            }
        }
        private string CreateNodeAnnotationContent(OpenNodeAnnotationEventArgs e)
        {
            var writer = new StringWriter();

            try
            {
                writer.WriteLine(DocumentationBrowserUtils.GetContentFromEmbeddedResource(STYLE_RESOURCE));

                // Get the Node info section
                var nodeDocumentation = NodeDocumentationHtmlGenerator.FromAnnotationEventArgs(e);
                writer.WriteLine(nodeDocumentation);

                // Convert the markdown file to html
                MarkdownHandlerInstance.ParseToHtml(ref writer, e.MinimumQualifiedName, e.PackageName);

                writer.Flush();
                var output = writer.ToString();

                // Sanitize html and warn if any changes where made
                if (MarkdownHandlerInstance.SanitizeHtml(ref output))
                {
                    LogWarning(Resources.ScriptTagsRemovalWarning, WarningLevel.Mild);
                }

                // inject the syntax highlighting script at the bottom at the document.
                output += DocumentationBrowserUtils.GetDPIScript();
                output += DocumentationBrowserUtils.GetSyntaxHighlighting();

                return(output);
            }
            finally
            {
                writer?.Dispose();
            }
        }
Example #4
0
        public UnitTest1()
        {
            Random rnd       = new System.Random();
            int    intResult = rnd.Next(1, 7);

            testString = Guid.NewGuid().ToString("N").Substring(0, intResult);

            Console.WriteLine("{0} / {1}", intResult.ToString(), testString);

            testArray = testString.ToCharArray();
            strResult = new List <string>();

            builder     = new System.Text.StringBuilder();
            writer      = new StringWriter(builder);
            premutation = new Permutation.Program();

            //結果文字列を取得
            Console.SetOut(writer);

            // テスト対象(このメソッドの中でコンソールに出力している)
            string result = premutation.PermutationPattern(testArray);

            // コンソール出力を読みだす
            reader = new StringReader(builder.ToString());
            writer?.Dispose();

            while (reader.Peek() > -1)
            {
                //一行ずつListに
                strResult.Add(reader.ReadLine());
            }
            reader?.Dispose();
        }
        private string CreateNodeAnnotationContent(OpenNodeAnnotationEventArgs e)
        {
            var writer = new StringWriter();

            try
            {
                writer.WriteLine(DocumentationBrowserUtils.GetContentFromEmbeddedResource(STYLE_RESOURCE));

                // Get the Node info section and remove script tags if any
                var nodeDocumentation = NodeDocumentationHtmlGenerator.FromAnnotationEventArgs(e);
                if (MarkdownHandlerInstance.SanitizeHtml(ref nodeDocumentation))
                {
                    LogWarning(Resources.ScriptTagsRemovalWarning, WarningLevel.Mild);
                }

                writer.WriteLine(nodeDocumentation);

                // Convert the markdown file to html and remove script tags if any
                if (MarkdownHandlerInstance.ParseToHtml(ref writer, e.MinimumQualifiedName))
                {
                    LogWarning(Resources.ScriptTagsRemovalWarning, WarningLevel.Mild);
                }

                writer.Flush();
                return(writer.ToString());
            }
            finally
            {
                writer?.Dispose();
            }
        }
        /// <summary>
        /// 将对象序列化成Xml字符串。
        /// </summary>
        /// <typeparam name="T">对象的类型。</typeparam>
        /// <param name="sourceObject">被序列化的对象。</param>
        /// <param name="prefix">The prefix associated with an XML namespace.</param>
        /// <param name="ns">An XML namespace.</param>
        /// <returns></returns>
        public static string SerializeObjectToXmlString <T>(T sourceObject, string prefix = "", string ns = "")
        {
            string       xmlString    = null;
            StringWriter stringWriter = null;
            XmlWriter    xmlWriter    = null;

            try
            {
                stringWriter = new StringWriter();

                var xmlNamespaces = new XmlSerializerNamespaces();
                xmlNamespaces.Add(prefix, ns);
                var settings = new XmlWriterSettings {
                    Indent = true, IndentChars = "\t"
                };
                xmlWriter = XmlWriter.Create(stringWriter, settings);

                var serializer = new XmlSerializer(typeof(T));
                serializer.Serialize(xmlWriter, sourceObject, xmlNamespaces);
                xmlString = xmlWriter.ToString();
            }
            finally
            {
                xmlWriter?.Close();
                xmlWriter?.Dispose();
                stringWriter?.Close();
                stringWriter?.Dispose();
            }

            return(xmlString);
        }
Example #7
0
        public static string FormatXml(XmlDocument doc)
        {
            StringWriter stringWriter = null;

            try
            {
                // Create a stream buffer that can be read as a string
                stringWriter = new StringWriter();

                // Create a specialized writer for XML code
                using (var xtw = new XmlTextWriter(stringWriter))
                {
                    // Set the writer to use indented (hierarchical) elements
                    xtw.Formatting = Formatting.Indented;

                    // Write the XML document to the stream
                    doc.WriteTo(xtw);
                    xtw.Flush();
                    xtw.Close();

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

                    // Return the stream as a string
                    return(stringWriter.ToString());
                }
            }
            finally
            {
                stringWriter?.Dispose();
            }
        }
Example #8
0
 public void Dispose()
 {
     _sw?.Dispose();
     if (_outputRedirected)
     {
         Console.SetOut(_tw);
     }
 }
 public void TestCleanup()
 {
     _shimsContext?.Dispose();
     _responseWriter?.Dispose();
     _dropDownList?.Dispose();
     _textBox?.Dispose();
     _page?.Dispose();
     _testObject?.Dispose();
 }
Example #10
0
        internal SourceCodeParser(string code)
        {
            foreach (var line in code.ReadLines())
            {
                if (_current == null)
                {
                    if (line.IsEmpty())
                    {
                        continue;
                    }

                    if (line.Trim().StartsWith("// START"))
                    {
                        _name = line.Split(':').Last().Trim();

                        // dispose the old writer before overriding the reference
                        _current?.Dispose();

                        _current = new StringWriter();
                    }
                }
                else
                {
                    if (line.Trim().StartsWith("// END"))
                    {
                        var classCode = _current.ToString();
                        _code[_name] = classCode;

                        _current = null;
                        _name    = null;
                    }
                    else
                    {
                        _current.WriteLine(line);
                    }
                }
            }
        }
Example #11
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                SystemConsole.SetOut(originalOutput);
                stringWriter?.Dispose();
            }

            disposed = true;
        }
            public void Dispose()
            {
                _prefixWriter?.Dispose();

                _handler._currentConditionalWriting = _previous;
                if (_previous != null)
                {
                    _previous._gotChildren = true;
                }

                if (!_gotChildren && Fragments.Count == 0)
                {
                    throw new InvalidOperationException();
                }
            }
Example #13
0
    public static string FormatReturn(int _flag, string _result)
    {
        string result;
        using (DataTable dt = new DataTable("table"))
        {
            dt.Columns.Add("flag");
            dt.Columns.Add("result");
            dt.Rows.Add(_flag, _result);
            StringWriter sw = new StringWriter();
            dt.WriteXml(sw);
            result = sw.ToString();
            sw.Dispose();
        }

        return result;
    }
Example #14
0
        /// <summary>
        /// Called after an inbound message has been received but before the message is dispatched to the
        /// intended operation.
        /// </summary>
        /// <param name="request">The request message.</param>
        /// <param name="channel">The incoming channel.</param>
        /// <param name="instanceContext">The current service instance.</param>
        /// <returns>
        /// The object used to correlate state. This object is passed back in the <see cref="BeforeSendReply" /> method.
        /// </returns>
        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            if (request == null)
            {
                return(null);
            }

            var buffer = request.CreateBufferedCopy(int.MaxValue);

            request = buffer.CreateMessage();

            var message = buffer.CreateMessage();

            StringWriter stringWriter = null;

            try
            {
                stringWriter = new StringWriter(CultureInfo.InvariantCulture);

                var xmlWriter = XmlWriter.Create(
                    stringWriter,
                    new XmlWriterSettings
                {
                    Indent      = true,
                    IndentChars = "    "
                });

                message.WriteMessage(xmlWriter);

                xmlWriter.Flush();

                this.log.DebugFormat("Service received inbound message:\r\n{0}", stringWriter);
            }
            catch (Exception e)
            {
                this.log.Warn("Logging inbound message threw an exception.", e);
            }
            finally
            {
                stringWriter?.Dispose();
            }

            return(null);
        }
Example #15
0
        /// <summary>
        /// Called after the operation has returned but before the reply message is sent.
        /// </summary>
        /// <param name="reply">The reply message. This value is <c>null</c> if the operation is one way.</param>
        /// <param name="correlationState">The correlation object returned from the <see cref="AfterReceiveRequest" /> method.</param>
        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            if (reply == null)
            {
                return;
            }

            var buffer = reply.CreateBufferedCopy(int.MaxValue);

            reply = buffer.CreateMessage();

            var          message = buffer.CreateMessage();
            StringWriter writer  = null;

            try
            {
                writer = new StringWriter(CultureInfo.InvariantCulture);

                var xmlWriter = XmlWriter.Create(
                    writer,
                    new XmlWriterSettings
                {
                    Indent      = true,
                    IndentChars = "    "
                });

                message.WriteMessage(xmlWriter);

                xmlWriter.Flush();

                this.log.DebugFormat("Service is sending outbound message:\r\n{0}", writer);
            }
            catch (Exception e)
            {
                this.log.Warn("Logging outbound message threw an exception.", e);
            }
            finally
            {
                writer?.Dispose();
            }
        }
Example #16
0
        public static XmlDocument SerializeTypeToXmlDocument <T>(T samlType) where T : class
        {
            XmlDocument       xmlDocument = ReadyXmlDocument;
            XmlWriterSettings xmlSettings = new XmlWriterSettings {
                OmitXmlDeclaration = true, Indent = true, Encoding = Encoding.UTF8
            };

            //Pattern complies with Microsoft Usage Code Analysis CA2202; NO nested using statements
            StringWriter stringWriter = new StringWriter();

            try {
                using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlSettings)) {
                    XmlSerializer xmlSerializer = new XmlSerializer(samlType.GetType());
                    xmlSerializer.Serialize(xmlWriter, samlType);
                    xmlDocument.LoadXml(stringWriter.ToString());
                };
            } finally {
                stringWriter?.Dispose();
            }
            return(xmlDocument);
        }
        public static String ToStringXmlMessage <T>(T t, Boolean needLog) where T : class
        {
            StringWriter writer = null;

            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(T));
                writer = new StringWriter();
                serializer.Serialize(writer, t);
                return(writer.ToString());
            }
            catch
            {
                return(String.Empty);
            }
            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
        }
Example #18
0
        public void WriteToMethodTest_ExpectedDataReturned()
        {
            StringBuilder actualResult = new StringBuilder();
            StringWriter  stringWriter = new StringWriter(actualResult);

            var catalog  = CreateCatalog();
            var entities = new IEntity[] { catalog };

            string expectedResult = @"<?xml version=""1.0"" encoding=""utf-16""?>" +
                                    "<Library>" +
                                    @"<Catalog unloadingTime=""01/20/2006"" libraryName=""National"">" +
                                    GetBookXml() +
                                    GetNewspaperXml() +
                                    GetPatentXml() +
                                    "</Catalog>" +
                                    "</Library>";

            libraryLoader.WriteTo(stringWriter, entities);

            stringWriter.Dispose();

            Assert.AreEqual(expectedResult, actualResult.ToString());
        }
Example #19
0
        /// <summary>
        /// 执行URL获取页面内容
        /// </summary>
        public static string UrlExecute(string urlPath)
        {
            if (string.IsNullOrEmpty(urlPath))
            {
                return("error");
            }
            StringWriter sw = new StringWriter();

            try
            {
                HttpContext.Current.Server.Execute(urlPath, sw);
                return(sw.ToString());
            }
            catch (Exception)
            {
                return("error");
            }
            finally
            {
                sw.Close();
                sw.Dispose();
            }
        }
Example #20
0
        private void CreateProcessFile()
        {
            StringWriter writer = null;

            try
            {
                writer = new StringWriter();
                XmlDocument document = new XmlDocument();
                document.CreateXmlDeclaration("1.0", "utf-8", "yes");
                XmlNode rootNode = document.CreateElement("process");
                document.AppendChild(rootNode);
                document.Save(writer);
                byte[] buffer = UTF8Encoding.UTF8.GetBytes(writer.GetStringBuilder().ToString());
                File.WriteAllText(practicalProcessFileName, string.Join(" ", buffer.Select(item => item.ToString()).ToArray()));
            }
            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
            }
        }
Example #21
0
        public static int Main(string[] args)
        {
            DebugMode.HandleDebugSwitch(ref args);

            var cancel = new CancellationTokenSource();

            Console.CancelKeyPress += (sender, e) => { cancel.Cancel(); };

            var outputWriter = new StringWriter();
            var errorWriter  = new StringWriter();

            // Prevent shadow copying.
            var loader  = new DefaultExtensionAssemblyLoader(baseDirectory: null);
            var checker = new DefaultExtensionDependencyChecker(loader, outputWriter, errorWriter);

            var application = new Application(
                cancel.Token,
                loader,
                checker,
                (path, properties) => MetadataReference.CreateFromFile(path, properties),
                outputWriter,
                errorWriter);

            var result = application.Execute(args);

            var output = outputWriter.ToString();
            var error  = errorWriter.ToString();

            outputWriter.Dispose();
            errorWriter.Dispose();

            // This will no-op if server logging is not enabled.
            ServerLogger.Log(output);
            ServerLogger.Log(error);

            return(result);
        }
Example #22
0
        private void DecompileCsharpCode()
        {
            var         asm = AssemblyDefinition.ReadAssembly(FilePath_edit.Text);
            IEnumerator e   = asm.MainModule.Types.GetEnumerator();

            while (e.MoveNext())
            {
                TypeDefinition td = (TypeDefinition)e.Current;
                IEnumerator    e2 = td.Methods.GetEnumerator();
                while (e2.MoveNext())
                {
                    MethodDefinition method = (MethodDefinition)e2.Current;
                    AstBuilder       ast    = null;

                    foreach (var type in asm.MainModule.Types)
                    {
                        ast = new AstBuilder(new DecompilerContext(asm.MainModule)
                        {
                            CurrentType = type
                        });
                        foreach (var method2 in type.Methods)
                        {
                            if (method2.Name == member_tree.SelectedNode.Text)
                            {
                                this.richTextBox1.Clear();
                                ast.AddMethod(method2);
                                StringWriter output = new StringWriter();
                                ast.GenerateCode(new PlainTextOutput(output));
                                string result = output.ToString();
                                this.richTextBox1.AppendText(result);
                                output.Dispose();
                            }
                        }
                    }
                }
            }
        }
        void RunTest(string c_code, string expectedXml)
        {
            StringReader reader = null;
            StringWriter writer = null;

            try
            {
                reader = new StringReader(c_code);
                writer = new StringWriter();
                var xWriter = new XmlnsHidingWriter(writer)
                {
                    Formatting = Formatting.Indented
                };
                var arch     = new FakeArchitecture();
                var platform = new DefaultPlatform(null, arch);
                var xc       = new XmlConverter(reader, xWriter, platform);
                xc.Convert();
                writer.Flush();
                Assert.AreEqual(expectedXml, writer.ToString());
            }
            catch
            {
                Debug.WriteLine(writer.ToString());
                throw;
            }
            finally
            {
                if (writer != null)
                {
                    writer.Dispose();
                }
                if (reader != null)
                {
                    reader.Dispose();
                }
            }
        }
Example #24
0
        public string Serialize(Reporter reporter)
        {
            string                  str = "";
            StringWriter            sw  = null;
            XmlWriter               xw  = null;
            XmlSerializerNamespaces ns  = null;

            try
            {
                XmlWriterSettings settings = new XmlWriterSettings()
                {
                    Encoding           = Encoding.UTF8,
                    Indent             = true,
                    OmitXmlDeclaration = true
                };
                ns = new XmlSerializerNamespaces();
                ns.Add(string.Empty, string.Empty);

                sw = new StringWriter();
                xw = XmlWriter.Create(sw, settings);

                xmlSerializer.Serialize(xw, this, ns);
                str = sw.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                xw?.Close();
                xw?.Dispose();
                sw?.Close();
                sw?.Dispose();
            }
            return(str);
        }
Example #25
0
        public static string TransformXml(string xml, string xsl, XsltArgumentList xsltArgs)
        {
            //create an object to perform the XSLT transformation
            XslCompiledTransform xct = new XslCompiledTransform();

            //create an object to recieve the results of the transformation
            StringWriter outStream = null;

            XmlDocument xmlDoc = new XmlDocument();
            XmlDocument xslDoc = new XmlDocument();

            xmlDoc.LoadXml(xml);
            xslDoc.Load(xsl);

            try
            {
                outStream = new StringWriter();

                // load the xslt
                xct.Load(xsl);

                // transform the xml document and pass the results to the Stream object
                xct.Transform(xmlDoc, xsltArgs, outStream);

                // send the result back to the calling function
                return(outStream.ToString());
            }
            finally
            {
                if (outStream != null)
                {
                    //close the stream
                    outStream.Close();
                    outStream.Dispose();
                }
            }
        }
Example #26
0
        /// <summary>
        ///  Populate CsharpCode
        /// </summary>
        private void populateCsharpCode()
        {
            var         assembly   = AssemblyDefinition.ReadAssembly(selectedFilename);
            IEnumerator enumerator = assembly.MainModule.Types.GetEnumerator();

            while (enumerator.MoveNext())
            {
                TypeDefinition td          = (TypeDefinition)enumerator.Current;
                IEnumerator    enumerator2 = td.Methods.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                    MethodDefinition method_definition = (MethodDefinition)enumerator2.Current;
                    AstBuilder       ast_Builder       = null;

                    foreach (var typeInAssembly in assembly.MainModule.Types)
                    {
                        ast_Builder = new AstBuilder(new ICSharpCode.Decompiler.DecompilerContext(assembly.MainModule)
                        {
                            CurrentType = typeInAssembly
                        });
                        foreach (var method in typeInAssembly.Methods)
                        {
                            if (method.Name == treeview_Definitions.SelectedNode.Text)
                            {
                                richTextBox_codeView.Clear();
                                ast_Builder.AddMethod(method);
                                StringWriter output = new StringWriter();
                                ast_Builder.GenerateCode(new PlainTextOutput(output));
                                string result = output.ToString();
                                richTextBox_codeView.AppendText(result);
                                output.Dispose();
                            }
                        }
                    }
                }
            }
        }
Example #27
0
        public string ToXmlString(object value, bool xmlDeclaration)
        {
            string str;

            lock (_object)
            {
                object[]      customAttributes = value.GetType().GetCustomAttributes(typeof(XmlRootAttribute), false);
                string        format           = (customAttributes.Length != 1) ? string.Format("<{0}>{{0}}</{0}>", value.GetType().Name) : string.Format("<{0}>{{0}}</{0}>", ((XmlRootAttribute)customAttributes[0]).ElementName);
                XmlSerializer serializer       = new XmlSerializer(_targetType);
                StringBuilder builder          = new StringBuilder();
                if (xmlDeclaration)
                {
                    builder.Append("<?xml version=\"1.0\"?>");
                }
                builder.Append(Environment.NewLine);
                StringWriter objA = new StringWriter();
                try
                {
                    object[] args = new object[] { value };
                    serializer.Serialize((TextWriter)objA, Activator.CreateInstance(_targetType, args));
                    XmlDocument document = new XmlDocument();
                    document.LoadXml(objA.ToString());
                    builder.AppendFormat(format, document.DocumentElement.InnerXml);
                    document = null;
                    str      = builder.ToString();
                }
                finally
                {
                    if (objA != null)
                    {
                        objA.Dispose();
                    }
                }
            }
            return(str);
        }
Example #28
0
        private static void LogToFileSystem(LogDetails logDetails)
        {
            XmlSerializer writer = null;
            StringWriter  stream = null;

            if (FileLogSize)
            {
                try
                {
                    string logFile = FileLogPath;
                    writer = new XmlSerializer(logDetails.GetType());
                    stream = new StringWriter();
                    writer.Serialize(stream, logDetails);
                    if (!string.IsNullOrEmpty(logFile))
                    {
                        File.AppendAllText(logFile, stream.ToString() + "\r\n");
                    }
                }
                catch (Exception ex)
                {
                    logDetails.Message += " ADDITIONAL_ERROR: " + ex.Message;
                    LogToDb(logDetails);
                    LogToEventLog(logDetails);
                    //throw ex;
                }
                finally
                {
                    if (stream != null)
                    {
                        stream.Close();
                        stream.Dispose();
                        stream = null;
                    }
                }
            }
        }
Example #29
0
        private string BuildModulesConfig()
        {
            var stringWriter = new StringWriter(CultureInfo.InvariantCulture);

            try
            {
                using (var writer = new JsonTextWriter(stringWriter))
                {
                    writer.WriteStartObject();
                    writer.WritePropertyName("remoteModuleConfig");
                    _registry.WriteModuleDescriptions(writer);
                    writer.WriteEndObject();
                }

                return(stringWriter.ToString());
            }
            finally
            {
                if (stringWriter != null)
                {
                    stringWriter.Dispose();
                }
            }
        }
Example #30
0
        public DataTable GetForumView(int portalId, int moduleId, int currentUserId, bool isSuperUser, string forumIds)
        {
            const string cacheKeyTemplate = "AF-FV-{0}-{1}-{2}-{3}";

            DataSet   ds;
            DataTable dt;
            var       cachekey = string.Format(cacheKeyTemplate, portalId, moduleId, currentUserId, forumIds);

            var dataSetXML = DataCache.CacheRetrieve(cachekey) as string;

            // cached datatable is held as an XML string (because data vanishes if just caching the DT in this instance)
            if (dataSetXML != null)
            {
                var sr = new StringReader(dataSetXML);
                ds = new DataSet();
                ds.ReadXml(sr);
                dt = ds.Tables[0];
            }
            else
            {
                ds = DataProvider.Instance().UI_ForumView(portalId, moduleId, currentUserId, isSuperUser, forumIds);
                dt = ds.Tables[0];

                var sw = new StringWriter();

                dt.WriteXml(sw);
                var result = sw.ToString();

                sw.Close();
                sw.Dispose();

                DataCache.CacheStore(cachekey, result);
            }

            return(dt);
        }
Example #31
0
        /// <summary>
        /// This method formats an XML string.
        /// </summary>
        /// <param name="xmlString">the XML string</param>
        /// <returns>formatted XML string</returns>
        public static string AsPrettyXml(this string xmlString)
        {
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(xmlString);
            StringWriter stringWriter = new StringWriter();

            try
            {
                // Format the XML text.
                XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
                xmlTextWriter.Formatting = Formatting.Indented;
                doc.WriteTo(xmlTextWriter);
                return(stringWriter.ToString());
            }
            catch (Exception)
            {
                return(string.Empty);
            }
            finally
            {
                stringWriter.Dispose();
            }
        }
Example #32
0
        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";
            string wordContent = string.Empty;
            IView  view        = ViewEngines.Engines.FindPartialView(ControllerContext, "Index").View;

            using (var writer = new StringWriter())
            {
                var viewContext = new ViewContext(ControllerContext, view, ViewData, TempData, writer);
                viewContext.View.Render(viewContext, writer);
                wordContent = writer.ToString();
                writer.Close();
                writer.Dispose();
            }
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            byte[]     pdfBuffer  = htmlToPdfConverter.ConvertHtmlToMemory(wordContent, null);
            FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");

            fileResult.FileDownloadName = "index.pdf";
            return(fileResult);

            return(View());
        }
		// 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;
			}
		}		
    public string GetXml(bool acceptDefaults, Dictionary<string, string> dict)
    {
        dict = (dict == null) ? new Dictionary<string, string>() : dict;

        //setting the HxFrom
        HxFrom.Text = ddlHxFrom.SelectedValue == "" ? tbHxOther.Text : ddlHxFrom.SelectedValue;

        StringWriter stringWriter = new StringWriter();
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.CheckCharacters = false;
        XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings);
        //XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
        
        //xmlWriter.WriteStartDocument();
        xmlWriter.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"");
        xmlWriter.WriteStartElement("patient");

        foreach (Control ctrl in pageControls)
        {
            string customColourType = "0";
            if (ctrl.GetType().Name == "TextBox" || ctrl.GetType().Name == "DropDownList")
            {
                if (acceptDefaults || ColourType.ContainsKey(ctrl.ID))
                    customColourType = "0";
                else
                    customColourType = ((WebControl)ctrl).Attributes["CustomColourType"];
            }

            switch (ctrl.GetType().Name)
            {
                case "TextBox":
                    TextBox tb = (TextBox)ctrl;
                    xmlWriter.WriteStartElement(ctrl.ID);
                    if (dict.ContainsKey(ctrl.ID) && dict[ctrl.ID] != tb.Text.Trim())
                        customColourType = "2";
                    xmlWriter.WriteAttributeString("CustomColourType", customColourType);
                    tb.Attributes["CustomColourType"] = customColourType;
                    xmlWriter.WriteCData(tb.Text.Trim().Replace("'", "''"));
                    xmlWriter.WriteEndElement();
                    break;
                case "HiddenField":
                    xmlWriter.WriteStartElement(ctrl.ID);
                    xmlWriter.WriteCData(((HiddenField)ctrl).Value);
                    xmlWriter.WriteEndElement();
                    break;
                case "DropDownList":
                    DropDownList ddl = (DropDownList)ctrl;
                    xmlWriter.WriteStartElement(ctrl.ID);
                    if (dict.ContainsKey(ctrl.ID) && dict[ctrl.ID] != ddl.SelectedValue.Trim())
                        customColourType = "2";
                    xmlWriter.WriteAttributeString("CustomColourType", customColourType);
                    ddl.Attributes["CustomColourType"] = customColourType;
                    xmlWriter.WriteCData(ddl.SelectedValue.Trim().Replace("'", "''"));
                    xmlWriter.WriteEndElement();
                    break;
                case "CheckBox":
                    xmlWriter.WriteStartElement(ctrl.ID);
                    xmlWriter.WriteString(((CheckBox)ctrl).Checked.ToString());
                    xmlWriter.WriteEndElement();
                    break;
            }
        }

        xmlWriter.WriteEndElement();
        //xmlWriter.WriteEndDocument();
        xmlWriter.Flush();
        xmlWriter.Close();
        stringWriter.Flush();
        string xml = stringWriter.ToString();
        stringWriter.Dispose();
        return xml;
    }
		// 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;
			}
		}