Dispose() protected method

protected Dispose ( bool disposing ) : void
disposing bool
return void
Exemplo n.º 1
0
 /// <summary>
 /// 将xml字符串格式化
 /// </summary>
 /// <param name="originalString">原始字符串</param>
 /// <param name="formatString">格式化后的数据,或错误信息</param>
 /// <returns>是否成功</returns>
 public static bool FormatXmlString(string originalString, out string formatString)
 {
     System.Xml.XmlDocument   xmlDoc = new System.Xml.XmlDocument();
     System.IO.StringWriter   sw     = new System.IO.StringWriter();
     System.Xml.XmlTextWriter xtw    = new System.Xml.XmlTextWriter(sw);
     xtw.Formatting  = System.Xml.Formatting.Indented;
     xtw.Indentation = 1;
     xtw.IndentChar  = '\t';
     try
     {
         xmlDoc.LoadXml(originalString);
         xmlDoc.WriteTo(xtw);
         formatString = sw.ToString();
         return(true);
     }
     catch (Exception ex)
     {
         formatString = ex.Message;
         return(false);
     }
     finally
     {
         sw.Dispose();
     }
 }
Exemplo n.º 2
0
 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 xc = new XmlConverter(reader, xWriter);
         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();
     }
 }
Exemplo n.º 3
0
        protected void btnExport_Click(Object sender, EventArgs e)
        {
            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
            Response.Charset = "utf-8";
            Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode("指标历史数据.xls",
                System.Text.Encoding.UTF8).ToString());
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            int RecordCount = 0;
            DateTime StartDate = Convert.ToDateTime(txtStartDate.Text);
            DateTime EndDate = Convert.ToDateTime(txtEndDate.Text);
            String ECID = Request.Params["ECID"];
            using (ECHistoryDataAccess DataAccess = new ECHistoryDataAccess()) {
                ECDataRepeater.DataSource = DataAccess.GetECHourData(ECID, StartDate, EndDate,
                   1, 20000, out RecordCount);
                ECDataRepeater.DataBind();
                ECDataRepeater.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.Flush();
                Response.End();
                sw.Close();
                sw.Dispose();
            }
            DataBind();
        }
        /// <summary>
        /// Assina o XML de origem subistituindo o antigo
        /// </summary>
        /// <param name="pathXml">Caminho do xml de origem</param>
        /// <returns></returns>
        public static bool AssinaXml(string pathXml)
        {
            try
            {
                if (string.IsNullOrEmpty(pathXml))
                {
                    return false;
                }

                var xmlDoc = new XmlDocument();
                xmlDoc.Load(pathXml);

                var xml = new StringWriter(new StringBuilder(xmlDoc.OuterXml));

                var rsaKey = RetornaAssinaturaRSA(xml);

                AssinaXml(xmlDoc, rsaKey);
                xmlDoc.Save(pathXml);
                xml.Dispose();
                return true;
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// Assina e salva o fonte de xml
        /// </summary>
        /// <param name="xmlSource"></param>
        /// <param name="pathXmlDestino"></param>
        /// <returns></returns>
        public static KeyValuePair<bool, string> AssinaXml(string xmlSource, string pathXmlDestino)
        {
            try
            {
                if (string.IsNullOrEmpty(xmlSource))
                {
                    throw new ArgumentNullException("xmlSource", "Parametro não pode ser nulo");
                }

                if (string.IsNullOrEmpty(pathXmlDestino))
                {
                    throw new ArgumentNullException("pathXmlDestino", "Parametro não pode ser nulo");
                }

                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xmlSource);

                using (var xml = new StringWriter(new StringBuilder(xmlDoc.OuterXml)))
                {
                    var rsaKey = RetornaAssinaturaRsa(xml);

                    AssinaXml(xmlDoc, rsaKey);
                    xmlDoc.Save(pathXmlDestino);
                    xml.Dispose();
                }

                return new KeyValuePair<bool, string>(true, "");
            }
            catch (Exception ex)
            {
                return new KeyValuePair<bool, string>(false, ex.Message);
            }
        }
 protected void btnExport_Click(object sender, EventArgs e)
 {
     int totalCount = 0;
     string kpiName = drpKPI.SelectedValue;
     string unityValue = drpUnits.SelectedValue;
     DateTime beginTime = Convert.ToDateTime(txtBeginTime.Text);
     beginTime = beginTime.AddHours(1);
     DateTime endTime = Convert.ToDateTime(txtEndTime.Text);
     endTime = endTime.AddHours(25);
     OverLimitRecordRepeater.DataSource = overLimitRecordDal.SearchOverLimitRecord(1,
         int.MaxValue, kpiName, unityValue, drpShifts.SelectedValue, beginTime, endTime, out totalCount);
     OverLimitRecordRepeater.DataBind();
     Response.ContentEncoding = Encoding.UTF8;
     Response.ContentType = "application/ms-excel";
     Response.Charset = "utf-8";
     Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("超限明细报表.xls", System.Text.Encoding.UTF8).ToString());
     StringWriter sw = new StringWriter();
     HtmlTextWriter htw = new HtmlTextWriter(sw);
     OverLimitRecordRepeater.RenderControl(htw);
     Response.Write(sw.ToString());
     Response.Flush();
     Response.End();
     sw.Close();
     sw.Dispose();
     DataBind();
 }
Exemplo n.º 7
0
 public static string FromHashtableQueue(Queue<Hashtable> queue)
 {
     StringWriter textWriter = new StringWriter();
     JsonWriter jsonWriter = new JsonWriter(textWriter);
     jsonWriter.WriteStartArray();
     JsonSerializer serializer = new JsonSerializer();
     UUIDConverter UUID = new UUIDConverter();
     serializer.Converters.Add(UUID);
     while (queue.Count > 0)
     {
         try
         {
             Hashtable hashtable = queue.Dequeue();
             serializer.Serialize(jsonWriter, hashtable);
         }
         catch(Exception e)
         {
             AjaxLife.Debug("MakeJson.FromHashTable", e.Message);
         }
     }
     jsonWriter.WriteEndArray();
     jsonWriter.Flush();
     string text = textWriter.ToString();
     jsonWriter.Close();
     textWriter.Dispose();
     return text;
 }
        /// <summary>
        /// Assina e salva o fonte de xml
        /// </summary>
        /// <param name="xmlSource"></param>
        /// <param name="pathXmlDestino"></param>
        /// <returns></returns>
        public static void AssinaXml(string xmlSource, string pathXmlDestino)
        {
            try
            {
                if (string.IsNullOrEmpty(xmlSource))
                {
                    throw new ArgumentNullException("xmlSource", "Parametro não pode ser nulo");
                }

                if (string.IsNullOrEmpty(pathXmlDestino))
                {
                    throw new ArgumentNullException("pathXmlDestino", "Parametro não pode ser nulo");
                }

                var xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(xmlSource);

                var xml = new StringWriter(new StringBuilder(xmlDoc.OuterXml));

                var rsaKey = RetornaAssinaturaRSA(xml);

                AssinaXml(xmlDoc, rsaKey);
                xmlDoc.Save(pathXmlDestino);
                xml.Dispose();
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Transforms the specified XML string
        /// </summary>
        /// <param name="xmlString"></param>
        /// <param name="embeddedResourcePath"></param>
        /// <returns></returns>
		public static string Transform(string xmlString, string embeddedResourcePath)
		{
            string xslString = ResourceReader.ReadFromResource(embeddedResourcePath);

            string result = string.Empty;

            try
            {
                XmlDocument xsl = new XmlDocument();
                xsl.LoadXml(xslString);

                StringWriter sw = new StringWriter();
                XmlTextReader xtr = new XmlTextReader(new StringReader(xmlString));
                XmlTextWriter xtw = new XmlTextWriter(sw);
                XslCompiledTransform t = new XslCompiledTransform();
                t.Load((IXPathNavigable)xsl, null, null);
                t.Transform(xtr, null, xtw, null);
                result = sw.ToString();
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }
            catch(Exception ex) 
            {
                result = string.Format("{0} had the following error with the XML file:\n{1}\n{2}", ex.Source, ex.Message, xmlString);
            }

			return result;

		}
        public static string ToJsonString(this JToken token)
        {
            if (token == null)
            {
                throw new ArgumentNullException("token");
            }

            // The following code is different from token.ToString(), which special-cases null to return "" instead of
            // "null".
            StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
            try
            {
                using (JsonWriter jsonWriter = JsonSerialization.CreateJsonTextWriter(stringWriter))
                {
                    token.WriteTo(jsonWriter);
                    jsonWriter.Flush();
                    stringWriter.Flush();

                    string result = stringWriter.ToString();
                    stringWriter = null;

                    return result;
                }
            }
            finally
            {
                if (stringWriter != null)
                {
                    stringWriter.Dispose();
                }
            }
        }
Exemplo n.º 11
0
 private string SaveXElementUsingXmlWriter(XElement elem, NamespaceHandling nsHandling)
 {
     StringWriter sw = new StringWriter();
     using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = nsHandling, OmitXmlDeclaration = true }))
     {
         elem.WriteTo(w);
     }
     sw.Dispose();
     return sw.ToString();
 }
