Inheritance: System.IO.TextWriter
        /// <summary>
        /// Processes the record.
        /// </summary>
        protected override void ProcessRecord()
        {
            this.WriteVerbose("Formatting log");
            using (var xmlReader = new StringReader(this.Log))
            {
                var xpath = new XPathDocument(xmlReader);
                using (var writer = new StringWriter())
                {
                    var transform = new XslCompiledTransform();
                    Func<string, string> selector = file => !Path.IsPathRooted(file) ? Path.Combine(Environment.CurrentDirectory, file) : file;
                    foreach (var fileToLoad in this.FormatFile.Select(selector))
                    {
                        this.WriteVerbose("Loading format file " + fileToLoad);
                        using (var stream = File.OpenRead(fileToLoad))
                        {
                            using (var reader = XmlReader.Create(stream))
                            {
                                transform.Load(reader);
                                transform.Transform(xpath, null, writer);
                            }
                        }
                    }

                    this.WriteObject(writer.GetStringBuilder().ToString(), false);
                }
            }
        }
 public static CoordinateCommand[] GetCommands(StringWriter trace)
 {
     return new[]
 {
     new CoordinateCommand(trace)    
 };
 }
Exemple #3
1
		public bool Invoke(string[] args)
		{
			output = new StringWriter ();
			method_arg [0] = args;
			method_arg [1] = output;
			return (bool)ep.Invoke (null, method_arg);
		}
		private void SetUpWriter()
		{
			sw = new StringWriter ();
			xtw = new XmlTextWriter (sw);
			xtw.QuoteChar = '\'';
			xtw.Formatting = Formatting.None;
		}
Exemple #5
1
        /// <summary>
        /// html标签导出到word
        /// </summary>
        /// <param name="html"></param>
        /// <param name="fileName">带后缀</param>
        /// <param name="IsWord2003"></param>
        /// <param name="ext"></param>
        public static void HtmlToWord(string html, string fileName, bool IsWord2003 = true)
        {
            try
            {
                HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.Buffer = false;
                response.Charset = "GB2312";
                response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
                response.ContentEncoding = Encoding.GetEncoding("GB2312");

                response.ContentType = IsWord2003 ? "application/ms-word" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                //response.ContentType = "application/octet-stream";

                CultureInfo formatProvider = new CultureInfo("zh-CN", true);
                StringWriter writer = new StringWriter(formatProvider);

                response.Write(html);

                response.End();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 /// <summary>
 /// Returns the C# literal representation of a given primitive expression.
 /// (Useful for escaping strings)
 /// </summary>
 private static string PrimitiveLiteral(this string input)
 {
     var writer = new StringWriter();
     var provider = new CSharpCodeProvider();
     provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
     return writer.ToString();
 }
        protected void Boton_Excel_Dios_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            Page page = new Page();
            HtmlForm form = new HtmlForm();
            GridView_Dios.DataSourceID = string.Empty;
            GridView_Dios.EnableViewState = false;
            GridView_Dios.AllowPaging = false;
            GridView_Dios.DataSource = LBPD.Logica_Mostrar_Precios();
            GridView_Dios.DataBind();
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            page.Controls.Add(form);
            form.Controls.Add(GridView_Dios);
            page.RenderControl(htw);
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "applicattion/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment;filename=data.xls");
            Response.Charset = "UTF-8";
            Response.ContentEncoding = Encoding.Default;
            Response.Write(sb.ToString());
            Response.End();
        }
        public ParsedArguments(string[] args) {
            var p = new OptionSet {
                {"sum", "If set Sum will be calculated", _ => _SumValues = true},
                {"max", "If set show Max value", _ => _MaxValue = true},
                {"min", "If set show Min value", _ => _MinValue = true},
                {"dir=", "Output directory", dir => _OutputDirectory = GetValidPath(dir)}, {
                    "count=", "Count of items to be generated. This value is mandatory.", count => {
                        if (!_CountIsSet && int.TryParse(count, out _Count) && _Count > 0) {
                            _CountIsSet = true;
                        }
                    }
                }
            };

            p.Parse(args);

            if (!ArgsAreValid) {
                Trace.WriteLine("Parameter args does not contain valid value for count.");

                using (var stringWriter = new StringWriter()) {
                    p.WriteOptionDescriptions(stringWriter);
                    _ErrorMessage = stringWriter.ToString();
                }
            }
        }
        protected string InjectAssets(string markup, Match match)
        {
            if (match == null)
            {
                return markup;
            }

            using (var writer = new StringWriter())
            {
                writer.Write(markup.Substring(0, match.Index));

                WriteLinks(writer, @"<link type=""text/css"" rel=""stylesheet"" href=""{0}"" />",
                           Compressor.CompressCss(GetSources(CssLinks)));
                WriteInlines(writer, "<style>", "</style>", CssInlines);
                WriteLinks(writer, @"<script type=""text/javascript"" src=""{0}""></script>",
                           Compressor.CompressJavascript(GetSources(JavascriptLinks)));
                WriteInlines(writer, @"<script type=""text/javascript"">", "</script>", JavascriptInlines);

                WriteInlines(
                    writer,
                    @"<script type=""text/javascript"">jQuery(document).ready(function () {",
                    "});</script>",
                    DomReadyInlines);

                writer.Write(markup.Substring(match.Index));
                return writer.ToString();
            }
        }
 private UpdateOutputLogCommand(IStorageBlockBlob outputBlob, Func<string, CancellationToken, Task> uploadCommand)
 {
     _outputBlob = outputBlob;
     _innerWriter = new StringWriter(CultureInfo.InvariantCulture);
     _synchronizedWriter = TextWriter.Synchronized(_innerWriter);
     _uploadCommand = uploadCommand;
 }
Exemple #11
1
 public static string ObjetoSerializado(Object Objeto)
 {
     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(Objeto.GetType());
     System.IO.StringWriter textWriter = new System.IO.StringWriter();
     x.Serialize(textWriter, Objeto);
     return textWriter.ToString();
 }
Exemple #12
1
        public void NormalSectionAndKey() {
            StringWriter writer = new StringWriter();
            writer.WriteLine("[Logging]");
            writer.WriteLine(" great logger =   log4net  ");
            writer.WriteLine("  [Pets] ; pets comment  ");
            IniReader reader = new IniReader(new StringReader(writer.ToString()));

            Assert.AreEqual(IniReadState.Initial, reader.ReadState);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniReadState.Interactive, reader.ReadState);
            Assert.AreEqual(IniType.Section, reader.Type);
            Assert.AreEqual("Logging", reader.Name);
            Assert.AreEqual("", reader.Value);
            Assert.IsNull(reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Key, reader.Type);
            Assert.AreEqual("great logger", reader.Name);
            Assert.AreEqual("log4net", reader.Value);
            Assert.AreEqual(null, reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Section, reader.Type);
            Assert.AreEqual("Pets", reader.Name);
            Assert.AreEqual("", reader.Value);
            Assert.IsNull(reader.Comment);
        }
		public static string GetHtml (string url, HelpSource helpSource, out Node match)
		{
			string htmlContent = null;
			match = null;
			
			if (helpSource != null)
				htmlContent = AppDelegate.Root.RenderUrl (url, generator, out match, helpSource);
			if (htmlContent == null) {
				// the displayed url have a lower case type code (e.g. t: instead of T:) which confuse monodoc
				if (url.Length > 2 && url[1] == ':')
					url = char.ToUpperInvariant (url[0]) + url.Substring (1);
				// It may also be url encoded so decode it
				url = Uri.UnescapeDataString (url);
				htmlContent = AppDelegate.Root.RenderUrl (url, generator, out match, helpSource);
				if (htmlContent != null && match != null && match.Tree != null)
					helpSource = match.Tree.HelpSource;
			}
			if (htmlContent == null)
				return null;
			
			var html = new StringWriter ();
   			html.Write ("<html>\n<head><title>{0}</title>", url);
			
			if (helpSource != null) {
				if (HtmlGenerator.InlineCss != null)
                    html.Write (" <style type=\"text/css\">{0}</style>\n", HtmlGenerator.InlineCss);
				/*if (helpSource.InlineJavaScript != null)
                    html.Write ("<script type=\"text/JavaScript\">{0}</script>\n", helpSource.InlineJavaScript);*/
            }

            html.Write ("</head><body>");
            html.Write (htmlContent);
            html.Write ("</body></html>\n");
            return html.ToString ();
		}
        public override void Specify()
        {
            when("repeatedly dispatching a command", delegate
            {
                var trace = new StringWriter();

                arrange(delegate
                {
                    ConsoleCommandDispatcher.DispatchCommand(SomeProgram.GetCommands(trace), new[] { "move", "-x", "1", "-y", "2" }, new StringWriter());
                    ConsoleCommandDispatcher.DispatchCommand(SomeProgram.GetCommands(trace), new[] { "move", "-x", "3" }, new StringWriter());
                    ConsoleCommandDispatcher.DispatchCommand(SomeProgram.GetCommands(trace), new[] { "move", "-y", "4" }, new StringWriter());
                    ConsoleCommandDispatcher.DispatchCommand(SomeProgram.GetCommands(trace), new[] { "move" }, new StringWriter());
                });

                then("all parameters are evaluated independently", delegate
                {
                    Expect.That(trace.ToString()).ContainsInOrder(
                            "You walk to 1, 2 and find a maze of twisty little passages, all alike.",
                            "You walk to 3, 0 and find a maze of twisty little passages, all alike.",
                            "You walk to 0, 4 and find a maze of twisty little passages, all alike.",
                            "You walk to 0, 0 and find a maze of twisty little passages, all alike."
                        );
                });
            });
        }
Exemple #15
0
 public static String CaptureOutput(Action Action, bool Capture = true)
 {
     if (Capture)
     {
         var OldOut = Console.Out;
         var StringWriter = new StringWriter();
         try
         {
             Console.SetOut(StringWriter);
             Action();
         }
         finally
         {
             Console.SetOut(OldOut);
         }
         try
         {
             return StringWriter.ToString();
         }
         catch
         {
             return "";
         }
     }
     else
     {
         Action();
         return "";
     }
 }
		public void GenerateCode(FileProjectItem item, CustomToolContext context)
		{
			context.RunAsync(
				()=> {
					string fileName = item.FileName;
					var projectNode = item.Project;
					SpecFlowProject specFlowProject = CreateSpecFlowProjectFrom(projectNode);
					var specFlowGenerator = new SpecFlowGenerator(specFlowProject);
					
					string outputFile = context.GetOutputFileName(item, ".feature");
					
					var specFlowFeatureFile = specFlowProject.GetOrCreateFeatureFile(fileName);
					
					var fileContents = File.ReadAllText(fileName);
					string outputFileContents;
					using(var reader = new StringReader(fileContents)) {
						using (var writer = new StringWriter(new StringBuilder())) {
							specFlowGenerator.GenerateTestFile(specFlowFeatureFile, projectNode.LanguageProperties.CodeDomProvider, reader, writer);
							outputFileContents = writer.ToString();
						}
					}
					File.WriteAllText(outputFile, outputFileContents);
					
					WorkbenchSingleton.SafeThreadCall(
						() => context.EnsureOutputFileIsInProject(item, outputFile));
				});
		}
Exemple #17
0
        /// <summary>
        /// Convert parameter list to json object
        /// </summary>
        public static string parameterFieldMapJson(parameters parms, string ProjectID, string QueryID)
        {
            StringWriter sw = new StringWriter();
            JsonTextWriter json = new JsonTextWriter(sw);

            json.WriteStartObject();
            json.WritePropertyName("results");
            json.WriteStartArray();
            json.WriteStartObject();
            // ProjectID and QueryID
            json.WritePropertyName("ProjectID");
            json.WriteValue(ProjectID);
            json.WritePropertyName("QueryID");
            json.WriteValue(QueryID);

            json.WritePropertyName("parameters");
            json.WriteRawValue(JsonConvert.SerializeObject(parms));

            json.WriteEndObject();
            json.WriteEndArray();
            json.WriteEndObject();

            json.Flush();
            sw.Flush();

            return sw.ToString();
        }
 public static string Filter(string stack)
 {
     if (stack == null)
     {
         return null;
     }
     StringWriter writer = new StringWriter();
     StringReader reader = new StringReader(stack);
     try
     {
         string str2;
         while ((str2 = reader.ReadLine()) != null)
         {
             if (!FilterLine(str2))
             {
                 writer.WriteLine(str2.Trim());
             }
         }
     }
     catch (Exception)
     {
         return stack;
     }
     return writer.ToString();
 }
        public static StringWriter CreateStringWriter(int capacity)
        {
            StringBuilder sb = new StringBuilder(capacity);
            StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture);

            return sw;
        }
Exemple #20
0
        public static void Serialization1(Human human)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Human));
            StringBuilder sb = new StringBuilder();

            /* SERIALIZATION */
            using (StringWriter writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, human);
            }
            // XML file
            //Console.WriteLine("SB: " +sb.ToString());
            /* END SERIALIZATION */



            /* DESERIALIZATION */
            Human newMartin = new Human();
            using (StringReader reader = new StringReader(sb.ToString()))
            {
                newMartin = serializer.Deserialize(reader) as Human;
            }
            Console.WriteLine(newMartin.ToString() + Environment.NewLine);
            /* END DESERIALIZATION */
        }
 public static string Serialize(MaterialList mats)
 {
     StringWriter sw = new StringWriter();
     XmlSerializer ser = new XmlSerializer(typeof(MaterialList));
     ser.Serialize(sw, mats);
     return sw.ToString();
 }
        public void TestConnectorSerialization()
        {
            var obj = new TwoInOneOutExpression();

            var tw = new StringWriter();
            using (var xw = XmlWriter.Create(tw))
            {
                xw.WriteStartElement("Node");
                obj.Serialize(xw);
                xw.WriteEndElement();
            }

            var sr = new StringReader(tw.ToString());
            using (var wr = XmlReader.Create(sr))
            {
                wr.ReadToFollowing("Node");
                var result = new TwoInOneOutExpression();
                result.Deserialize(wr);

                Assert.AreEqual(obj.Id, result.Id);
                Assert.AreEqual(obj.Connector1In.Id, result.Connector1In.Id);
                Assert.AreEqual(obj.Connector2In.Id, result.Connector2In.Id);
                Assert.AreEqual(obj.ConnectorOut.Id, result.ConnectorOut.Id);
            }
        }
Exemple #23
0
        public void Errors_of_type_MutuallyExclusiveSetError_are_properly_formatted()
        {
            // Fixture setup
            var help = new StringWriter();
            var sut = new Parser(config => config.HelpWriter = help);

            // Exercize system
            sut.ParseArguments<FakeOptionsWithTwoRequiredAndSets>(
                new[] { "--weburl=value.com", "--ftpurl=value.org" });
            var result = help.ToString();

            // Verify outcome
            result.Length.Should().BeGreaterThan(0);
            var lines = result.ToNotEmptyLines().TrimStringArray();
            lines[0].Should().StartWithEquivalent("CommandLine");
            lines[1].ShouldBeEquivalentTo("Copyright (c) 2005 - 2015 Giacomo Stelluti Scala");
            lines[2].ShouldBeEquivalentTo("ERROR(S):");
            lines[3].ShouldBeEquivalentTo("Option: 'weburl' is not compatible with: 'ftpurl'.");
            lines[4].ShouldBeEquivalentTo("Option: 'ftpurl' is not compatible with: 'weburl'.");
            lines[5].ShouldBeEquivalentTo("--weburl     Required.");
            lines[6].ShouldBeEquivalentTo("--ftpurl     Required.");
            lines[7].ShouldBeEquivalentTo("-a");
            lines[8].ShouldBeEquivalentTo("--help       Display this help screen.");
            lines[9].ShouldBeEquivalentTo("--version    Display version information.");
            // Teardown
        }
Exemple #24
0
        public override CommandResultCode Execute(IExecutionContext context, CommandArguments args)
        {
            if (!args.MoveNext()) {
                ProductInfo product = ProductInfo.Current;
                StringWriter writer = new StringWriter();
                writer.WriteLine("---------------------------------------------------------------------------");
                writer.WriteLine(" {0} {1} {2}", product.Title, product.Version, product.Copyright);
                writer.WriteLine();
                writer.WriteLine(" CloudB Admin is provided AS IS and comes with ABSOLUTELY NO WARRANTY");
                writer.WriteLine(" This is free software, and you are welcome to redistribute it under the");
                writer.WriteLine(" conditions of the Lesser GNU Public License.");
                writer.WriteLine("---------------------------------------------------------------------------");
                Out.Write(writer.ToString());
                return CommandResultCode.Success;
            }

            if (args.Current == "version") {
                //TODO:
            } else if (args.Current == "license") {
                Out.WriteLine("Lesser GNU Public License <http://www.gnu.org/licenses/lgpl.txt>");
                return CommandResultCode.Success;
            }

            return CommandResultCode.SyntaxError;
        }
Exemple #25
0
        public static string Generate(this ICalculationCodeGenerator codeGenerator, ICalculationComponent component)
        {
            var writer = new StringWriter();
            codeGenerator.Generate(component, writer);

            return writer.ToString();
        }
 public JsonResult Add(string name, string visitDate, string arrivalDate, string contact, string emailAddress, int visitType, int officeID, int eventID, int convensionID, int serviceID, int fsmID, int bookingStatus, float gsbAmount, float donationAmount)
 {
     var audienceManager = new DataAccess.AudienceManager();
     var visitDateTime = Convert.ToDateTime(visitDate);
     DateTime? arrivalDateTime = string.IsNullOrEmpty(arrivalDate) ? (DateTime?)null : Convert.ToDateTime(arrivalDate);
     var audienceID = audienceManager.Add(name, contact, emailAddress, visitDateTime, arrivalDateTime, visitType, officeID, eventID, fsmID, convensionID, serviceID, bookingStatus, gsbAmount, donationAmount);
     if (audienceID != 0)
     {
         using (var sw = new StringWriter())
         {
             var fsmSelectionMail = audienceManager.GetFSMSelectionSlipByAudienceID(audienceID);
             ViewData.Model = fsmSelectionMail;
             ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, "FSMSelectionMail");
             ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
             try
             {
                 viewResult.View.Render(viewContext, sw);
                 audienceManager.SendSelectionSlipMail(fsmID, emailAddress, sw.GetStringBuilder().ToString());
             }
             catch (Exception ex)
             { }
         }
     }
     return Json(audienceID);
 }
    protected void bt_Export_Click(object sender, EventArgs e)
    {
        gv_Summary.AllowPaging = false;
        BindGrid();

        string filename = HttpUtility.UrlEncode("汇总单导出_" + DateTime.Now.ToString("yyyyMMddHHmmss"));
        Response.Charset = "UTF-8";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.ContentType = "application/ms-excel";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
        Page.EnableViewState = false;

        StringWriter tw = new System.IO.StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(tw);
        gv_Summary.RenderControl(hw);

        StringBuilder outhtml = new StringBuilder(tw.ToString());
        outhtml = outhtml.Replace("&nbsp;", "").Replace("<br />", "");

        Response.Write(outhtml.ToString());
        Response.End();

        gv_Summary.AllowPaging = true;
        BindGrid();
    }
