System.IO.StreamReader.ReadToEnd()

Here are the examples of the csharp api System.IO.StreamReader.ReadToEnd() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5164 Examples 7

19 Source : FaceDancer.cs
with MIT License
from 001SPARTaN

static void Main(string[] args)
        {
            int procId;
            string file;

            if (args.Length < 2)
            {
                file = "whoami /priv";
                if (args.Length == 0)
                {
                    // If we don't have a process ID as an argument, find winlogon.exe
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                }
                else if (args[0].Contains('.'))
                {
                    procId = Process.GetProcessesByName("winlogon").First().Id;
                    if (args != null)
                    {
                        file = args[0];
                    }
                }
                else
                {
                    procId = Convert.ToInt32(args[0]);
                }
            }
            else
            {
                procId = Convert.ToInt32(args[0]);
                file = args[1];
            }
            Console.WriteLine("Stealing token from PID " + procId);

            IntPtr tokenHandle = IntPtr.Zero;
            IntPtr dupHandle = IntPtr.Zero;

            SafeWaitHandle procHandle = new SafeWaitHandle(Process.GetProcessById(procId).Handle, true);
            Console.WriteLine("Process handle: True");

            bool procToken = OpenProcessToken(procHandle.DangerousGetHandle(), (uint)TokenAccessLevels.MaximumAllowed, out tokenHandle);
            Console.WriteLine("OpenProcessToken: " + procToken);

            bool duplicateToken = DuplicateTokenEx(tokenHandle, (uint)TokenAccessLevels.MaximumAllowed, IntPtr.Zero, 
                (uint)TokenImpersonationLevel.Impersonation, TOKEN_TYPE.TokenImpersonation, out dupHandle);
            Console.WriteLine("DuplicateTokenEx: " + duplicateToken);
            WindowsIdenreplacedy ident = new WindowsIdenreplacedy(dupHandle);
            Console.WriteLine("Impersonated user: " + ident.Name);

            STARTUPINFO startInfo = new STARTUPINFO();

            PipeSecurity sec = new PipeSecurity();
            sec.SetAccessRule(new PipeAccessRule("NT AUTHORITY\\Everyone", PipeAccessRights.FullControl, AccessControlType.Allow));

            using (AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable, 4096, sec))
            {
                using (AnonymousPipeClientStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, pipeServer.ClientSafePipeHandle))
                {
                    // Set process to use anonymous pipe for input/output
                    startInfo.hStdOutput = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.hStdError = pipeClient.SafePipeHandle.DangerousGetHandle();
                    startInfo.dwFlags = STARTF.STARTF_USESTDHANDLES | STARTF.STARTF_USESHOWWINDOW;
                    // END NAME PIPE INITIALIZATION

                    PROCESS_INFORMATION newProc = new PROCESS_INFORMATION();
                    using (StreamReader reader = new StreamReader(pipeServer))
                    {
                        bool createProcess = CreateProcessWithTokenW(dupHandle, IntPtr.Zero, null, file, IntPtr.Zero, IntPtr.Zero, "C:\\Temp", ref startInfo, out newProc);
                        Process proc = Process.GetProcessById(newProc.dwProcessId);
                        while (!proc.HasExited)
                        {
                            Thread.Sleep(1000);
                        }
                        pipeClient.Close();
                        string output = reader.ReadToEnd();
                        Console.WriteLine("Started process with ID " + newProc.dwProcessId);
                        Console.WriteLine("CreateProcess return code: " + createProcess);
                        Console.WriteLine("Process output: " + output);
                    }
                    
                    CloseHandle(tokenHandle);
                    CloseHandle(dupHandle);
                }
            }
        }

19 Source : GoPhishIntegration.cs
with GNU General Public License v3.0
from 0dteam

public static string sendReportNotificationToServer(string reportURL)
        {
            ServicePointManager.SecurityProtocol = Tls12;

            try
            {
                var request = (HttpWebRequest)WebRequest.Create(reportURL);            
                var response = (HttpWebResponse)request.GetResponse();
                string html = new StreamReader(response.GetResponseStream()).ReadToEnd();
                return "OK";
            }
            catch (System.Exception exc)
            {
                return "ERROR"; // "GoPhish Listener is not responding or there is no Internet connection."
            }
        }

19 Source : Ribbon.cs
with GNU General Public License v3.0
from 0dteam

private static string GetResourceText(string resourceName)
        {
            replacedembly asm = replacedembly.GetExecutingreplacedembly();
            string[] resourceNames = asm.GetManifestResourceNames();
            for (int i = 0; i < resourceNames.Length; ++i)
            {
                if (string.Compare(resourceName, resourceNames[i], StringComparison.OrdinalIgnoreCase) == 0)
                {
                    using (StreamReader resourceReader = new StreamReader(asm.GetManifestResourceStream(resourceNames[i])))
                    {
                        if (resourceReader != null)
                        {
                            return resourceReader.ReadToEnd();
                        }
                    }
                }
            }
            return null;
        }

19 Source : EdisFace.cs
with MIT License
from 0ffffffffh

private Dictionary<string,string> BuildForm(HttpListenerContext ctx)
        {
            string[] items;

            string post;

            using (StreamReader sr = new StreamReader(ctx.Request.InputStream))
            {
                post = sr.ReadToEnd();
            }

            if (string.IsNullOrEmpty(post))
                return null;

            items = post.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);

            var dict = new Dictionary<string, string>();

            foreach (var item in items)
            {
                string[] kv = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);

                if (kv.Length == 2)
                {
                    kv[1] = System.Web.HttpUtility.UrlDecode(kv[1],Encoding.GetEncoding("iso-8859-9"));


                    dict.Add(kv[0], kv[1]);
                }

            }

            return dict;
        }

19 Source : StreamObj.cs
with MIT License
from 1217950746

public static string ToString(Stream stream)
        {
            try { return new StreamReader(stream).ReadToEnd(); }
            catch { return ""; }
        }

19 Source : UdpClientEx.cs
with MIT License
from 1iveowl

public static void WriteToConsole(this MemoryStream stream)
        {
            var temporary = stream.Position;
            stream.Position = 0;

            using (var reader = new StreamReader(stream, Encoding.UTF8, false, 0x1000, true))
            {
                var text = reader.ReadToEnd();
                if (!string.IsNullOrEmpty(text))
                {
                    Console.WriteLine(text);
                }
            }

            stream.Position = temporary;
        }

19 Source : X86Assembly.cs
with MIT License
from 20chan