Exemplo n.º 12
0
        /// <summary>
        /// 导出GridView中的数据到Excel
        /// </summary>
        /// <param name="gvw"></param>
        /// <param name="DataList"></param>
        private static void ExportToExcel(GridView gvw, string title, string TableName)
        {
            //int coun = ExistsRegedit();
            //string fileName = string.Format("DataInfo{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now);
            //if (coun >0)
            //{
            //    fileName = string.Format("DataInfo{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now);
            //    //HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF7;
            //}
            //else
            //{
            //    HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    //Page.RegisterStartupScript("mess", "<script>alert('该机器没有安装任何office软件');</script>");
            //    //return;
            //}

            for (int i = 0; i < gvw.Rows.Count; i++)
            {
                for (int j = 0; j < gvw.HeaderRow.Cells.Count; j++)
                {
                    //这里给指定的列编辑格式,将数字输出为文本,防止数字溢出
                    gvw.Rows[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }
            }
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            //fileName = string.Format("DataInfo{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now);
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + TableName + System.Web.HttpUtility.UrlEncode(title) + DateTime.Now.ToShortDateString() + ".xls");
            HttpContext.Current.Response.Charset         = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");


            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.Write("<html><head><style type='text/css'>h1 {font-family: Arial, sans-serif;font-size: 24px;margin: 5px;color: #369;text-align:center}h3 {text-align:center;color:#0099FF;}table{border-collapse: collapse;font-family: 'Lucida Sans Unicode','Lucida Grande',Sans-Serif;font-size: 12px;margin: 20px;text-align: left;width: 97%}td {padding: 8px;}th{text-align:center;}</style></head><body>");
            StringWriter   tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

            gvw.RenderControl(hw);
            if (!string.IsNullOrEmpty(title))
            {
                //HttpContext.Current.Response.Write("<b><center><font size=3 face=Verdana color=#0000FF>" + title + "</font></center></b>");
            }
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.Write("</body></html>");
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Close();
            HttpContext.Current.Response.End();
            gvw.Dispose();
            tw.Dispose();
            hw.Dispose();
            gvw = null;
            tw  = null;
            hw  = null;
        }
Exemplo n.º 13
0
        private XmlWriter CreateMemWriter(XmlWriterSettings settings)
        {
            XmlWriterSettings wSettings = settings.Clone();
            wSettings.CloseOutput = false;
            wSettings.OmitXmlDeclaration = true;
            wSettings.CheckCharacters = false;
            XmlWriter w = null;

            switch (WriterType)
            {
                case WriterType.UTF8Writer:
                    wSettings.Encoding = Encoding.UTF8;
                    if (_strWriter != null) _strWriter.Dispose();
                    _strWriter = new StringWriter();
                    w = WriterHelper.Create(_strWriter, wSettings);
                    break;
                case WriterType.UnicodeWriter:
                    wSettings.Encoding = Encoding.Unicode;
                    if (_strWriter != null) _strWriter.Dispose();
                    _strWriter = new StringWriter();
                    w = WriterHelper.Create(_strWriter, wSettings);
                    break;
                case WriterType.WrappedWriter:
                    if (_strWriter != null) _strWriter.Dispose();
                    _strWriter = new StringWriter();
                    XmlWriter ww = WriterHelper.Create(_strWriter, wSettings);
                    w = WriterHelper.Create(ww, wSettings);
                    break;
                case WriterType.CharCheckingWriter:
                    if (_strWriter != null) _strWriter.Dispose();
                    _strWriter = new StringWriter();
                    XmlWriter cw = WriterHelper.Create(_strWriter, wSettings);
                    XmlWriterSettings cws = settings.Clone();
                    cws.CheckCharacters = true;
                    w = WriterHelper.Create(cw, cws);
                    break;
                case WriterType.UTF8WriterIndent:
                    wSettings.Encoding = Encoding.UTF8;
                    wSettings.Indent = true;
                    if (_strWriter != null) _strWriter.Dispose();
                    _strWriter = new StringWriter();
                    w = WriterHelper.Create(_strWriter, wSettings);
                    break;
                case WriterType.UnicodeWriterIndent:
                    wSettings.Encoding = Encoding.Unicode;
                    wSettings.Indent = true;
                    if (_strWriter != null) _strWriter.Dispose();
                    _strWriter = new StringWriter();
                    w = WriterHelper.Create(_strWriter, wSettings);
                    break;
                default:
                    throw new Exception("Unknown writer type");
            }
            return w;
        }
Exemplo n.º 14
0
 public void IfNoLoggerIsAttachedWeGetAWarning()
 {
     const string Warning = "Ohoh";
     const string Message = "No loggers have been created for this message: " + Warning;
     var defaultOut = Console.Out;
     var console = new StringWriter();
     Console.SetOut(console);
     Logger.Warning(Warning);
     Assert.IsTrue(console.ToString().Contains(Message), console.ToString());
     Console.SetOut(defaultOut);
     console.Dispose();
 }