Exemple #28
0
        public void NormalComment() {
            StringWriter writer = new StringWriter();
            writer.WriteLine("");
            writer.WriteLine(" ; Something");
            writer.WriteLine(" ;   Some comment  ");
            writer.WriteLine(" ;");
            IniReader reader = new IniReader(new StringReader(writer.ToString()));

            Assert.AreEqual(IniReadState.Initial, reader.ReadState);
            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniReadState.Interactive, reader.ReadState);
            Assert.AreEqual(IniType.Empty, reader.Type);
            Assert.AreEqual("", reader.Name);
            Assert.AreEqual(null, reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Empty, reader.Type);
            Assert.AreEqual("Something", reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual(IniType.Empty, reader.Type);
            Assert.AreEqual("Some comment", reader.Comment);

            Assert.IsTrue(reader.Read());
            Assert.AreEqual("", reader.Comment);

            Assert.IsFalse(reader.Read());
        }
        protected void btnExcel_Click(object sender, EventArgs e)
        {
            //Create a dummy GridView
            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = BindGridView();
            GridView1.DataBind();

            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition",
             "attachment;filename=" + DateTime.Now.Year + "-Newly_Hired" + ".xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                //Apply text style to each Row
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }
            GridView1.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
        public void AsyncFieldIndex1()
        {
            var engine = new FileHelperAsyncEngine(typeof (SampleType));

            var sw = new StringWriter();
            engine.BeginWriteStream(sw);

            engine[0] = new DateTime(2003, 2, 1);
            engine[1] = "B";
            engine[2] = 18;

            engine.WriteNextValues();

            engine.Close();

            engine.BeginReadString(sw.GetStringBuilder().ToString());
            engine.ReadNext();

            Assert.AreEqual(new DateTime(2003, 2, 1), engine[0]);
            Assert.AreEqual("B", engine[1]);
            Assert.AreEqual(18, engine[2]);

            Assert.AreEqual(new DateTime(2003, 2, 1), engine.LastRecordValues[0]);
            Assert.AreEqual("B", engine.LastRecordValues[1]);
            Assert.AreEqual(18, engine.LastRecordValues[2]);

            engine.ReadNext();

            Assert.IsNull(engine.LastRecord);
            Assert.IsNull(engine.LastRecordValues);
        }
        public static HtmlString CreateTagLinks(this IHtmlHelper html, Tag[] tags)
        {
            string GetString(IHtmlContent htmlContent)
            {
                using (var writer = new System.IO.StringWriter())
                {
                    htmlContent.WriteTo(writer, HtmlEncoder.Default);
                    return(writer.ToString());
                }
            }

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < tags.Length; i++)
            {
                IHtmlContent content = html.ActionLink(tags[i].NameForLabels, "List", "Books", new { tag = tags[i].NameForLinks }, new { @class = "tag-a" });
                sb.Append(GetString(content));
                if (i != tags.Length - 1) // not last element
                {
                    sb.Append(", ");
                }
            }
            return(new HtmlString(sb.ToString()));
        }
 public void ExportToExcel(DataTable dt)
 {
     if (dt.Rows.Count > 0)
     {
         string filename = "Missing Dc.xls";
         System.IO.StringWriter       tw = new System.IO.StringWriter();
         System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
         DataGrid dgGrid = new DataGrid();
         dgGrid.DataSource = dt;
         dgGrid.DataBind();
         dgGrid.HeaderStyle.ForeColor   = System.Drawing.Color.Black;
         dgGrid.HeaderStyle.BackColor   = System.Drawing.Color.LightSkyBlue;
         dgGrid.HeaderStyle.BorderColor = System.Drawing.Color.RoyalBlue;
         dgGrid.HeaderStyle.Font.Bold   = true;
         //Get the HTML for the control.
         dgGrid.RenderControl(hw);
         //Write the HTML back to the browser.
         Response.ContentType = "application/vnd.ms-excel";
         Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
         this.EnableViewState = false;
         Response.Write(tw.ToString());
         Response.End();
     }
 }
Exemple #33
0
    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        // Clear all content output from the buffer stream
        Response.ClearContent();
        // Specify the default file name using "content-disposition" RESPONSE header
        Response.AppendHeader("content-disposition", "attachment; filename=PendingApprovals.xls");
        // Set excel as the HTTP MIME type
        Response.ContentType = "application/excel";
        // Create an instance of stringWriter for writing information to a string
        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        // Create an instance of HtmlTextWriter class for writing markup
        // characters and text to an ASP.NET server control output stream
        HtmlTextWriter htw = new HtmlTextWriter(stringWriter);

        // Set white color as the background color for gridview header row
        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");

        // Set background color of each cell of GridView1 header row
        foreach (TableCell tableCell in GridView1.HeaderRow.Cells)
        {
            tableCell.Style["background-color"] = "#A55129";
        }

        // Set background color of each cell of each data row of GridView1
        foreach (GridViewRow gridViewRow in GridView1.Rows)
        {
            gridViewRow.BackColor = System.Drawing.Color.White;
            foreach (TableCell gridViewRowTableCell in gridViewRow.Cells)
            {
                gridViewRowTableCell.Style["background-color"] = "#FFF7E7";
            }
        }
        GridView1.RenderControl(htw);
        Response.Write(stringWriter.ToString());
        Response.End();
    }
Exemple #34
0
        private void WriteHTMLOutput(Type type, object value, Stream writeStream)
        {
            StreamWriter writer = new StreamWriter(writeStream, Encoding.UTF8);

            writer.WriteLine("<html>");
            writer.WriteLine("<head>");
            writer.WriteLine("  <link href=\"/Content/fhir-html.css\" rel=\"stylesheet\"></link>");
            writer.WriteLine("</head>");
            writer.WriteLine("<body>");
            if (type == typeof(OperationOutcome))
            {
                OperationOutcome oo = (OperationOutcome)value;

                if (oo.Text != null)
                {
                    writer.Write(oo.Text.Div);
                }
            }
            else if (type == typeof(Resource))
            {
                if (value is Bundle)
                {
                    Bundle resource = (Bundle)value;

                    if (resource.SelfLink != null)
                    {
                        writer.WriteLine(String.Format("Searching: {0}<br/>", resource.SelfLink.OriginalString));

                        // Hl7.Fhir.Model.Parameters query = FhirParser.ParseQueryFromUriParameters(collection, parameters);

                        NameValueCollection ps = resource.SelfLink.ParseQueryString();
                        if (ps.AllKeys.Contains(FhirParameter.SORT))
                        {
                            writer.WriteLine(String.Format("    Sort by: {0}<br/>", ps[FhirParameter.SORT]));
                        }
                        if (ps.AllKeys.Contains(FhirParameter.SUMMARY))
                        {
                            writer.WriteLine("    Summary only<br/>");
                        }
                        if (ps.AllKeys.Contains(FhirParameter.COUNT))
                        {
                            writer.WriteLine(String.Format("    Count: {0}<br/>", ps[FhirParameter.COUNT]));
                        }
                        if (ps.AllKeys.Contains(FhirParameter.SNAPSHOT_INDEX))
                        {
                            writer.WriteLine(String.Format("    From RowNum: {0}<br/>", ps[FhirParameter.SNAPSHOT_INDEX]));
                        }
                        if (ps.AllKeys.Contains(FhirParameter.SINCE))
                        {
                            writer.WriteLine(String.Format("    Since: {0}<br/>", ps[FhirParameter.SINCE]));
                        }


                        foreach (var item in ps.AllKeys.Where(k => !k.StartsWith("_")))
                        {
                            if (ModelInfo.SearchParameters.Exists(s => s.Name == item))
                            {
                                writer.WriteLine(String.Format("    {0}: {1}<br/>", item, ps[item]));
                                //var parameters = transportContext..Request.TupledParameters();
                                //int pagesize = Request.GetIntParameter(FhirParameter.COUNT) ?? Const.DEFAULT_PAGE_SIZE;
                                //bool summary = Request.GetBooleanParameter(FhirParameter.SUMMARY) ?? false;
                                //string sortby = Request.GetParameter(FhirParameter.SORT);
                            }
                            else
                            {
                                writer.WriteLine(String.Format("    <i>{0}: {1} (excluded)</i><br/>", item, ps[item]));
                            }
                        }
                    }

                    if (resource.FirstLink != null)
                    {
                        writer.WriteLine(String.Format("First Link: {0}<br/>", resource.FirstLink.OriginalString));
                    }
                    if (resource.PreviousLink != null)
                    {
                        writer.WriteLine(String.Format("Previous Link: {0}<br/>", resource.PreviousLink.OriginalString));
                    }
                    if (resource.NextLink != null)
                    {
                        writer.WriteLine(String.Format("Next Link: {0}<br/>", resource.NextLink.OriginalString));
                    }
                    if (resource.LastLink != null)
                    {
                        writer.WriteLine(String.Format("Last Link: {0}<br/>", resource.LastLink.OriginalString));
                    }

                    // Write the other Bundle Header data
                    writer.WriteLine(String.Format("<span style=\"word-wrap: break-word; display:block;\">Type: {0}, {1} of {2}</span>", resource.Type.ToString(), resource.Entry.Count, resource.Total));

                    foreach (var item in resource.Entry)
                    {
                        //IKey key = item.ExtractKey();

                        writer.WriteLine("<div class=\"item-tile\">");
                        if (item.IsDeleted())
                        {
                            if (item.Request != null)
                            {
                                string id = item.Request.Url;
                                writer.WriteLine(String.Format("<span style=\"word-wrap: break-word; display:block;\">{0}</span>", id));
                            }

                            //if (item.Deleted.Instant.HasValue)
                            //    writer.WriteLine(String.Format("<i>Deleted: {0}</i><br/>", item.Deleted.Instant.Value.ToString()));

                            writer.WriteLine("<hr/>");
                            writer.WriteLine("<b>DELETED</b><br/>");
                        }
                        else if (item.Resource != null)
                        {
                            Key    key       = item.Resource.ExtractKey();
                            string visualurl = key.WithoutBase().ToUriString();
                            string realurl   = key.ToUriString() + "?_format=html";

                            writer.WriteLine(String.Format("<a style=\"word-wrap: break-word; display:block;\" href=\"{0}\">{1}</a>", realurl, visualurl));
                            if (item.Resource.Meta != null && item.Resource.Meta.LastUpdated.HasValue)
                            {
                                writer.WriteLine(String.Format("<i>Modified: {0}</i><br/>", item.Resource.Meta.LastUpdated.Value.ToString()));
                            }
                            writer.WriteLine("<hr/>");

                            if (item.Resource is DomainResource)
                            {
                                if ((item.Resource as DomainResource).Text != null && !string.IsNullOrEmpty((item.Resource as DomainResource).Text.Div))
                                {
                                    writer.Write((item.Resource as DomainResource).Text.Div);
                                }
                                else
                                {
                                    writer.WriteLine(String.Format("Blank Text: {0}<br/>", item.Resource.ExtractKey().ToUriString()));
                                }
                            }
                            else
                            {
                                writer.WriteLine("This is not a domain resource");
                            }
                        }
                        writer.WriteLine("</div>");
                    }
                }
                else
                {
                    DomainResource resource = (DomainResource)value;
                    string         org      = resource.ResourceBase + "/" + resource.ResourceType.ToString() + "/" + resource.Id;
                    // TODO: This is probably a bug in the service (Id is null can throw ResourceIdentity == null
                    // reference ResourceIdentity : org = resource.ResourceIdentity().OriginalString;
                    writer.WriteLine(String.Format("Retrieved: {0}<hr/>", org));

                    string text = (resource.Text != null) ? resource.Text.Div : null;
                    writer.Write(text);
                    writer.WriteLine("<hr/>");

                    SummaryType summary = requestMessage.RequestSummary();
                    string      xml     = FhirSerializer.SerializeResourceToXml(resource, summary);
                    System.Xml.XPath.XPathDocument xmlDoc = new System.Xml.XPath.XPathDocument(new StringReader(xml));

                    // And we also need an output writer
                    System.IO.TextWriter output = new System.IO.StringWriter(new System.Text.StringBuilder());

                    // Now for a little magic
                    // Create XML Reader with style-sheet
                    System.Xml.XmlReader stylesheetReader = System.Xml.XmlReader.Create(new StringReader(Resources.RenderXMLasHTML));

                    System.Xml.Xsl.XslCompiledTransform xslTransform = new System.Xml.Xsl.XslCompiledTransform();
                    xslTransform.Load(stylesheetReader);
                    xslTransform.Transform(xmlDoc, null, output);

                    writer.WriteLine(output.ToString());
                }
            }

            writer.WriteLine("</body>");
            writer.WriteLine("</html>");
            writer.Flush();
        }
Exemple #35
0
        private string ConvertMarkdownToHTML(List <MarkdownFile> files)
        {
            Log("Converting Markdown to HTML");
            StringBuilder sb = new StringBuilder();



            for (var i = 0; i < files.Count; i++)
            {
                var mf   = files[i];
                var file = new FileInfo(files[i].AbsolutePath);

                Log($"parsing file {file.Name}", LogLevel.Debug);
                var htmlfile = file.FullName.Replace(".md", ".html");

                if (!File.Exists(file.FullName))
                {
                    Log($"File {file.FullName} specified in the order file was not found and will be skipped!", LogLevel.Error);
                    continue;
                }

                var md = File.ReadAllText(file.FullName);

                // remove scalings from image links
                var regexImageScalings = @"\(((.[^\)]*?(png|jpg|jpeg))( =((\d+).*x(\d+).*)))\)";
                md = Regex.Replace(md, regexImageScalings, @"($2){width=$6 height=$7}");

                //setup the markdown pipeline to support tables
                var pipeline = new MarkdownPipelineBuilder()
                               .UsePipeTables()
                               .UseEmojiAndSmiley()
                               .UseAdvancedExtensions()
                               .Build();

                //parse the markdown document so we can alter it later
                var document = (MarkdownObject)Markdown.Parse(md, pipeline);

                //adjust the links
                CorrectLinksAndImages(document, file, mf);

                string html    = null;
                var    builder = new StringBuilder();
                using (var writer = new System.IO.StringWriter(builder))
                {
                    // write the HTML output
                    var renderer = new HtmlRenderer(writer);
                    pipeline.Setup(renderer);
                    renderer.Render(document);
                }
                html = builder.ToString();

                //add html anchor
                var anchorPath = file.FullName.Substring(_path.Length);
                anchorPath = anchorPath.Replace("\\", "");
                anchorPath = anchorPath.ToLower();
                anchorPath = anchorPath.Replace(".md", "");

                var relativePath = file.FullName.Substring(_path.Length);

                var anchor = $"<a id=\"{anchorPath}\">&nbsp;</a>";

                Log($"\tAnchor: {anchorPath}");

                html = anchor + html;

                if (_options.PathToHeading)
                {
                    var filename = file.Name;
                    filename = HttpUtility.UrlDecode(relativePath);
                    var heading = $"<b>{filename}</b>";
                    html = heading + html;
                }

                if (_options.Heading)
                {
                    var filename = file.Name.Replace(".md", "");
                    filename = HttpUtility.UrlDecode(filename);
                    var filenameEscapes = new Dictionary <string, string>
                    {
                        { "%3A", ":" },
                        { "%3C", "<" },
                        { "%3E", ">" },
                        { "%2A", "*" },
                        { "%3F", "?" },
                        { "%7C", "|" },
                        { "%2D", "-" },
                        { "%22", "\"" },
                        { "-", " " }
                    };

                    var title = new StringBuilder(filename);
                    foreach (var filenameEscape in filenameEscapes)
                    {
                        title.Replace(filenameEscape.Key, filenameEscape.Value);
                    }

                    var heading = $"<h1>{title.ToString()}</h1>";
                    html = heading + html;
                }

                if (_options.BreakPage)
                {
                    //if not one the last page
                    if (i + 1 < files.Count)
                    {
                        Log("Adding new page to PDF");
                        html = "<div style='page-break-after: always;'>" + html + "</div>";
                    }
                }

                if (_options.Debug)
                {
                    Log($"html:\n{html}");
                }
                sb.Append(html);
            }

            var result = sb.ToString();


            return(result);
        }
Exemple #36
0
        private static void GenerateFsEnumsFile(List <FsEventInfo> fsEventList, string fileName)
        {
            System.IO.StringWriter baseTextWriter = new System.IO.StringWriter();
            System.CodeDom.Compiler.IndentedTextWriter indentWriter = new IndentedTextWriter(baseTextWriter, "    ");

            // Sets the indentation level.
            indentWriter.Indent = 0;
            indentWriter.WriteLine($"// Generated by FsEnumGenerator on {DateTime.Now:s}");
            indentWriter.WriteLine("namespace CTrue.FsConnect");
            indentWriter.WriteLine("{");
            indentWriter.Indent++;

            indentWriter.WriteLine("/// <summary>");
            indentWriter.WriteLine("/// The <see cref=\"FsEventNameId\"/> enum contains all known events.");
            indentWriter.WriteLine("/// </summary>");
            indentWriter.WriteLine("/// <remarks>");
            indentWriter.WriteLine("/// Note: This list is based on known legacy events. Not all events are supported by Microsoft Flight Simulator 2020.");
            indentWriter.WriteLine("/// </remarks>");
            indentWriter.WriteLine("public enum FsEventNameId");
            indentWriter.WriteLine("{");
            indentWriter.Indent++;

            foreach (var fsEvent in fsEventList)
            {
                indentWriter.WriteLine($"/// <summary>");
                indentWriter.WriteLine($"/// {fsEvent.Description}");
                indentWriter.WriteLine($"/// </summary>");
                indentWriter.WriteLine($"{fsEvent.Id},");
            }

            indentWriter.Indent--;
            indentWriter.WriteLine("};");

            indentWriter.WriteLine();

            indentWriter.WriteLine($"/// <summary>");
            indentWriter.WriteLine($"/// Provides lookup of FsEventNameId enums to event names that can be registered in MSFS.");
            indentWriter.WriteLine($"/// </summary>");
            indentWriter.WriteLine("internal static class FsEventNameLookup");
            indentWriter.WriteLine("{");
            indentWriter.Indent++;

            indentWriter.WriteLine("private static string[] _fsEventName = new string[] {");
            indentWriter.Indent++;

            foreach (var fsEvent in fsEventList)
            {
                indentWriter.WriteLine($"\"{fsEvent.Name}\",");
            }

            indentWriter.Indent--;
            indentWriter.WriteLine("};");

            indentWriter.WriteLine();
            indentWriter.WriteLine($"/// <summary>");
            indentWriter.WriteLine($"/// Returns an event name for a given event name id.");
            indentWriter.WriteLine($"/// </summary>");
            indentWriter.WriteLine($"/// <param name=\"eventNameId\">An <see cref=\"FsEventNameId\"/> representing a MSFS event.</param>");
            indentWriter.WriteLine("public static string GetFsEventName(FsEventNameId eventNameId)");
            indentWriter.WriteLine("{");
            indentWriter.Indent++;

            indentWriter.WriteLine("return _fsEventName[(int)eventNameId];");

            indentWriter.Indent--;
            indentWriter.WriteLine("}");

            indentWriter.Indent--;
            indentWriter.WriteLine("}");

            indentWriter.Indent--;
            indentWriter.WriteLine("}");

            File.WriteAllText(fileName, baseTextWriter.ToString());
        }