public static byte[] CompileToMachineCode(string asmcode)
        {
            var fullcode = $".intel_syntax noprefix\n_main:\n{asmcode}";
            var path = Path.Combine(Directory.GetCurrentDirectory(), "temp");
            var asmfile = $"{path}.s";
            var objfile = $"{path}.o";
            File.WriteAllText(asmfile, fullcode, new UTF8Encoding(false));
            var psi = new ProcessStartInfo("gcc", $"-m32 -c {asmfile} -o {objfile}")
            {
                RedirectStandardError = true,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
            var gcc = Process.Start(psi);
            gcc.WaitForExit();
            if (gcc.ExitCode == 0)
            {
                psi.FileName = "objdump";
                psi.Arguments = $"-z -M intel -d {objfile}";
                var objdump = Process.Start(psi);
                objdump.WaitForExit();
                if (objdump.ExitCode == 0)
                {
                    var output = objdump.StandardOutput.ReadToEnd();
                    var matches = Regex.Matches(output, @"\b[a-fA-F0-9]{2}(?!.*:)\b");
                    var result = new List<byte>();
                    foreach (Match match in matches)
                    {
                        result.Add((byte)Convert.ToInt32(match.Value, 16));
                    }

                    return result.TakeWhile(b => b != 0x90).ToArray();
                }
            }
            else
            {
                var err = gcc.StandardError.ReadToEnd();
            }

            throw new ArgumentException();
        }

19 Source : Form1.cs
with MIT License
from 200Tigersbloxed

void checkForMessage()
        {
            WebClient client = new WebClient();
            Stream stream = client.OpenRead("https://pastebin.com/raw/vaXRephy");
            StreamReader reader = new StreamReader(stream);
            String content = reader.ReadToEnd();
            string[] splitcontent = content.Split('|');
            if(splitcontent[0] == "Y")
            {
                MessageBox.Show(splitcontent[1], "Message From Developer", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

19 Source : Common.cs
with MIT License
from 1y0n

public static string Execute_Cmd(string cmd)
        {
            string output = "";
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;

            //获取cmd窗口的输出信息
            output = p.StandardOutput.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();
            return output;
        }

19 Source : Form1.cs
with MIT License
from 200Tigersbloxed

private void Form1_Load(object sender, EventArgs e)
        {
            // check for internet
            if (CheckForInternetConnection() == true) { }
            else
            {
                MessageBox.Show("An Internet Connection is required!", "Not Connected to Internet", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            // check if user can access website
            if (CheckForWebsiteConnection() == true) { }
            else
            {
                MessageBox.Show("Failed to connect to https://tigersserver.xyz. Please try again soon.", "Failed to Connect", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }

            WebClient client = new WebClient();
            Stream stream = client.OpenRead("https://pastebin.com/raw/S8v9a7Ba");
            StreamReader reader = new StreamReader(stream);
            String content = reader.ReadToEnd();
            if(version != content)
            {
                DialogResult drUpdate = MessageBox.Show("BSMulti-Installer is not up to date! Would you like to download the newest version?", "Uh Oh!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if(drUpdate == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start("https://github.com/200Tigersbloxed/BSMulti-Installer/releases/latest");
                    Application.Exit();
                }
            }

            checkForMessage();
            
            Directory.CreateDirectory("Files");
        }

19 Source : Command.cs
with Apache License 2.0
from 214175590

public static CmdResult run(String cmd)
        {
            CmdResult result = new CmdResult();
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;    //是否使用操作系统shell启动
            p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
            p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
            p.StartInfo.RedirectStandardError = true;//重定向标准错误输出
            p.StartInfo.CreateNoWindow = true;//不显示程序窗口
            p.Start();//启动程序

            //向cmd窗口发送输入信息
            p.StandardInput.WriteLine(cmd + "&exit");

            p.StandardInput.AutoFlush = true;
            //p.StandardInput.WriteLine("exit");
            //向标准输入写入要执行的命令。这里使用&是批处理命令的符号,表示前面一个命令不管是否执行成功都执行后面(exit)命令,如果不执行exit命令,后面调用ReadToEnd()方法会假死
            //同类的符号还有&&和||前者表示必须前一个命令执行成功才会执行后面的命令,后者表示必须前一个命令执行失败才会执行后面的命令

            //获取cmd窗口的输出信息
            result.result = p.StandardOutput.ReadToEnd();
            result.error = p.StandardError.ReadToEnd();

            p.WaitForExit();//等待程序执行完退出进程
            p.Close();

            return result;
        }

19 Source : JcApiHelperUIMiddleware.cs
with MIT License
from 279328316

private async Task RespondWithIndexHtml(HttpResponse response)
        {
            response.StatusCode = 200;
            response.ContentType = "text/html;charset=utf-8";

            using (Stream stream = apiHelperreplacedembly.GetManifestResourceStream($"{embeddedFileNamespace}.index.html"))
            {
                // Inject arguments before writing to response
                StringBuilder htmlBuilder = new StringBuilder(new StreamReader(stream).ReadToEnd());

                //处理index.html baseUrl 以兼容非根目录以及Nginx代理转发情况
                htmlBuilder.Replace("<base id=\"base\" href=\"/\">", $"<base id=\"base\" href=\"/ApiHelper/\">");
                await response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
            }
        }

19 Source : ConsoleApp.cs
with MIT License
from 2881099

public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
			if (bat == null || bat.Any() == false) return ("", "", "");
            if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
			var proc = new System.Diagnostics.Process();
			proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
				CreateNoWindow = true,
				FileName = "cmd.exe",
				UseShellExecute = false,
				RedirectStandardError = true,
				RedirectStandardInput = true,
				RedirectStandardOutput = true,
				WorkingDirectory = cddir
			};
			proc.Start();
			foreach (var cmd in bat)
				proc.StandardInput.WriteLine(cmd);
			proc.StandardInput.WriteLine("exit");
			var outStr = proc.StandardOutput.ReadToEnd();
			var errStr = proc.StandardError.ReadToEnd();
			proc.Close();
			var idx = outStr.IndexOf($">{bat[0]}");
			if (idx != -1) {
				idx = outStr.IndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Substring(idx + 1);
			}
			idx = outStr.LastIndexOf(">exit");
			if (idx != -1) {
				idx = outStr.LastIndexOf("\n", idx);
				if (idx != -1) outStr = outStr.Remove(idx);
			}
			outStr = outStr.Trim();
			if (outStr == "") outStr = null;
			if (errStr == "") errStr = null;
			return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
		}

19 Source : V2rayHandler.cs
with GNU General Public License v3.0
from 2dust

private void V2rayStart()
        {
            ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));

            try
            {
                string fileName = V2rayFindexe();
                if (fileName == "") return;

                Process p = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = fileName,
                        WorkingDirectory = Utils.StartupPath(),
                        UseShellExecute = false,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                };
                p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.Start();
                p.PriorityClreplaced = ProcessPriorityClreplaced.High;
                p.BeginOutputReadLine();
                //processId = p.Id;
                _process = p;

                if (p.WaitForExit(1000))
                {
                    throw new Exception(p.StandardError.ReadToEnd());
                }

                Global.processJob.AddProcess(p.Handle);
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                string msg = ex.Message;
                ShowMsg(true, msg);
            }
        }

19 Source : V2rayHandler.cs
with GNU General Public License v3.0
from 2dust

private int V2rayStartNew(string configStr)
        {
            ShowMsg(false, string.Format(UIRes.I18N("StartService"), DateTime.Now.ToString()));

            try
            {
                string fileName = V2rayFindexe();
                if (fileName == "") return -1;

                Process p = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = fileName,
                        Arguments = "-config stdin:",
                        WorkingDirectory = Utils.StartupPath(),
                        UseShellExecute = false,
                        RedirectStandardInput = true,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        CreateNoWindow = true,
                        StandardOutputEncoding = Encoding.UTF8
                    }
                };
                p.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
                {
                    if (!String.IsNullOrEmpty(e.Data))
                    {
                        string msg = e.Data + Environment.NewLine;
                        ShowMsg(false, msg);
                    }
                });
                p.Start();
                p.BeginOutputReadLine();

                p.StandardInput.Write(configStr);
                p.StandardInput.Close();

                if (p.WaitForExit(1000))
                {
                    throw new Exception(p.StandardError.ReadToEnd());
                }

                Global.processJob.AddProcess(p.Handle);
                return p.Id;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                string msg = ex.Message;
                ShowMsg(false, msg);
                return -1;
            }
        }