Exemplo n.º 15
0
        public static void ExportToExcel(DataTable dataList, string filename, string context)
        {
            GridView gvw = new GridView();

            gvw.AutoGenerateColumns = true;
            gvw.DataSource          = dataList;
            // SetStype(gvw);
            gvw.DataBind();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            //fileName = string.Format("DataInfo{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now);
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + System.Web.HttpUtility.UrlEncode(filename) + DateTime.Now.ToShortDateString() + ".xls");
            HttpContext.Current.Response.Charset         = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");


            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.Write("<html><head><style type='text/css'>h1 {font-family: Arial, sans-serif;font-size: 24px;margin: 5px;color: #369;text-align:center}h3 {text-align:center;color:#0099FF;}table{border-collapse: collapse;font-family: 'Lucida Sans Unicode','Lucida Grande',Sans-Serif;font-size: 12px;margin: 20px;text-align: left;width: 97%}td {padding: 8px;}th{text-align:center;}</style></head><body>");
            HttpContext.Current.Response.Write(context);
            StringWriter   tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

            gvw.RenderControl(hw);

            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.Write("</tbody> </table>");
            HttpContext.Current.Response.Write("</body></html>");
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Close();
            HttpContext.Current.Response.End();
            gvw.Dispose();
            tw.Dispose();
            hw.Dispose();
            gvw = null;
            tw  = null;
            hw  = null;


            //var res = System.Web.HttpContext.Current.Response;
            //content = String.Format("<style type='text/css'>{0}</style>{1}", cssText, content);

            //res.Clear();
            //res.Buffer = true;
            //res.Charset = "UTF-8";
            //res.AddHeader("Content-Disposition", "attachment; filename=" + filename);
            //res.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            //res.ContentType = "application/vnd.ms-excel;charset=UTF-8";
            ////res.ContentType = "application/ms-excel;charset=UTF-8";
            //res.Write(content);
            //res.Flush();
            //res.End();
        }
        public string Serializar()
        {
            string retorno;

            TextWriter salida = new StringWriter();
            XmlSerializer serializador = new XmlSerializer(this.GetType());
            serializador.Serialize(salida, this);
            retorno = salida.ToString();
            salida.Dispose();

            return retorno;
        }
Exemplo n.º 17
0
 public void Compression(System.Web.UI.HtmlTextWriter writer)
 {
     StringWriter sr = new StringWriter();
     HtmlTextWriter tw = new HtmlTextWriter(sr);
     base.Render(tw);
     tw.Flush();
     tw.Dispose();
     StringBuilder sb = new StringBuilder(sr.ToString());
     string outhtml = Regex.Replace(sb.ToString(), "\\r+\\n+\\s+", string.Empty);
     writer.Write(outhtml);
     sr.Dispose();
 }
Exemplo n.º 18
0
        private void BundleMinifier_ErrorMinifyingFile(object sender, MinifyFileEventArgs e)
        {
            var logger    = Hood.Core.Engine.Services.Resolve <ILogService>();
            var logWriter = new System.IO.StringWriter();

            logWriter.WriteLine($"Bundle errors from {e.Result.FileName} - {DateTime.UtcNow.ToDisplay()}");
            foreach (var error in e.Result.Errors)
            {
                logWriter.WriteLine($"Line {error.LineNumber} and column {error.ColumnNumber}: {error.Message}");
            }
            logger.AddLogAsync <PageBuilder>($"Bundle errors from {e.Result.FileName}", logWriter.ToString(), Models.LogType.Error);
            logWriter.Dispose();
        }
Exemplo n.º 19
0
        public void WriteTo_WritesToTheSpecifiedWriter()
        {
            // Arrange
            var expectedText = "Some Text";
            var content = new HtmlString(expectedText);
            var writer = new StringWriter();

            // Act
            content.WriteTo(writer, new CommonTestEncoder());

            // Assert
            Assert.Equal(expectedText, writer.ToString());
            writer.Dispose();
        }
Exemplo n.º 20
0
 public static string FromObject(object obj)
 {
     StringWriter textWriter = new StringWriter();
     JsonWriter jsonWriter = new JsonWriter(textWriter);
     JsonSerializer serializer = new JsonSerializer();
     LLUUIDConverter UUID = new LLUUIDConverter();
     serializer.Converters.Add(UUID);
     serializer.Serialize(jsonWriter, obj);
     jsonWriter.Flush();
     string text = textWriter.ToString();
     jsonWriter.Close();
     textWriter.Dispose();
     return text;
 }
        public void JsonMessageSerializer_WhenUnderlyingMediumFails_ThrowsMessageException() {
            // given
            IMessageTypeResolver resolver = new UnitTestMessageTypeResolver();
            TextWriter textWriter = new StringWriter();
            textWriter.Dispose(); // so stringwriter will throw ObjectDisposedException

            // when / then
            MessageTransferException exception =
                Assert.Throws<MessageTransferException>(
                    () => new JsonMessageSerializer(resolver, textWriter).SerializeMessage(new FakeMessage()));

            // then
            Assert.That(() => exception.InnerException, Is.InstanceOf<ObjectDisposedException>());
        }
Exemplo n.º 22
0
 protected void btnExport_Click(Object sender, EventArgs e)
 {
     Response.ContentEncoding = Encoding.UTF8;
     Response.ContentType = "application/ms-excel";
     Response.Charset = "utf-8";
     Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("个人得分报表.xls", System.Text.Encoding.UTF8).ToString());
     StringWriter sw = new StringWriter();
     HtmlTextWriter htw = new HtmlTextWriter(sw);
     PersonScoreRepeater.RenderControl(htw);
     Response.Write(sw.ToString());
     Response.Flush();
     Response.End();
     sw.Close();
     sw.Dispose();
 }
 public void AskUntilValidMatrixSizeEntered(string input)
 {
     StringReader reader = new StringReader(input + "\n3");
     StringWriter writer = new StringWriter();
     Console.SetIn(reader);
     Console.SetOut(writer);
     FillMatrix.Main();
     string expectedOutput = "Enter a positive number \r\n" +
                             "You haven't entered a correct positive number\r\n" +
                             "     1     7     8\r\n" +
                             "     6     2     9\r\n" +
                             "     5     4     3\r\n";
     Assert.AreEqual(expectedOutput, writer.ToString());
     reader.Dispose();
     writer.Dispose();
 }
Exemplo n.º 24
0
    /// <summary>
    /// 输出HTML
    /// </summary>
    /// <param name="writer"></param>
    protected override void Render(HtmlTextWriter writer)
    {
        //将当前产生的文件写到HTML里
        System.IO.StringWriter sw = new System.IO.StringWriter();
        Html32TextWriter       hw = new Html32TextWriter(sw);

        base.Render(hw);
        if (IsCresteHTMLPage)
        {
            // System.IO.File.WriteAllText(Server.MapPath("./index.htm"), sw.ToString());
        }

        //输出页面
        writer.Write(sw.ToString());

        sw.Dispose();
        hw.Dispose();
    }
        private string CreateProcessXmlFieldSchemaString(string name)
        {
            System.Xml.Schema.XmlSchema            xmlSchema   = new System.Xml.Schema.XmlSchema();
            System.Xml.Schema.XmlSchemaComplexType complexType = new System.Xml.Schema.XmlSchemaComplexType();
            System.Xml.Schema.XmlSchemaSequence    sequence    = new System.Xml.Schema.XmlSchemaSequence();
            complexType.Particle = sequence;
            System.Xml.Schema.XmlSchemaElement rootElement = new System.Xml.Schema.XmlSchemaElement();
            rootElement.SchemaType = complexType;
            rootElement.Name       = name;
            xmlSchema.Items.Add(rootElement);
            System.IO.StringWriter stream = new System.IO.StringWriter();
            xmlSchema.Write(stream);
            string outString = stream.ToString();

            stream.Close();
            stream.Dispose();
            return(outString);
        }
Exemplo n.º 26
0
 public override string ToString()
 {
     var sw = new System.IO.StringWriter();
     using (XmlTextWriter writer = new XmlTextWriter(sw))
     {
         writer.Formatting = Formatting.Indented;
         writer.Indentation = 4;
         writer.WriteStartElement("Script");
         writer.WriteElementString("Enable", Enable.ToString());
         writer.WriteElementString("Name", FullName);
         writer.WriteElementString("Comment", Comment);
         writer.WriteElementString("Params", Params);
         writer.WriteEndElement();
     }
     string retval = sw.ToString();
     sw.Close();
     sw.Dispose();
     return retval;
 }