Exemple #37
0
        /// <summary>
        /// Grava XML com algumas informações do aplicativo, dentre elas os dados do certificado digital configurado nos parâmetros, versão, última modificação, etc.
        /// </summary>
        /// <param name="sArquivo">Pasta e nome do arquivo XML a ser gravado com as informações</param>
        public void GravarXMLInformacoes(string sArquivo, bool somenteConfigGeral)
        {
            int emp = Empresas.FindEmpresaByThread();

            string cStat   = "1";
            string xMotivo = "Consulta efetuada com sucesso";

            //Ler os dados do certificado digital
            string sSubject = "";
            string sValIni  = "";
            string sValFin  = "";

            if (!somenteConfigGeral)
            {
                CertificadoDigital cert = new CertificadoDigital();

                if (Empresas.Configuracoes[emp].UsaCertificado)
                {
                    if (cert.PrepInfCertificado(Empresas.Configuracoes[emp]))
                    {
                        sSubject = cert.sSubject;
                        sValIni  = cert.dValidadeInicial.ToString("dd/MM/yyyy HH:mm:ss");
                        sValFin  = cert.dValidadeFinal.ToString("dd/MM/yyyy HH:mm:ss");
                    }
                    else
                    {
                        //if (!Empresas.Configuracoes[emp].UsaCertificado)
                        //    xMotivo = "Empresa sem certificado digital informado e/ou não necessário";
                        //else
                        {
                            cStat   = "2";
                            xMotivo = "Certificado digital não foi localizado";
                        }
                    }
                }
                else
                {
                    xMotivo = "Empresa sem certificado digital informado e/ou não necessário";
                }
            }

            //danasa 22/7/2011
            //pega a data da ultima modificacao do 'uninfe.exe' diretamente porque pode ser que esteja sendo executado o servico
            //então, precisamos dos dados do uninfe.exe e não do servico
            string dtUltModif;
            URLws  item;
            string tipo = "";

            dtUltModif = File.GetLastWriteTime(Propriedade.NomeAplicacao + ".exe").ToString("dd/MM/yyyy - HH:mm:ss");

            //Gravar o XML com as informações do aplicativo
            try
            {
                bool   isXml = false;
                object oXmlGravar;

                if (Path.GetExtension(sArquivo).ToLower() == ".txt")
                {
                    oXmlGravar = new System.IO.StringWriter();
                }
                else
                {
                    isXml = true;

                    XmlWriterSettings oSettings = new XmlWriterSettings();
                    UTF8Encoding      c         = new UTF8Encoding(true);

                    //Para começar, vamos criar um XmlWriterSettings para configurar nosso XML
                    oSettings.Encoding            = c;
                    oSettings.Indent              = true;
                    oSettings.IndentChars         = "";
                    oSettings.NewLineOnAttributes = false;
                    oSettings.OmitXmlDeclaration  = false;

                    //Agora vamos criar um XML Writer
                    oXmlGravar = XmlWriter.Create(sArquivo, oSettings);
                }
                //Abrir o XML
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartDocument();
                    ((XmlWriter)oXmlGravar).WriteStartElement("retConsInf");
                }
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.cStat.ToString(), cStat);
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.xMotivo.ToString(), xMotivo);

                if (!somenteConfigGeral)
                {
                    if (Empresas.Configuracoes[emp].UsaCertificado)
                    {
                        //Dados do certificado digital
                        if (isXml)
                        {
                            ((XmlWriter)oXmlGravar).WriteStartElement("DadosCertificado");
                        }
                        Functions.GravaTxtXml(oXmlGravar, "sSubject", sSubject);
                        Functions.GravaTxtXml(oXmlGravar, "dValIni", sValIni);
                        Functions.GravaTxtXml(oXmlGravar, "dValFin", sValFin);
                        if (isXml)
                        {
                            ((XmlWriter)oXmlGravar).WriteEndElement();        //DadosCertificado
                        }
                    }
                }

                //Dados gerais do Aplicativo
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement("DadosUniNfe");
                }
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.versao.ToString(), Propriedade.Versao);
                Functions.GravaTxtXml(oXmlGravar, "dUltModif", dtUltModif);
                Functions.GravaTxtXml(oXmlGravar, "PastaExecutavel", Propriedade.PastaExecutavel);
                Functions.GravaTxtXml(oXmlGravar, "NomeComputador", Environment.MachineName);
                Functions.GravaTxtXml(oXmlGravar, "UsuarioComputador", Environment.UserName);
                //danasa 22/7/2011
                Functions.GravaTxtXml(oXmlGravar, "ExecutandoPeloServico", Propriedade.ServicoRodando.ToString());
                Functions.GravaTxtXml(oXmlGravar, "ConexaoInternet", Functions.IsConnectedToInternet().ToString());

                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement();        //DadosUniNfe
                }
                //Dados das configurações do aplicativo
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement(NFeStrConstants.nfe_configuracoes);
                }
                //Functions.GravaTxtXml(oXmlGravar, NFe.Components.NFeStrConstants.DiretorioSalvarComo, Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString());

                if (!somenteConfigGeral)
                {
                    bool hasFTP = false;
                    foreach (var pT in Empresas.Configuracoes[emp].GetType().GetProperties())
                    {
                        if (pT.CanWrite)
                        {
                            if (pT.Name.Equals("diretorioSalvarComo"))
                            {
                                continue;
                            }

                            if (isXml)
                            {
                                if (!hasFTP && pT.Name.StartsWith("FTP"))
                                {
                                    ((XmlWriter)oXmlGravar).WriteStartElement("FTP");
                                    hasFTP = true;
                                }
                                else
                                if (hasFTP && !pT.Name.StartsWith("FTP"))
                                {
                                    ((XmlWriter)oXmlGravar).WriteEndElement();
                                    hasFTP = false;
                                }
                            }
                            object v = pT.GetValue(Empresas.Configuracoes[emp], null);
                            NFe.Components.Functions.GravaTxtXml(oXmlGravar, pT.Name, v == null ? "" : v.ToString());
                        }
                    }
                    if (hasFTP && isXml)
                    {
                        ((XmlWriter)oXmlGravar).WriteEndElement();
                    }

                    ///
                    /// o ERP poderá verificar se determinado servico está definido no UniNFe
                    ///
                    foreach (webServices list in WebServiceProxy.webServicesList)
                    {
                        if (list.ID == Empresas.Configuracoes[emp].UnidadeFederativaCodigo)
                        {
                            if (isXml)
                            {
                                ((XmlWriter)oXmlGravar).WriteStartElement(list.UF);
                            }
                            if (Empresas.Configuracoes[emp].AmbienteCodigo == 2)
                            {
                                item = list.LocalHomologacao;
                                if (isXml)
                                {
                                    ((XmlWriter)oXmlGravar).WriteStartElement("Homologacao");
                                }
                                else
                                {
                                    tipo = list.UF + ".Homologacao.";
                                }
                            }
                            else
                            {
                                item = list.LocalProducao;
                                if (isXml)
                                {
                                    ((XmlWriter)oXmlGravar).WriteStartElement("Producao");
                                }
                                else
                                {
                                    tipo = list.UF + ".Producao.";
                                }
                            }
                            switch (Empresas.Configuracoes[emp].Servico)
                            {
                            case TipoAplicativo.Nfse:
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeCancelar.ToString(), (!string.IsNullOrEmpty(item.CancelarNfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultar.ToString(), (!string.IsNullOrEmpty(item.ConsultarNfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultarLoteRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarLoteRps)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultarPorRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarNfsePorRps)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultarNFSePDF.ToString(), (!string.IsNullOrEmpty(item.ConsultarNFSePDF)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultarNFSePNG.ToString(), (!string.IsNullOrEmpty(item.ConsultarNFSePNG)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultarURL.ToString(), (!string.IsNullOrEmpty(item.ConsultarURLNfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultarSituacaoLoteRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarSituacaoLoteRps)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeRecepcionarLoteRps.ToString(), (!string.IsNullOrEmpty(item.RecepcionarLoteRps)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeInutilizarNFSe.ToString(), (!string.IsNullOrEmpty(item.InutilizarNFSe)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeObterNotaFiscal.ToString(), (!string.IsNullOrEmpty(item.ObterNotaFiscal)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeConsultaSequenciaLoteNotaRPS.ToString(), (!string.IsNullOrEmpty(item.ConsultaSequenciaLoteNotaRPS)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.NFSeSubstituirNfse.ToString(), (!string.IsNullOrEmpty(item.SubstituirNfse)).ToString());
                                break;

                            default:
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.NFCe ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Nfe ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeConsulta", (!string.IsNullOrEmpty(item.NFeConsulta)).ToString());
                                    //Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRecepcao", (!string.IsNullOrEmpty(item.NFeRecepcao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRecepcaoEvento", (!string.IsNullOrEmpty(item.NFeRecepcaoEvento)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeConsultaCadastro", (!string.IsNullOrEmpty(item.NFeConsultaCadastro)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeInutilizacao", (!string.IsNullOrEmpty(item.NFeInutilizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeManifDest", (!string.IsNullOrEmpty(item.NFeManifDest)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeStatusServico", (!string.IsNullOrEmpty(item.NFeStatusServico)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeAutorizacao", (!string.IsNullOrEmpty(item.NFeAutorizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRetAutorizacao", (!string.IsNullOrEmpty(item.NFeRetAutorizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "DFeRecepcao", (!string.IsNullOrEmpty(item.DFeRecepcao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.LMCAutorizacao.ToString(), (!string.IsNullOrEmpty(item.LMCAutorizacao)).ToString());
                                }
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.MDFe ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeRecepcao", (!string.IsNullOrEmpty(item.MDFeRecepcao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeRecepcaoSinc", (!string.IsNullOrEmpty(item.MDFeRecepcaoSinc)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeRetRecepcao", (!string.IsNullOrEmpty(item.MDFeRetRecepcao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeConsulta", (!string.IsNullOrEmpty(item.MDFeConsulta)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeStatusServico", (!string.IsNullOrEmpty(item.MDFeStatusServico)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.MDFeRecepcaoEvento.ToString(), (!string.IsNullOrEmpty(item.MDFeRecepcaoEvento)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.MDFeConsultaNaoEncerrado.ToString(), (!string.IsNullOrEmpty(item.MDFeNaoEncerrado)).ToString());
                                }
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.Cte ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.CTeRecepcaoEvento.ToString(), (!string.IsNullOrEmpty(item.CTeRecepcaoEvento)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "CTeConsultaCadastro", (!string.IsNullOrEmpty(item.CTeConsultaCadastro)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "CTeInutilizacao", (!string.IsNullOrEmpty(item.CTeInutilizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "CTeStatusServico", (!string.IsNullOrEmpty(item.CTeStatusServico)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "CTeDistribuicaoDFe", (!string.IsNullOrEmpty(item.CTeDistribuicaoDFe)).ToString());
                                }
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.EFDReinf ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.EFDReinfeSocial ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.RecepcaoLoteReinf.ToString(), (!string.IsNullOrEmpty(item.RecepcaoLoteReinf)).ToString());
                                }
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.eSocial ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.ConsultarLoteeSocial.ToString(), (!string.IsNullOrEmpty(item.ConsultarLoteeSocial)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.RecepcaoLoteeSocial.ToString(), (!string.IsNullOrEmpty(item.RecepcaoLoteeSocial)).ToString());
                                }
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.CancelarCfse.ToString(), (!string.IsNullOrEmpty(item.CancelarCfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.ConfigurarTerminalCfse.ToString(), (!string.IsNullOrEmpty(item.ConfigurarTerminalCfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.ConsultarCfse.ToString(), (!string.IsNullOrEmpty(item.ConsultarCfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.ConsultarDadosCadastroCfse.ToString(), (!string.IsNullOrEmpty(item.ConsultarDadosCadastroCfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.ConsultarLoteCfse.ToString(), (!string.IsNullOrEmpty(item.ConsultarLoteCfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.EnviarInformeManutencaoCfse.ToString(), (!string.IsNullOrEmpty(item.EnviarInformeManutencaoCfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.InformeTrasmissaoSemMovimentoCfse.ToString(), (!string.IsNullOrEmpty(item.InformeTrasmissaoSemMovimentoCfse)).ToString());
                                Functions.GravaTxtXml(oXmlGravar, tipo + Servicos.RecepcionarLoteCfse.ToString(), (!string.IsNullOrEmpty(item.RecepcionarLoteCfse)).ToString());

                                break;
                            }

                            if (isXml)
                            {
                                ((XmlWriter)oXmlGravar).WriteEndElement();   //Ambiente
                                ((XmlWriter)oXmlGravar).WriteEndElement();   //list.UF
                            }
                        }
                    }
                }

                //Finalizar o XML
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement(); //nfe_configuracoes
                    ((XmlWriter)oXmlGravar).WriteEndElement(); //retConsInf
                    ((XmlWriter)oXmlGravar).WriteEndDocument();
                    ((XmlWriter)oXmlGravar).Flush();
                    ((XmlWriter)oXmlGravar).Close();
                }
                else
                {
                    ((StringWriter)oXmlGravar).Flush();
                    File.WriteAllText(sArquivo, ((StringWriter)oXmlGravar).GetStringBuilder().ToString());
                    ((StringWriter)oXmlGravar).Close();
                }
            }
            catch (Exception ex)
            {
                Functions.DeletarArquivo(sArquivo);
                ///
                /// danasa 8-2009
                ///
                Auxiliar oAux = new Auxiliar();
                oAux.GravarArqErroERP(Path.GetFileNameWithoutExtension(sArquivo) + ".err", ex.Message);
            }
        }
        private void RunTests()
        {
            var serverAddresses = Intent.GetStringExtra(TestRunner.ParadoxServerIp);
            var serverPort      = Int32.Parse(Intent.GetStringExtra(TestRunner.ParadoxServerPort) ?? "8080");
            var buildNumber     = Int32.Parse(Intent.GetStringExtra(TestRunner.ParadoxBuildNumber) ?? "-1");
            var branchName      = Intent.GetStringExtra(TestRunner.ParadoxBranchName) ?? "";

            // Remove extra (if activity is recreated)
            Intent.RemoveExtra(TestRunner.ParadoxServerIp);
            Intent.RemoveExtra(TestRunner.ParadoxServerPort);
            Intent.RemoveExtra(TestRunner.ParadoxBuildNumber);
            Intent.RemoveExtra(TestRunner.ParadoxBranchName);


            Logger.Info(@"*******************************************************************************************************************************");
            Logger.Info(@"date: " + DateTime.Now);
            Logger.Info(@"server addresses: " + serverAddresses);
            Logger.Info(@"port: " + serverPort);
            Logger.Info(@"*******************************************************************************************************************************");

            // Connect to server right away to let it know we're alive
            var client = Connect(serverAddresses, serverPort);

            // Update build number (if available)
            ImageTester.ImageTestResultConnection.BuildNumber = buildNumber;
            ImageTester.ImageTestResultConnection.BranchName  = branchName ?? "";

            // Connect beforehand to image tester, so that first test timing is not affected by initial connection
            try
            {
                ImageTester.Connect();
            }
            catch (Exception e)
            {
                Logger.Error("Error connecting to image tester server: {0}", e);
            }

            // Start unit test
            var cachePath = CacheDir.AbsolutePath;
            var timeNow   = DateTime.Now;

            // Generate result file name
            var resultFile = Path.Combine(cachePath, string.Format("TestResult-{0:yyyy-MM-dd_hh-mm-ss-tt}.xml", timeNow));

            Logger.Debug(@"Execute tests");

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

            new TextUI(stringWriter).Execute(new [] { "-format:nunit2", string.Format("-result:{0}", resultFile) });

            Logger.Debug(@"Execute tests done");

            // Read result file
            var result = File.ReadAllText(resultFile);

            // Delete result file
            File.Delete(resultFile);

            // Display some useful info
            var output = stringBuilder.ToString();

            Console.WriteLine(output);

            Logger.Debug(@"Sending results to server");

            // Send back result
            var binaryWriter = new BinaryWriter(client.GetStream());

            binaryWriter.Write(output);
            binaryWriter.Write(result);

            Logger.Debug(@"Close connection");

            ImageTester.Disconnect();

            client.Close();

            Finish();
        }
Exemple #39
0
        List <Result> handleXML(string text)
        {
            try {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(text);
                string fmt = null, zip = null;
                {
                    StringWriter sw = new System.IO.StringWriter();
                    using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw)) {
                        writer.Indentation = 4;  // the Indentation
                        writer.Formatting  = System.Xml.Formatting.Indented;
                        doc.WriteContentTo(writer);
                        writer.Close();
                    }
                    fmt = sw.ToString();
                }

                {
                    StringWriter sw = new StringWriter();
                    using (System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(sw)) {
                        doc.WriteContentTo(writer);
                        writer.Close();
                    }
                    zip = sw.ToString();
                }

                Result fmtItem = new Result()
                {
                    Title    = "复制格式化后的XML文本",
                    SubTitle = abbr(fmt),
                    IcoPath  = "Images\\format.png",
                    Action   = e => {
                        Clipboard.SetDataObject(fmt);
                        return(true);
                    }
                };

                Result zipItem = new Result()
                {
                    Title    = "复制压缩后的XML文本",
                    SubTitle = abbr(zip),
                    IcoPath  = "Images\\zip.png",
                    Action   = e => {
                        Clipboard.SetDataObject(zip);
                        return(true);
                    }
                };

                Result viewItem = new Result()
                {
                    Title   = "在浏览器中查看XML结构",
                    IcoPath = "Images\\browser.png",
                    Action  = e => {
                        File.WriteAllText(Path.Combine(pluginDir, XMLJsFile), "var xmlData=`" + tobs64(fmt) + "`");
                        Process.Start(Path.Combine(pluginDir, XMLHtmlFile));
                        return(true);
                    }
                };
                return(new List <Result> {
                    fmtItem, zipItem, viewItem
                });
            } catch {
                return(null);
            }
        }
    protected void BtnExcelExport_Click(object sender, EventArgs e)
    {
        try
        {
            DataSet dscheck = sqlobj.ExecuteSP("SP_CheckNotUpdatedItems",
                                               new SqlParameter()
            {
                ParameterName = "@PSCode", SqlDbType = SqlDbType.NVarChar, Value = Session["PSCode"].ToString()
            });

            int icount = 0;


            if (dscheck.Tables[0].Rows.Count > 0)
            {
                icount = Convert.ToInt32(dscheck.Tables[0].Rows[0]["Count"].ToString());
            }

            dscheck.Dispose();


            if (icount == 0)
            {
                DataSet dsExporttoexcel = sqlobj.ExecuteSP("SP_GetExcelforPhysicalStock",
                                                           new SqlParameter()
                {
                    ParameterName = "@PSCode", SqlDbType = SqlDbType.NVarChar, Value = Session["PSCode"].ToString()
                });

                if (dsExporttoexcel.Tables[0].Rows.Count > 0)
                {
                    DataTable dt = dsExporttoexcel.Tables[0];

                    string filename = "Physical Stock Verification _ " + DateTime.Today.ToString("dd-MM-yyyy") + ".xls";
                    System.IO.StringWriter       tw = new System.IO.StringWriter();
                    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                    hw.Write("<table style='width:100%'><tr><td colspan='10'>Physical Stock Verification Update Sheet.</td></tr>");
                    hw.Write("<tr><td colspan='10'>Use this as a working sheet to post stock transactions.</td></tr>");
                    hw.Write("<tr><td colspan='10'>BatchCode:" + Session["PSCode"].ToString() + " Date:" + Session["BatchDate"].ToString() + "&nbsp;&nbsp;&nbsp;&nbsp&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp&nbsp&nbsp;&nbsp;&nbsp;&nbsp;Printed On:" + DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + "</td></tr></table>");

                    DataGrid dgGrid = new DataGrid();
                    dgGrid.DataSource = dt;
                    dgGrid.DataBind();
                    dgGrid.RenderControl(hw);

                    Response.ContentType = "application/vnd.ms-excel";
                    Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
                    Response.Write(tw.ToString());
                    Response.End();
                }

                dsExporttoexcel.Dispose();
            }
            else
            {
                WebMsgBox.Show("Please check! Have you update all items in this batch.");
            }
        }
        catch (Exception ex)
        {
        }
    }
Exemple #41
0
        protected void DownWord()
        {
            string wordTemplate = "";
            var    model        = new Eyousoft_yhq.BLL.Product().GetModel(Utils.GetQueryStringValue("routeid"));

            if (model != null)
            {
                #region 文本内容
                wordTemplate = @"
                <html>
                <head>
                    <title>打印预览</title>
                    <style type=""text/css"">
                    body {{color:#000000;font-size:12px;font-family:""宋体"";background:#fff; margin:0px;}}
                    img {{border: thin none;}}
                    table {{border-collapse:collapse;width:790px;}}
                    td {{font-size: 12px; line-height:18px;color: #000000;  }}	
                    .headertitle {{font-family:""黑体""; font-size:25px; line-height:120%; font-weight:bold;}}
                    </style>
                </head>
                <body>
                    <div id=""divAllHtml"" style=""width: 760px; margin: 0 auto;"">
        <div id=""divContent"">
            <table width=""696"" border=""0"" align=""center"" cellpadding=""0"" cellspacing=""0"">
                <tr>
                    <td height=""40"" align=""center"">
                        <b class=""font24"">
                            {0}</b>
                    </td>
                </tr>
            </table>
            <table width=""696"" border=""0"" align=""center"" cellpadding=""0"" cellspacing=""0"" runat=""server""
                id=""TPlanFeature"" class=""borderline_2"">
                <tr>
                    <td height=""30"" class=""small_title"">
                        <b class=""font16"">产品介绍</b>
                    </td>
                </tr>
                <tr>
                    <td class=""td_text"">
                        {1}
                    </td>
                </tr>
            </table>
            <table width=""696"" cellspacing=""0"" cellpadding=""0"" border=""0"" align=""center"" id=""TAll""
                runat=""server"" class=""borderline_2"">
                <tbody>
                    <tr>
                        <td height=""30"" class=""small_title"">
                            <b class=""font16"">参考行程</b>
                        </td>
                    </tr>
                    <tr>
                        <td class=""td_text"">
                            {2}
                        </td>
                    </tr>
                </tbody>
            </table>
            <div id=""TOption"" runat=""server"">
                <table width=""696"" cellspacing=""0"" cellpadding=""0"" border=""0"" align=""center"" class=""list_2"">
                    <tbody>
                        <tr>
                            <td height=""30"" class=""small_title"">
                                <b class=""font16"">出团须知</b>
                            </td>
                        </tr>
                        <tr>
                            <td class=""td_text"">
                               {3}
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div runat=""server"" id=""TPlanService"">
                <table width=""696"" border=""0"" align=""center"" cellpadding=""0"" cellspacing=""0"" runat=""server""
                    id=""TService"" class=""borderline_2"">
                    <tr>
                        <td height=""30"" class=""small_title"">
                            <b class=""font16"">价格标准</b>
                        </td>
                    </tr>
                    <tr>
                        <td class=""td_text borderline_2"">
                           市场价格:{4},会员价格:{5}
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>
                </body>
                </html>";
                #endregion

                HttpContext.Current.Response.Clear();
                string saveFileName       = HttpUtility.UrlEncode(DateTime.Now.ToString("yyyyMMddhhssffff") + ".doc", System.Text.Encoding.Default);
                System.IO.StringWriter tw = new System.IO.StringWriter();

                tw.Write(string.Format(wordTemplate, model.ProductName, model.ProductDis, model.TourDis, model.SendTourKnow, model.MarketPrice.ToString("C0"), model.AppPrice.ToString("C0")).ToString());
                WriteFile(tw.ToString(), saveFileName);
                FileInfo Inf = new FileInfo(Server.MapPath(@"TemFile/" + saveFileName));
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + saveFileName);
                HttpContext.Current.Response.Charset         = "GB2312";
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
                HttpContext.Current.Response.ContentType     = "application/ms-word ";
                Page.EnableViewState = false;

                HttpContext.Current.Response.WriteFile(Inf.FullName);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }
Exemple #42
0
    //protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.DataRow)
    //    {
    //    }
    //}

    //protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.Pager)
    //    {
    //        PresentationUtils.SetPagerButtonStates(GridView1, e.Row, this);
    //    }
    //}

    public void ExportToExcel(string filename, DataSet ds, int types)
    {
        if (ds != null)
        {
            DataTable dt = ds.Tables[0];

            if (dt.Rows.Count > 0)
            {
                System.IO.StringWriter       tw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                DataGrid dgGrid = new DataGrid();
                dgGrid.DataSource = dt;
                dgGrid.DataBind();
                //rptData.DataSource = ds;
                //rptData.DataBind();
                //Get the HTML for the control.
                dgGrid.RenderControl(hw);
                //Write the HTML back to the browser.
                Response.ContentType = "application/vnd.ms-excel";
                Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
                this.EnableViewState = false;
                Response.Write(tw.ToString());
                Response.End();
            }
            else
            {
                if (types == 1)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 2)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Missing Ledger in sales');", true);
                    return;
                }
                else if (types == 3)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Missing Ledger in Purchase');", true);
                    return;
                }
                else if (types == 4)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 5)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 6)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 7)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 8)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 9)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 10)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 11)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 12)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 13)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 14)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 15)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 16)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 17)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
                else if (types == 18)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "alert('No Data Found in Stock Consistency Check');", true);
                    return;
                }
            }
        }
    }