19 Source : FileManager.cs
with GNU General Public License v3.0
from 2dust

public static string NonExclusiveReadAllText(string path, Encoding encoding)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (StreamReader sr = new StreamReader(fs, encoding))
                {
                    return sr.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                throw ex;
            }
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from 2dust

public static string GetEmbedText(string res)
        {
            string result = string.Empty;

            try
            {
                replacedembly replacedembly = replacedembly.GetExecutingreplacedembly();
                using (Stream stream = replacedembly.GetManifestResourceStream(res))
                using (StreamReader reader = new StreamReader(stream))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
            }
            return result;
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from 2dust

public static string LoadResource(string res)
        {
            string result = string.Empty;

            try
            {
                using (StreamReader reader = new StreamReader(res))
                {
                    result = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                SaveLog(ex.Message, ex);
            }
            return result;
        }

19 Source : UpdateHandle.cs
with GNU General Public License v3.0
from 2dust

private string getCoreVersion(string type)
        {
            try
            {
                var core = string.Empty;
                var match = string.Empty;
                if (type == "v2fly")
                {
                    core = "v2ray.exe";
                    match = "V2Ray";
                }
                else if (type == "xray")
                {
                    core = "xray.exe";
                    match = "Xray";
                }
                string filePath = Utils.GetPath(core);
                if (!File.Exists(filePath))
                {
                    string msg = string.Format(UIRes.I18N("NotFoundCore"), @"");
                    //ShowMsg(true, msg);
                    return "";
                }

                Process p = new Process();
                p.StartInfo.FileName = filePath;
                p.StartInfo.Arguments = "-version";
                p.StartInfo.WorkingDirectory = Utils.StartupPath();
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.CreateNoWindow = true;
                p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                p.Start();
                p.WaitForExit(5000);
                string echo = p.StandardOutput.ReadToEnd();
                string version = Regex.Match(echo, $"{match} ([0-9.]+) \\(").Groups[1].Value;
                return version;
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
                _updateFunc(false, ex.Message);
                return "";
            }
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void LoadConfig(Options o)
        {
            //Write all the blah blah
            var replacedembly = replacedembly.GetExecutingreplacedembly();
            var resourceStream = replacedembly.GetManifestResourceStream("S2AN.config.json");
            StreamReader reader = new StreamReader(resourceStream);
            var config = JsonConvert.DeserializeObject<JObject>(reader.ReadToEnd());
            Console.WriteLine($"\n S2AN by 3CORESec - {config["repo_url"]}\n");
            //Load default configuration for ATT&CK technique and tactic mismatch search
            if (o.MitreMatrix == null)
            {
                o.MitreMatrix = config["category_matrix_url"]?.ToString();
            }
        }

19 Source : HttpClient.cs
with GNU Affero General Public License v3.0
from 3drepo

protected T_out HttpPostJson<T_in, T_out>(string uri, T_in data)
        {
            AppendApiKey(ref uri);

            // put together the json object with the login form data
            string parameters = JsonMapper.ToJson(data);
            byte[] postDataBuffer = Encoding.UTF8.GetBytes(parameters);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.ContentLength = postDataBuffer.Length;
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("POST " + uri + " data: " + parameters);

            Stream postDataStream = request.GetRequestStream();

            postDataStream.Write(postDataBuffer, 0, postDataBuffer.Length);
            postDataStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            Stream responseStream = response.GetResponseStream();

            StreamReader responseReader = new StreamReader(responseStream);
            string responseData = responseReader.ReadToEnd();

            Cookie responseCookie = response.Cookies[0];
            string responseDomain = responseCookie.Domain;

            // Only replacedume one cookie per domain
            if (!cookieDict.ContainsKey(responseDomain))
            {
                cookieDict.Add(responseCookie.Domain, responseCookie);
                responseCookie.Domain = "." + responseCookie.Domain;
            }

            Uri myUri = new Uri(uri);

            foreach (KeyValuePair<string, Cookie> entry in cookieDict)
            {
                int uriHostLength = myUri.Host.Length;

                if (myUri.Host.Substring(uriHostLength - responseDomain.Length, responseDomain.Length) == entry.Key)
                {
                    cookies.Add(myUri, entry.Value);
                }
            }

            return JsonMapper.ToObject<T_out>(responseData);
        }

19 Source : HttpClient.cs
with GNU Affero General Public License v3.0
from 3drepo

protected T HttpGetJson<T>(string uri, int tries = 1)
        {
            AppendApiKey(ref uri);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Proxy = proxy;
            request.Method = "GET";
            request.Accept = "application/json";
            //request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
            request.ReadWriteTimeout = timeout_ms;
            request.Timeout = timeout_ms;
            request.CookieContainer = cookies;
            Console.WriteLine("GET " + uri + " TRY: " + tries);

            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                Stream responseStream = response.GetResponseStream();
                StreamReader responseReader = new StreamReader(responseStream);
                string responseData = responseReader.ReadToEnd();

                JsonMapper.RegisterImporter<Double, Single>((Double value) =>
                {
                    return (Single)value;
                });
                return JsonMapper.ToObject<T>(responseData);
            }
            catch (WebException)
            {
                if (--tries == 0)
                    throw;

                return HttpGetJson<T>(uri, tries);
            }
        }

19 Source : SimulationDatabase.cs
with MIT License
from 5argon

internal static void Refresh()
        {
            if (db == null) db = new Dictionary<string, SimulationDevice>();

            db.Clear();

            var deviceDirectory = new System.IO.DirectoryInfo(NotchSimulatorUtility.DevicesFolder);
            if (!deviceDirectory.Exists) return;
            var deviceDefinitions = deviceDirectory.GetFiles("*.device.json");

            foreach (var deviceDefinition in deviceDefinitions)
            {
                SimulationDevice deviceInfo;
                using (var sr = deviceDefinition.OpenText())
                {
                    deviceInfo = JsonUtility.FromJson<SimulationDevice>(sr.ReadToEnd());
                }
                db.Add(deviceInfo.Meta.friendlyName, deviceInfo);
            }
            KeyList = db.Keys.ToArray();
        }

19 Source : Utility.Http.cs
with MIT License
from 7Bytes-Studio

public static string Post(string Url, string postDataStr, CookieContainer cookieContainer = null)
            {
                cookieContainer = cookieContainer ?? new CookieContainer();
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
                request.CookieContainer = cookieContainer;
                Stream myRequestStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
                myStreamWriter.Write(postDataStr);
                myStreamWriter.Close();

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                response.Cookies = cookieContainer.GetCookies(response.ResponseUri);
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 Source : Utility.Http.cs
with MIT License
from 7Bytes-Studio

public static string Get(string Url, string gettDataStr)
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (gettDataStr == "" ? "" : "?") + gettDataStr);
                request.Method = "GET";
                request.ContentType = "text/html;charset=UTF-8";

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }

19 Source : HTTP.cs
with MIT License
from 944095635

private void SetPostData(HttpItem item)
        {
            //验证在得到结果时是否有传入数据
            if (!request.Method.Trim().ToLower().Contains("get"))
            {
                if (item.PostEncoding != null)
                {
                    postencoding = item.PostEncoding;
                }
                byte[] buffer = null;
                //写入Byte类型
                if (item.PostDataType == PostDataType.Byte && item.PostdataByte != null && item.PostdataByte.Length > 0)
                {
                    //验证在得到结果时是否有传入数据
                    buffer = item.PostdataByte;
                }//写入文件
                else if (item.PostDataType == PostDataType.FilePath && !string.IsNullOrWhiteSpace(item.Postdata))
                {
                    StreamReader r = new StreamReader(item.Postdata, postencoding);
                    buffer = postencoding.GetBytes(r.ReadToEnd());
                    r.Close();
                } //写入字符串
                else if (!string.IsNullOrWhiteSpace(item.Postdata))
                {
                    buffer = postencoding.GetBytes(item.Postdata);
                }
                if (buffer != null)
                {
                    request.ContentLength = buffer.Length;
                    request.GetRequestStream().Write(buffer, 0, buffer.Length);
                }
                else
                {
                    request.ContentLength = 0;
                }
            }
        }

19 Source : XMLFormatter.cs
with MIT License
from 99x

public override string Format(object input)
        {
            string outData;

            if (input !=null)
            using (MemoryStream stream1 = new MemoryStream())
            {
                DataContractSerializer serializer = new DataContractSerializer(input.GetType());
                serializer.WriteObject(stream1, input);
                using (StreamReader sr = new StreamReader(stream1))
                {
                    outData = sr.ReadToEnd();
                }
            }


            return "";
        }

19 Source : LanguageHelper.cs
with GNU General Public License v3.0
from 9vult

private string GetFileContents(string filename)
        {
            var replacedembly = replacedembly.GetExecutingreplacedembly();
            string resourceName = replacedembly.GetManifestResourceNames().Single(str => str.EndsWith(filename));

            using (Stream stream = replacedembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                return reader.ReadToEnd();
            }
        }

19 Source : FrmMain.cs
with MIT License
from A-Tabeshfard

private void MnuFileOpen_Click(object sender, EventArgs e)
        {
            try
            {
                if (_openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    _streamReader = new StreamReader(_openFileDialog.OpenFile());
                    ((FrmContent)ActiveMdiChild).textBox.Text = _streamReader.ReadToEnd();
                }
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "Note Pad", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (_streamReader != null)
                    _streamReader.Close();
            }
        }

19 Source : SerializeHelper.cs
with GNU General Public License v3.0
from a2659802

public static T LoadGlobalSettings<T>()
        {
            var _globalSettingsPath = GLOBAL_FILE_DIR;
            if (!File.Exists(_globalSettingsPath))
                return default;

            Log("Loading Global Settings");

            using (FileStream fileStream = File.OpenRead(_globalSettingsPath))
            {
                using (var reader = new StreamReader(fileStream))
                {
                    string json = reader.ReadToEnd();
                    Type settingsType = typeof(T);
                    T settings = default;

                    try
                    {
                        settings = (T)JsonConvert.DeserializeObject(
                            json,
                            settingsType,
                            new JsonSerializerSettings
                            {
                                TypeNameHandling = TypeNameHandling.Auto,
                            }
                        );
                    }
                    catch (Exception e)
                    {
                        LogError("Failed to load settings using Json.Net.");
                        LogError(e);
                    }

                    return settings;
                }
            }
        }

19 Source : SerializeHelper.cs
with GNU General Public License v3.0
from a2659802

public static T LoadSceneSettings<T>(string sceneName)
        {
            string dir = Path.Combine(DATA_DIR, sceneName + ".json");
            if (!File.Exists(dir))
                return default;

            Log($"Loading {sceneName} Settings");

            using (FileStream fileStream = File.OpenRead(dir))
            {
                using (var reader = new StreamReader(fileStream))
                {
                    string json = reader.ReadToEnd();
                    Type settingsType = typeof(T);
                    T settings = default;

                    try
                    {
                        settings = (T)JsonConvert.DeserializeObject(
                            json,
                            settingsType,
                            new JsonSerializerSettings
                            {
                                TypeNameHandling = TypeNameHandling.Auto,
                            }
                        );
                    }
                    catch (Exception e)
                    {
                        LogError("Failed to load settings using Json.Net.");
                        LogError(e);
                    }

                    return settings;
                }
            }
        }

19 Source : ShellManager.cs
with GNU General Public License v3.0
from a4004

public static bool RunCommand(out string output, string process, string arguments = null)
        {
            ProcessStartInfo cmdSi = new ProcessStartInfo()
            {
                FileName = process,
                Arguments = $"{(arguments == null ? "" : arguments)}",
                UseShellExecute = false,
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden,
                RedirectStandardOutput = true,
                RedirectStandardError = true
            };

            Program.Debug("shellmgr", $"Running command \"{process}{(arguments == null ? "" : " " + arguments)}\"");

            try
            {
                Process cmd = Process.Start(cmdSi);

                try
                {
                    Program.Debug("shellmgr", "The system reports no errors at the moment.");
                    Program.Debug("shellmgr", $"[INFO] The process (pid {cmd.Id}) is running as a task " +
                        $"and is limited to a runtime of 1800 seconds.", Event.Warning);
                }
                catch
                {
                    output = "The pid was invalid.";
                    return false;
                }

                cmd.WaitForExit(1800);

                output = cmd.StandardOutput.ReadToEnd().Replace("\r", "").Replace("\n", "");
                string error = cmd.StandardError.ReadToEnd().Replace("\r", "").Replace("\n", "");

                Program.Debug("shellmgr", $"{process} stderr: {error}", Event.Critical);

                if (!cmd.HasExited)
                    return ExitProcess(cmd) == 0;
                else
                    return cmd.ExitCode == 0;
            }
            catch (Exception ex)
            {
                Program.Debug("shellmgr", $"An error was encountered. {ex.Message}", Event.Critical);
                output = ex.Message;
                return false;
            }
        }

19 Source : FileUtils.cs
with Apache License 2.0
from A7ocin

public static string ReadAllText(string path)
		{
			using (var sr = new System.IO.StreamReader(path))
			{
				return sr.ReadToEnd();
			}
		}

19 Source : compiler.cs
with MIT License
from aaaddress1

public static bool geneateAsmSource(string srcPath, string outAsmPath)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
            p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;

            p.StartInfo.Arguments = string.Format("-S {0} -masm=intel {2} -o {1}", srcPath, outAsmPath, Properties.Settings.Default.clArg);
            p.Start();

            string errr = p.StandardError.ReadToEnd();
            string oupt = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            if (File.Exists(outAsmPath)) return true;

            Program.mainUi.Invoke((MethodInvoker)delegate ()
            {
                if (logText == null) return;
                logMsg("============= Error =============", Color.Red);
                logMsg(errr + oupt, Color.Red);
            });
            return false;
        }