Exemplo n.º 27
0
 public static string FromHashtableQueue(Queue<Hashtable> queue)
 {
     StringWriter textWriter = new StringWriter();
     JsonWriter jsonWriter = new JsonWriter(textWriter);
     jsonWriter.WriteStartArray();
     JsonSerializer serializer = new JsonSerializer();
     LLUUIDConverter UUID = new LLUUIDConverter();
     serializer.Converters.Add(UUID);
     while (queue.Count > 0)
     {
         Hashtable hashtable = queue.Dequeue();
         serializer.Serialize(jsonWriter, hashtable);
     }
     jsonWriter.WriteEndArray();
     jsonWriter.Flush();
     string text = textWriter.ToString();
     jsonWriter.Close();
     textWriter.Dispose();
     return text;
 }
Exemplo n.º 28
0
        //生成首页静态
        public static void CreateIndexHtml()
        {
            Model.siteconfig config = new BLL.siteconfig().loadConfig(Utils.GetXmlMapPath(DTKeys.FILE_SITE_XML_CONFING));
            string urlPath = string.Format("{0}{1}/{2}", config.webpath, DTKeys.DIRECTORY_REWRITE_ASPX, "index.aspx"); //文件相对路径
            string htmlPath = string.Format("{0}{1}/{2}", config.webpath, DTKeys.DIRECTORY_REWRITE_HTML, "index." + config.staticextension); //保存相对路径
            //检查文件是否存在
            if (!File.Exists(Utils.GetMapPath(urlPath)))
            {

            }
            Stopwatch watch = new Stopwatch(); //测量时间
            watch.Start();
            StringWriter sw = new StringWriter();
            HttpContext.Current.Server.Execute(urlPath, sw);
            File.WriteAllText(Utils.GetMapPath(htmlPath), sw.ToString(), Encoding.UTF8);
            watch.Stop();
            //watch.Elapsed
            sw.Close();
            sw.Dispose();
        }
Exemplo n.º 29
0
    /// <summary>
    /// 输出HTML
    /// </summary>
    /// <param name="writer"></param>
    protected override void Render(HtmlTextWriter writer)
    {
        //将当前产生的文件写到HTML里
        System.IO.StringWriter sw = new System.IO.StringWriter();
        Html32TextWriter       hw = new Html32TextWriter(sw);

        base.Render(hw);
        if (IsCresteHTMLPage)
        {
            if (currentDoc != null)
            {
                currentDoc.CreateStaticHTMLFile(sw.ToString());
            }
        }
        //输出页面
        writer.Write(sw.ToString());

        sw.Dispose();
        hw.Dispose();
    }
Exemplo n.º 30
0
        /// <summary>
        /// <geoloc xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://jabber.org/protocol/geoloc"><lat>32.234</lat><lon>-97.3453</lon></geoloc>
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetXMLStringFromObject(object obj)
        {
            //MemoryStream stream = new MemoryStream();
            StringWriter stream = new StringWriter();
            XmlSerializerNamespaces namespaces = new XmlSerializerNamespaces();
            //namespaces.
            /// Get the default namespace
            ///
            Type type = obj.GetType();
            object[] attr = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlRootAttribute), true);
            if ((attr != null) && (attr.Length > 0))
            {
                System.Xml.Serialization.XmlRootAttribute xattr = attr[0] as System.Xml.Serialization.XmlRootAttribute;
                namespaces.Add("", xattr.Namespace);
            }

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(stream,settings);

            XmlSerializer ser = new XmlSerializer(obj.GetType());
            ser.Serialize(writer, obj, namespaces);

            writer.Flush();
            writer.Close();

            string strRet = stream.ToString();

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

            stream.Close();
            stream.Dispose();

               // string strRet = System.Text.UTF8Encoding.UTF8.GetString(bData, 0, bData.Length);

            //strRet = strRet.Replace(@"<?xml version=""1.0""?>", "");
            return strRet;
        }
Exemplo n.º 31
0
        /// <summary>
        /// 导出GridView中的数据到Excel
        /// </summary>
        /// <param name="gvw">GridView</param>
        /// <param name="title">表头</param>
        /// <param name="footer">表尾</param>
        private static void ExportToExcel(GridView gvw, string title, string[] footer)
        {
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=GB2312>");
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            HttpContext.Current.Response.ContentType     = "application/vnd.xls";
            StringWriter   tw = new System.IO.StringWriter();
            HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

            gvw.RenderControl(hw);
            HttpContext.Current.Response.Write(style);
            if (!string.IsNullOrEmpty(title))
            {
                HttpContext.Current.Response.Write("<b><center><font size=3 face=Verdana>" + title + "</font></center></b>");
            }

            HttpContext.Current.Response.Write(tw.ToString());
            if (footer != null)
            {
                for (int i = 0; i < footer.Length; i++)
                {
                    HttpContext.Current.Response.Write("<br><font size=2>" + footer[i].ToString() + "</font>");
                }
            }

            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.Close();
            HttpContext.Current.Response.End();
            gvw.Dispose();
            tw.Dispose();
            hw.Dispose();
            gvw = null;
            tw  = null;
            hw  = null;
        }
Exemplo n.º 32
0
 public override string ToString()
 {
     var sw = new System.IO.StringWriter();
     using (XmlTextWriter writer = new XmlTextWriter(sw))
     {
         writer.Formatting = Formatting.Indented;
         writer.Indentation = 4;
         writer.WriteStartDocument();
         writer.WriteStartElement("TestSuite");
         writer.WriteElementString("Description", Description);
         writer.WriteElementString("TearDownScript", TearDownScript);
         writer.WriteStartElement("Tests");
         foreach (TestSuiteEntity entity in Entities)
             writer.WriteRaw(entity.ToString());
         writer.WriteEndElement();
         writer.WriteEndElement();
         writer.WriteEndDocument();
     }
     string retval = sw.ToString().Replace("utf-16", "utf-8"); ;
     sw.Close();
     sw.Dispose();
     return retval;
 }
Exemplo n.º 33
0
 /// <summary>
 /// 将对象系列化成字符串
 /// </summary>
 /// <param name="obj"></param>
 public static string GetSerializationString(object obj)
 {
     StringBuilder t = new StringBuilder();
     StringWriter w = new StringWriter(t);
     try
     {
         XmlSerializer serializer = new XmlSerializer(obj.GetType());
         serializer.Serialize(w, obj);
         return t.ToString();
     }
     catch (Exception ex)
     {
         throw ex;
     }
     finally
     {
         if (w != null)
         {
             w.Close();
             w.Dispose();
         }
     }
 }
Exemplo n.º 34
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();
                }
            }
        }
Exemplo n.º 35
0
        protected void btnExport_Click(object sender, EventArgs e)
        {
            //if (gvData.Rows.Count > 0)
            //{
            //    DocExport docEexport = new DocExport();

            //    docEexport.Dt = GridViewHelper.GridView2DataTable(gvData);

            //    docEexport.Export("SIS实时运行绩效报表");
            //}

            Response.ContentEncoding = Encoding.UTF8;
            Response.ContentType = "application/ms-excel";
            Response.Charset = "utf-8";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("SIS实时运行绩效报表.xls", System.Text.Encoding.UTF8).ToString());
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);
            gvData.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.Flush();
            Response.End();
            sw.Close();
            sw.Dispose();
        }