Exemple #43
0
        static Program()
        {
            //this needs to be done before the warnings/errors show up
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            //http://www.codeproject.com/Articles/310675/AppDomain-AssemblyResolve-Event-Tips
#if WINDOWS
            //try loading libraries we know we'll need
            //something in the winforms, etc. code below will cause .net to popup a missing msvcr100.dll in case that one's missing
            //but oddly it lets us proceed and we'll then catch it here
            var  d3dx9 = Win32.LoadLibrary("d3dx9_43.dll");
            var  vc2015 = Win32.LoadLibrary("vcruntime140.dll");
            var  vc2012 = Win32.LoadLibrary("msvcr120.dll");            //TODO - check version?
            var  vc2010 = Win32.LoadLibrary("msvcr100.dll");            //TODO - check version?
            var  vc2010p = Win32.LoadLibrary("msvcp100.dll");
            bool fail = false, warn = false;
            warn |= d3dx9 == IntPtr.Zero;
            fail |= vc2015 == IntPtr.Zero;
            fail |= vc2010 == IntPtr.Zero;
            fail |= vc2012 == IntPtr.Zero;
            fail |= vc2010p == IntPtr.Zero;
            if (fail || warn)
            {
                var sw = new System.IO.StringWriter();
                sw.WriteLine("[ OK ] .Net 4.6.1 (You couldn't even get here without it)");
                sw.WriteLine("[{0}] Direct3d 9", d3dx9 == IntPtr.Zero ? "FAIL" : " OK ");
                sw.WriteLine("[{0}] Visual C++ 2010 SP1 Runtime", (vc2010 == IntPtr.Zero || vc2010p == IntPtr.Zero) ? "FAIL" : " OK ");
                sw.WriteLine("[{0}] Visual C++ 2012 Runtime", (vc2012 == IntPtr.Zero) ? "FAIL" : " OK ");
                sw.WriteLine("[{0}] Visual C++ 2015 Runtime", (vc2015 == IntPtr.Zero) ? "FAIL" : " OK ");
                var str = sw.ToString();
                var box = new BizHawk.Client.EmuHawk.CustomControls.PrereqsAlert(!fail);
                box.textBox1.Text = str;
                box.ShowDialog();
                if (!fail)
                {
                }
                else
                {
                    System.Diagnostics.Process.GetCurrentProcess().Kill();
                }
            }

            Win32.FreeLibrary(d3dx9);
            Win32.FreeLibrary(vc2015);
            Win32.FreeLibrary(vc2012);
            Win32.FreeLibrary(vc2010);
            Win32.FreeLibrary(vc2010p);

            // this will look in subdirectory "dll" to load pinvoked stuff
            string dllDir = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "dll");
            SetDllDirectory(dllDir);

            //in case assembly resolution fails, such as if we moved them into the dll subdiretory, this event handler can reroute to them
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            //but before we even try doing that, whack the MOTW from everything in that directory (thats a dll)
            //otherwise, some people will have crashes at boot-up due to .net security disliking MOTW.
            //some people are getting MOTW through a combination of browser used to download bizhawk, and program used to dearchive it
            WhackAllMOTW(dllDir);

            //We need to do it here too... otherwise people get exceptions when externaltools we distribute try to startup
#endif
        }
Exemple #44
0
        protected override void Render(HtmlTextWriter writer)
        {
            System.IO.StringWriter str = new System.IO.StringWriter();
            HtmlTextWriter         wrt = new HtmlTextWriter(str);

            // render html
            base.Render(wrt); //CAPTURE THE CURRENT PAGE HTML SOURCE AS STRING
            //wrt.Close();

            string html = str.ToString();

            /*if(IsAjaxRequest)
             * {
             *  writer.Write(html);
             *  return;
             * }*/

            /*if (CurrentMediaDetail != null && !html.Contains("<html"))
             * {
             *  var masterPage = CurrentMediaDetail.GetMasterPage();
             *
             *  if (masterPage != null)
             *  {
             *      if (masterPage.UseLayout)
             *      {
             *          html = masterPage.Layout.Replace("{PageContent}", html);
             *          html = LoaderHelper.RenderPage(this, html);
             *      }
             *  }
             * }*/

            /*if (!IsInAdminSection)
             * {
             *  if ((AppSettings.EnableMobileDetection) && (FrontEndBasePage.IsMobile))
             *      html = HandleMobileLayout(html);
             *  else
             *      html = HandleNonMobileLayout(html);
             * }*/

            if (!IsPostBack)
            {
                if (AppSettings.MinifyOutput)
                {
                    html = StringHelper.StripExtraSpacesBetweenMarkup(html);
                }
            }

            /*if (CurrentMediaDetail != null)
             * {
             *  if (!IsAjaxRequest && !IsInAdminSection && Request["VisualLayoutEditor"] != "true")
             *  {
             *      html = MediaDetailsMapper.ParseSpecialTags(CurrentMediaDetail, html);
             *  }
             * }*/

            /*if (!IsInAdminSection)
             * {
             *  HtmlNode.ElementsFlags.Remove("form");
             *  document = new HtmlAgilityPack.HtmlDocument();
             *  document.LoadHtml(html);
             *
             *  var forms = document.DocumentNode.SelectNodes("//form");
             *
             *  if (forms != null && forms.Count > 1)
             *  {
             *      forms.RemoveAt(0);
             *      foreach (HtmlNode item in forms)
             *      {
             *          item.ParentNode.InnerHtml = item.ParentNode.InnerHtml.Replace("form", "div data-form");
             *      }
             *
             *      html = document.DocumentNode.WriteContentTo();
             *  }
             * }*/


            /*var settings = SettingsMapper.GetSettings();
             *
             * if (settings.EnableGlossaryTerms && !IsInAdminSection)
             * {
             *  var document = new HtmlAgilityPack.HtmlDocument();
             *  document.LoadHtml(html);
             *
             *  var selectedNodes = document.DocumentNode.SelectNodes("//p/text()|//li/text()");
             *  var terms = GlossaryTermsMapper.GetAll();
             *
             *  if (selectedNodes != null)
             *  {
             *      foreach (HtmlNode node in selectedNodes)
             *      {
             *          foreach (var term in terms)
             *          {
             *              var tempTerm = term.Term.Trim();
             *
             *              node.InnerHtml = Regex.Replace(node.InnerHtml, @"\b" + Regex.Escape(tempTerm) + @"\b" + "(?![^<]*</[a-z]+>)", me =>
             *              {
             *                  var template = "<span data-toggle=\"tooltip\" title=\"" + term.Definition + "\">" + me.Value + "</span>";
             *                  return template;
             *              }, RegexOptions.IgnoreCase);
             *          }
             *      }
             *  }
             *
             *  html = document.DocumentNode.WriteContentTo();
             * }*/

            html = ParserHelper.ParseData(html, TemplateVars);

            if (FrameworkSettings.CurrentUser == null && Request.QueryString.Count == 0)
            {
                if (CurrentMediaDetail != null)
                {
                    /*if (!IsAjaxRequest)
                     * {*/
                    if (AppSettings.EnableOutputCaching && CurrentMediaDetail.CanCache)
                    {
                        if (AppSettings.EnableLevel1MemoryCaching)
                        {
                            CurrentMediaDetail.SaveToMemoryCache(UserSelectedVersion, html);
                        }

                        if (AppSettings.EnableLevel2FileCaching)
                        {
                            CurrentMediaDetail.SaveToFileCache(UserSelectedVersion, html);
                        }

                        if (AppSettings.EnableLevel3RedisCaching)
                        {
                            CurrentMediaDetail.SaveToRedisCache(UserSelectedVersion, html);
                        }
                    }

                    ContextHelper.SetToSession("CurrentMediaDetail", CurrentMediaDetail);
                    //}
                }
            }

            /*if(AppSettings.ForceSSL)
             * {
             *  html = html.Replace("http:", "https:");
             * }*/

            html = ParserHelper.ReplaceHrefAndSrcsToAbsoluteUrls(html);

            writer.Write(html);
        }
        public override Stream GetFragment(string id, string mimeType)
        {
            try
            {
                var g = new Graph();

                // id is the url
                var odataQuery = id;
                var xmlReader  = XmlReader.Create(odataQuery, new XmlReaderSettings()
                {
                    CloseInput = true
                });
                var syndicationItem = SyndicationItem.Load(xmlReader);
                xmlReader.Close();

                if (syndicationItem != null)
                {
                    // add the title
                    g.Assert(g.CreateUriNode(new Uri(id)), g.CreateUriNode(new Uri(_rdfsNamespacePrefix + "label")), g.CreateLiteralNode(syndicationItem.Title.Text));

                    // process basic properties
                    var xmlContent = syndicationItem.Content as XmlSyndicationContent;
                    if (xmlContent != null)
                    {
                        var odataEntityXml = XDocument.Load(xmlContent.GetReaderAtContent());

                        // get properties
                        var odataProperties =
                            odataEntityXml.Descendants().Where(elem => elem.Name.Namespace.Equals(DataServicesNamespace));

                        foreach (var odataProperty in odataProperties)
                        {
                            var propertyName  = odataProperty.Name.LocalName;
                            var propertyValue = odataProperty.Value;

                            // remove later
                            propertyValue = propertyValue.Replace("&oslash;", "ø");
                            propertyValue = propertyValue.Replace("&aring;", "å");
                            propertyValue = propertyValue.Replace("&", "");

                            if (string.IsNullOrEmpty(propertyValue))
                            {
                                continue;
                            }

                            // see if there is a data type
                            if (odataProperty.Attribute(MetadataNamespace + "type") != null)
                            {
                                g.Assert(g.CreateUriNode(new Uri(id)),
                                         g.CreateUriNode(new Uri(_defaultSchemaNamespacePrefix + propertyName)),
                                         g.CreateLiteralNode(propertyValue, ConvertEdmToXmlSchemaDataType(odataProperty.Attribute(MetadataNamespace + "type").Value)));
                            }
                            else
                            {
                                g.Assert(g.CreateUriNode(new Uri(id)), g.CreateUriNode(new Uri(_defaultSchemaNamespacePrefix + propertyName)), g.CreateLiteralNode(propertyValue));
                            }
                        }
                    }
                }

                // add a instance-of relationship in to the graph for the entity
                foreach (var category in syndicationItem.Categories)
                {
                    var term = _defaultSchemaNamespacePrefix + category.Name.Replace('.', '/');
                    g.Assert(g.CreateUriNode(new Uri(id)),
                             g.CreateUriNode(new Uri(_rdfNamespacePrefix + "type")),
                             g.CreateUriNode(new Uri(term)));
                }

                // process relationships
                var links = syndicationItem.Links.Where(l => l.RelationshipType.StartsWith(OdataRelationshipRelTypePrefix));
                foreach (var syndicationLink in links)
                {
                    // property name
                    var propertyName = syndicationLink.RelationshipType.Substring(OdataRelationshipRelTypePrefix.Length);

                    // go fetch the related entities
                    // todo: we might look to use expand here but as there is no wildcard its a bit of a pain right now unless we pull the schema.

                    // need to check if we need to load an entry or a feed
                    IEnumerable <SyndicationItem> items = null;
                    try
                    {
                        if (syndicationLink.MediaType.ToLower().Contains("type=entry"))
                        {
                            xmlReader = XmlReader.Create(id + "/" + propertyName, new XmlReaderSettings()
                            {
                                CloseInput = true
                            });
                            items = new List <SyndicationItem>()
                            {
                                SyndicationItem.Load(xmlReader)
                            };
                            xmlReader.Close();
                        }
                        else
                        {
                            xmlReader = XmlReader.Create(id + "/" + propertyName, new XmlReaderSettings()
                            {
                                CloseInput = true
                            });
                            items = SyndicationFeed.Load(xmlReader).Items;
                            xmlReader.Close();
                        }
                    } catch (Exception)
                    {
                        // log and carry on
                        xmlReader.Close();
                    }

                    if (items != null)
                    {
                        foreach (var item in items)
                        {
                            // predicate value
                            g.Assert(g.CreateUriNode(new Uri(id)),
                                     g.CreateUriNode(new Uri(_defaultSchemaNamespacePrefix + propertyName)),
                                     g.CreateUriNode(new Uri(item.Id)));
                        }
                    }
                }

                // return data
                var rdfxmlwriter = new RdfXmlWriter();
                var strw         = new System.IO.StringWriter();
                rdfxmlwriter.Save(g, strw);
                var data = strw.ToString();
                data = data.Replace("utf-16", "utf-8");

                var ms = new MemoryStream();
                var sw = new StreamWriter(ms, Encoding.UTF8);
                sw.Write(data);
                sw.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                return(ms);
            } catch (Exception ex)
            {
                Logging.LogError(1, "Unable to fetch fragment for {0}. {1} {2}", id, ex.Message, ex.StackTrace);
            }
            return(null);
        }