19 Source : compiler.cs
with MIT License
from aaaddress1

public static bool generateExe(string asmPath, string exeOutPath)
        {
            Process p = new Process();
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.FileName = Path.Combine(Properties.Settings.Default.gwPath, "g++.exe");
            p.StartInfo.WorkingDirectory = Properties.Settings.Default.gwPath;
            p.StartInfo.Arguments = string.Format("{0} -masm=intel {2} -o {1}", asmPath, exeOutPath, Properties.Settings.Default.linkArg);
            p.Start();

            string errr = p.StandardError.ReadToEnd();
            string oupt = p.StandardOutput.ReadToEnd();
            p.WaitForExit();
            if (File.Exists(exeOutPath)) return true;

            Program.mainUi.Invoke((MethodInvoker)delegate ()
            {
                if (logText == null) return;
                logMsg("============= Error =============", Color.Red);
                logMsg(errr + oupt, Color.Red);
            });
            return false;
        }

19 Source : BTCChinaAPI.cs
with MIT License
from aabiryukov

private string DoMethod(NameValueCollection jParams)
	    {
		    const int RequestTimeoutMilliseconds = 2*1000; // 2 sec 

		    string tempResult = "";

		    try
		    {
			    lock (m_tonceLock)
			    {
				    //get tonce
				    TimeSpan timeSpan = DateTime.UtcNow - genesis;
				    long milliSeconds = Convert.ToInt64(timeSpan.TotalMilliseconds*1000);
				    jParams[pTonce] = Convert.ToString(milliSeconds, CultureInfo.InvariantCulture);
				    //mock json request id
				    jParams[pId] = jsonRequestID.Next().ToString(CultureInfo.InvariantCulture);
				    //build http head
				    string paramsHash = GetHMACSHA1Hash(jParams);
				    string base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes(accessKey + ':' + paramsHash));
				    string postData = "{\"method\": \"" + jParams[pMethod] + "\", \"params\": [" + jParams[pParams] + "], \"id\": " +
				                      jParams[pId] + "}";

				    //get webrequest,respawn new object per call for multiple connections
				    var webRequest = (HttpWebRequest) WebRequest.Create(url);
				    webRequest.Timeout = RequestTimeoutMilliseconds;

				    var bytes = Encoding.ASCII.GetBytes(postData);

				    webRequest.Method = jParams[pRequestMethod];
				    webRequest.ContentType = "application/json-rpc";
				    webRequest.ContentLength = bytes.Length;
				    webRequest.Headers["Authorization"] = "Basic " + base64String;
				    webRequest.Headers["Json-Rpc-Tonce"] = jParams[pTonce];

				    // Send the json authentication post request
				    using (var dataStream = webRequest.GetRequestStream())
				    {
					    dataStream.Write(bytes, 0, bytes.Length);
				    }

				    // Get authentication response
				    using (var response = webRequest.GetResponse())
				    {
					    using (var stream = response.GetResponseStream())
					    {
// ReSharper disable once replacedignNullToNotNullAttribute
						    using (var reader = new StreamReader(stream))
						    {
							    tempResult = reader.ReadToEnd();
						    }
					    }
				    }
			    }
		    }
		    catch (WebException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], ex.Message, ex);
		    }

		    //there are two kinds of API response, result or error.
		    if (tempResult.IndexOf("result", StringComparison.Ordinal) < 0)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "API error:\n" + tempResult);
		    }

		    //compare response id with request id and remove it from result
		    try
		    {
			    int cutoff = tempResult.LastIndexOf(':') + 2;//"id":"1"} so (last index of ':')+2=length of cutoff=start of id-string
			    string idString = tempResult.Substring(cutoff, tempResult.Length - cutoff - 2);//2=last "}
			    if (idString != jParams[pId])
			    {
				    throw new BTCChinaException(jParams[pMethod], jParams[pId], "JSON-request id is not equal with JSON-response id.");
			    }
			    else
			    {
				    //remove json request id from response json string
				    int fromComma = tempResult.LastIndexOf(',');
				    int toLastBrace = tempResult.Length - 1;
				    tempResult = tempResult.Remove(fromComma, toLastBrace - fromComma);
			    }
		    }
		    catch (ArgumentOutOfRangeException ex)
		    {
			    throw new BTCChinaException(jParams[pMethod], jParams[pId], "Argument out of range in parsing JSON response id:" + ex.Message, ex);
		    }

		    return tempResult;
	    }