Exemplo n.º 36
0
        static public CompileResult Evaluate(string code, bool autoCompleteComma = true)
        {
            if (autoCompleteComma && !code.EndsWith(";"))
            {
                code += ";";
            }

            var result = new CompileResult();

            result.code = code;

            // find commands and expand it if found.
            if (RuntimeCommands.ConvertIntoCodeIfCommand(ref code) ||
                Commands.ConvertIntoCodeIfCommand(ref code))
            {
                // the give code is a command and converted into an actua code.
            }

            // eval the code using Mono.
            object ret            = null;
            bool   hasReturnValue = false;

//		var originalOutput = Mono.CSharp.Evaluator.MessageOutput;
            var  errorWriter = new System.IO.StringWriter();
            bool isPartial   = false;

//		Mono.CSharp.Evaluator.MessageOutput = errorWriter;
            SetEvaluatorMessageOutput(errorWriter);
            try {
//			isPartial = Mono.CSharp.Evaluator.Evaluate(code, out ret, out hasReturnValue) != null;
                isPartial = evaluatorInstance.Evaluate(code, out ret, out hasReturnValue) != null;
            } catch (System.Exception e) {
                errorWriter.Write(e.Message);
            }
//		Mono.CSharp.Evaluator.MessageOutput = originalOutput;
            SetDefaultEvaluatorMessageOutput();

            var error = errorWriter.ToString();

            if (!string.IsNullOrEmpty(error))
            {
                error = error.Replace("{interactive}", "");
                var lastLineBreakPos = error.LastIndexOf('\n');
                if (lastLineBreakPos != -1)
                {
                    error = error.Remove(lastLineBreakPos);
                }
                result.type  = CompileResult.Type.Error;
                result.error = error;
                return(result);
            }
            errorWriter.Dispose();

            if (isPartial)
            {
                result.type = CompileResult.Type.Partial;
                return(result);
            }

            result.type  = CompileResult.Type.Success;
            result.value = (hasReturnValue && ret != null) ? ret : "null";
            return(result);
        }
Exemplo n.º 37
0
 public void TestInvalidInputCommand()
 {
     StringWriter sw = new StringWriter();
     Console.SetOut(sw);
     string command = "exit2";
     ConsolePrinter.PrintInvalidCommandMessage();
     string expected = sw.ToString();
     sw.Dispose();
     StringWriter sw2 = new StringWriter();
     Console.SetOut(sw2);
     Game.ProcessTextCommand(command);
     string result = sw2.ToString();
     sw2.Dispose();
     Assert.AreEqual(expected, result);
 }
Exemplo n.º 38
0
        /// <summary>
        /// 导出GridView中的数据到Excel
        /// </summary>
        /// <param name="gvw"></param>
        private void ExportToExcel(GridView gvw)
        {
            var fileName = InitFileName();

            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.Charset         = this.Charset;
            HttpContext.Current.Response.ContentEncoding = this.ContentEncoding;
            HttpContext.Current.Response.Buffer          = true;
            HttpContext.Current.Response.HeaderEncoding  = this.ContentEncoding;
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            HttpContext.Current.Response.AppendHeader("Content-Type", string.Format("application/vnd.ms-excel;charset={0};", this.Charset));
            HttpContext.Current.Response.AppendHeader("Content-Language", "zh-CN");
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

            HttpContext.Current.Response.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
            HttpContext.Current.Response.Write(string.Format("<html>\n<head>\n<title>{0}</title>\n", this.Options.TitleText));
            HttpContext.Current.Response.Write(string.Format("<meta http-equiv=\"Content-Type\" content=\"text/html; charset={0}\">\n", this.Charset));
            HttpContext.Current.Response.Write("<style type=\"text/css\" title=\"\">\n<!--\n");
            HttpContext.Current.Response.Write("body {margin:0;padding:0;color:#000;background-color:#FFF;}\n");
            HttpContext.Current.Response.Write("body,p {font-size:12px;line-height:150%;font-family:Arial, Helvetica, sans-serif;}\n");
            HttpContext.Current.Response.Write("//-->\n</style>\n</head>\n");
            HttpContext.Current.Response.Write("<body>\n");

            System.Globalization.CultureInfo m_CI = new System.Globalization.CultureInfo("ZH-CN", true);//区域设置
            StringWriter   tw = new System.IO.StringWriter(m_CI);
            HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);

            gvw.RenderControl(hw);

            int spancol = this.Columns.Count;

            if (gvw.HeaderRow != null)
            {
                spancol = gvw.HeaderRow.Cells.Count;
            }
            if (!string.IsNullOrEmpty(Options.TitleText))
            {
                string css = " style=\"{0}\" ";
                if (Options.TitleIsBold)
                {
                    css = string.Format(css, "font-weight:bolder;{0}");
                }
                if (Options.TitleIsItalic)
                {
                    css = string.Format(css, "font-style:italic;{0}");
                }

                if (!string.IsNullOrEmpty(Options.TitleFontName))
                {
                    css = string.Format(css, "font-family:" + Options.TitleFontName + ";{0}");
                }
                else
                {
                    css = string.Format(css, "font-family:Arial, Helvetica, sans-serif;{0}");
                }

                if (!Options.TitleFontSize.IsEmpty)
                {
                    css = string.Format(css, "font-size:" + Options.TitleFontSize.ToString() + ";{0}");
                }
                if (!Options.TitleBackColor.IsEmpty)
                {
                    css = string.Format(css, "background-color:" + Options.TitleBackColor.Name + ";{0}");
                }
                if (!Options.TitleForeColor.IsEmpty)
                {
                    css = string.Format(css, "color:" + Options.TitleForeColor.Name + ";{0}");
                }
                switch (Options.TitleHorizontalAlign)
                {
                case HorizontalAlign.Center:
                    css = string.Format(css, "text-align:center;{0}");
                    break;

                case HorizontalAlign.Justify:
                    css = string.Format(css, "text-align:justify;{0}");
                    break;

                case HorizontalAlign.Right:
                    css = string.Format(css, "text-align:right;{0}");
                    break;

                case HorizontalAlign.Left:
                case HorizontalAlign.NotSet:
                default:
                    break;
                }
                if (!Options.TitleHeight.IsEmpty)
                {
                    css = string.Format(css, "height:" + Options.TitleHeight.Value.ToString("f0") + "px;{0}");
                }
                css = css.Replace("{0}", "");
                HttpContext.Current.Response.Write(string.Format("<table><tr><td {0} colspan=\"{2}\">{1}</td></tr></table>", css, Utils.EncodeHtml(Options.TitleText), spancol));
            }
            if (!string.IsNullOrEmpty(Options.TitleInfoHtml))
            {
                HttpContext.Current.Response.Write(string.Format("<table><tr><td  colspan=\"{0}\">{1}</td></tr></table>", spancol, Options.TitleInfoHtml));
            }

            HttpContext.Current.Response.Write(tw.ToString());

            if (!string.IsNullOrWhiteSpace(Options.InfoHtml))
            {
                HttpContext.Current.Response.Write(string.Format("<table><tr><td colspan=\"{1}\"></td></tr><tr><td colspan=\"{1}\">{0}</td></tr><tr><td colspan=\"{1}\"></td></tr></table>", Options.InfoHtml, spancol));
            }

            _watch.Stop();

            HttpContext.Current.Response.Write(string.Format("<div align=\"right\" style=\"color:#AAAAAA;font-family:Verdana\">导出时间:{0}, 记录数量(s): {2}, 耗时: {1}ms</div>", DateTime.Now, _watch.ElapsedMilliseconds, gvw.Rows.Count));
            HttpContext.Current.Response.Write("\n</body>\n</html>");
            //HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();

            gvw.Dispose();
            tw.Dispose();
            hw.Dispose();

            gvw = null;
            tw  = null;
            hw  = null;
        }