Exemple #46
0
        public static string GetJSON()
        {
            IList <Earthquake> earthquakes = new List <Earthquake>();
            Country            Chile       = new Country("CHILE");
            Country            Argentina   = new Country("ARGENTINA");

            var    usgs      = "http://earthquake.usgs.gov/earthquakes/feed/v0.1/summary/1.0_hour.geojson";
            var    urlInpres = "http://www.inpres.gov.ar/seismology/xultimos.php";
            var    ssuch     = "http://www.sismologia.cl/links/ultimos_sismos.html";
            string filename  = "http://www.emsc-csem.org/service/rss/rss.php";

            var urlInpres1 = "J:\\Instituto Nacional de Prevención Sísmica.htm";
            var ssuch1     = "J:\\Ultimos Sismos.mht";
            var usgs1      = "J:\\earthquake\\2.5_day.csv";

            //-----------------------------------------------------------------------------------------
            while (true)
            {
                if (earthquakes.Count > 0)
                {
                    Console.WriteLine("                                                                                                                                                   ");
                    Console.WriteLine("                                                                                                                                                   ");
                    Console.WriteLine("                                                                                                                                                   ");

                    var earthquakesArgentina = earthquakes.Where(e => e.Place.Country.CountryName.Equals("ARGENTINA")).OrderByDescending(e => e.UTCDateTime);

                    var earthquakesChile = earthquakes.Where(e => e.Place.Country.CountryName.Equals("CHILE")).OrderByDescending(e => e.UTCDateTime);

                    var earthquakesWorld = earthquakes.Except(earthquakesArgentina).Except(earthquakesChile).OrderByDescending(e => e.UTCDateTime);


                    foreach (var earthquake in earthquakesArgentina)
                    {
                        if (earthquake.IsSensible)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;

                            if (earthquake.Place.PlaceName.Contains("MENDOZA"))
                            {
                                PlayAlertSound();
                            }
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                        }
                        Console.WriteLine(earthquake);
                        Console.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------------");
                        Thread.Sleep(1000);
                    }

                    foreach (var earthquake in earthquakesChile)
                    {
                        if (earthquake.IsSensible)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                        }
                        Console.WriteLine(earthquake);
                        Console.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------------");
                        Thread.Sleep(1000);
                    }

                    foreach (var earthquake in earthquakesWorld)
                    {
                        if (earthquake.IsSensible)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                        }
                        Console.WriteLine(earthquake);
                        Console.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------------");
                        Thread.Sleep(1000);
                    }
                }


                earthquakes = new List <Earthquake>();
                try
                {
                    #region ARGENTINA

                    //Console.WriteLine("#################################ARGENTINA###################################ARGENTINA#################################ARGENTINA#######################################");


                    // Load the html document
                    HtmlWeb      webArgentina = new HtmlWeb();
                    HtmlDocument docArgentina = webArgentina.Load(urlInpres);


                    // Get all tables in the document
                    HtmlNodeCollection tables = docArgentina.DocumentNode.SelectNodes("//table");

                    var earthquakeTable = tables.Where(tb => tb.Id.Equals("sismos")).Single();

                    // Iterate all rows in the first table
                    HtmlNodeCollection rows1 = earthquakeTable.SelectNodes(".//tr");
                    for (int i = 1; 6 > i; ++i)
                    {
                        // Iterate all columns in this row
                        HtmlNodeCollection cols = rows1[i].SelectNodes(".//td");

                        var  sensible1  = cols[8];
                        bool isSensible = sensible1.OuterHtml.Contains("#D40000");


                        string     LocalDateTimeHour = string.Empty;
                        string     LocalDateTimeYear = string.Empty;
                        DateTime   LocalDateTime     = new DateTime();
                        Coordenate Latitude          = null;
                        Coordenate Longitude         = null;
                        Depth      Depth             = null;
                        Magnitude  Magnitude         = null;
                        decimal    decimalValue      = 0;
                        Source     Source            = null;
                        Place      Place             = null;

                        for (int j = 1; j < cols.Count; ++j)
                        {
                            string value = cols[j].InnerText;
                            switch (j)
                            {
                            //Local time
                            case (1):
                                LocalDateTimeYear = value;
                                break;

                            case (2):
                                LocalDateTimeHour = value;

                                DateTime.TryParse(LocalDateTimeYear + " " + LocalDateTimeHour, out LocalDateTime);
                                break;

                            //Latitude
                            case (3):
                                string[] coord1  = value.Split('�');
                                string[] coord2  = coord1[1].Split('\'');
                                var      degrees = Convert.ToDecimal(coord1[0], CultureInfo.InvariantCulture);
                                var      minutes = Convert.ToDecimal(coord2[0], CultureInfo.InvariantCulture);
                                var      seconds = Convert.ToDecimal(coord2[1], CultureInfo.InvariantCulture);
                                Latitude = new Coordenate(degrees, minutes, seconds);
                                break;

                            //Longitude
                            case (4):
                                string[] coord3   = value.Split('�');
                                string[] coord4   = coord3[1].Split('\'');
                                var      degrees1 = Convert.ToDecimal(coord3[0], CultureInfo.InvariantCulture);
                                var      minutes1 = Convert.ToDecimal(coord4[0], CultureInfo.InvariantCulture);
                                var      seconds1 = Convert.ToDecimal(coord4[1], CultureInfo.InvariantCulture);
                                Longitude = new Coordenate(degrees1, minutes1, seconds1);
                                break;

                            //Depth
                            case (5):
                                string[] depthArray = value.Split(' ');
                                decimalValue = Convert.ToDecimal(depthArray[0], CultureInfo.InvariantCulture);
                                Depth        = new Depth(decimalValue, depthArray[1]);
                                break;

                            //Magnitude
                            case (6):
                                string[] magnitudArray = value.Split(' ');
                                decimalValue = Convert.ToDecimal(magnitudArray[0], CultureInfo.InvariantCulture);
                                Magnitude    = new Magnitude(decimalValue, "??");
                                break;

                            //Place
                            case (7):
                                Place  = new Place(value, Argentina, -3);
                                Source = new Source("INPRES", "");
                                break;
                            }
                        }

                        earthquakes.Add(new Earthquake(LocalDateTime, Latitude, Longitude, Depth, Magnitude, isSensible, Place, Source));
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("ARGENTINA REGION ERROR:" + ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("ARGENTINA REGION ERROR:" + ex.Message);
                    }
                }
                try{
                    //---------------------------------------------------------------------------------------------------------------------------------------------------------------
                    #region Twitter

                    /*
                     * The Twitter REST API v1 will soon stop functioning. Please migrate to API v1.1.
                     * https://dev.twitter.com/docs/api/1.1/overview
                     */


                    var twitter = new Twitter("xNBdzXy7tkyD1kstIDcg", "0nSriIwDZkFR7qcf6nsnQh3bqecn7IGoTqpIr8Xk6gc",
                                              "1451422718-kwIAaVppRGys6dltQXKIUt39vNbIg5e4PFD1Rgu",
                                              "1LPbBbwYcAELk3dl50WIwZMp38gt2wWGwkOkzVQGQM");


                    var responseTwitter = twitter.GetTweets("sismo argentina");

                    JObject jobjectTwitter1 = JObject.Parse(responseTwitter);

                    var resultado12 = jobjectTwitter1["statuses"];

                    var twittsList2 = resultado12.ToList();

                    Console.ForegroundColor = ConsoleColor.Blue;
                    Console.WriteLine("--------------------Twitter---------------Twitter----------------Twitter------------------Twitter--------------------Twitter-----------------Twitter");
                    foreach (var twitt in twittsList2)
                    {
                        Console.ForegroundColor = ConsoleColor.Blue;
                        //Wed, 22 May 2013 14:01:58 +0000
                        DateTime timestamp;
                        //var rrrr = twitt.First.First.ToString().Replace(",", "").Replace("\\", "").Replace("\"","");

                        // DateTime.TryParseExact(rrrr, "ddd MMM dd HH:mm:ss K yyyy", null, DateTimeStyles.None, out timestamp);



                        var text = twitt["text"];
                        var date = twitt["created_at"].ToString().Replace("\\", "").Replace("\"", "");

                        const string format   = "ddd MMM dd HH:mm:ss zzzz yyyy";
                        var          realtime = DateTime.ParseExact(date, format, CultureInfo.InvariantCulture);


                        if (text.ToString().Contains("gol") || text.ToString().Contains("futbol") || text.ToString().Contains("jugador"))
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                        }


                        Console.WriteLine(string.Concat(realtime.ToString(), " ", text));
                        Console.WriteLine("------------------------------------------------------------------------------------------------------------------------------------------------------");
                        Thread.Sleep(500);
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("TWITTER ERROR:" + ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("TWITTER ERROR:" + ex.Message);
                    }
                    Thread.Sleep(3000);
                }

                try{
                    //---------------------------------------------------------------------------------------------------------------------------------------------------------------

                    #region Chile
                    //Console.WriteLine("########################CHILE######################CHILE########################CHILE####################################################");

                    // Load the html document
                    HtmlWeb      webChile = new HtmlWeb();
                    HtmlDocument docChile = webChile.Load(ssuch);


                    // Get all tables in the document
                    HtmlNodeCollection tables1 = docChile.DocumentNode.SelectNodes("//table");

                    var earthquakeTable1 = tables1[0];

                    // Iterate all rows in the first table
                    HtmlNodeCollection rows = earthquakeTable1.SelectNodes(".//tr");
                    for (int i = 1; 6 > i; ++i)
                    {
                        bool IsSensible = false;
                        //determina si fue percibido
                        string sensible = rows[i].Attributes[0].Value;

                        if (sensible.Contains("sensible"))
                        {
                            IsSensible = true;
                        }



                        // Iterate all columns in this row
                        HtmlNodeCollection cols = rows[i].SelectNodes(".//th");
                        if (cols == null)
                        {
                            cols = rows[i].SelectNodes(".//td");
                        }



                        DateTime   LocalDateTime = new DateTime();
                        Coordenate Latitude      = null;
                        Coordenate Longitude     = null;
                        Depth      Depth         = null;
                        Magnitude  Magnitude     = null;
                        decimal    decimalValue  = 0;
                        Source     Source        = null;
                        Place      Place         = null;

                        for (int j = 0; j < cols.Count; ++j)
                        {
                            string value = cols[j].InnerText;

                            switch (j)
                            {
                            //Local time : ignore
                            case (0):
                                break;

                            //UTC time
                            case (1):
                                DateTime.TryParse(value, out LocalDateTime);
                                break;

                            //Latitude
                            case (2):
                                decimalValue = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
                                Latitude     = new Coordenate(decimalValue);
                                break;

                            //Longitude
                            case (3):
                                decimalValue = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
                                Longitude    = new Coordenate(decimalValue);
                                break;

                            //Depth
                            case (4):
                                decimalValue = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
                                Depth        = new Depth(decimalValue, "KM.");
                                break;

                            //Magnitude
                            case (5):
                                string[] magnitudArray = value.Trim().Split(' ');
                                decimalValue = Convert.ToDecimal(magnitudArray[0], CultureInfo.InvariantCulture);
                                Magnitude    = new Magnitude(decimalValue, magnitudArray[1]);
                                break;

                            //Source
                            case (6):
                                Source = new Source(value, "");
                                break;

                            //Place
                            case (7):
                                Place = new Place(value, Chile, -4);
                                break;
                            }
                        }

                        earthquakes.Add(new Earthquake(LocalDateTime, Latitude, Longitude, Depth, Magnitude, IsSensible, Place, Source));
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    Thread.Sleep(3000);
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("CHILE REGION ERROR:" + ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("CHILE REGION ERROR:" + ex.Message);
                    }
                }
                //---------------------------------------------------------------------------------------------------------------------------------------------------------------
                try{
                    #region EMS


                    XDocument doc = XDocument.Load(filename);
                    IEnumerable <XElement> query  = from c in doc.Descendants("item") select c;
                    IEnumerable <XElement> query5 = from d in query.Descendants("title") /*.Where(d => d.Value.Contains("ARGENTINA"))*/ select d.Parent;

                    /*
                     * ML 2.3 WESTERN TURKEY
                     * ML 2.3 CRETE, GREECE
                     * Mw 5.8 EASTERN UZBEKISTAN
                     * ML 4.3 JUJUY, ARGENTINA
                     * ML 3.5 SOUTHERN IRAN
                     * M 4.1 POTOSI, BOLIVIA
                     * ML 3.2 OFF COAST OF ATACAMA, CHILE
                     * ML 2.8 FYR OF MACEDONIA
                     * ML 3.8 OFFSHORE COQUIMBO, CHILE
                     * mb 4.8 PAPUA, INDONESIA
                     * mb 4.1 SEA OF OKHOTSK
                     * ML 3.0  ALBANIA
                     * M  4.6  OFF COAST OF SOUTHEASTERN ALASKA"
                     */
                    foreach (var aaa in query5)
                    {
                        var        cantidad          = query5.Count();
                        string[]   asdf              = aaa.ToString().Split(new Char[] { '\n' });
                        string     LocalDateTimeHour = string.Empty;
                        string     LocalDateTimeYear = string.Empty;
                        DateTime   LocalDateTime     = new DateTime();
                        Coordenate Latitude          = null;
                        Coordenate Longitude         = null;
                        Depth      Depth             = null;
                        Magnitude  Magnitude         = null;
                        decimal    decimalValue      = 0;
                        Source     Source            = null;
                        Place      Place             = null;
                        bool       IsSensible        = false;

                        for (int j = 1; j < asdf.Length; ++j)
                        {
                            var value = asdf[j];
                            switch (j)
                            {
                            //Local time
                            case (1):


                                var      haber = value.Replace("<title>", "").Replace("</title>", "").Trim();
                                string[] ololo = haber.Split(',');
                                if (ololo.Length == 2)
                                {
                                    var carac = ololo[0].ToCharArray();

                                    int cantidadEspacios = 0;

                                    StringBuilder sbs           = new StringBuilder();
                                    bool          anteriorSpace = false;

                                    for (int i = 0; i < carac.Length; ++i)
                                    {
                                        if (cantidadEspacios == 2)
                                        {
                                            sbs.Append(carac[i]);
                                        }

                                        if (cantidadEspacios < 2 && carac[i].Equals(' ') && !anteriorSpace)
                                        {
                                            cantidadEspacios++;
                                            anteriorSpace = true;
                                        }
                                        else
                                        {
                                            anteriorSpace = false;
                                        }
                                    }


                                    var locationTemp = sbs.ToString().Trim();

                                    var location = locationTemp.ToString();
                                    var pais     = ololo[1].Trim();
                                    var country  = new Country(pais);
                                    Place = new Place(location, country, 0);
                                }
                                else
                                {
                                    char[] carac            = ololo[0].ToCharArray();
                                    int    cantidadEspacios = 0;

                                    StringBuilder sbs           = new StringBuilder();
                                    bool          anteriorSpace = false;
                                    for (int i = 0; i < carac.Length; ++i)
                                    {
                                        if (cantidadEspacios == 2)
                                        {
                                            sbs.Append(carac[i]);
                                        }

                                        if (cantidadEspacios < 2 && carac[i].Equals(' ') && !anteriorSpace)
                                        {
                                            cantidadEspacios++;
                                            anteriorSpace = true;
                                        }
                                        else
                                        {
                                            anteriorSpace = false;
                                        }
                                    }

                                    if (!sbs.ToString().Equals(string.Empty))
                                    {
                                        var      locationTemp = sbs.ToString().Trim();
                                        string[] side         = new string[6] {
                                            "EASTERN", "SOUTHERN", "WESTERN", "NORTHEM", "CENTRAL", "GULF OF"
                                        };

                                        string[] aaasas   = locationTemp.Split(' ');
                                        var      pais     = aaasas[aaasas.Length - 1].Trim();;
                                        var      location = locationTemp.ToString();


                                        if (side.Contains(pais))
                                        {
                                            var country = new Country(pais);
                                            Place = new Place(location, country, 0);
                                        }
                                        else
                                        {
                                            var country = new Country(location);
                                            Place = new Place(location, country, 0);
                                        }
                                    }
                                }

                                break;

                            //ignore, id earthquake
                            case (2):
                                break;

                            //Latitude
                            case (3):
                                var decimalString = value.Replace("<geo:lat xmlns:geo=\"http://www.w3.org/2003/01/geo/\">", "").Replace("</geo:lat>", "").Trim();
                                var val           = Convert.ToDecimal(decimalString, CultureInfo.InvariantCulture);
                                Latitude = new Coordenate(val);
                                break;

                            //Longitude
                            case (4):
                                var decimalString1 = value.Replace("<geo:long xmlns:geo=\"http://www.w3.org/2003/01/geo/\">", "").Replace("</geo:long>", "").Trim();
                                var val1           = Convert.ToDecimal(decimalString1, CultureInfo.InvariantCulture);
                                Longitude = new Coordenate(val1);
                                break;

                            //Depth
                            case (5):
                                var      decimalString2 = value.Replace("<emsc:depth xmlns:emsc=\"http://www.emsc-csem.org\">", "").Replace("</emsc:depth>", "").Trim();
                                string[] tempString     = decimalString2.Split(' ');
                                var      val2           = Convert.ToDecimal(tempString[0], CultureInfo.InvariantCulture);
                                Depth = new Depth(val2, "Km.");
                                break;

                            //Magnitude
                            case (6):
                                var      decimalString3 = value.Replace("<emsc:magnitude xmlns:emsc=\"http://www.emsc-csem.org\">", "").Replace("</emsc:magnitude>", "").Trim();
                                string[] magnitudArray  = decimalString3.Split(' ');
                                decimalValue = Convert.ToDecimal(magnitudArray[magnitudArray.Length - 1], CultureInfo.InvariantCulture);
                                Magnitude    = new Magnitude(decimalValue, magnitudArray[0]);
                                break;

                            //DateTime
                            case (7):
                                var      decimalString4 = value.Replace("<emsc:time xmlns:emsc=\"http://www.emsc-csem.org\">", "").Replace("</emsc:time>", "").Trim();
                                string[] a1             = decimalString4.Split('-');
                                string[] a2             = a1[2].Split(' ');
                                string[] a3             = a2[1].Replace("UTC", "").Split(':');
                                LocalDateTime = new DateTime(int.Parse(a1[0]), int.Parse(a1[1]), int.Parse(a2[0]), int.Parse(a3[0]), int.Parse(a3[1]), int.Parse(a3[2]));

                                break;
                            }
                        }

                        Source = new Source("emsc-csem.", "");
                        if (Magnitude.MagnitudeValue > Convert.ToDecimal(4.5))
                        {
                            IsSensible = true;
                        }

                        earthquakes.Add(new Earthquake(LocalDateTime, Latitude, Longitude, Depth, Magnitude, IsSensible, Place, Source));
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    Thread.Sleep(3000);
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("EMS ERROR:" + ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("EMS ERROR:" + ex.Message);
                    }
                }

                try
                {
                    //--------------------------------------------------------------------------------------------------------------------------------------------------------------------
                    #region USA REGION
                    //Console.WriteLine("########################USA######################WORLD########################USA######################WORDL##############################");

                    /* Stream str = new FileStream(usgs1, FileMode.Open,FileAccess.Read);
                     * StreamReader sr = new StreamReader(str);
                     * string line = string.Empty;
                     *
                     * int lineNumber= 0;
                     * string[] dataLine = null;
                     *
                     *
                     * DateTime LocalDateTimeUsa = new DateTime();
                     * Coordenate LatitudeUsa = null;
                     * Coordenate LongitudeUsa = null;
                     * Depth DepthUsa = null;
                     * Magnitude MagnitudeUsa = null;
                     * decimal decimalValueUsa = 0;
                     * Source SourceUsa = null;
                     * Place PlaceUsa = null;
                     *
                     * while (line != null )
                     * {
                     *    line = sr.ReadLine();
                     *    if(lineNumber != 0 && lineNumber != 6){
                     *
                     *        dataLine = line.ToString().Split(',');
                     *
                     *
                     *
                     *        decimalValueUsa = Convert.ToDecimal(dataLine[0], CultureInfo.InvariantCulture);
                     *    }
                     *    else if(lineNumber ==  6){
                     *     break;
                     *    }
                     *    lineNumber++;
                     * }*/

                    //create the constructor with post type and few data
                    MyWebRequest myRequest = new MyWebRequest(usgs, "POST", "");
                    //show the response string on the console screen.
                    var response = myRequest.GetResponse();


                    JObject jobject  = JObject.Parse(response);
                    JToken  metadata = null;
                    JToken  type     = null;
                    JToken  features = null;

                    jobject.TryGetValue("metadata", out metadata);
                    jobject.TryGetValue("features", out features);
                    jobject.TryGetValue("type", out type);

                    var cantidadIncidentes = features.Count();

                    var eee = features.ToArray <JToken>();

                    for (int i = 0; i < cantidadIncidentes; i++)
                    {
                        var incidente = eee[i];



                        var jTokenIntensity = (JToken)incidente.First.Next.First.First.First;
                        var jTokenTime      = (JToken)((incidente.First.Next.First.First).Next).Next.Last;

                        string miliseconds = (string)jTokenTime.Value <Newtonsoft.Json.Linq.JValue>();

                        Newtonsoft.Json.Linq.JValue valor = jTokenIntensity.Value <Newtonsoft.Json.Linq.JValue>();
                        JTokenType jtype = jTokenIntensity.Type;



                        Int64  intensidadInteger = 0;
                        double intensidadDouble  = 0.0;

                        if (jtype.Equals(JTokenType.Float))
                        {
                            intensidadDouble = (double)valor.Value;
                        }
                        else if (jtype.Equals(JTokenType.Integer))
                        {
                            intensidadInteger = (Int64)valor.Value;
                        }

                        bool isSensible = false;

                        if (intensidadInteger != 0 && intensidadDouble == 0.0)
                        {
                            isSensible = intensidadInteger >= 4.5;
                        }
                        else if (intensidadInteger == 0 && intensidadDouble != 0.0)
                        {
                            isSensible = intensidadDouble >= 4.5;
                        }

                        if (isSensible)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine(incidente.ToString());
                            Console.WriteLine("..........................................................................................................................");
                            Thread.Sleep(2000);
                        }
                        else
                        {
                            Console.ForegroundColor = ConsoleColor.Green;
                            Console.WriteLine(incidente.ToString());
                            Console.WriteLine("..........................................................................................................................");
                            Thread.Sleep(2000);
                        }
                    }

                    #endregion
                }

                catch (Exception ex) {
                    Thread.Sleep(3000);
                    if (ex.InnerException != null)
                    {
                        Console.WriteLine("USA REGION ERROR:" + ex.InnerException.Message);
                    }
                    else
                    {
                        Console.WriteLine("USA REGION ERROR:" + ex.Message);
                    }
                }
                //---------------------------------------------------------------------------------------------------------------------------------------------------------------------


                Console.WriteLine("ªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª");
                Console.WriteLine("ªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª");
                Console.WriteLine("ªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªªª");
            }

            //-------------------------------------------------------------------------------------------



            while (true)
            {
                //create the constructor with post type and few data
                MyWebRequest myRequest = new MyWebRequest(usgs, "POST", "");
                //show the response string on the console screen.
                var response = myRequest.GetResponse();


                JObject jobject  = JObject.Parse(response);
                JToken  metadata = null;
                JToken  type     = null;
                JToken  features = null;

                jobject.TryGetValue("metadata", out metadata);
                jobject.TryGetValue("features", out features);
                jobject.TryGetValue("type", out type);

                var cantidadIncidentes = features.Count();

                var eee = features.ToArray <JToken>();

                for (int i = 0; i < cantidadIncidentes; i++)
                {
                    var incidente = eee[i];
                    Console.WriteLine(incidente.ToString());
                    Console.WriteLine("..........................................................................................................................");
                    Thread.Sleep(2000);
                }
                Console.WriteLine("------------------------------------------------------------------------------------------------------------------------");
                Console.WriteLine("------------------------------------------------------------------------------------------------------------------------");
                Console.WriteLine("------------------------------------------------------------------------------------------------------------------------");

                Thread.Sleep(10000);
            }


            /*
             *   {
             *          "type": "FeatureCollection",
             *          "features": [
             *                  {
             *                          "geometry": {
             *                                  "type": "Point",
             *                                  "coordinates": [6.18218, 45.5949]
             *                          },
             *                          "type": "Feature",
             *                          "properties": {
             *                                  "elevation": 1770,
             *                                  "name": "Col d'Arclusaz"
             *                          },
             *                          "id": 472
             *                  }, ... more features...
             *          }
             *  }
             */

            object MyCollection = new MyFeatureCollection
            {
                Features = new MyFeature[] {
                    new MyFeature {
                        ID         = "472",
                        Geometry   = new GeoJSON.Point(6.18218, 45.5949),
                        Properties = new MyProperties {
                            Elevation = "1770",
                            Name      = "CollectionBase d'Arclusaz"
                        }
                    },
                    new MyFeature {
                        ID         = "458",
                        Geometry   = new GeoJSON.Point(6.27827, 45.6769),
                        Properties = new MyProperties {
                            Elevation = "1831",
                            Name      = "Pointe de C\\u00f4te Favre"
                        }
                    }
                }
            };

            StringBuilder Builder = new System.Text.StringBuilder();
            StringWriter  Writer  = new System.IO.StringWriter(Builder);

            new Newtonsoft.Json.JsonSerializer().Serialize(Writer, MyCollection);

            return(Builder.ToString());
        }