19 Source : ServerManager.cs
with Apache License 2.0
from AantCoder

public bool StartPrepare(string path)
        {
            var jsonFile = GetSettingsFileName(path);
            if (!File.Exists(jsonFile))
            {
                using (StreamWriter file = File.CreateText(jsonFile))
                {
                    var jsonText = JsonSerializer.Serialize(ServerSettings, new JsonSerializerOptions() { WriteIndented = true });
                    file.WriteLine(jsonText);
                }

                Console.WriteLine("Created Settings.json, server was been stopped");
                Console.WriteLine($"RU: Настройте сервер, заполните {jsonFile}");
                Console.WriteLine("Enter some key");
                Console.ReadKey();
                return false;
            }
            else
            {
                try
                {
                    using (var fs = new StreamReader(jsonFile, Encoding.UTF8))
                    {
                        var jsonString = fs.ReadToEnd();
                        ServerSettings = JsonSerializer.Deserialize<ServerSettings>(jsonString);
                    }

                    ServerSettings.WorkingDirectory = path;
                    var results = new List<ValidationResult>();
                    var context = new ValidationContext(ServerSettings);
                    if (!Validator.TryValidateObject(ServerSettings, context, results, true))
                    {
                        foreach (var error in results)
                        {
                            Console.WriteLine(error.ErrorMessage);
                            Loger.Log(error.ErrorMessage);
                        }

                        Console.ReadKey();
                        return false;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.WriteLine($"RU: Проверьте настройки сервера {jsonFile}");
                    Console.WriteLine("EN: Check Settings.json");
                    Console.ReadKey();
                    return false;
                }
            }

            MainHelper.OffAllLog = false;
            Loger.PathLog = path;
            Loger.IsServer = true;

            var rep = Repository.Get;
            rep.SaveFileName = GetWorldFileName(path);
            rep.Load();
            CheckDiscrordUser();
            FileHashChecker = new FileHashChecker(ServerSettings);

            return true;
        }

19 Source : Program.cs
with MIT License
from abanu-org

private static ProcessResult ExecAsync(CommandArgs args, bool redirect, Action<string, Process> onNewLine = null, TimeSpan? timeout = null)
        {
            if (!args.IsSet())
                return null;

            var fileName = args[0].GetEnv();
            var arguments = args.Pop(1).ToString().GetEnv();

            var start = new ProcessStartInfo(fileName);

            if (arguments.Length > 0)
                start.Arguments = arguments;

            if (redirect)
            {
                start.RedirectStandardOutput = true;
                start.RedirectStandardError = true;
                start.RedirectStandardError = true;
                start.UseShellExecute = false;
            }

            Console.WriteLine(fileName + " " + arguments);

            var proc = Process.Start(start);
            var result = new ProcessResult(proc, timeout);

            if (redirect)
            {

                var th = new Thread(() =>
                {
                    var buf = new char[1];
                    var sb = new StringBuilder();
                    while (true)
                    {
                        var count = proc.StandardOutput.Read(buf, 0, 1);
                        if (count == 0)
                            break;
                        Console.Write(buf[0]);
                        if (buf[0] == '\n')
                        {
                            var line = sb.ToString();
                            onNewLine?.Invoke(line, proc);
                            sb.Clear();
                        }
                        else
                        {
                            if (buf[0] != '\r')
                                sb.Append(buf[0]);
                        }
                    }
                });
                th.Start();

                //var data = proc.StandardOutput.ReadToEnd();
                var error = proc.StandardError.ReadToEnd();
                //Console.WriteLine(data);
                Console.WriteLine(error);
            }

            return result;
        }

19 Source : FileReader.cs
with MIT License
from Abdesol

public static string ReadFileContent(Stream stream, Encoding defaultEncoding)
		{
			using (StreamReader reader = OpenStream(stream, defaultEncoding)) {
				return reader.ReadToEnd();
			}
		}

19 Source : TextEditor.cs
with MIT License
from Abdesol

public void Load(Stream stream)
		{
			using (StreamReader reader = FileReader.OpenStream(stream, this.Encoding ?? Encoding.UTF8)) {
				this.Text = reader.ReadToEnd();
				SetCurrentValue(EncodingProperty, reader.CurrentEncoding); // replacedign encoding after ReadToEnd() so that the StreamReader can autodetect the encoding
			}
			SetCurrentValue(IsModifiedProperty, Boxes.False);
		}

19 Source : PackageManifestUpdater.cs
with Apache License 2.0
from abist-co-ltd

internal static void EnsureMSBuildForUnity()
        {
            PackageManifest manifest = null;

            string manifestPath = GetPackageManifestFilePath();
            if (string.IsNullOrWhiteSpace(manifestPath))
            {
                return;
            }

            // Read the package manifest into a list of strings (for easy finding of entries)
            // and then deserialize.
            List<string> manifestFileLines = new List<string>();
            using (FileStream manifestStream = new FileStream(manifestPath, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader reader = new StreamReader(manifestStream))
                {
                    // Read the manifest file a line at a time.
                    while (!reader.EndOfStream)
                    {
                        string line = reader.ReadLine();
                        manifestFileLines.Add(line);
                    }

                    // Go back to the start of the file.
                    manifestStream.Seek(0, 0);

                    // Deserialize the scoped registries portion of the package manifest.
                    manifest = JsonUtility.FromJson<PackageManifest>(reader.ReadToEnd());
                }
            }

            if (manifest == null)
            {
                Debug.LogError($"Failed to read the package manifest file ({manifestPath})");
                return;
            }

            // Ensure that pre-existing scoped registries are retained.
            List<ScopedRegistry> scopedRegistries = new List<ScopedRegistry>();
            if ((manifest.scopedRegistries != null) && (manifest.scopedRegistries.Length > 0))
            {
                scopedRegistries.AddRange(manifest.scopedRegistries);
            }

            // Attempt to find an entry in the scoped registries collection for the MSBuild for Unity URL
            bool needToAddRegistry = true;
            foreach (ScopedRegistry registry in scopedRegistries)
            {
                if (registry.url == MSBuildRegistryUrl)
                {
                    needToAddRegistry = false;
                }
            }

            // If no entry was found, add one.
            if (needToAddRegistry)
            {
                ScopedRegistry registry = new ScopedRegistry();
                registry.name = MSBuildRegistryName;
                registry.url = MSBuildRegistryUrl;
                registry.scopes = MSBuildRegistryScopes;

                scopedRegistries.Add(registry);
            }

            // Update the manifest's scoped registries, as the collection may have been modified.
            manifest.scopedRegistries = scopedRegistries.ToArray();

            int dependenciesStartIndex = -1;
            int scopedRegistriesStartIndex = -1;
            int scopedRegistriesEndIndex = -1;
            int packageLine = -1;

            // Presume that we need to add the MSBuild for Unity package. If this value is false,
            // we will check to see if the currently configured version meets or exceeds the
            // minimum requirements.
            bool needToAddPackage = true;

            // Attempt to find the MSBuild for Unity package entry in the dependencies collection
            // This loop also identifies the dependencies collection line and the start / end of a
            // pre-existing scoped registries collections
            for (int i = 0; i < manifestFileLines.Count; i++)
            {
                if (manifestFileLines[i].Contains("\"scopedRegistries\":"))
                {
                    scopedRegistriesStartIndex = i;
                }
                if (manifestFileLines[i].Contains("],") && (scopedRegistriesStartIndex != -1) && (scopedRegistriesEndIndex == -1))
                {
                    scopedRegistriesEndIndex = i;
                }
                if (manifestFileLines[i].Contains("\"dependencies\": {"))
                {
                    dependenciesStartIndex = i;
                }
                if (manifestFileLines[i].Contains(MSBuildPackageName))
                {
                    packageLine = i;
                    needToAddPackage = false;
                }
            }

            // If no package was found add it to the dependencies collection.
            if (needToAddPackage)
            {
                // Add the package to the collection (pad the entry with four spaces)
                manifestFileLines.Insert(dependenciesStartIndex + 1, $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",");
            }
            else
            {
                // Replace the line that currently exists
                manifestFileLines[packageLine] = $"    \"{MSBuildPackageName}\": \"{MSBuildPackageVersion}\",";
            }

            // Update the manifest file.
            // First, serialize the scoped registry collection.
            string serializedRegistriesJson = JsonUtility.ToJson(manifest, true);

            // Ensure that the file is truncated to ensure it is always valid after writing.
            using (FileStream outFile = new FileStream(manifestPath, FileMode.Truncate, FileAccess.Write))
            {
                using (StreamWriter writer = new StreamWriter(outFile))
                {
                    bool scopedRegistriesWritten = false;

                    // Write each line of the manifest back to the file.
                    for (int i = 0; i < manifestFileLines.Count; i++)
                    {
                        if ((i >= scopedRegistriesStartIndex) && (i <= scopedRegistriesEndIndex))
                        {
                            // Skip these lines, they will be replaced.
                            continue;
                        }

                        if (!scopedRegistriesWritten && (i > 0))
                        {
                            // Trim the leading '{' and '\n' from the serialized scoped registries
                            serializedRegistriesJson = serializedRegistriesJson.Remove(0, 2);
                            // Trim, the trailing '\n' and '}'
                            serializedRegistriesJson = serializedRegistriesJson.Remove(serializedRegistriesJson.Length - 2);
                            // Append a trailing ',' to close the scopedRegistries node
                            serializedRegistriesJson = serializedRegistriesJson.Insert(serializedRegistriesJson.Length, ",");
                            writer.WriteLine(serializedRegistriesJson);

                            scopedRegistriesWritten = true;
                        }

                        writer.WriteLine(manifestFileLines[i]);
                    }
                }
            }
        }

19 Source : HttpGetSearch.cs
with MIT License
from ABN-SFLookupTechnicalSupport

private static string ReadResponse(HttpWebRequest webRequest) {
         StreamReader Reader;
         HttpWebResponse Response;
         String ResponseContents = "";
         try {
            Response = ((HttpWebResponse)(webRequest.GetResponse()));
            Reader = new StreamReader(Response.GetResponseStream());
            ResponseContents = Reader.ReadToEnd();
            Reader.Close();
         }
         catch (ObjectDisposedException) {
            throw;
         }
         catch (IOException) {
            throw;
         }
         catch (SystemException) {
            throw;
         }
         return ResponseContents;
      }

19 Source : ResultsInterpreter.cs
with MIT License
from ABN-SFLookupTechnicalSupport

public static string SerialisePayload(ServiceReferenceAbnLookup.Payload searchPayload) {
         try {
            MemoryStream XmlStream = new MemoryStream();
            StreamReader XmlReader = new StreamReader(XmlStream);
            XmlSerializer Serializer = new XmlSerializer(typeof(ServiceReferenceAbnLookup.Payload));
            Serializer.Serialize(XmlStream, searchPayload);
            XmlStream.Seek(0, System.IO.SeekOrigin.Begin);
            return XmlReader.ReadToEnd();
         }
         catch {
            throw;
         }
      }

19 Source : ResultsInterpreter.cs
with MIT License
from ABN-SFLookupTechnicalSupport

public static string SerialisePayload(ServiceReferenceAbnLookupRpc.Payload searchPayload) {
         try {
            MemoryStream XmlStream = new MemoryStream();
            StreamReader XmlReader = new StreamReader(XmlStream);
            XmlSerializer Serializer = new XmlSerializer(typeof(ServiceReferenceAbnLookupRpc.Payload), ExtraTypes());
            Serializer.Serialize(XmlStream, searchPayload);
            XmlStream.Seek(0, System.IO.SeekOrigin.Begin);
            return XmlReader.ReadToEnd();
         }
         catch {
            throw;
         }
      }

19 Source : ExampleLoader.cs
with MIT License
from ABTSoftware

public static string LoadSourceFile(string name)
        {
            replacedembly replacedembly = typeof(ExampleLoader).replacedembly;

            var names = replacedembly.GetManifestResourceNames();

            var allExampleSourceFiles = names.Where(x => x.Contains("SciChart.Examples.Examples"));

            var find = name.Replace('/', '.').Replace(".txt", string.Empty).Replace("Resources.ExampleSourceFiles.", string.Empty);
            var file = allExampleSourceFiles.FirstOrDefault(x => x.EndsWith(find));

            if (file == null)
                throw new Exception(string.Format("Unable to find the source code resource {0}", find));

            using (var s = replacedembly.GetManifestResourceStream(file))
            using (var sr = new StreamReader(s))
            {
                return sr.ReadToEnd();
            }
        }

19 Source : ExampleLoader.cs
with MIT License
from ABTSoftware

private IDictionary<ExampleKey, string> DiscoverAllExampleDefinitions()
        {
            var dict = new Dictionary<ExampleKey, string>();
            replacedembly replacedembly = typeof (ExampleLoader).replacedembly;

            var names = replacedembly.GetManifestResourceNames();

            var allXmlManifestResources = names.Where(x => x.Contains("ExampleDefinitions")).ToList();
            allXmlManifestResources.Sort();

            foreach(var xmlResource in allXmlManifestResources)
            {
                using (var s = replacedembly.GetManifestResourceStream(xmlResource))
                using (var sr = new StreamReader(s))
                {
                    string exampleKeyString = xmlResource.Replace("SciChart.Examples.Resources.ExampleDefinitions.", string.Empty)
                        .Replace("SciChart.Examples.SL.Resources.ExampleDefinitions.", string.Empty);

                    string[] chunks = exampleKeyString.Split('.');
                    var exampleKey = new ExampleKey()
                    {
                        ExampleCategory = Trim(chunks[0], true),
                        ChartGroup = Trim(chunks[1]),
                        Examplereplacedle = Trim(chunks[2])
                    };
                    dict.Add(exampleKey, sr.ReadToEnd());
                }
            }
            return dict;
        }

19 Source : ExampleManager.cs
with MIT License
from ABTSoftware

public static IDictionary<string, string> GetAllExampleDefinitions()
        {
            var dictionary = new Dictionary<string, string>();
            var replacedembly = typeof(ExampleManager).replacedembly;

            var exampleNames = replacedembly.GetManifestResourceNames().Where(x => x.Contains("ExampleSourceFiles")).ToList();
            exampleNames.Sort();

            foreach (var example in exampleNames)
            {
                using (var s = replacedembly.GetManifestResourceStream(example))
                using (var sr = new StreamReader(s))
                {
                    dictionary.Add(example.Replace("SciChart.Example.Resources.ExampleDefinitions.", string.Empty),
                                   sr.ReadToEnd());
                }
            }
            return dictionary;
        }

19 Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware

public static void ExportExampleToHtml(Example example, bool isUniqueExport = true)
        {
            if (isUniqueExport)
            {
                if (!GetPathForExport())
                {
                    MessageBox.Show("Bad path. Please, try export once more.");
                    return;
                }
            }

            var replacedembly = typeof (HtmlExportHelper).replacedembly;

            string[] names = replacedembly.GetManifestResourceNames();

            var templateFile = names.SingleOrDefault(x => x.Contains(TemplateFileName));

            using (var s = replacedembly.GetManifestResourceStream(templateFile))
            using (var sr = new StreamReader(s))
            {
                string lines = sr.ReadToEnd();

                var exampleFolderPath = ExportPath;//string.Format("{0}{1}\\", ExportPath, example.replacedle);
                //CreateExampleFolder(exampleFolderPath);

                PrintMainWindow("scichart-wpf-chart-example-" + example.replacedle.ToLower().Replace(" ", "-"), exampleFolderPath);
                
                lines = ReplaceTagsWithExample(lines, example);
                var fileName = string.Format("wpf-{0}chart-example-{1}.html",                    
                    example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
                    example.replacedle.ToLower().Replace(" ", "-"));

                File.WriteAllText(Path.Combine(ExportPath, fileName), lines);
            }
            
        }

19 Source : ProjectWriter.cs
with MIT License
from ABTSoftware

public static string WriteProject(Example example, string selectedPath, string replacedembliesPath, bool showMessageBox = true)
        {
            var files = new Dictionary<string, string>();
            var replacedembly = typeof(ProjectWriter).replacedembly;

            var names = replacedembly.GetManifestResourceNames();
            var templateFiles = names.Where(x => x.Contains("Templates")).ToList();

            foreach (var templateFile in templateFiles)
            {
                var fileName = GetFileNameFromNs(templateFile);

                using (var s = replacedembly.GetManifestResourceStream(templateFile))
                {
                    if (s == null) break;

                    using (var sr = new StreamReader(s))
                    {
                        files.Add(fileName, sr.ReadToEnd());
                    }
                }
            }

            string projectName = "SciChart_" + Regex.Replace(example.replacedle, @"[^A-Za-z0-9]+", string.Empty);

            files[ProjectFileName] = GenerateProjectFile(files[ProjectFileName], example, replacedembliesPath);
            files[SolutionFileName] = GenerateSolutionFile(files[SolutionFileName], projectName);

            files.RenameKey(ProjectFileName, projectName + ".csproj");
            files.RenameKey(SolutionFileName, projectName + ".sln");

            files[MainWindowFileName] = GenerateShellFile(files[MainWindowFileName], example).Replace("[Examplereplacedle]", example.replacedle);

            foreach (var codeFile in example.SourceFiles)
            {
                files.Add(codeFile.Key, codeFile.Value);
            }

            WriteProjectFiles(files, Path.Combine(selectedPath, projectName));

            if (showMessageBox && Application.Current.MainWindow != null)
            {
                var message = $"The {example.replacedle} example was successfully exported to {selectedPath + projectName}"; 
                MessageBox.Show(Application.Current.MainWindow, message, "Success!");
            }

            return projectName;
        }

19 Source : HtmlExportHelper.cs
with MIT License
from ABTSoftware

private static void ExportIndexToHtml(IModule module)
        {
            var replacedembly = typeof(HtmlExportHelper).replacedembly;

            string[] names = replacedembly.GetManifestResourceNames();

            var templateFile = names.SingleOrDefault(x => x.Contains(IndexTemplateFileName));

            using (var s = replacedembly.GetManifestResourceStream(templateFile))
            using (var sr = new StreamReader(s))
            {
                string lines = sr.ReadToEnd();

                StringBuilder sb = new StringBuilder();
                foreach (var categoryGroup in module.Examples.Values.GroupBy(x => x.TopLevelCategory))
                {
                    sb.Append("<h2>").Append(categoryGroup.Key).Append("</h2>").Append(Environment.NewLine);

                    foreach (var exampleGroup in categoryGroup.GroupBy(x => x.Group))
                    {
                        sb.Append("<h4>").Append(exampleGroup.Key).Append("</h4>").Append(Environment.NewLine);
                        sb.Append("<ul>").Append(Environment.NewLine);
                        foreach (var example in exampleGroup)
                        {
                            var fileName = string.Format("wpf-{0}chart-example-{1}",
                                example.TopLevelCategory.ToUpper().Contains("3D") || example.replacedle.ToUpper().Contains("3D") ? "3d-" : string.Empty,
                                example.replacedle.ToLower().Replace(" ", "-"));
                            sb.Append("<li>").Append("<a href=\"").Append(fileName).Append("\">").Append(example.replacedle).Append("</a></li>");
                        }
                        sb.Append("</ul>").Append(Environment.NewLine);
                    }                    
                }
                lines = lines.Replace("[Index]", sb.ToString());

                File.WriteAllText(Path.Combine(ExportPath, "wpf-chart-examples.html"), lines);
            }
        }

See More Examples