Exemplo n.º 39
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (RouteData.Values["idsesion"] != null)
        {
            idsesion = Convert.ToInt32(RouteData.Values["idsesion"]);
        }
        if (!ValidarSesion.sesionactiva())
        {
            Response.Redirect("~/Default.aspx");
        }

        StringBuilder    sb  = new StringBuilder();
        UserControl      ctr = (UserControl)LoadControl("~/Minutas/TemplateDetalleSesion.ascx");
        StringWriter     sw  = new StringWriter(sb);
        Html32TextWriter htw = new Html32TextWriter(sw);

        ctr.RenderControl(htw);
        string templete = sb.ToString();

        templete = templete.Replace("#FOLIOSESION#", string.Format("{0,22:D8}", idsesion));

        MinutasBL bl  = new MinutasBL();
        Minutas   min = new Minutas()
        {
            ObjUsuarios = new UsuariosDatos()
            {
                User = new Usuarios()
            }
        };

        min.IdSesion = idsesion;
        min.ObjUsuarios.User.IdUser = Convert.ToInt32(Session["IdUser"]);
        min = bl.GetMinutasbyFolio(min);

        templete = templete.Replace("#STATUSMINUTA#", min.ObjStatus.nomstatus);
        templete = templete.Replace("#FECHAREGISTRO#", min.Fecharegistro.ToShortDateString());
        templete = templete.Replace("#FECHAPROGRAMADA#", min.Fechafin.HasValue ? min.Fechafin.Value.ToShortDateString() : "");
        templete = templete.Replace("#FECHACONC#", min.FechaConclusion.HasValue ? min.FechaConclusion.Value.ToShortDateString():"");
        templete = templete.Replace("#TIPOSESION#", min.ObjTipoSesion.TipoSesion);
        templete = templete.Replace("#COACHING#", min.ObjUsuarios.NombreCompleto);
        templete = templete.Replace("#DETALLEENTREGA#", min.LabelDias);

        templete = templete.Replace("#OBJETIVO#", HttpUtility.HtmlDecode(min.Objetivo));
        templete = templete.Replace("#DESCRIPCION#", HttpUtility.HtmlDecode(min.Descripcion));


        //usuarios sesion
        /*AGREGAMOS EL DETALLE DE PAGO A PROVEEDORES*/
        StringBuilder sbltvUsuariosMinuta = new StringBuilder();

        System.IO.StringWriter         stringWrite = new System.IO.StringWriter(sbltvUsuariosMinuta);
        System.Web.UI.Html32TextWriter htmlWrite   = new Html32TextWriter(stringWrite);

        MinutasUsuarios mu = new MinutasUsuarios()
        {
            ObjMinutas = new Minutas(), ObjUsuarios = new UsuariosDatos()
            {
                User = new Usuarios()
            }
        };

        mu.ObjMinutas.IdSesion     = idsesion;
        mu.ObjUsuarios.User.IdUser = Convert.ToInt32(Session["IdUser"]);
        MinutasBL blmu = new MinutasBL();

        ltvUsuariosSesion.DataSource = blmu.GetUsuariosSesion(mu);
        ltvUsuariosSesion.DataBind();
        ltvUsuariosSesion.RenderControl(htmlWrite);
        templete = templete.Replace("#LISTAUSUARIOS#", sbltvUsuariosMinuta.ToString());

        stringWrite.Dispose();
        htmlWrite.Dispose();

        ltvUsuariosSesion.Visible = false;
        htmlMinutas.InnerHtml     = templete;
    }