Exemple #47
0
        private string BuildData1HD(string MT32ID)
        {
            string     Data = "";
            List <Inv> lInv = new List <Inv>();

            DataRow[] ldrMT = dtInvoices.Select("MT32ID='" + MT32ID + "'");
            if (ldrMT.Length == 0)
            {
                return(Data);
            }
            DataRow drMT = ldrMT[0];

            Invoice invoice = new Invoice();

            invoice.ArisingDate    = DateTime.Parse(drMT["NgayCT"].ToString());
            invoice.CusCode        = drMT["MaKH"].ToString();
            invoice.CusName        = drMT["TenKH"].ToString();
            invoice.CusTaxCode     = drMT["MST"].ToString();
            invoice.CusAddress     = drMT["DiaChi"].ToString();
            invoice.CusBankNo      = drMT["TkNganHang"].ToString();
            invoice.CusBankName    = drMT["NganHang"].ToString();
            invoice.CusPhone       = drMT["SDT"].ToString();
            invoice.EmailDeliver   = drMT["Email"].ToString();
            invoice.Buyer          = drMT["Ongba"].ToString();
            invoice.SellBankNo     = "";
            invoice.InvNote        = drMT["Diengiai"].ToString();;
            invoice.PaymentMethod  = drMT["TenHTTT"].ToString();
            invoice.Currency       = drMT["MaNT"].ToString();
            invoice.ExRate         = double.Parse(drMT["TyGia"].ToString());
            invoice.Amount         = double.Parse(drMT["TTienH"].ToString());
            invoice.DiscountAmount = double.Parse(drMT["TCK"].ToString());
            if (drMT["MaThue"].ToString() == "KT")
            {
                invoice.VATRate = 0;
            }
            else
            {
                invoice.VATRate = double.Parse(drMT["MaThue"].ToString());
            }
            invoice.VATAmount     = double.Parse(drMT["TThue"].ToString());
            invoice.Total         = double.Parse(drMT["TTien"].ToString());
            invoice.AmountInWords = NumberReader.ReadMoney(double.Parse(drMT["TTien"].ToString()).ToString("###############0")) + "  đồng";
            DataRow[]      ldrdt = dtDetails.Select("MT32ID='" + drMT["MT32ID"].ToString() + "'");
            List <Product> lpro  = new List <Product>();

            for (int i = 0; i < ldrdt.Length; i++)
            {
                DataRow dr  = ldrdt[i];
                Product pro = new Product();
                pro.No             = i;
                pro.ProdCode       = dr["MaVT"].ToString();
                pro.ProdName       = dr["TenVT"].ToString();
                pro.ProdUnit       = dr["TenDVT"].ToString();
                pro.ProdQuantity   = double.Parse(dr["Soluong"].ToString());
                pro.ProdPrice      = double.Parse(dr["Gia"].ToString());
                pro.Amount         = double.Parse(dr["ps"].ToString());
                pro.ProdVat        = double.Parse(dr["Thuesuat"].ToString());
                pro.ProdVATAmount  = double.Parse(dr["thue"].ToString());
                pro.DiscountRate   = double.Parse(dr["tileck"].ToString());
                pro.DiscountAmount = double.Parse(dr["ck"].ToString());
                if (double.Parse(dr["ps"].ToString()) == 0)
                {
                    pro.Promotion = 1;
                }
                else
                {
                    pro.Promotion = 0;
                }
                lpro.Add(pro);
            }
            invoice.Products = lpro.ToArray();
            Inv inv = new Inv();

            inv.key     = drMT["MT32ID"].ToString();
            inv.Invoice = invoice;
            lInv.Add(inv);

            invoices = lInv.ToArray();
            StringWriter stringwriter = new System.IO.StringWriter();

            XmlSerializer           serializer = new XmlSerializer(invoices.GetType());
            XmlSerializerNamespaces ns         = new XmlSerializerNamespaces();

            ns.Add("", "");

            // serializer.Serialize(stringwriter, invoices,ns);
            serializer.Serialize(stringwriter, invoices);

            string xmlInvData = stringwriter.ToString();

            string[] lines = xmlInvData.Split("\n".ToCharArray()).Skip(2).ToArray();
            Data = string.Join("\n", lines);
            Data = "<Invoices>\n" + Data.Replace("</ArrayOfInv>", "</Invoices>");
            return(Data);
        }
Exemple #48
0
        ///////////////////////////////////////////////////////////////////////
        // This used to send the emails, but not now.  Now it just queues
        // the emails to be sent, then spawns a thread to send them.
        public static void send_notifications(int insert_or_update,          // The implementation
                                              int bugid,
                                              Security security,
                                              int just_to_this_userid,
                                              bool status_changed,
                                              bool assigned_to_changed,
                                              int prev_assigned_to_user)
        {
            // If there's something worth emailing about, then there's
            // probably something worth updating the index about.
            // Really, though, we wouldn't want to update the index if it were
            // just the status that were changing...
            if (btnet.Util.get_setting("EnableLucene", "1") == "1")
            {
                MyLucene.update_lucene_index(bugid);
            }

            bool notification_email_enabled = (btnet.Util.get_setting("NotificationEmailEnabled", "1") == "1");

            if (!notification_email_enabled)
            {
                return;
            }
            // MAW -- 2006/01/27 -- Determine level of change detected
            int changeLevel = 0;

            if (insert_or_update == INSERT)
            {
                changeLevel = 1;
            }
            else if (status_changed)
            {
                changeLevel = 2;
            }
            else if (assigned_to_changed)
            {
                changeLevel = 3;
            }
            else
            {
                changeLevel = 4;
            }

            string sql;

            if (just_to_this_userid > 0)
            {
                sql = @"
/* get notification email for just one user  */
select us_email, us_id, us_admin, og.*
from bug_subscriptions
inner join users on bs_user = us_id
inner join orgs og on us_org = og_id
inner join bugs on bg_id = bs_bug
left outer join project_user_xref on pu_user = us_id and pu_project = bg_project
where us_email is not null
and us_enable_notifications = 1
-- $status_change
and us_active = 1
and us_email <> ''
and
case
when
	us_org <> bg_org
	and og_other_orgs_permission_level < 2
	and og_other_orgs_permission_level < isnull(pu_permission_level,$dpl)
		then og_other_orgs_permission_level
else
	isnull(pu_permission_level,$dpl)
end <> 0
and bs_bug = $id
and us_id = $just_this_usid";

                sql = sql.Replace("$just_this_usid", Convert.ToString(just_to_this_userid));
            }
            else
            {
                // MAW -- 2006/01/27 -- Added different notifications if reported or assigned-to
                sql = @"
/* get notification emails for all subscribers */
select us_email, us_id, us_admin, og.*
from bug_subscriptions
inner join users on bs_user = us_id
inner join orgs og on us_org = og_id
inner join bugs on bg_id = bs_bug
left outer join project_user_xref on pu_user = us_id and pu_project = bg_project
where us_email is not null
and us_enable_notifications = 1
-- $status_change
and us_active = 1
and us_email <> ''
and (   ($cl <= us_reported_notifications and bg_reported_user = bs_user)
or ($cl <= us_assigned_notifications and bg_assigned_to_user = bs_user)
or ($cl <= us_assigned_notifications and $pau = bs_user)
or ($cl <= us_subscribed_notifications))
and
case
when
us_org <> bg_org
and og_other_orgs_permission_level < 2
and og_other_orgs_permission_level < isnull(pu_permission_level,$dpl)
	then og_other_orgs_permission_level
else
isnull(pu_permission_level,$dpl)
end <> 0
and bs_bug = $id
and (us_id <> $us or isnull(us_send_notifications_to_self,0) = 1)";
            }

            sql = sql.Replace("$cl", changeLevel.ToString());
            sql = sql.Replace("$pau", prev_assigned_to_user.ToString());
            sql = sql.Replace("$id", Convert.ToString(bugid));
            sql = sql.Replace("$dpl", btnet.Util.get_setting("DefaultPermissionLevel", "2"));
            sql = sql.Replace("$us", Convert.ToString(security.user.usid));


            DataSet ds_subscribers = btnet.DbUtil.get_dataset(sql);

            if (ds_subscribers.Tables[0].Rows.Count > 0)
            {
                bool added_to_queue = false;


                // Get bug html
                DataRow bug_dr = btnet.Bug.get_bug_datarow(bugid, security);

                string from = btnet.Util.get_setting("NotificationEmailFrom", "");

                // Format the subject line
                string subject = btnet.Util.get_setting("NotificationSubjectFormat", "$THING$:$BUGID$ was $ACTION$ - $SHORTDESC$ $TRACKINGID$");

                subject = subject.Replace("$THING$", btnet.Util.capitalize_first_letter(btnet.Util.get_setting("SingularBugLabel", "bug")));

                string action = "";
                if (insert_or_update == INSERT)
                {
                    action = "added";
                }
                else
                {
                    action = "updated";
                }

                subject = subject.Replace("$ACTION$", action);
                subject = subject.Replace("$BUGID$", Convert.ToString(bugid));
                subject = subject.Replace("$SHORTDESC$", (string)bug_dr["short_desc"]);

                string tracking_id = " (";
                tracking_id += btnet.Util.get_setting("TrackingIdString", "DO NOT EDIT THIS:");
                tracking_id += Convert.ToString(bugid);
                tracking_id += ")";
                subject      = subject.Replace("$TRACKINGID$", tracking_id);

                subject = subject.Replace("$PROJECT$", (string)bug_dr["current_project"]);
                subject = subject.Replace("$ORGANIZATION$", (string)bug_dr["og_name"]);
                subject = subject.Replace("$CATEGORY$", (string)bug_dr["category_name"]);
                subject = subject.Replace("$PRIORITY$", (string)bug_dr["priority_name"]);
                subject = subject.Replace("$STATUS$", (string)bug_dr["status_name"]);
                subject = subject.Replace("$ASSIGNED_TO$", (string)bug_dr["assigned_to_username"]);


                // send a separate email to each subscriber
                foreach (DataRow dr in ds_subscribers.Tables[0].Rows)
                {
                    string to = (string)dr["us_email"];

                    // Create a fake response and let the code
                    // write the html to that response
                    System.IO.StringWriter writer      = new System.IO.StringWriter();
                    HttpResponse           my_response = new HttpResponse(writer);
                    my_response.Write("<html>");
                    my_response.Write("<base href=\"" +
                                      btnet.Util.get_setting("AbsoluteUrlPrefix", "http://127.0.0.1/") + "\"/>");

                    // create a security rec for the user receiving the email
                    Security sec2 = new Security();

                    // fill in what we know is needed downstream
                    sec2.user.is_admin      = Convert.ToBoolean(dr["us_admin"]);
                    sec2.user.external_user = Convert.ToBoolean(dr["og_external_user"]);
                    sec2.user.tags_field_permission_level        = (int)dr["og_category_field_permission_level"];
                    sec2.user.category_field_permission_level    = (int)dr["og_category_field_permission_level"];
                    sec2.user.priority_field_permission_level    = (int)dr["og_priority_field_permission_level"];
                    sec2.user.assigned_to_field_permission_level = (int)dr["og_assigned_to_field_permission_level"];
                    sec2.user.status_field_permission_level      = (int)dr["og_status_field_permission_level"];
                    sec2.user.project_field_permission_level     = (int)dr["og_project_field_permission_level"];
                    sec2.user.org_field_permission_level         = (int)dr["og_org_field_permission_level"];
                    sec2.user.udf_field_permission_level         = (int)dr["og_udf_field_permission_level"];

                    DataSet ds_custom = Util.get_custom_columns();
                    foreach (DataRow dr_custom in ds_custom.Tables[0].Rows)
                    {
                        string bg_name = (string)dr_custom["name"];
                        string og_name = "og_"
                                         + (string)dr_custom["name"]
                                         + "_field_permission_level";

                        object obj = dr[og_name];
                        if (Convert.IsDBNull(obj))
                        {
                            sec2.user.dict_custom_field_permission_level[bg_name] = Security.PERMISSION_ALL;
                        }
                        else
                        {
                            sec2.user.dict_custom_field_permission_level[bg_name] = (int)dr[og_name];
                        }
                    }

                    PrintBug.print_bug(
                        my_response,
                        bug_dr,
                        sec2,
                        true,                         /* include style */
                        false,                        /* images_inline */
                        true /* history_inline */);

                    // at this point "writer" has the bug html

                    sql = @"
delete from queued_notifications where qn_bug = $bug and qn_to = N'$to'

insert into queued_notifications
(qn_date_created, qn_bug, qn_user, qn_status, qn_retries, qn_to, qn_from, qn_subject, qn_body, qn_last_exception)
values (getdate(), $bug, $user, N'not sent', 0, N'$to', N'$from', N'$subject', N'$body', N'')";

                    sql = sql.Replace("$bug", Convert.ToString(bugid));
                    sql = sql.Replace("$user", Convert.ToString(dr["us_id"]));
                    sql = sql.Replace("$to", to.Replace("'", "''"));
                    sql = sql.Replace("$from", from.Replace("'", "''"));
                    sql = sql.Replace("$subject", subject.Replace("'", "''"));
                    sql = sql.Replace("$body", writer.ToString().Replace("'", "''"));

                    btnet.DbUtil.execute_nonquery_without_logging(sql);

                    added_to_queue = true;
                }                 // end loop through ds_subscribers

                if (added_to_queue)
                {
                    // spawn a worker thread to send the emails
                    System.Threading.ThreadStart worker = new System.Threading.ThreadStart(threadproc_notifications);
                    System.Threading.Thread      thread = new System.Threading.Thread(worker);
                    thread.Start();
                }
            }              // if there are any subscribers
        }
    protected void BtnExcelExportSummary_Click(object sender, EventArgs e)
    {
        try
        {
            SqlProcsNew sqlobj = new SqlProcsNew();

            DataSet dsStockTransaction = sqlobj.ExecuteSP("SP_StockTransactionReport",
                                                          new SqlParameter()
            {
                ParameterName = "@StockGroup", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.NVarChar, Value = ddlGroup.SelectedValue == "All" ? null : ddlGroup.SelectedValue
            },
                                                          new SqlParameter()
            {
                ParameterName = "@TransType", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.NVarChar, Value = ddlTransactionType.SelectedValue == "All" ? null : ddlTransactionType.SelectedValue
            },
                                                          new SqlParameter()
            {
                ParameterName = "@FromDate", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.DateTime, Value = dtpfordate.SelectedDate
            },
                                                          new SqlParameter()
            {
                ParameterName = "@ToDate", Direction = ParameterDirection.Input, SqlDbType = SqlDbType.DateTime, Value = dtpuntildate.SelectedDate
            }
                                                          );


            if (dsStockTransaction.Tables[1].Rows.Count > 0)
            {
                DataGrid dg = new DataGrid();

                dg.DataSource = dsStockTransaction.Tables[1];
                dg.DataBind();

                DateTime sdate = dtpfordate.SelectedDate.Value;
                DateTime edate = dtpuntildate.SelectedDate.Value;

                // THE EXCEL FILE.
                string sFileName = "Stock Transaction Summary Report From " + sdate.ToString("dd/MM/yyyy") + " To " + edate.ToString("dd/MM/yyyy") + ".xls";
                sFileName = sFileName.Replace("/", "");



                // SEND OUTPUT TO THE CLIENT MACHINE USING "RESPONSE OBJECT".
                Response.ClearContent();
                Response.Buffer = true;
                Response.AddHeader("content-disposition", "attachment; filename=" + sFileName);
                Response.ContentType = "application/vnd.ms-excel";
                EnableViewState      = false;

                System.IO.StringWriter       objSW  = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter objHTW = new System.Web.UI.HtmlTextWriter(objSW);

                dg.HeaderStyle.Font.Bold = true;     // SET EXCEL HEADERS AS BOLD.
                dg.RenderControl(objHTW);


                //"," + strdesc.ToString() +

                Response.Write("<table><tr><td>Stock Transaction Summary Report</td><td> From:" + sdate.ToString("dd/MM/yyyy") + "</td><td> To:" + edate.ToString("dd/MM/yyyy") + "</td></tr></table>");


                // STYLE THE SHEET AND WRITE DATA TO IT.
                Response.Write("<style> TABLE { border:dotted 1px #999; } " +
                               "TD { border:dotted 1px #D5D5D5; text-align:center } </style>");
                Response.Write(objSW.ToString());


                Response.End();
                dg = null;
            }
            else
            {
                WebMsgBox.Show("No transaction found for the period from " + dtpfordate.SelectedDate.Value + " To " + dtpuntildate.SelectedDate.Value);
            }
        }
        catch (Exception ex)
        {
            WebMsgBox.Show(ex.Message);
        }
    }
        private string ConvertMarkdownToHTML(List <MarkdownFile> files)
        {
            Log("Converting Markdown to HTML");
            StringBuilder sb = new StringBuilder();

            for (var i = 0; i < files.Count; i++)
            {
                var mf   = files[i];
                var file = new FileInfo(files[i].AbsolutePath);

                Log($"parsing file {file.Name}", LogLevel.Debug);
                var htmlfile = file.FullName.Replace(".md", ".html");
                var md       = File.ReadAllText(file.FullName);

                //setup the markdown pipeline to support tables
                var pipeline = new MarkdownPipelineBuilder().UsePipeTables().Build();

                //parse the markdown document so we can alter it later
                var document = (MarkdownObject)Markdown.Parse(md, pipeline);

                //adjust the links
                CorrectLinksAndImages(document, file, mf);

                string html    = null;
                var    builder = new StringBuilder();
                using (var writer = new System.IO.StringWriter(builder))
                {
                    // write the HTML output
                    var renderer = new HtmlRenderer(writer);
                    pipeline.Setup(renderer);
                    renderer.Render(document);
                }
                html = builder.ToString();

                //add html anchor
                var anchorPath = file.FullName.Substring(_path.Length);
                anchorPath = anchorPath.Replace("\\", "");
                anchorPath = anchorPath.ToLower();
                anchorPath = anchorPath.Replace(".md", "");

                var relativePath = file.FullName.Substring(_path.Length);

                var anchor = $"<a id=\"{anchorPath}\">&nbsp;</a>";

                Log($"\tAnchor: {anchorPath}");

                html = anchor + html;

                if (_options.PathToHeading)
                {
                    var filename = file.Name;
                    filename = HttpUtility.UrlDecode(relativePath);
                    var heading = $"<b>{filename}</b>";
                    html = heading + html;
                }

                if (_options.Heading)
                {
                    var filename = file.Name.Replace(".md", "");
                    filename = HttpUtility.UrlDecode(filename);
                    var heading = $"<h1>{filename}</h1>";
                    html = heading + html;
                }



                if (_options.BreakPage)
                {
                    //if not one the last page
                    if (i + 1 < files.Count)
                    {
                        Log("Adding new page to PDF");
                        html = "<div style='page-break-after: always;'>" + html + "</div>";
                    }
                }

                if (_options.Debug)
                {
                    Log($"html:\n{html}");
                }
                sb.Append(html);
            }

            var result = sb.ToString();


            return(result);
        }
Exemple #51
0
        public void generateCSR(string electoralEampaign, string user, string password)
        {
            X509Name                   name         = new X509Name("C=PL, ST=Mazowieckie, L=Warszawa, O=KBW, E=-, OU=" + electoralEampaign + ", CN=" + user);
            RsaKeyPairGenerator        keyGenerator = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters param        = new RsaKeyGenerationParameters(BigInteger.ValueOf(3L), new SecureRandom(), 2048, 25);

            keyGenerator.Init(param);
            AsymmetricCipherKeyPair    ackp = keyGenerator.GenerateKeyPair();
            Pkcs10CertificationRequest csr  = new Pkcs10CertificationRequest("SHA1WITHRSA", name, ackp.Public, null, ackp.Private);

            System.Text.StringBuilder CSRPem = new System.Text.StringBuilder();
            PemWriter CSRPemWriter           = new PemWriter(new System.IO.StringWriter(CSRPem));

            CSRPemWriter.WriteObject(csr);
            CSRPemWriter.Writer.Flush();
            this.generatedCSR = CSRPem.ToString();
            System.Text.StringBuilder PrivateKeyPem = new System.Text.StringBuilder();
            PemWriter PrivateKeyPemWriter           = new PemWriter(new System.IO.StringWriter(PrivateKeyPem));

            PrivateKeyPemWriter.WriteObject(ackp.Private);
            CSRPemWriter.Writer.Flush();
            this.keys = PrivateKeyPem.ToString();
            AsymmetricKeyParameter publicKey  = ackp.Public;
            AsymmetricKeyParameter privateKey = ackp.Private;

            System.IO.StringWriter sw = new System.IO.StringWriter();
            PemWriter pw = new PemWriter(sw);

            pw.WriteObject(privateKey, "AES-256-CBC", password.ToCharArray(), new SecureRandom());
            pw.Writer.Close();
            this.keys = sw.ToString();
            if (!System.IO.Directory.Exists(this.path + "\\Licenses"))
            {
                try
                {
                    System.IO.Directory.CreateDirectory(this.path + "\\Licenses");
                }
                catch (System.ArgumentNullException)
                {
                    MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
                }
                catch (System.ArgumentException)
                {
                    MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
                }
                catch (System.UnauthorizedAccessException)
                {
                    MessageBox.Show("Nie masz uprawnień do tworzenia katalogów. Otwórz aplikacje jako adnimistrator.", "Uwaga");
                }
                catch (System.IO.PathTooLongException)
                {
                    MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
                }
                catch (System.IO.DirectoryNotFoundException)
                {
                    MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
                }
                catch (System.NotSupportedException)
                {
                    MessageBox.Show("Nieprawidłowy format ścieżki. Nie można utworzyć katalogu \"Licenses\"", "Error");
                }
                catch (System.IO.IOException)
                {
                    MessageBox.Show("Nieprawidłowa ścieżka. Nie można utworzyć katalogu \"Licenses\"", "Error");
                }
            }
            string namefile = "";

            try
            {
                int tmp = System.IO.Directory.GetFiles(this.path + "\\Licenses", electoralEampaign.Replace("/", "_") + "_" + user + "*.csr").Length + 1;
                if (tmp > 1)
                {
                    string num = tmp.ToString();
                    namefile = string.Concat(new string[]
                    {
                        electoralEampaign.Replace("/", "_"),
                        "_",
                        user,
                        " ",
                        num
                    });
                }
                else
                {
                    namefile = electoralEampaign.Replace("/", "_") + "_" + user;
                }
            }
            catch (System.Exception)
            {
                namefile = electoralEampaign.Replace("/", "_") + "_" + user;
            }
            try
            {
                System.IO.StreamWriter sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".csr", false);
                sw2.Write(this.generatedCSR);
                sw2.Close();
                sw2 = new System.IO.StreamWriter(this.path + "\\Licenses\\" + namefile + ".key", false);
                sw2.Write(this.keys);
                sw2.Close();
            }
            catch (System.ArgumentNullException)
            {
                MessageBox.Show("Błędna ścieżka", "Error");
            }
            catch (System.ArgumentException)
            {
                MessageBox.Show("Błędna ścieżka", "Error");
            }
            catch (System.IO.DirectoryNotFoundException)
            {
                MessageBox.Show("Nie znaleziono katalogu", "Error");
            }
            catch (System.IO.PathTooLongException)
            {
                MessageBox.Show("Zbyt długa ścieżka do katalogu", "Error");
            }
            catch (System.IO.IOException)
            {
                MessageBox.Show("Podano ścieżke do pliku zamiast katalogu", "Error");
            }
            catch (System.UnauthorizedAccessException)
            {
                MessageBox.Show("Program nie posiada uprawnień do zapisywania plików. Otwórz aplikacje jako Administrator", "Error");
            }
            catch (System.Exception e)
            {
                MessageBox.Show("Nie można zapisać pliku. Orginal error: " + e.Message, "Error");
            }
        }