Exemplo n.º 40
0
    protected void MailTemplate()
    {
        try
        {
            if (gdvParticipantes.Rows.Count > 0)
            {
                StringBuilder    sb  = new StringBuilder();
                UserControl      ctr = (UserControl)LoadControl("~/Minutas/TemplateMailMinuta.ascx");
                StringWriter     sw  = new StringWriter(sb);
                Html32TextWriter htw = new Html32TextWriter(sw);
                ctr.RenderControl(htw);
                string templete = sb.ToString();
                idsesion = Convert.ToInt32(hd_idsesion.Value);
                MinutasUsuarios mu = new MinutasUsuarios()
                {
                    ObjMinutas = new Minutas(), ObjUsuarios = new UsuariosDatos()
                    {
                        User = new Usuarios()
                    }
                };
                mu.ObjMinutas.IdSesion     = idsesion;
                mu.ObjUsuarios.User.IdUser = Convert.ToInt32(Session["IdUser"]);
                MinutasBL blmu = new MinutasBL();


                MinutasBL bl  = new MinutasBL();
                Minutas   min = new Minutas()
                {
                    ObjUsuarios = new UsuariosDatos()
                    {
                        User = new Usuarios()
                    }
                };
                min.IdSesion = idsesion;
                min.ObjUsuarios.User.IdUser = Convert.ToInt32(Session["IdUser"]);
                min = bl.GetMinutasbyFolio(min);

                templete = templete.Replace("#Foliominuta#", string.Format("{0:D8}", idsesion));
                templete = templete.Replace("#Fechacreacion#", min.Fecharegistro.ToShortDateString());
                templete = templete.Replace("#Usuariocreador#", min.ObjUsuarios.NombreUser);
                templete = templete.Replace("#Tematica#", min.ObjTemas.descripcion);
                templete = templete.Replace("#Fechaentrega#", min.Fechafin.HasValue ? min.Fechafin.Value.ToShortDateString() : "");
                templete = templete.Replace("#Tiposesion#", min.ObjTipoSesion.TipoSesion);

                templete = templete.Replace("#Objetivo#", HttpUtility.HtmlDecode(min.Objetivo));
                templete = templete.Replace("#Descripcion#", HttpUtility.HtmlDecode(min.Descripcion));

                string minutacompleta = "";

                Email   objemail = new Email();
                EmailBL blmail   = new EmailBL();
                objemail.Principal = true;
                objemail.IdMail    = 0;
                objemail.Usermail  = string.Empty;

                objemail        = blmail.GetEmail(objemail);
                objemail.Asunto = "Notificación de nueva Sesión de minuta. Folio " + string.Format("{0:D8}", idsesion);


                foreach (MinutasUsuarios item in blmu.GetUsuariosSesion(mu))
                {
                    MinutasUsuarios obj = new MinutasUsuarios()
                    {
                        ObjMinutas = new Minutas(), ObjUsuarios = new UsuariosDatos()
                        {
                            User = new Usuarios()
                        }
                    };
                    obj.ObjMinutas.IdSesion     = idsesion;
                    obj.ObjUsuarios.User.IdUser = item.IdUserMinuta;
                    MinutasBL mbl = new MinutasBL();

                    StringBuilder    sb1  = new StringBuilder();
                    UserControl      ctr1 = (UserControl)LoadControl("~/Minutas/TemplateMailMinuta.ascx");
                    StringWriter     sw1  = new StringWriter(sb1);
                    Html32TextWriter htw1 = new Html32TextWriter(sw1);
                    ctr1.RenderControl(htw1);
                    string templeteaux = sb1.ToString();

                    templeteaux = templeteaux.Replace("#Usuario#", item.ObjUsuarios.NombreCompleto);
                    templeteaux = templeteaux.Replace("#Foliominuta#", string.Format("{0:D8}", idsesion));
                    templeteaux = templeteaux.Replace("#Fechacreacion#", min.Fecharegistro.ToShortDateString());
                    templeteaux = templeteaux.Replace("#Usuariocreador#", min.ObjUsuarios.NombreUser);
                    templeteaux = templeteaux.Replace("#Tematica#", min.ObjTemas.descripcion);
                    templeteaux = templeteaux.Replace("#Fechaentrega#", min.Fechafin.HasValue ? min.Fechafin.Value.ToShortDateString() : "");
                    templeteaux = templeteaux.Replace("#Tiposesion#", min.ObjTipoSesion.TipoSesion);

                    templeteaux = templeteaux.Replace("#Objetivo#", HttpUtility.HtmlDecode(min.Objetivo));
                    templeteaux = templeteaux.Replace("#Descripcion#", HttpUtility.HtmlDecode(min.Descripcion));

                    StringBuilder                  sbltvUsuariosMinuta = new StringBuilder();
                    System.IO.StringWriter         stringWrite         = new System.IO.StringWriter(sbltvUsuariosMinuta);
                    System.Web.UI.Html32TextWriter htmlWrite           = new Html32TextWriter(stringWrite);

                    ltvUsuariosSesion.DataSource = mbl.GetUsuariosSesion(obj);
                    ltvUsuariosSesion.DataBind();
                    ltvUsuariosSesion.RenderControl(htmlWrite);

                    minutacompleta += sbltvUsuariosMinuta.ToString();
                    templeteaux     = templeteaux.Replace("#Acuerdos#", sbltvUsuariosMinuta.ToString());

                    generales gral = new generales();
                    if (gral.IsValidEmail(item.ObjUsuarios.User.Username))
                    {
                        objemail.Body    = templeteaux;
                        objemail.MailTo  = item.ObjUsuarios.User.Username;
                        objemail.MailCC  = string.Empty;
                        objemail.MailBcc = string.Empty;
                        generales.enviarMail(objemail);
                    }
                    stringWrite.Dispose();
                    htmlWrite.Dispose();

                    sw1.Dispose();
                    htw1.Dispose();
                }

                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "$('.modalfinsesion').modal('show')", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "bootbox.alert('<div class=\" alert alert-warning\">No existe participantes para ésta sesión. Para enviar la notificación es necesario incluir a los participantes.</div>')", true);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "bootbox.alert('<div class=\"alert alert-danger\">Se produjo un error al enviar el mail! " + ex.Message.Replace("'", "") + "</div>');", true);
        }
    }
        private void DoUpdateFileTags(Project project, string filename)
        {
            if (!DepsInstalled)
            {
                return;
            }

            string[]      headers        = Headers(project, filename, false);
            string[]      system_headers = diff(Headers(project, filename, true), headers);
            StringBuilder ctags_kinds    = new StringBuilder("--C++-kinds=+px");

            if (PropertyService.Get <bool> ("CBinding.ParseLocalVariables", true))
            {
                ctags_kinds.Append("+l");
            }

            // Maybe we should only ask for locals for 'local' files? (not external #includes?)
            ctags_kinds.AppendFormat(" --fields=+aStisk-fz --language-force=C++ --excmd=number --line-directives=yes -f - '{0}'", filename);
            foreach (string header in headers)
            {
                ctags_kinds.AppendFormat(" '{0}'", header);
            }

            string ctags_output = string.Empty;

            ProcessWrapper p = null;

            System.IO.StringWriter output = null, error = null;
            try {
                output = new System.IO.StringWriter();
                error  = new System.IO.StringWriter();

                p = Runtime.ProcessService.StartProcess("ctags", ctags_kinds.ToString(), project.BaseDirectory, output, error, null);
                p.WaitForOutput(10000);
                if (p.ExitCode != 0)
                {
                    LoggingService.LogError("Ctags did not successfully populate the tags database from '{0}' within ten seconds.\nError output: {1}", filename, error.ToString());
                    return;
                }
                ctags_output = output.ToString();
            } catch (Exception ex) {
                throw new IOException("Could not create tags database (You must have exuberant ctags installed).", ex);
            } finally {
                if (output != null)
                {
                    output.Dispose();
                }
                if (error != null)
                {
                    error.Dispose();
                }
                if (p != null)
                {
                    p.Dispose();
                }
            }

            ProjectInformation info = ProjectInformationManager.Instance.Get(project);

            lock (info) {
                info.RemoveFileInfo(filename);
                string tagEntry;

                using (StringReader reader = new StringReader(ctags_output)) {
                    while ((tagEntry = reader.ReadLine()) != null)
                    {
                        if (tagEntry.StartsWith("!_"))
                        {
                            continue;
                        }

                        Tag tag = ParseTag(tagEntry);

                        if (tag != null)
                        {
                            AddInfo(info, tag, ctags_output);
                        }
                    }
                }
            }

            OnFileUpdated(new ClassPadEventArgs(project));

            if (PropertyService.Get <bool> ("CBinding.ParseSystemTags", true))
            {
                UpdateSystemTags(project, filename, system_headers);
            }

            if (cache.Count > cache_size)
            {
                cache.Clear();
            }
        }
        private void FillFileInformation(FileInformation fileInfo)
        {
            if (!DepsInstalled)
            {
                return;
            }

            string confdir         = PropertyService.ConfigPath;
            string tagFileName     = Path.GetFileName(fileInfo.FileName) + ".tag";
            string tagdir          = Path.Combine(confdir, "system-tags");
            string tagFullFileName = Path.Combine(tagdir, tagFileName);
            string ctags_kinds     = "--C++-kinds=+px";

            if (PropertyService.Get <bool> ("CBinding.ParseLocalVariables", true))
            {
                ctags_kinds += "l";
            }

            string ctags_options = ctags_kinds + " --fields=+aStisk-fz --language-force=C++ --excmd=number --line-directives=yes -f '" + tagFullFileName + "' '" + fileInfo.FileName + "'";

            if (!Directory.Exists(tagdir))
            {
                Directory.CreateDirectory(tagdir);
            }

            if (!File.Exists(tagFullFileName) || File.GetLastWriteTimeUtc(tagFullFileName) < File.GetLastWriteTimeUtc(fileInfo.FileName))
            {
                ProcessWrapper         p      = null;
                System.IO.StringWriter output = null;
                try {
                    output = new System.IO.StringWriter();

                    p = Runtime.ProcessService.StartProcess("ctags", ctags_options, null, null, output, null);
                    p.WaitForOutput(10000);
                    if (p.ExitCode != 0 || !File.Exists(tagFullFileName))
                    {
                        LoggingService.LogError("Ctags did not successfully populate the tags database '{0}' within ten seconds.\nOutput: {1}", tagFullFileName, output.ToString());
                        return;
                    }
                } catch (Exception ex) {
                    throw new IOException("Could not create tags database (You must have exuberant ctags installed).", ex);
                } finally {
                    if (output != null)
                    {
                        output.Dispose();
                    }
                    if (p != null)
                    {
                        p.Dispose();
                    }
                }
            }

            string ctags_output;
            string tagEntry;

            using (StreamReader reader = new StreamReader(tagFullFileName)) {
                ctags_output = reader.ReadToEnd();
            }

            using (StringReader reader = new StringReader(ctags_output)) {
                while ((tagEntry = reader.ReadLine()) != null)
                {
                    if (tagEntry.StartsWith("!_"))
                    {
                        continue;
                    }

                    Tag tag = ParseTag(tagEntry);

                    if (tag != null)
                    {
                        AddInfo(fileInfo, tag, ctags_output);
                    }
                }
            }

            fileInfo.IsFilled = true;
        }