Exemple #52
0
    private string GenerateExportData(string dataFormat)
    {
        DataTable dtExcelData = Session["CVCAdderData"] as DataTable;

        string styleSheet    = "<style>.text { mso-number-format:\\@; } </style>";
        string headerContent = string.Empty;
        string footerContent = string.Empty;
        string excelContent  = string.Empty;

        headerContent  = "<table border='1' width='100%'>";
        headerContent += "<tr><th colspan='17' style='color:blue' align=left><center>CVC Addder Report</center></th></tr>";
        headerContent += "<tr><td colspan='17' align=right><b>Run By: " + Session["UserName"].ToString() + "&nbsp;&nbsp;  Run Date: " + DateTime.Now.ToShortDateString() + "</></td></tr>";
        headerContent += "<tr><th colspan='17' style='color:blue' align=left></th></tr>";

        if (dtExcelData.Rows.Count > 0)
        {
            dv.AutoGenerateColumns         = false;
            dv.ShowHeader                  = true;
            dv.ShowFooter                  = true;
            dv.FooterStyle.HorizontalAlign = HorizontalAlign.Right;
            //if(dataFormat == "Print")
            //dv.RowDataBound += new GridViewRowEventHandler(dv_RowDataBound);

            BoundField bfExcel = new BoundField();
            bfExcel.HeaderText = "Category";
            bfExcel.DataField  = "Category";
            bfExcel.ItemStyle.HorizontalAlign   = HorizontalAlign.Left;
            bfExcel.FooterStyle.HorizontalAlign = HorizontalAlign.Center;
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "Plating";
            bfExcel.DataField  = "Plating";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "CVC";
            bfExcel.DataField  = "CVCCd";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "Std Cost";
            bfExcel.DataField  = "STDCostAdder";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "Pkg/Case";
            bfExcel.DataField  = "PackageCaseAdder";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "West";
            bfExcel.DataField  = "1West";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "NW";
            bfExcel.DataField  = "2NW";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "Mtn";
            bfExcel.DataField  = "3Mtn";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "SW";
            bfExcel.DataField  = "4SW";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "CNTRL";
            bfExcel.DataField  = "5Cntrl";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "SE";
            bfExcel.DataField  = "6SE";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "NE";
            bfExcel.DataField  = "7NE";
            dv.Columns.Add(bfExcel);

            bfExcel                  = new BoundField();
            bfExcel.HeaderText       = "Eff Date";
            bfExcel.DataField        = "EffectiveDt";
            bfExcel.DataFormatString = "{0:MM/dd/yy}";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "Entry ID";
            bfExcel.DataField  = "EntryID";
            dv.Columns.Add(bfExcel);

            bfExcel                  = new BoundField();
            bfExcel.HeaderText       = "Entry Dt";
            bfExcel.DataField        = "EntryDt";
            bfExcel.DataFormatString = "{0:MM/dd/yy}";
            dv.Columns.Add(bfExcel);

            bfExcel            = new BoundField();
            bfExcel.HeaderText = "Change ID";
            bfExcel.DataField  = "ChangeID";
            dv.Columns.Add(bfExcel);

            bfExcel                  = new BoundField();
            bfExcel.HeaderText       = "Change Dt";
            bfExcel.DataField        = "ChangeDt";
            bfExcel.DataFormatString = "{0:MM/dd/yy}";
            dv.Columns.Add(bfExcel);

            dv.DataSource = dtExcelData;
            dv.DataBind();

            System.Text.StringBuilder sb  = new System.Text.StringBuilder();
            System.IO.StringWriter    sw  = new System.IO.StringWriter(sb);
            HtmlTextWriter            htw = new HtmlTextWriter(sw);
            dv.RenderControl(htw);
            excelContent = sb.ToString();
        }
        else
        {
            excelContent = "<tr  ><th width='100%' align ='center' colspan='17' > No records found</th></tr> </table>";
        }

        return(styleSheet + headerContent + excelContent);
    }