Exemplo n.º 43
0
 public static void Close(this StringWriter writer)
 {
     writer.Dispose();
 }
        private void CommitFormatting()
        {
            XmlDocument xml = new XmlDocument();
            xml.LoadXml(editorControlsUserControl.GetText());

            XmlDeclaration dec = null;

            if (xml.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
            {
                dec = (XmlDeclaration)xml.FirstChild;
            }

            XmlWriterSettings writerSettings = new XmlWriterSettings();

            writerSettings.OmitXmlDeclaration = true;
            writerSettings.IndentChars = "\t";
            writerSettings.Indent = true;

            StringWriter stringWriter = new StringWriter();
            XmlWriter xmlWriter = XmlWriter.Create(stringWriter, writerSettings);

            if (dec != null)
            {
                stringWriter.WriteLine(xml.CreateXmlDeclaration(dec.Version, dec.Encoding, dec.Standalone).OuterXml);
            }

            xmlWriter.Flush();
            stringWriter.Flush();

            xml.Save(xmlWriter);

            editorControlsUserControl.SetText(stringWriter.ToString());

            xmlWriter.Close();
            stringWriter.Dispose();
        }
Exemplo n.º 45
0
        public ActionResult Feedback([Bind(Include = "MobileNumber,Aspect1,Aspect2,Aspect3,Aspect4,Aspect5,Rating1,Rating2,Rating3,Rating4,Rating5,Comments1,Comments2,Comments3,Comments4,Comments5")] Feedbacks Fb)
        {
            if (ModelState.IsValid)
            {
                UserDetails objUserDetails = new UserDetails();
                Fb.MobileNumber = objUserDetails.MobileFormat(Fb.MobileNumber);
                Int64 isNumber = 0;
                Int64.TryParse(Fb.MobileNumber, out isNumber);
                if (Fb.MobileNumber.Length == 10 && isNumber > 0)
                {
                    DataTable dtXml = new DataTable();
                    dtXml.TableName = "Details";
                    dtXml.Columns.Add("Aspect", typeof(string));
                    dtXml.Columns.Add("Rating", typeof(int));
                    dtXml.Columns.Add("Comments", typeof(string));

                    DataRow dr1 = dtXml.NewRow();
                    dr1["Aspect"]   = Fb.Aspect1;
                    dr1["Rating"]   = Fb.Rating1;
                    dr1["Comments"] = string.IsNullOrEmpty(Fb.Comments1) == true?"": Fb.Comments1.Trim();
                    dtXml.Rows.Add(dr1);

                    DataRow dr2 = dtXml.NewRow();
                    dr2["Aspect"]   = Fb.Aspect2;
                    dr2["Rating"]   = Fb.Rating2;
                    dr2["Comments"] = string.IsNullOrEmpty(Fb.Comments2) == true ? "" : Fb.Comments2.Trim();
                    dtXml.Rows.Add(dr2);

                    DataRow dr3 = dtXml.NewRow();
                    dr3["Aspect"]   = Fb.Aspect3;
                    dr3["Rating"]   = Fb.Rating3;
                    dr3["Comments"] = string.IsNullOrEmpty(Fb.Comments3) == true ? "" : Fb.Comments3.Trim();
                    dtXml.Rows.Add(dr3);

                    DataRow dr4 = dtXml.NewRow();
                    dr4["Aspect"]   = Fb.Aspect4;
                    dr4["Rating"]   = Fb.Rating4;
                    dr4["Comments"] = string.IsNullOrEmpty(Fb.Comments4) == true ? "" : Fb.Comments4.Trim();
                    dtXml.Rows.Add(dr4);

                    DataRow dr5 = dtXml.NewRow();
                    dr5["Aspect"]   = Fb.Aspect5;
                    dr5["Rating"]   = Fb.Rating5;
                    dr5["Comments"] = string.IsNullOrEmpty(Fb.Comments5) == true ? "" : Fb.Comments5.Trim();
                    dtXml.Rows.Add(dr5);
                    StringWriter  swSQL2;
                    StringBuilder sbSQL2 = new StringBuilder();
                    swSQL2 = new System.IO.StringWriter(sbSQL2);
                    dtXml.WriteXml(swSQL2);
                    swSQL2.Dispose();
                    string feedbackDetails = sbSQL2.ToString();
                    if (objUserDetails.SaveFeedback(Fb.MobileNumber, feedbackDetails))
                    {
                        TempData["Success"] = "Your feedback have been submitted successfully!";

                        return(this.RedirectToAction("Feedback", new { mobile = Fb.MobileNumber }));
                    }
                    else
                    {
                        TempData["Success"] = "We found some issue on feedback submit!";
                        return(this.RedirectToAction("Feedback", new { mobile = Fb.MobileNumber }));
                    }
                }
                else
                {
                    TempData["Success"] = "Invalid  mobile number!";
                    return(this.RedirectToAction("Feedback", new { mobile = Fb.MobileNumber }));
                }
            }
            return(View(Fb));
        }
Exemplo n.º 46
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();
     }
 }
Exemplo n.º 47
0
    /// <summary>
    /// DataTable转换JSON DataTime类型列转换为String类型
    /// </summary>
    /// <param name="Table"></param>
    /// <param name="TableName"></param>
    /// <param name="Sort"></param>
    /// <returns></returns>
    public static string ToJson(this DataTable Table, string Sort)
    {
        string Result = string.Empty;

        try
        {
            if (Table.Rows.Count <= 0)
            {
                throw new Exception();
            }
            string XML        = string.Empty;
            bool   IsHasDatac = false;

            #region 检查是否存在日期格式
            foreach (DataColumn Dc in Table.Columns)
            {
                if (Dc.DataType == typeof(System.DateTime))
                {
                    IsHasDatac = true;
                    break;
                }
            }
            #endregion

            #region 生成XML
            if (IsHasDatac)
            {
                DataTable T = Table.Clone();
                foreach (DataColumn Dc in T.Columns)
                {
                    if (Dc.DataType == typeof(System.DateTime))
                    {
                        Dc.DataType = typeof(String);
                    }
                }

                T.Load(Table.CreateDataReader());
                System.IO.StringWriter W = new System.IO.StringWriter();
                if (!string.IsNullOrEmpty(Sort) && Table.Rows.Count > 0)
                {
                    T.DefaultView.Sort = Sort;
                }

                T.TableName = T.TableName.IsNullOrEmpty() ? "Temp" : T.TableName;
                T.DefaultView.ToTable().WriteXml(W);
                XML = W.ToString();
                W.Close();
                W.Dispose();
                T.Clear();
                T.Dispose();
            }
            else
            {
                System.IO.StringWriter W = new System.IO.StringWriter();
                if (!string.IsNullOrEmpty(Sort) && Table.Rows.Count > 0)
                {
                    Table.DefaultView.Sort = Sort;
                }

                Table.TableName = Table.TableName.IsNullOrEmpty() ? "Temp" : Table.TableName;
                Table.DefaultView.ToTable().WriteXml(W);
                XML = W.ToString();
                W.Close();
                W.Dispose();
            }
            #endregion

            #region 替换 格式
            XML = XML.Replace("<DocumentElement>", "<data>")
                  .Replace("</DocumentElement>", "</data>")
                  .Replace("<DocumentElement />", "");


            XML = XML.Replace("<Table>", String.Concat("<rows>")).Replace("</Table>", String.Concat("</rows>"));
            System.Xml.XmlDocument XMLD = new System.Xml.XmlDocument();
            XMLD.LoadXml(XML);
            Result = XmlToJSONParser.XmlToJSON(XMLD);
            Result = Result.Replace(@"\", @"\\");
            #endregion
        }
        catch
        {
        }
        return(Result);
    }