Exemple #53
0
        protected void BtnExportarAExcel_Click(object sender, EventArgs e)
        {
            try
            {
                if (Session["dsReporteRemitosFaltantes"] != null)
                {
                    List <RemitosFaltantesClaseReporte> lstRemitosFaltantesAll = new List <RemitosFaltantesClaseReporte>();
                    lstRemitosFaltantesAll = (List <RemitosFaltantesClaseReporte>)Session["dsReporteRemitosFaltantes"];

                    if (lstRemitosFaltantesAll.Count > 0)
                    {
                        PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(RemitosFaltantesClaseReporte));

                        DataTable table = new DataTable();

                        foreach (PropertyDescriptor prop in properties)
                        {
                            table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
                        }


                        foreach (RemitosFaltantesClaseReporte item in lstRemitosFaltantesAll)
                        {
                            DataRow row = table.NewRow();
                            foreach (PropertyDescriptor prop in properties)
                            {
                                row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                            }
                            table.Rows.Add(row);
                        }


                        DataSet dsExcel = new DataSet();
                        dsExcel.Tables.Add(table);

                        dsExcel.Tables[0].Columns["FechaRendicion"].SetOrdinal(0);
                        dsExcel.Tables[0].Columns["Comentario"].SetOrdinal(1);
                        dsExcel.Tables[0].Columns["FechaCarga"].SetOrdinal(2);
                        dsExcel.Tables[0].Columns["RazonSocial"].SetOrdinal(3);
                        dsExcel.Tables[0].Columns["Remito"].SetOrdinal(4);
                        dsExcel.Tables[0].Columns["FechaEmision"].SetOrdinal(5);
                        dsExcel.Tables[0].Columns["FacturaCliente"].SetOrdinal(6);
                        dsExcel.Tables[0].Columns["NroGuia"].SetOrdinal(7);
                        dsExcel.Tables[0].Columns["RazonSocialOrigen"].SetOrdinal(8);
                        dsExcel.Tables[0].Columns["RazonSocialDestino"].SetOrdinal(9);
                        dsExcel.Tables[0].Columns["UnidadVentaDescrip"].SetOrdinal(10);
                        dsExcel.Tables[0].Columns["ModalidadEntregaDescrip"].SetOrdinal(11);
                        dsExcel.Tables[0].Columns["Destinatario"].SetOrdinal(12);
                        dsExcel.Tables[0].Columns["EstadoAdministrativo"].SetOrdinal(13);
                        dsExcel.Tables[0].Columns["FechaEstadoAdministrativo"].SetOrdinal(14);
                        dsExcel.Tables[0].Columns["EstadoMovimiento"].SetOrdinal(15);
                        dsExcel.Tables[0].Columns["FechaEstadoMovimiento"].SetOrdinal(16);
                        dsExcel.Tables[0].Columns["EstadoUbicacion"].SetOrdinal(17);
                        dsExcel.Tables[0].Columns["FechaEstadoUbicacion"].SetOrdinal(18);
                        dsExcel.Tables[0].Columns["EstadoEntrega"].SetOrdinal(19);
                        dsExcel.Tables[0].Columns["FechaEstadoEntrega"].SetOrdinal(20);
                        dsExcel.Tables[0].Columns["Observaciones"].SetOrdinal(21);
                        dsExcel.Tables[0].Columns["RendicionConformacion"].SetOrdinal(22);
                        dsExcel.Tables[0].Columns["GuiaDigitalizada"].SetOrdinal(23);
                        dsExcel.Tables[0].Columns["RemitoDigitalizado"].SetOrdinal(24);
                        dsExcel.Tables[0].Columns["PesoTotal"].SetOrdinal(25);
                        dsExcel.Tables[0].Columns["CantidadBultosTotal"].SetOrdinal(26);
                        dsExcel.Tables[0].Columns["ImporteNetoTotal"].SetOrdinal(27);

                        DataGrid dg = new DataGrid();
                        dg.ShowFooter     = false;
                        dg.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(dgReporteRemitosFaltantes_ItemDataBound);

                        DataColumnCollection columns = dsExcel.Tables[0].Columns;

                        if (columns.Contains("Rinde"))
                        {
                            dsExcel.Tables[0].Columns.Remove("Rinde");
                        }

                        if (columns.Contains("GuiaID"))
                        {
                            dsExcel.Tables[0].Columns.Remove("GuiaID");
                        }

                        if (columns.Contains("FacturaID"))
                        {
                            dsExcel.Tables[0].Columns.Remove("FacturaID");
                        }

                        if (columns.Contains("FacturacionBolsinesID"))
                        {
                            dsExcel.Tables[0].Columns.Remove("FacturacionBolsinesID");
                        }

                        if (columns.Contains("CodigoCliente"))
                        {
                            dsExcel.Tables[0].Columns.Remove("CodigoCliente");
                        }

                        if (columns.Contains("RemitoClienteNro"))
                        {
                            dsExcel.Tables[0].Columns.Remove("RemitoClienteNro");
                        }

                        if (columns.Contains("FechaCarga"))
                        {
                            dsExcel.Tables[0].Columns["FechaCarga"].ColumnName = "Fecha Carga";
                        }

                        if (columns.Contains("RazonSocial"))
                        {
                            dsExcel.Tables[0].Columns["RazonSocial"].ColumnName = "Cliente";
                        }

                        if (columns.Contains("FechaEmision"))
                        {
                            dsExcel.Tables[0].Columns["FechaEmision"].ColumnName = "Fecha Emisión";
                        }

                        if (columns.Contains("FacturaCliente"))
                        {
                            dsExcel.Tables[0].Columns["FacturaCliente"].ColumnName = "Factura Cliente";
                        }

                        if (columns.Contains("NroGuia"))
                        {
                            dsExcel.Tables[0].Columns["NroGuia"].ColumnName = "Nro. Guía";
                        }

                        if (columns.Contains("RazonSocialOrigen"))
                        {
                            dsExcel.Tables[0].Columns["RazonSocialOrigen"].ColumnName = "Agencia Origen";
                        }

                        if (columns.Contains("RazonSocialDestino"))
                        {
                            dsExcel.Tables[0].Columns["RazonSocialDestino"].ColumnName = "Agencia Destino";
                        }

                        if (columns.Contains("UnidadVentaDescrip"))
                        {
                            dsExcel.Tables[0].Columns["UnidadVentaDescrip"].ColumnName = "Unidad Venta";
                        }

                        if (columns.Contains("ModalidadEntregaDescrip"))
                        {
                            dsExcel.Tables[0].Columns["ModalidadEntregaDescrip"].ColumnName = "Modalidad Entrega";//
                        }

                        if (columns.Contains("EstadoAdministrativo"))
                        {
                            dsExcel.Tables[0].Columns["EstadoAdministrativo"].ColumnName = "Estado Administrativo";
                        }

                        if (columns.Contains("FechaEstadoAdministrativo"))
                        {
                            dsExcel.Tables[0].Columns["FechaEstadoAdministrativo"].ColumnName = "Fecha Estado Administrativo";
                        }

                        if (columns.Contains("EstadoMovimiento"))
                        {
                            dsExcel.Tables[0].Columns["EstadoMovimiento"].ColumnName = "Estado Movimiento";//
                        }

                        if (columns.Contains("FechaEstadoMovimiento"))
                        {
                            dsExcel.Tables[0].Columns["FechaEstadoMovimiento"].ColumnName = "Fecha Estado Movimiento";
                        }

                        if (columns.Contains("EstadoUbicacion"))
                        {
                            dsExcel.Tables[0].Columns["EstadoUbicacion"].ColumnName = "Estado Ubicacion";//
                        }

                        if (columns.Contains("FechaEstadoUbicacion"))
                        {
                            dsExcel.Tables[0].Columns["FechaEstadoUbicacion"].ColumnName = "Fecha Estado Ubicacion";
                        }

                        if (columns.Contains("EstadoEntrega"))
                        {
                            dsExcel.Tables[0].Columns["EstadoEntrega"].ColumnName = "Estado Entrega";//
                        }

                        if (columns.Contains("FechaEstadoEntrega"))
                        {
                            dsExcel.Tables[0].Columns["FechaEstadoEntrega"].ColumnName = "Fecha Estado Entrega";
                        }

                        if (columns.Contains("RendicionConformacion"))
                        {
                            dsExcel.Tables[0].Columns["RendicionConformacion"].ColumnName = "Rendicion Conformacion";//
                        }

                        if (columns.Contains("GuiaDigitalizada"))
                        {
                            dsExcel.Tables[0].Columns["GuiaDigitalizada"].ColumnName = "Guia Digitalizada";
                        }

                        if (columns.Contains("RemitoDigitalizado"))
                        {
                            dsExcel.Tables[0].Columns["RemitoDigitalizado"].ColumnName = "Remito Digitalizado";
                        }

                        if (columns.Contains("PesoTotal"))
                        {
                            dsExcel.Tables[0].Columns["PesoTotal"].ColumnName = "Peso Total";//
                        }

                        if (columns.Contains("CantidadBultosTotal"))
                        {
                            dsExcel.Tables[0].Columns["CantidadBultosTotal"].ColumnName = "Bultos";
                        }

                        if (columns.Contains("ImporteNetoTotal"))
                        {
                            dsExcel.Tables[0].Columns["ImporteNetoTotal"].ColumnName = "Importe NETO";
                        }

                        dsExcel.AcceptChanges();

                        dg.DataSource = dsExcel.Tables[0];
                        dg.DataBind();

                        this.EnableViewState = false;
                        Response.Clear();
                        Response.Buffer          = true;
                        Response.ContentType     = "application/vnd.ms-excel";
                        Response.Charset         = "";
                        Response.ContentEncoding = System.Text.Encoding.Default;
                        Response.AddHeader("Content-Disposition", "filename=ReporteRemitosFaltantes.xls");
                        System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
                        System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
                        dg.RenderControl(oHtmlTextWriter);
                        Response.Write(oStringWriter.ToString());
                        Response.End();
                    }
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemple #54
0
        private void CreateUser(string login, string password) ///////Creates a user by adding his name to userlist.txt and creating his user folder with hashed pass and salt
        {                                                      //////////also create RSA keys
            string path    = @"..\..\UsersFiles\UserList.txt";
            string dirpath = @"..\..\UsersFiles\";

            dirpath += login;
            try
            {
                using (StreamWriter sw = File.AppendText(path)) ///////adding to userlist
                {
                    sw.WriteLine(login);
                }

                byte[] salt1 = new byte[8];
                using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
                {
                    // Fill the array with a random value.
                    rngCsp.GetBytes(salt1);
                }
                System.IO.Directory.CreateDirectory(dirpath);
                string passpath = dirpath + "\\\\paswd.txt";
                using (StreamWriter sw = File.CreateText(passpath)) {   //create the file for password
                    sw.WriteLine(SHA2salted.GenerateSHA512String(password, salt1));
                }
                string saltpath = dirpath + "\\\\salt.txt";
                using (StreamWriter sw = File.CreateText(saltpath))   //create the file for salt
                {
                    sw.WriteLine(SHA2salted.GetStringFromHash(salt1));
                }
                string who = "Hi " + login;
                MessageBox.Show("User Created", who, MessageBoxButton.OK, MessageBoxImage.None);
                //lets take a new CSP with a new 2048 bit rsa key pair
                var csp = new RSACryptoServiceProvider(2048);

                //how to get the private key
                var    privKey = csp.ExportParameters(true);
                string privKeyString;
                //we need some buffer
                var sw1 = new System.IO.StringWriter();
                //we need a serializer
                var xs1 = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                //serialize the key into the stream
                xs1.Serialize(sw1, privKey);
                //get the string from the stream
                privKeyString = sw1.ToString();

                var sw2 = new System.IO.StringWriter();
                //we need a serializer
                var xs2 = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                //and the public key ...
                var    pubKey = csp.ExportParameters(false);
                string pubKeyString;
                //serialize the key into the stream
                xs2.Serialize(sw2, pubKey);
                //get the string from the stream
                pubKeyString = sw2.ToString();


                string dirpathPub = dirpath + @"\PUGB";
                System.IO.Directory.CreateDirectory(dirpathPub);
                dirpathPub += @"\PUGB.txt";
                File.WriteAllText(dirpathPub, pubKeyString);
                //using (StreamWriter sw = File.CreateText(dirpathPub))
                //{   //create the file for publicKey
                //    sw.WriteLine(pubKeyString);
                //}


                string dirpathPriv = dirpath + @"\PRIV";
                System.IO.Directory.CreateDirectory(dirpathPriv);
                dirpathPriv += @"\PRIV.txt";
                RSAHandle.EncryptPrivate(privKeyString, SHA2salted.GenerateSHA512String(password, salt1), dirpathPriv);
                string resultPrivRSA = RSAHandle.DecryptPrivate(SHA2salted.GenerateSHA512String(password, salt1), dirpathPriv);
                var    key           = RSAHandle.StringToKey(resultPrivRSA);

                //we want to decrypt, therefore we need a csp and load our private key
                var csp2 = new RSACryptoServiceProvider();
                csp2.ImportParameters(key);
                csp.PersistKeyInCsp = false;
                this.Close();
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #55
0
    void Import(string szFilePath, string szErrListRawFile, out uint nImported, out uint nFailed)
    {
        ErrorLines = new ArrayList();
        nImported  = 0;
        nFailed    = 0;
        string strline;

        StreamWriter tWrite = new StreamWriter(szErrListRawFile, false, Encoding.GetEncoding("gb2312"));

        System.IO.StreamReader mysr      = new StreamReader(Server.MapPath(szFilePath), Encoding.GetEncoding("gb2312"));
        REQUESTCODE            uResponse = REQUESTCODE.EXECUTE_FAIL;

        System.IO.StringWriter swCSV = new System.IO.StringWriter();
        bool bAllRight = true;
        int  count     = 0;

        while ((strline = mysr.ReadLine()) != null)
        {
            count = count + 1;
            string[] szList = strline.Split(',');
            if (szList.Length < 8)
            {
                continue;
            }
            string researchSN   = szList[0];
            string researchName = szList[1];
            string szLogonName  = szList[2];
            string szTrueName   = szList[3];
            string szDeptName   = szList[4];

            string       szDate      = szList[5];
            string       szDeptName2 = szList[6];
            string       szLevel     = szList[7];
            UNIACCOUNT   studentAcc;
            UNIACCOUNT[] accList;
            string       szLogonNameError = "不能存在账户:";
            string       szMemo           = "";

            if (GetAccByLogonName(szLogonName.Trim(), out studentAcc))
            {
            }
            else
            {
                accList = GetAccByTrueName(szTrueName.Trim());
                if (accList == null)
                {
                    szMemo = "账户不存在";
                }
                else if (accList.Length > 1)
                {
                    for (int i = 0; i < accList.Length; i++)
                    {
                        szMemo += accList[i].szLogonName + "," + accList[i].szTrueName + "," + accList[i].szDeptName + ";";
                    }
                }
                else
                {
                    studentAcc = accList[0];
                }
            }
            if (studentAcc.dwAccNo == null)
            {
                System.Text.StringBuilder sbText = new System.Text.StringBuilder();
                sbText = AppendCSVFields(sbText, researchSN);
                sbText = AppendCSVFields(sbText, researchName);
                sbText = AppendCSVFields(sbText, szLogonName);
                sbText = AppendCSVFields(sbText, szTrueName);
                sbText = AppendCSVFields(sbText, szDeptName);  //协助
                sbText = AppendCSVFields(sbText, szDate);      ////使用
                sbText = AppendCSVFields(sbText, szDeptName2); //样品费
                sbText = AppendCSVFields(sbText, szLevel);     //样品费
                sbText = AppendCSVFields(sbText, szMemo);      //样品费
                sbText.Remove(sbText.Length - 1, 1);
                swCSV.WriteLine(sbText.ToString());

                if (count != 1)
                {
                    bAllRight = false;
                }

                continue;
            }
            UNIDEPT      dept;
            RESEARCHTEST setValue = new RESEARCHTEST();
            if (GetDeptByName(szDeptName, out dept))
            {
                setValue.dwDeptID = dept.dwID;
            }
            else
            {
                setValue.dwDeptID = 0;
            }
            setValue.dwLeaderID   = studentAcc.dwAccNo;
            setValue.dwLeaderID   = studentAcc.dwAccNo;
            setValue.szLeaderName = studentAcc.szTrueName;
            setValue.szLeaderName = studentAcc.szTrueName;
            setValue.szRTName     = researchName;
            setValue.szRTSN       = researchSN;
            setValue.dwBeginDate  = GetDate(szDate);
            setValue.dwRTLevel    = Parse(szLevel);
            setValue.szFromUnit   = szDeptName2;
            UNIGROUP setGroup;
            if (NewGroup(setValue.szRTName, (uint)UNIGROUP.DWKIND.GROUPKIND_RERV, out setGroup))
            {
                setValue.dwGroupID = setGroup.dwGroupID;
            }
            else
            {
                continue;
            }
            uResponse = m_Request.Reserve.SetResearchTest(setValue, out setValue);
            if (uResponse == REQUESTCODE.EXECUTE_SUCCESS)
            {
                nImported = nImported + 1;
                AddGroupMember(setGroup.dwGroupID, setValue.dwLeaderID, (uint)GROUPMEMBER.DWKIND.MEMBERKIND_PERSONAL);
                EXTIDENTACC setTutor = new EXTIDENTACC();
                setTutor.dwAccNo = setValue.dwLeaderID;
                m_Request.Account.ExtIdentAccSet(setTutor);
            }
            else
            {
                szMemo = m_Request.szErrMessage;
                System.Text.StringBuilder sbText = new System.Text.StringBuilder();
                sbText = AppendCSVFields(sbText, researchSN);
                sbText = AppendCSVFields(sbText, researchName);
                sbText = AppendCSVFields(sbText, szLogonName);
                sbText = AppendCSVFields(sbText, szTrueName);
                sbText = AppendCSVFields(sbText, szDeptName);  //协助
                sbText = AppendCSVFields(sbText, szDate);      ////使用
                sbText = AppendCSVFields(sbText, szDeptName2); //样品费
                sbText = AppendCSVFields(sbText, szLevel);     //样品费
                sbText = AppendCSVFields(sbText, szMemo);      //样品费
                sbText.Remove(sbText.Length - 1, 1);
                swCSV.WriteLine(sbText.ToString());
                bAllRight = false;
                uResponse = m_Request.Group.DelGroup(setGroup);
            }
            {
                szLogonNameError += szLogonName + ",";
            }
        }
        if (!bAllRight)
        {
            DownloadFile(Response, swCSV.GetStringBuilder(), "resarchTestImport.csv");
        }
        swCSV.Close();
        Response.End();
    }
Exemple #56
0
    void Import(string szFilePath, string szErrListRawFile, out uint nImported, out uint nFailed)
    {
        ErrorLines = new ArrayList();
        nImported  = 0;
        nFailed    = 0;
        string strline;

        StreamWriter tWrite = new StreamWriter(szErrListRawFile, false, Encoding.GetEncoding("gb2312"));

        System.IO.StreamReader mysr      = new StreamReader(Server.MapPath(szFilePath), Encoding.GetEncoding("gb2312"));
        REQUESTCODE            uResponse = REQUESTCODE.EXECUTE_FAIL;

        System.IO.StringWriter swCSV = new System.IO.StringWriter();
        bool bAllRight  = true;
        uint count      = 0;
        uint uCountFali = 0;

        while ((strline = mysr.ReadLine()) != null)
        {
            count = count + 1;
            string[] szList = strline.Split(',');

            string szDevName    = szList[0];
            string szStartDate  = szList[1];
            string szEndDate    = szList[2];
            string szSelectWeek = szList[3];
            string szResvTime   = szList[4];

            string      szLogonNames = szList[5];
            string[]    szOwnerList  = szLogonNames.ToString().Split(';');
            UNIDEVICE[] devList;

            devList = getDevByName(szDevName);
            if (szDevName == "" || devList == null || devList.Length == 0 || devList.Length > 1)
            {
                uCountFali = uCountFali + 1;
                continue;
            }
            DateTime startDate = DateTime.Parse(szStartDate);
            DateTime endDate   = DateTime.Parse(szEndDate);
            TimeSpan span      = endDate - startDate;
            while (span.Days > -1)
            {
                int uweek = (int)startDate.DayOfWeek;
                if (uweek == 0)
                {
                    uweek = 7;
                }
                if (szSelectWeek == null || szSelectWeek == "" || szSelectWeek.IndexOf(uweek.ToString()) > -1)
                {
                    string[] resvTimesList = szResvTime.Split(';');
                    if (resvTimesList == null || resvTimesList.Length == 0)
                    {
                        return;
                    }
                    for (int m = 0; m < resvTimesList.Length; m++)
                    {
                        UNIRESERVE setValue = new UNIRESERVE();
                        UNIGROUP   resvGroup;
                        if (NewGroup("管理员新建预约", (uint)UNIGROUP.DWKIND.GROUPKIND_RERV, out resvGroup))
                        {
                            for (int i = 0; i < szOwnerList.Length; i++)
                            {
                                UNIACCOUNT acc = new UNIACCOUNT();
                                if (GetAccByLogonName(szOwnerList[i], out acc))
                                {
                                    AddGroupMember(resvGroup.dwGroupID, acc.dwAccNo, (uint)GROUPMEMBER.DWKIND.MEMBERKIND_PERSONAL);
                                }
                            }


                            setValue.dwMemberID   = resvGroup.dwGroupID;
                            setValue.dwMemberKind = (uint)UNIRESERVE.DWMEMBERKIND.MEMBERKIND_GROUP;

                            UNIACCOUNT vrAccInfo = ((ADMINLOGINRES)Session["LoginResult"]).AccInfo;
                            setValue.dwOwner     = vrAccInfo.dwAccNo;
                            setValue.szOwnerName = vrAccInfo.szTrueName;
                            setValue.szTestName  = Request["szMemo"];

                            UNIDEVICE dev = new UNIDEVICE();
                            dev = devList[0];
                            setValue.ResvDev               = new RESVDEV[1];
                            setValue.ResvDev[0].dwDevEnd   = dev.dwDevSN;
                            setValue.ResvDev[0].dwDevStart = dev.dwDevSN;
                            setValue.ResvDev[0].dwDevNum   = 1;
                            setValue.ResvDev[0].dwDevKind  = dev.dwKindID;
                            setValue.ResvDev[0].szRoomNo   = dev.szRoomNo;
                            setValue.ResvDev[0].szDevName  = dev.szDevName;
                            setValue.dwLabID               = dev.dwLabID;
                            setValue.szLabName             = dev.szLabName;


                            setValue.dwProperty = (uint)UNIRESERVE.DWPROPERTY.RESVPROP_SELFDO;
                            setValue.dwPurpose  = (uint)UNIRESERVE.DWPURPOSE.USEFOR_PERSONNAL;


                            string[] szResvTimeListIn = resvTimesList[m].Split('-');
                            if (szResvTimeListIn == null || szResvTimeListIn.Length < 2)
                            {
                                continue;
                            }
                            string szStartTime     = szResvTimeListIn[0];
                            string szEndTime       = szResvTimeListIn[1];
                            string szStartTimeTemp = startDate.ToString("yyyy-MM-dd") + " " + szStartTime;
                            string szEndTimeTemp   = startDate.ToString("yyyy-MM-dd") + " " + szEndTime;

                            setValue.dwBeginTime = Get1970Seconds(szStartTimeTemp);
                            setValue.dwEndTime   = Get1970Seconds(szEndTimeTemp);


                            if (m_Request.Reserve.Set(setValue, out setValue) == REQUESTCODE.EXECUTE_SUCCESS)
                            {
                                count = count + 1;
                            }
                            else
                            {
                                uCountFali = uCountFali + 1;
                            }
                            setValue.dwResvID = null;
                        }
                    }
                }
                startDate = startDate.AddDays(1);
                span      = endDate - startDate;
            }
        }
        if (!bAllRight)
        {
            DownloadFile(Response, swCSV.GetStringBuilder(), "resarchTestImport.csv");
        }
        nImported = count;
        nFailed   = uCountFali;
        tWrite.Close();
    }
Exemple #57
0
        private void PerformActMainframeGetDetails(Act act)
        {
            ActMainframeGetDetails MFGD = (ActMainframeGetDetails)act;

            //todo Implement get Type and others


            switch (MFGD.DetailsToFetch)
            {
            case ActMainframeGetDetails.eDetailsToFetch.GetText:

                ActMainFrameGetText(act);

                break;

            case ActMainframeGetDetails.eDetailsToFetch.GetDetailsFromText:

                MainframeGetDetailsFromText(act);
                break;

            case ActMainframeGetDetails.eDetailsToFetch.GetAllEditableFeilds:

                XmlDocument    XD  = new XmlDocument();
                XmlDeclaration dec = XD.CreateXmlDeclaration("1.0", null, null);
                XD.AppendChild(dec);
                XmlElement root = XD.CreateElement("EditableFields");
                XD.AppendChild(root);

                string CaretValuePair = @"<?xml version='1.0' encoding='UTF-8'?><nodes>";

                XMLScreen XC = MFE.GetScreenAsXML();
                foreach (XMLScreenField XSF in XC.Fields)
                {
                    if (XSF.Attributes.Protected)
                    {
                        continue;
                    }
                    string node = "<node caret=\"" + XSF.Location.position.ToString() + "\" text=\"" + XSF.Text + "\"> </node>";

                    CaretValuePair = CaretValuePair + node;

                    XmlElement EditableField = XD.CreateElement("EditableField");
                    EditableField.SetAttribute("Caret", XSF.Location.position.ToString());
                    EditableField.SetAttribute("Text", XSF.Text);
                    root.AppendChild(EditableField);
                }

                act.AddOrUpdateReturnParamActual("Fields", XD.OuterXml);

                break;

            case ActMainframeGetDetails.eDetailsToFetch.GetCurrentScreenAsXML:

                Open3270.TN3270.XMLScreen XMLS = MFE.GetScreenAsXML();
                System.Xml.Serialization.XmlSerializer xsSubmit = new System.Xml.Serialization.XmlSerializer(typeof(Open3270.TN3270.XMLScreen));
                System.IO.StringWriter sww    = new System.IO.StringWriter();
                System.Xml.XmlWriter   writer = System.Xml.XmlWriter.Create(sww);

                xsSubmit.Serialize(writer, XMLS);
                String ScreenXML = sww.ToString();     // Your XML

                act.AddOrUpdateReturnParamActual("ScreenXML", ScreenXML);

                break;

            default:
                throw new NotSupportedException("The action is not supporte yet");
            }
        }
Exemple #58
0
    protected void Export_Click(object sender, EventArgs e)
    {
        this.Submit_Click(null, null);
        if (this.ChartExport == null)
        {
            this.GridViewToExcel(this.Response, null);
            return;
        }
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=ChartExport.xls");
        Response.ContentType = "application/vnd.ms-excel";
        Response.Charset     = "";
        StringWriter   sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        this.ChartExport.RenderControl(hw);
        string src = Regex.Match(sw.ToString(), "<img.+?src=[\"'](.+?)[\"'].+?>", RegexOptions.IgnoreCase).Groups[1].Value;
        string img = string.Format("<img src = '{0}{1}' />", Request.Url.GetLeftPart(UriPartial.Authority), src);

        Table    table = new Table();
        TableRow row   = new TableRow();

        row.Cells.Add(new TableCell());
        row.Cells[0].Width           = 200;
        row.Cells[0].RowSpan         = 26;
        row.Cells[0].HorizontalAlign = HorizontalAlign.Center;
        // row.Cells[0].Controls.Add(new Label { Text = "Fruits Distribution (India)", ForeColor = Color.Red });
        row.Cells[0].Controls.Add(new Literal {
            Text = img
        });
        table.Rows.Add(row);
        //row = new TableRow();
        //row.Cells.Add(new TableCell());
        //row.Cells[0].Controls.Add(new Literal { Text = img });
        //table.Rows.Add(row);

        sw = new StringWriter();
        hw = new HtmlTextWriter(sw);
        table.RenderControl(hw);

        System.IO.StringWriter       writer = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter html   = new HtmlTextWriter(writer);
        GridView gv = this.GridView1;

        foreach (TableCell cell in gv.HeaderRow.Cells)
        {
            if (cell.Text == "c")
            {
                cell.Text = "Total Count";
            }
        }
        gv.Rows[gv.Rows.Count - 1].Cells[0].Text = "Total";
        foreach (TableCell cell in gv.Rows[gv.Rows.Count - 1].Cells)
        {
            cell.Font.Bold = true;
        }
        gv.RenderControl(html);
        string s = writer.ToString();

        Response.Write(sw.ToString() + s);
        Response.Flush();
        Response.End();
    }
Exemple #59
0
    public void Save(string path, bool pretty = true, int MainVersion = 0, int SubVersion = 0)
    {
        List <Pack> packs = new List <Pack>();

        foreach (Pack pack in _packs.Values)
        {
            packs.Add(pack);
        }

        List <File> files = new List <File>();

        foreach (File file in _files.Values)
        {
            files.Add(file);
        }

        List <Scene> scenes = new List <Scene>();

        foreach (Scene scene in _scenes.Values)
        {
            scenes.Add(scene);
        }

        List <SpritePack> spritePacks = new List <SpritePack>();

        foreach (SpritePack spritePack in _spritePacks.Values)
        {
            spritePacks.Add(spritePack);
        }

        List <BundlePackRule> bundleRules = new List <BundlePackRule>();

        foreach (BundlePackRule bundleRule in _bundleRules)
        {
            bundleRules.Add(bundleRule);
        }

#if UNITY_EDITOR
        #region CACHE
        BundleExtraCacheInfo cacheInfo    = null;
        List <string>        cacheInScene = null;
        List <string>        cacheAllTime = null;
        List <string>        notCache     = null;
        string infoText = BundleExtraInfoUtils.GetBundleExtraCacheInfoText();
        if (!string.IsNullOrEmpty(infoText))
        {
            cacheInfo = LitJson.JsonMapper.ToObject <BundleExtraCacheInfo>(infoText);
            if (cacheInfo != null)
            {
                cacheInScene = BundleExtraInfoUtils.ArrayToList <string>(cacheInfo.CacheInScene);
                if (cacheInScene == null)
                {
                    cacheInScene = new List <string>();
                }
                cacheAllTime = BundleExtraInfoUtils.ArrayToList <string>(cacheInfo.CacheAllTime);
                if (cacheAllTime == null)
                {
                    cacheAllTime = new List <string>();
                }

                notCache = BundleExtraInfoUtils.ArrayToList <string>(cacheInfo.NotCache);
                if (notCache == null)
                {
                    notCache = new List <string>();
                }

                foreach (Pack pack in packs)
                {
                    SetupBundleCacheType(pack, notCache, cacheInScene, cacheAllTime);
                }

                foreach (Scene scene in scenes)
                {
                    SetupBundleCacheType(scene, notCache, cacheInScene, cacheAllTime);
                }
            }
        }
        else
        {
            Debug.LogError("NOT FOUND BUNDLE EXTRA INFO TEXT!!!!!!!!!!!!");
        }

        #endregion      //CACHE
#endif

        XManifestInfo manifest = new XManifestInfo();
        manifest.packs       = packs;
        manifest.files       = files;
        manifest.scenes      = scenes;
        manifest.spritePacks = spritePacks;
        manifest.bundleRules = bundleRules;
        manifest.MainVersion = MainVersion;
        manifest.SubVersion  = SubVersion;

        Debug.LogFormat("Mainfest_Save {0}, {1}", MainVersion, SubVersion);

        System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        if (fs != null)
        {
            StringBuilder          sb     = new StringBuilder();
            System.IO.StringWriter writer = new System.IO.StringWriter(sb);
            LitJson.JsonMapper.ToJson(manifest,
                                      new LitJson.JsonWriter(writer)
            {
                PrettyPrint = pretty
            });

            byte[] buff = Encoding.UTF8.GetBytes(sb.ToString());

            fs.Write(buff, 0, buff.Length);
            fs.Close();
        }
    }
    public void btnBuscar_Click(object sender, EventArgs e)
    {
        ws_VehiculosYPF ws = new ws_VehiculosYPF();

        List <dynamic> datosExportar = ws.getExportacion().ToList <dynamic>();


        List <string> camposExcluir       = new List <string>();;
        Dictionary <string, string> alias = new Dictionary <string, string>();

        alias.Add("Patente", "Dominio");
        alias.Add("Modelo", "Marca y Modelo");
        alias.Add("Año", "Año");
        alias.Add("TipoCombustible", "Combustible");
        alias.Add("VtoTarjVerde", "Vencimiento T. Verde");
        alias.Add("VtoRevTecnica", "Vencimiento Rev. Tec.");
        alias.Add("VelocimetroFecha", "Fecha Odom.");
        alias.Add("VelocimetroOdometro", "Velocidad Odom.");

        alias.Add("Contrato", "Conrtato YER");
        alias.Add("CentroCosto", "CeCo");
        alias.Add("TipoAsignacion", "Asignación");
        alias.Add("RazonSocial", "Razon Social Contrato YER");
        alias.Add("NroTarjeta", "Tarjeta YER Nro.");

        alias.Add("TarjetasActivas", "Tarjetas Activas");
        alias.Add("LimiteCredito", "Límite Crédito");

        alias.Add("Departamento", "Area");
        alias.Add("Sector", "Departamento");



        alias.Add("ControlAlarma", "Control de Alarma");
        alias.Add("LlaveAlarma", "Llave con Alarma");
        alias.Add("LimiteConsMensual", "Límite Consumo Mensual");
        alias.Add("TipoVehiculo", "Tipo Vehiculo");


        alias.Add("TitularPin", "Usuario PIN");
        alias.Add("TitularPin1", "Usuario PIN1");
        alias.Add("TitularPin2", "Usuario PIN2");
        alias.Add("TitularPin3", "Usuario PIN3");
        alias.Add("TitularPin4", "Usuario PIN4");
        alias.Add("TitularPin5", "Usuario PIN5");
        alias.Add("TitularPin6", "Usuario PIN6");
        alias.Add("TitularPin7", "Usuario PIN7");


        camposExcluir.Add("IdEstado");
        camposExcluir.Add("IdTipoVehiculo");
        camposExcluir.Add("IdDepartamento");
        camposExcluir.Add("IdSector");
        camposExcluir.Add("IdTipoAsignacion");
        camposExcluir.Add("IdTipoCombustible");


        List <string> DatosReporte = new List <string>();

        DatosReporte.Add("Veh&iacute;culos YPF");
        DatosReporte.Add("Fecha y Hora emisi&oacute;n:" + DateTime.Now.ToString());
        DatosReporte.Add("");
        DatosReporte.Add("Incluye todos los Veh&iacute;culos YPF que fueron dados de alta");


        GridView gv = Helpers.GenerarExportExcel(datosExportar.ToList <dynamic>(), alias, camposExcluir, DatosReporte);

        System.IO.StringWriter       stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite   = new HtmlTextWriter(stringWrite);
        gv.RenderControl(htmlWrite);

        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=VehiculosYpf" + "_" + DateTime.Now.ToString("M_dd_yyyy_H_M_s") + ".xls");
        HttpContext.Current.Response.ContentType = "application/xls";
        HttpContext.Current.Response.Write(stringWrite.ToString());
        HttpContext.Current.Response.End();
    }