System.IO.StreamWriter.Write(string)

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

2171 Examples 7

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 : Utils.cs
with GNU General Public License v3.0
from 2dust

public static void SaveLog(string strreplacedle, Exception ex)
        {
            try
            {
                string path = Path.Combine(StartupPath(), "guiLogs");
                string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!File.Exists(FilePath))
                {
                    FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
                    FsCreate.Close();
                    FsCreate.Dispose();
                }
                FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
                StreamWriter SwWrite = new StreamWriter(FsWrite);

                string strContent = ex.ToString();

                SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
                SwWrite.Write(strContent);
                SwWrite.WriteLine(Environment.NewLine);
                SwWrite.WriteLine(" ");
                SwWrite.Flush();
                SwWrite.Close();
            }
            catch { }
        }

19 Source : Machine.cs
with MIT License
from 3RD-Dimension

private void Work()
        {
            try
            {
                StreamReader reader = new StreamReader(Connection);
                StreamWriter writer = new StreamWriter(Connection);

                int StatusPollInterval = Properties.Settings.Default.StatusPollInterval;

                int ControllerBufferSize = Properties.Settings.Default.ControllerBufferSize;
                BufferState = 0;

                TimeSpan WaitTime = TimeSpan.FromMilliseconds(0.5);
                DateTime LastStatusPoll = DateTime.Now + TimeSpan.FromSeconds(0.5);
                DateTime StartTime = DateTime.Now;

                DateTime LastFilePosUpdate = DateTime.Now;
                bool filePosChanged = false;

                bool SendMacroStatusReceived = false;

                writer.Write("\n$G\n");
                writer.Write("\n$#\n");
                writer.Flush();

                while (true)
                {
                    Task<string> lineTask = reader.ReadLineAsync();

                    while (!lineTask.IsCompleted)
                    {
                        if (!Connected)
                        {
                            return;
                        }

                        while (ToSendPriority.Count > 0)
                        {
                            writer.Write((char)ToSendPriority.Dequeue());
                            writer.Flush();
                        }
                        if (Mode == OperatingMode.SendFile)
                        {
                            if (File.Count > FilePosition && (File[FilePosition].Length + 1) < (ControllerBufferSize - BufferState))
                            {
                                string send_line = File[FilePosition].Replace(" ", ""); // don't send whitespace to machine

                                writer.Write(send_line);
                                writer.Write('\n');
                                writer.Flush();

                                RecordLog("> " + send_line);

                                RaiseEvent(UpdateStatus, send_line);
                                RaiseEvent(LineSent, send_line);

                                BufferState += send_line.Length + 1;

                                Sent.Enqueue(send_line);

                                if (PauseLines[FilePosition] && Properties.Settings.Default.PauseFileOnHold)
                                {
                                    Mode = OperatingMode.Manual;
                                }

                                if (++FilePosition >= File.Count)
                                {
                                    Mode = OperatingMode.Manual;
                                }

                                filePosChanged = true;
                            }
                        }
                        else if (Mode == OperatingMode.SendMacro)
                        {
                            switch (Status)
                            {
                                case "Idle":
                                    if (BufferState == 0 && SendMacroStatusReceived)
                                    {
                                        SendMacroStatusReceived = false;

                                        string send_line = (string)ToSendMacro.Dequeue();

                                        send_line = Calculator.Evaluate(send_line, out bool success);

                                        if (!success)
                                        {
                                            ReportError("Error while evaluating macro!");
                                            ReportError(send_line);

                                            ToSendMacro.Clear();
                                        }
                                        else
                                        {
                                            send_line = send_line.Replace(" ", "");

                                            writer.Write(send_line);
                                            writer.Write('\n');
                                            writer.Flush();

                                            RecordLog("> " + send_line);

                                            RaiseEvent(UpdateStatus, send_line);
                                            RaiseEvent(LineSent, send_line);

                                            BufferState += send_line.Length + 1;

                                            Sent.Enqueue(send_line);
                                        }
                                    }
                                    break;
                                case "Run":
                                case "Hold":
                                    break;
                                default:    // grbl is in some kind of alarm state
                                    ToSendMacro.Clear();
                                    break;
                            }

                            if (ToSendMacro.Count == 0)
                                Mode = OperatingMode.Manual;
                        }
                        else if (ToSend.Count > 0 && (((string)ToSend.Peek()).Length + 1) < (ControllerBufferSize - BufferState))
                        {
                            string send_line = ((string)ToSend.Dequeue()).Replace(" ", "");

                            writer.Write(send_line);
                            writer.Write('\n');
                            writer.Flush();

                            RecordLog("> " + send_line);

                            RaiseEvent(UpdateStatus, send_line);
                            RaiseEvent(LineSent, send_line);

                            BufferState += send_line.Length + 1;

                            Sent.Enqueue(send_line);
                        }


                        DateTime Now = DateTime.Now;

                        if ((Now - LastStatusPoll).TotalMilliseconds > StatusPollInterval)
                        {
                            writer.Write('?');
                            writer.Flush();
                            LastStatusPoll = Now;
                        }

                        //only update file pos every X ms
                        if (filePosChanged && (Now - LastFilePosUpdate).TotalMilliseconds > 500)
                        {
                            RaiseEvent(FilePositionChanged);
                            LastFilePosUpdate = Now;
                            filePosChanged = false;
                        }

                        Thread.Sleep(WaitTime);
                    }

                    string line = lineTask.Result;

                    RecordLog("< " + line);

                    if (line == "ok")
                    {
                        if (Sent.Count != 0)
                        {
                            BufferState -= ((string)Sent.Dequeue()).Length + 1;
                        }
                        else
                        {
                            MainWindow.Logger.Info("Received OK without anything in the Sent Buffer");
                            BufferState = 0;
                        }
                    }
                    else
                    {
                        if (line.StartsWith("error:"))
                        {
                            if (Sent.Count != 0)
                            {
                                string errorline = (string)Sent.Dequeue();

                                RaiseEvent(ReportError, $"{line}: {errorline}");
                                BufferState -= errorline.Length + 1;
                            }
                            else
                            {
                                if ((DateTime.Now - StartTime).TotalMilliseconds > 200)
                                    RaiseEvent(ReportError, $"Received <{line}> without anything in the Sent Buffer");

                                BufferState = 0;
                            }

                            Mode = OperatingMode.Manual;
                        }
                        else if (line.StartsWith("<"))
                        {
                            RaiseEvent(ParseStatus, line);
                            SendMacroStatusReceived = true;
                        }
                        else if (line.StartsWith("[PRB:"))
                        {
                            RaiseEvent(ParseProbe, line);
                            RaiseEvent(LineReceived, line);
                        }                      
                        else if (line.StartsWith("["))
                        {
                            RaiseEvent(UpdateStatus, line);
                            RaiseEvent(LineReceived, line);
                        }
                        else if (line.StartsWith("ALARM"))
                        {
                            RaiseEvent(ReportError, line);
                            Mode = OperatingMode.Manual;
                            ToSend.Clear();
                            ToSendMacro.Clear();
                        }
                        else if (line.Length > 0)
                            RaiseEvent(LineReceived, line);
                    }
                }
            }
            catch (Exception ex)
            {
                RaiseEvent(ReportError, $"Fatal Error in Work Loop: {ex.Message}");
                RaiseEvent(() => Disconnect());
            }
        }

19 Source : ExtendableEnums.cs
with MIT License
from 7ark

static void AddNewEnum(string clreplacedFile, string path, string enumName, string newEnum)
    {
        string[] originalSplit = clreplacedFile.Split(new[] { "enum " + enumName }, System.StringSplitOptions.RemoveEmptyEntries);
        string newHalf = originalSplit[1];
        string enumSection = newHalf.Split('}')[0];
        string[] commas = enumSection.Split(',');
        if (commas.Length == 0 && enumSection.Split('{')[0].Trim().Length == 0) //They've left the enum empty... for some reason.
        {
            Debug.Log("Uhh idk yet");
            newHalf = newHalf.Replace(enumSection, enumSection + newEnum);
        }
        else
        {
            bool commaAfter = commas[commas.Length - 1].Trim().Length == 0; //This should check if they added a comma after their last enum value.

            if (commaAfter)
            {
                newHalf = newHalf.Replace(enumSection, enumSection + newEnum + ", ");
            }
            else
            {
                while (enumSection.Length > 0 && enumSection[enumSection.Length - 1] == ' ')
                    enumSection = enumSection.Substring(0, enumSection.Length - 1);
                newHalf = newHalf.Replace(enumSection, enumSection + ", " + newEnum);
            }
        }

        string result = clreplacedFile.Replace(originalSplit[1], newHalf);
        using (var file = File.Open(path, FileMode.Create))
        {
            using (var writer = new StreamWriter(file))
            {
                writer.Write(result);
            }
        }
        replacedetDatabase.Refresh();
    }

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 : Test.cs
with GNU General Public License v3.0
from a2659802

public IEnumerator Dump(string sceneName = null)
		{

			List<string> scenes = new List<string>();
			for (int j = 0; j < USceneManager.sceneCountInBuildSettings; j++)
			{
				string scenePath = SceneUtility.GetScenePathByBuildIndex(j);
				string name = Path.GetFileNameWithoutExtension(scenePath);
				scenes.Add(name);
				var load = USceneManager.LoadSceneAsync(j, LoadSceneMode.Single);
				while (!load.isDone)
				{
					yield return new WaitForEndOfFrame();
				}
				yield return new WaitForSeconds(0.2f);
				Scene s = USceneManager.GetActiveScene();
				StringBuilder sb = new StringBuilder();
				foreach (var g in s.GetRootGameObjects())
                {
					Visit(g.transform, 0, null,sb);
                }
				try
				{
					var fs = File.Create($"Z:\\1\\{s.name}.txt");
					StreamWriter sw = new StreamWriter(fs);
					sw.Write(sb.ToString());
					sw.Close();
					fs.Close();
				}
				catch { }
				
				//
			}
			var load_ = USceneManager.LoadSceneAsync(2, LoadSceneMode.Single);
			while (!load_.isDone)
			{
				yield return new WaitForEndOfFrame();
			}
			yield return USceneManager.LoadSceneAsync("Quit_To_Menu");
			while (USceneManager.GetActiveScene().name != Constants.MENU_SCENE)
			{
				yield return new WaitForEndOfFrame();
			}

			
			
		}

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

private static void Send(HttpWebRequest webRequest, string soapMessage) {
         StreamWriter StreamWriter;
         StreamWriter = new StreamWriter(webRequest.GetRequestStream());
         StreamWriter.Write(soapMessage);
         StreamWriter.Flush();
         StreamWriter.Close();
      }

19 Source : ProjectWriter.cs
with MIT License
from ABTSoftware

private static void WriteProjectFiles(Dictionary<string, string> files, string selectedPath)
        {
            Directory.CreateDirectory(selectedPath);

            foreach (var file in files)
            {
                using (var f = new StreamWriter(Path.Combine(selectedPath, file.Key)))
                {
                    f.Write(file.Value);
                }
            }
        }

19 Source : SyncUsageHelper.cs
with MIT License
from ABTSoftware

public void WriteToIsolatedStorage()
        {
            try
            {
                using (var isf = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.replacedembly,
                    null, null))
                {
                    using (var stream = new IsolatedStorageFileStream("Usage.xml", FileMode.Create, isf))
                    {
                        var xml = SerializationUtil.Serialize(
                            _usageCalculator.Usages.Values.Where(e => e.VisitCount > 0));
                        xml.Root.Add(new XAttribute("UserId", userId));
                        xml.Root.Add(new XAttribute("Enabled", Enabled));
                        xml.Root.Add(new XAttribute("LastSent", lastSent.ToString("o")));

                        using (var stringWriter = new StringWriter())
                        {
                            xml.Save(stringWriter);

                            var encryptedUsage = _encryptionHelper.Encrypt(stringWriter.ToString());
                            using (StreamWriter writer = new StreamWriter(stream))
                            {
                                writer.Write(encryptedUsage);
                            }
                        }
                    }
                }
            }
            catch { }
        }

19 Source : SecureExtensions.cs
with MIT License
from Accelerider

public static string EncryptByRijndael(this string text, byte[] key = null, byte[] iv = null)
        {
            byte[] encryptedInfo;
            using (var rijndaelAlgorithm = new RijndaelManaged())
            {
                rijndaelAlgorithm.Key = key ?? DefaultKey;
                rijndaelAlgorithm.IV = iv ?? DefaultIv;
                var encryptor = rijndaelAlgorithm.CreateEncryptor(rijndaelAlgorithm.Key, rijndaelAlgorithm.IV);

                using (var msEncrypt = new MemoryStream())
                using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (var swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(text);
                    }
                    encryptedInfo = msEncrypt.ToArray();
                }
            }
            return BitConverter.ToString(encryptedInfo).Replace("-", string.Empty);
        }

19 Source : CmdLineActions.cs
with MIT License
from action-bi-toolkit

[ArgActionMethod, ArgShortcut("export-usage"), OmitFromUsageDocs]
        public void ExportUsage(
            [ArgDescription("The optional path to a file to write into. Prints to console if not provided.")] string outPath
        )
        {
            var sb = new StringBuilder();
            
            var definitions = CmdLineArgumentsDefinitionExtensions.For<CmdLineActions>().RemoveAutoAliases();

            sb.AppendLine("## Usage");
            sb.AppendLine();
            sb.AppendLine($"    {definitions.UsageSummary}");
            sb.AppendLine();
            sb.AppendLine($"_{definitions.Description}_");
            sb.AppendLine();
            sb.AppendLine("### Actions");
            sb.AppendLine();

            foreach (var action in definitions.UsageActions)
            {
                sb.AppendLine($"#### {action.DefaultAlias}");
                sb.AppendLine();
                sb.AppendLine($"    {action.UsageSummary}");
                sb.AppendLine();
                sb.AppendLine(action.Description);
                sb.AppendLine();

                if (action.HasArguments)
                { 
                    sb.AppendLine("| Option | Default Value | Is Switch | Description |");
                    sb.AppendLine("| --- | --- | --- | --- |");

                    foreach (var arg in action.UsageArguments.Where(a => !a.OmitFromUsage))
                    {
                        var enumValues = arg.EnumValuesAndDescriptions.Aggregate(new StringBuilder(), (sb, fullDescr) => {
                            var pos = fullDescr.IndexOf(" - ");
                            var value = fullDescr.Substring(0, pos);
                            var descr = fullDescr.Substring(pos);
                            sb.Append($" <br> `{value}` {descr}");
                            return sb;
                        });
                        sb.AppendLine($"| {arg.DefaultAlias}{(arg.IsRequired ? "*" : "")} | {(arg.HasDefaultValue ? $"`{arg.DefaultValue}`" : "")} | {(arg.ArgumentType == typeof(bool) ? "X" : "")} | {arg.Description}{enumValues} |");
                    }
                    sb.AppendLine();
                }

                if (action.HasExamples)
                {
                    foreach (var example in action.Examples)
                    {
                        if (example.Hasreplacedle)
                        { 
                            sb.AppendLine($"**{example.replacedle}**");
                            sb.AppendLine();
                        }

                        sb.AppendLine($"    {example.Example}");
                        sb.AppendLine();
                        sb.AppendLine($"_{example.Description}_");
                        sb.AppendLine();
                    }
                }
            }

            if (String.IsNullOrEmpty(outPath))
            { 
                using (_appSettings.SuppressConsoleLogs())
                {
                    Console.WriteLine(sb.ToString());
                }
            }
            else
            {
                using (var writer = File.CreateText(outPath))
                {
                    writer.Write(sb.ToString());
                }
            }
        }

19 Source : MashupSerializerTests.cs
with MIT License
from action-bi-toolkit

[Fact]
        public void SerializePackage__Deletes_section_file_before_writing_to_section_folder()
        {
            var mockFolder = new Mock<IProjectFolder>();
            mockFolder.Setup(folder => folder.ContainsFile("Formulas/Section1.m")).Returns(true);
            mockFolder.Setup(folder => folder.WriteText(It.IsAny<string>(), It.IsAny<Action<TextWriter>>()))
                .Callback<string, Action<TextWriter>>((_, onWriter) => // this is necessary to avoid NRE in test code
                {
                    using (var writer = new StringWriter())
                    {
                        onWriter(writer);
                    }
                });
            mockFolder.Setup(folder => folder.GetSubfolder(It.IsAny<string[]>())).Returns(mockFolder.Object);

            var serializer = new MashupSerializer(new MockRootFolder(() => mockFolder.Object), new ProjectSystem.MashupSettings { SerializationMode = ProjectSystem.MashupSerializationMode.Expanded  });

            using (var stream = new MemoryStream())
            {
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
                {
                    var packageXml = archive.CreateEntry("Config/Package.xml");
                    using (var writer = new StreamWriter(packageXml.Open()))
                    {
                        writer.Write(@"<?xml version=""1.0"" encoding=""utf-8""?><Package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""><Version>2.55.5010.641</Version><MinVersion>1.5.3296.0</MinVersion><Culture>en-GB</Culture></Package>");
                    }

                    var contentTypesXml = archive.CreateEntry("[Content_Types].xml"); // must have written previous entry before opening new one, see https://stackoverflow.com/a/37533305/736263
                    using (var writer = new StreamWriter(contentTypesXml.Open()))
                    {
                        writer.Write(@"<?xml version=""1.0"" encoding=""utf-8""?><Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types""><Default Extension=""xml"" ContentType=""text/xml"" /><Default Extension=""m"" ContentType=""application/x-ms-m"" /></Types>");
                    }

                    var section1 = archive.CreateEntry("Formulas/Section1.m");
                    using (var writer = new StreamWriter(section1.Open()))
                    {
                        writer.Write("section Section1;\n\nshared Version = \"1.0\";");
                    }
                }

                stream.Position = 0;

                using (var archive = new ZipArchive(stream))
                {
                    serializer.SerializePackage(archive);
                }
            }

            mockFolder.Verify(folder => folder.DeleteFile("Formulas/Section1.m"));
        }

19 Source : TestData.cs
with MIT License
from action-bi-toolkit

private static byte[] BuildMinimalMashupPackage()
        {
            using (var stream = new MemoryStream())
            {
                using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
                {
                    var packageXml = zip.CreateEntry("Config/Package.xml");
                    using (var writer = new StreamWriter(packageXml.Open()))
                    {
                        writer.Write(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Package xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
    <Version>2.55.5010.641</Version>
    <MinVersion>1.5.3296.0</MinVersion>
    <Culture>en-GB</Culture>
</Package>");
                    }

                    var contentTypesXml = zip.CreateEntry("[Content_Types].xml"); // must have written previous entry before opening new one, see https://stackoverflow.com/a/37533305/736263
                    using (var writer = new StreamWriter(contentTypesXml.Open()))
                    {
                        writer.Write(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Types xmlns=""http://schemas.openxmlformats.org/package/2006/content-types"">
    <Default Extension=""xml"" ContentType=""text/xml"" />
    <Default Extension=""m"" ContentType=""application/x-ms-m"" />
</Types>");
                    }

                    var section1 = zip.CreateEntry("Formulas/Section1.m");
                    using (var writer = new StreamWriter(section1.Open()))
                    {
                        writer.Write(
@"section Section1;");
                    }
                }

                return stream.ToArray();
            }
        }

19 Source : VssFileStorage.cs
with MIT License
from actions

private void SaveFile(string path, string content)
            {
                bool success = false;
                int tries = 0;
                int retryDelayMilliseconds = 10;
                const int maxNumberOfRetries = 6;
                do
                {
                    try
                    {
                        using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Delete))
                        {
                            using (var sw = new StreamWriter(fs, Encoding.UTF8))
                            {
                                sw.Write(content);
                            }
                        }
                        success = true;
                    }
                    catch (IOException)
                    {
                        if (++tries > maxNumberOfRetries)
                        {
                            throw;
                        }
                        Task.Delay(retryDelayMilliseconds).Wait();
                        retryDelayMilliseconds *= 2;
                    }
                }
                while (!success);
            }

19 Source : RichTextBoxExtended.cs
with MIT License
from Actipro

public void LoadDoreplacedent(string text) {
			MemoryStream stream = new MemoryStream();
			StreamWriter writer = new StreamWriter(stream);
			writer.Write(text);
			writer.Flush();
			stream.Position = 0;
			TextRange range = new TextRange(this.Doreplacedent.ContentStart, this.Doreplacedent.ContentEnd);
            range.Load(stream, DataFormats.Rtf);
			stream.Close();
		}

19 Source : MainControl.xaml.cs
with MIT License
from Actipro

private void LoadRtf(string rtf) {
			if (string.IsNullOrEmpty(rtf))
				return;

			TextRange textRange = new TextRange(previewRichTextBox.Doreplacedent.ContentStart, previewRichTextBox.Doreplacedent.ContentEnd);

			using (MemoryStream stream = new MemoryStream()) {
				using (StreamWriter writer = new StreamWriter(stream)) {
					writer.Write(rtf);
					writer.Flush();
					stream.Seek(0, SeekOrigin.Begin);

					textRange.Load(stream, DataFormats.Rtf);
				}
			}
		}

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

static void Main(string[] args)
        {
            bool DonotLoadGrid = true;
            var grid = new List<IList<double>>();
            if (!DonotLoadGrid)
            {
                Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
                var sr = new StreamReader(@"C:\data\table.csv");

                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var fieldValues = line.Split(',');
                    var fields = new List<double>();
                    var rdm = new Random(100000);
                    foreach (var field in fieldValues)
                    {
                        var res = 0d;
                        var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
                        fields.Add(add);
                    }
                    grid.Add(fields);
                }
                Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
            }
            var keepProcessing = true;
            while (keepProcessing)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine("Enter Expression:");
                var expression = Console.ReadLine();
                if (expression.ToLower() == "exit")
                {
                    keepProcessing = false;
                }
                else
                {
                    try
                    {
                        if(expression.Equals("zspread"))
                        {
                            var result = ConnectedInstruction.GetZSpread(grid,3,503);
                        }
                        if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
                        {
                            keepProcessing = true;
                            var paths = expression.Split(' '); 
                            #region Python
                                var script =@"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

creditData = pd.read_csv("+paths[1]+@")

print(creditData.head())
print(creditData.describe())
print(creditData.corr())

features = creditData[['income', 'age', 'loan']]
target = creditData.default

feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)

model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)

print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
                            var sw = new StreamWriter(@"c:\data\logistic.py");
                            sw.Write(script);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if(expression.Substring(0,12) == "videoreplacedyse")
                        {
                            #region python
                            var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con

#mydb = con.connect(
#  host=""localhost"",
#  user=""yourusername"",
#  preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()

g = geocoder.ip('me')

# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'

# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]


# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))

# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")

while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)


canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)



preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue



for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]

                
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)


#    for c in range(0, 3):
#        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
#        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
#        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)


cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

camera.release()
cv2.destroyAllWindows()
";
                            var sw = new StreamWriter(@"c:\data\face.py");
                            sw.Write(python);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
                        {
                            keepProcessing = true;
                            var columnsOfconcern = expression.Split(' ');
                            Console.WriteLine("Preparing...");
                            var observations = new List<PairedObservation>();
                            var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
                            var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
                            var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
                            for(int i=0;i<ca.Count;i++)
                            {
                                observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
                            }
                            var kp = new KaplanMeier(observations);
                        }
                        if (expression.Equals("write"))
                        {
                            keepProcessing = true;
                            ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
                        }
                        if (expression.Substring(0, 9) == "getvalue(")
                        {
                            keepProcessing = true;
                            Regex r = new Regex(@"\(([^()]+)\)*");
                            var res = r.Match(expression);
                            var val = res.Value.Split(',');
                            try
                            {
                                var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
                                    [int.Parse(val[1].Replace("(", "").Replace(")", ""))];
                                Console.WriteLine(gridVal.ToString() + "\n");
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
                            }
                        }
                        else
                        {
                            keepProcessing = true;
                            Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
                            var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
                            Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {

                    }
                }
            }
        }

19 Source : APIConsumerHelper.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static ReturnType ReceiveHTTPObjectPointer<ParameterType,ReturnType>
            (ParameterType parameterLObject, 
            string url,
            RESTMethodType methodType)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest
                     .Create(url);
            request.Method = methodType.ToString();
            request.ContentType = "application/json";
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            using (var sw = new StreamWriter(request.GetRequestStream()))
            {
                string json = serializer.Serialize(parameterLObject);
                sw.Write(json);
                sw.Flush();
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream receiveStream = response.GetResponseStream();
            string strP = ReadResponseStream(receiveStream);
            var result = JsonConvert.DeserializeObject<ReturnType>(strP);
            return result;
        }

19 Source : MemoryFileProvider.cs
with MIT License
from adams85

public void CreateFile(string path, string content = null, Encoding encoding = null)
        {
            path = NormalizePath(path);
            lock (_catalog)
            {
                CheckPath(path);

                var file = new File();
                file.Content = new File.Stream(this, file);

                if (content != null)
                {
                    var writer = new StreamWriter(file.Content, encoding ?? Encoding.UTF8);
                    writer.Write(content);
                    writer.Flush();
                }

                _catalog.Add(path, file);
            }
        }

19 Source : MemoryFileProvider.cs
with MIT License
from adams85

public void WriteContent(string path, string content, Encoding encoding = null, bool append = false)
        {
            path = NormalizePath(path);

            CancellationTokenSource changeTokenSource = null;
            lock (_catalog)
                using (MemoryStream stream = GetStreamCore(path, out File file))
                {
                    if (content.Length == 0)
                        return;

                    if (!append)
                        stream.SetLength(0);
                    else
                        stream.Seek(0, SeekOrigin.End);

                    var writer = new StreamWriter(stream, encoding ?? Encoding.UTF8);
                    writer.Write(content);
                    writer.Flush();

                    if (file.ChangeTokenSource != null)
                    {
                        changeTokenSource = file.ChangeTokenSource;
                        file.ChangeTokenSource = new CancellationTokenSource();
                    }
                }

            changeTokenSource?.Cancel();
        }

19 Source : Requestor.cs
with MIT License
from adoprog

public void PostRequest(string url, string json)
    {
      try
      {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
          streamWriter.Write(json);
          streamWriter.Flush();
          streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
          var result = streamReader.ReadToEnd();
        }
      }
      catch (Exception ex)
      {
        Log.Error("PostToFlow: Action failed to execute", ex);
      }
    }

19 Source : SendToFlow.cs
with MIT License
from adoprog

public void PostRequest(string url, string json)
    {
      try
      {
        var httpWebRequest = (HttpWebRequest) WebRequest.Create(url);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "POST";

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
          streamWriter.Write(json);
          streamWriter.Flush();
          streamWriter.Close();
        }

        var httpResponse = (HttpWebResponse) httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
          var result = streamReader.ReadToEnd();
        }
      }
      catch
      {
        // TODO: Use MA logging API to log error 
      }
    }

19 Source : PaypalHelper.cs
with MIT License
from Adoxio

public WebResponse GetPaymentWebResponse(string incomingReqStr)
		{
			var newReq = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);

			//Set values for the request back
			newReq.Method = "POST";
			newReq.ContentType = "application/x-www-form-urlencoded";

			var newRequestStr = incomingReqStr + "&cmd=_notify-validate";
			newReq.ContentLength = newRequestStr.Length;

			//write out the full parameters into the request
			var streamOut = new StreamWriter(newReq.GetRequestStream(), System.Text.Encoding.ASCII);
			streamOut.Write(newRequestStr);
			streamOut.Close();

			//Send request back to Paypal and receive response
			var response = newReq.GetResponse();
			return response;
		}

19 Source : PaypalHelper.cs
with MIT License
from Adoxio

public IPayPalPaymentDataTransferResponse GetPaymentDataTransferResponse(string idenreplacedyToken, string transactionId)
		{
			var query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionId, idenreplacedyToken);

			var request = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl);

			request.Method = WebRequestMethods.Http.Post;
			request.ContentType = "application/x-www-form-urlencoded";
			request.ContentLength = query.Length;

			var streamOut = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
			streamOut.Write(query);
			streamOut.Close();
			var streamIn = new StreamReader(request.GetResponse().GetResponseStream());
			var response = streamIn.ReadToEnd();
			streamIn.Close();
			
			return new PayPalPaymentDataTransferResponse(response);
		}

19 Source : HttpURLConnectionClient.cs
with MIT License
from Adyen

public string Request(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null )
        {
            string responseText = null;
            _environment = config.Environment;
            var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions );
            if (config.HttpRequestTimeout > 0)
            {
                httpWebRequest.Timeout = config.HttpRequestTimeout;
            }
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            try
            {
                using (var response = (HttpWebResponse) httpWebRequest.GetResponse())
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
                    {
                        responseText = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException e)
            {
                HandleWebException(e);
            }
            return responseText;
        }

19 Source : HttpURLConnectionClient.cs
with MIT License
from Adyen

public async Task<string> RequestAsync(string endpoint, string json, Config config, bool isApiKeyRequired, RequestOptions requestOptions = null)
        {
            string responseText = null;
            //Set security protocol. Only TLS1.2
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var httpWebRequest = GetHttpWebRequest(endpoint, config, isApiKeyRequired, requestOptions);
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            try
            {
                using (var response = (HttpWebResponse)await httpWebRequest.GetResponseAsync())
                {
                    using (var reader = new StreamReader(response.GetResponseStream(), _encoding))
                    {
                        responseText = await reader.ReadToEndAsync();
                    }
                }
            }
            catch (WebException e)
            {
                HandleWebException(e);
            }
            return responseText;
        }

19 Source : File.cs
with GNU General Public License v3.0
from aelariane

public void Create()
        {
            lock (locker)
            {
                if (info.Exists)
                {
                    info.Delete();
                }

                info.Create();
                using (StreamWriter writer = new StreamWriter(Path, false))
                {
                    writer.Write(string.Empty);
                }
            }
        }

19 Source : LogFile.cs
with GNU General Public License v3.0
from aelariane

public void Clear()
        {
            using (var writer = new System.IO.StreamWriter(info.FullName, false))
            {
                writer.Write(string.Empty);
            }
        }

19 Source : EpubFile.cs
with MIT License
from Aeroblast

public override void PutInto(ZipArchive zip)
        {
            var entry = zip.CreateEntry(fullName);
            using (StreamWriter writer = new StreamWriter(entry.Open()))
            {
                writer.Write(text);
            }

        }

19 Source : EpubFile.cs
with MIT License
from Aeroblast

public override void PutInto(ZipArchive zip)
        {
            var entry = zip.CreateEntry("mimetype", CompressionLevel.NoCompression);

            using (StreamWriter writer = new StreamWriter(entry.Open()))
            {
                writer.Write("application/epub+zip");
            }

        }

19 Source : EpubBuilder.cs
with GNU General Public License v3.0
from Aeroblast

public void Save(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create))
            using (ZipArchive zip = new ZipArchive(fs, ZipArchiveMode.Create))
            {
                {
                    var entry = zip.CreateEntry("mimetype", CompressionLevel.NoCompression);
                    using (StreamWriter writer = new StreamWriter(entry.Open()))
                        writer.Write("application/epub+zip");
                }
                ZipWriteAllText(zip, "META-INF/container.xml", container);
                for (int i = 0; i < xhtml_names.Count; i++)
                {
                    string p = "OEBPS/Text/" + xhtml_names[i];
                    string ss;
                    var xmlSettings = new XmlWriterSettings { Indent = true, NewLineChars = "\n" };
                    using (var stringWriter = new StringWriter())
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter, xmlSettings))
                    {
                        xhtmls[i].WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                        ss = stringWriter.GetStringBuilder().ToString();
                    }
                    ss = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html>\n"
                    + ss.Substring(ss.IndexOf("<html"));
                    ZipWriteAllText(zip, p, ss);
                }
                for (int i = 0; i < css_names.Count; i++)
                {
                    ZipWriteAllText(zip, "OEBPS/Styles/" + css_names[i], csss[i]);
                }
                for (int i = 0; i < img_names.Count; i++)
                {
                    ZipWriteAllBytes(zip, "OEBPS/Images/" + img_names[i], imgs[i]);
                }
                for (int i = 0; i < font_names.Count; i++)
                {
                    ZipWriteAllBytes(zip, "OEBPS/Fonts/" + font_names[i], fonts[i]);
                }
                ZipWriteAllText(zip, "OEBPS/toc.ncx", ncx);
                ZipWriteAllText(zip, "OEBPS/nav.xhtml", nav);
                ZipWriteAllText(zip, "OEBPS/content.opf", opf);
            }
            Log.log("Saved: " + path);
        }

19 Source : EpubBuilder.cs
with GNU General Public License v3.0
from Aeroblast

void ZipWriteAllText(ZipArchive zip, string path, string text)
        {
            var entry = zip.CreateEntry(path);
            using (StreamWriter writer = new StreamWriter(entry.Open()))
            {
                writer.Write(text);
            }
        }

19 Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis

protected virtual void BuildEmpty(string str, string empty)
	{
		if (str == null)
			return;

		for (int i = str.Length; i > 0;) {
			if (empty.Length <= i) {
				writer.Write(empty);
				i -= empty.Length;
			}
			else {
				writer.Write(empty.Substring(0, i));
				i = 0;
			}
		}
	}

19 Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis

protected virtual void BuildPrefix(string str)
	{
		writer.Write(str);
	}

19 Source : RedBlackTree.cs
with GNU General Public License v2.0
from afrantzis

public void DumpToDot(string filename, string replacedle)
	{
		lock(lockObj) {
			StringBuilder sb = new StringBuilder("digraph {\nlabel=\""+replacedle+"\"\n");
			DumpToDotInternal(root, sb);
			sb.Append("}\n");
			
			StreamWriter sw = new StreamWriter(filename);
			sw.Write(sb.ToString());
			sw.Close();
		}
	}

19 Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis

public virtual void BuildString(string str)
	{
		writer.Write(str);
		writer.Flush();
	}

19 Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis

protected virtual void BuildSeparator(string separator)
	{
		writer.Write(separator);
	}

19 Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis

protected virtual void BuildByteData(string str)
	{
		writer.Write(str);
	}

19 Source : TextExportBuilder.cs
with GNU General Public License v2.0
from afrantzis

protected virtual void BuildSuffix(string str)
	{
		writer.Write(str);
	}

19 Source : IOHelper.cs
with Mozilla Public License 2.0
from agebullhu

public static T XMLDeSerializer<T>(string args)
        {
            if (string.IsNullOrWhiteSpace(args) || args[0] != '<')
            {
                return default(T);
            }
            byte[] buffers;
            long len;
            using (var ms = new MemoryStream())
            {
                var sw = new StreamWriter(ms);
                sw.Write(args);
                sw.Flush();
                len = ms.Position;
                buffers = ms.GetBuffer();
            }
            using (var reader = XmlDictionaryReader.CreateTextReader(buffers, 0, (int)len, new XmlDictionaryReaderQuotas()))
            {
                var ds = new DataContractSerializer(typeof(T));
                var re = (T)ds.ReadObject(reader, false);
                return re;
            }
        }

19 Source : MainForm.cs
with GNU General Public License v3.0
from AgentRev

void SaveGameMode()
        {
            if (saveSettings && !currentlyReading)
            {
                try
                {
                    using (StreamWriter sw = new StreamWriter(gameModeFile))
                    {
                        if (rbMultiplayer.Checked)
                            sw.Write("mp");
                        else if (rbSingleplayer.Checked)
                            sw.Write("sp");
                    }
                }
                catch
                {
                    try
                    {
                        File.Delete(gameModeFile);
                    }
                    catch { }
                }
            }
        }

19 Source : Extension.cs
with MIT License
from Agenty

public static void TableToFile(this DataTable table, string path, bool append = true)
        {
            StringBuilder stringBuilder = new StringBuilder();
            if (!File.Exists(path) || !append)
                stringBuilder.AppendLine(string.Join("\t", table.Columns.Cast<DataColumn>().Select(arg => arg.ColumnName)));

            using (StreamWriter sw = new StreamWriter(path, append))
            {
                foreach (DataRow dataRow in table.Rows)
                    stringBuilder.AppendLine(string.Join("\t", dataRow.ItemArray.Select(arg => arg.ToString())));
                sw.Write(stringBuilder.ToString());
            }
        }

19 Source : WebvttSubripConverter.cs
with GNU General Public License v3.0
from AhmedOS

public void ConvertToSubrip(string inputFilePath, string outputFolderPath)
        {
            String webvttSubreplacedle;
            using (StreamReader stream = new StreamReader(inputFilePath))
                webvttSubreplacedle = stream.ReadToEnd();

            String subripSubreplacedle = ConvertToSubrip(webvttSubreplacedle);

            string fileName = Path.GetFileNameWithoutExtension(inputFilePath) + subripFileExtension;
            string outputFilePath = outputFolderPath + '\\' + fileName;
            using (StreamWriter outputFile = new StreamWriter(outputFilePath))
                outputFile.Write(subripSubreplacedle);
        }

19 Source : Encryption.cs
with GNU General Public License v3.0
from aiportal

private static string Encrypt(string data, Byte[] key, Byte[] iv)
		{
			Byte[] tmp = null;
			System.Security.Cryptography.TripleDES tripleDes = System.Security.Cryptography.TripleDES.Create();
			ICryptoTransform encryptor = tripleDes.CreateEncryptor(key, iv);
			using (MemoryStream ms = new MemoryStream())
			{
				using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
				{
					StreamWriter writer = new StreamWriter(cs);
					writer.Write(data);
					writer.Flush();
				}
				tmp = ms.ToArray();
			}
			return Convert.ToBase64String(tmp);
		}

19 Source : Crypto.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static string EncryptStage(string plaintext)
        {
            using (Aes aes = Aes.Create())
            {
                // Use our PSK (generated in Apfell payload config) as the AES key
                aes.Key = Convert.FromBase64String(Config.Psk);
                aes.Padding = PaddingMode.PKCS7;
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream encryptMemStream = new MemoryStream())
                using (CryptoStream encryptCryptoStream = new CryptoStream(encryptMemStream, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter encryptStreamWriter = new StreamWriter(encryptCryptoStream))
                        encryptStreamWriter.Write(plaintext);
                    // We need to send uuid:iv:ciphertext:hmac
                    // Concat iv:ciphertext
                    byte[] encrypted = aes.IV.Concat(encryptMemStream.ToArray()).ToArray();
                    HMACSHA256 sha256 = new HMACSHA256(Convert.FromBase64String(Config.Psk));
                    // Attach hmac to iv:ciphertext
                    byte[] hmac = sha256.ComputeHash(encrypted);
                    // Attach uuid to iv:ciphertext:hmac
                    byte[] final = Encoding.UTF8.GetBytes(Config.PayloadUUID).Concat(encrypted.Concat(hmac).ToArray()).ToArray();
                    // Return base64 encoded ciphertext
                    return Convert.ToBase64String(final);
                }
            }
        }

19 Source : Crypto.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static string Encrypt(string plaintext)
        {
            using (Aes aes = Aes.Create())
            {
                // Use our PSK (generated in Apfell payload config) as the AES key
                aes.Key = Convert.FromBase64String(Config.Psk);
                aes.Padding = PaddingMode.PKCS7;
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream encryptMemStream = new MemoryStream())
                using (CryptoStream encryptCryptoStream = new CryptoStream(encryptMemStream, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter encryptStreamWriter = new StreamWriter(encryptCryptoStream))
                        encryptStreamWriter.Write(plaintext);
                    // We need to send uuid:iv:ciphertext:hmac
                    // Concat iv:ciphertext
                    byte[] encrypted = aes.IV.Concat(encryptMemStream.ToArray()).ToArray();
                    HMACSHA256 sha256 = new HMACSHA256(Convert.FromBase64String(Config.Psk));
                    // Attach hmac to iv:ciphertext
                    byte[] hmac = sha256.ComputeHash(encrypted);
                    // Attach uuid to iv:ciphertext:hmac
                    byte[] final = Encoding.UTF8.GetBytes(Config.UUID).Concat(encrypted.Concat(hmac).ToArray()).ToArray();
                    // Return base64 encoded ciphertext
                    return Convert.ToBase64String(final);
                }
            }
        }

19 Source : Crypto.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static string EncryptCheckin(string plaintext)
        {
            using (Aes aes = Aes.Create())
            {
                // Use our PSK (generated in Apfell payload config) as the AES key
                aes.Key = Convert.FromBase64String(Config.Psk);
                aes.Padding = PaddingMode.PKCS7;
                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream encryptMemStream = new MemoryStream())
                using (CryptoStream encryptCryptoStream = new CryptoStream(encryptMemStream, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter encryptStreamWriter = new StreamWriter(encryptCryptoStream))
                        encryptStreamWriter.Write(plaintext);
                    // We need to send uuid:iv:ciphertext:hmac
                    // Concat iv:ciphertext
                    byte[] encrypted = aes.IV.Concat(encryptMemStream.ToArray()).ToArray();
                    HMACSHA256 sha256 = new HMACSHA256(Convert.FromBase64String(Config.Psk));
                    // Attach hmac to iv:ciphertext
                    byte[] hmac = sha256.ComputeHash(encrypted);
                    // Attach uuid to iv:ciphertext:hmac
#if (DEFAULT_EKE || HTTP_EKE)
                    byte[] final = Encoding.UTF8.GetBytes(Config.tempUUID).Concat(encrypted.Concat(hmac).ToArray()).ToArray();
#else
                    byte[] final = Encoding.UTF8.GetBytes(Config.PayloadUUID).Concat(encrypted.Concat(hmac).ToArray()).ToArray();
#endif
                    // Return base64 encoded ciphertext
                    return Convert.ToBase64String(final);
                }
            }
        }

19 Source : OpensslEsiaSigner.cs
with GNU General Public License v3.0
from AISGorod

public string Sign(byte[] data)
        {
            Process a = new Process();
            a.StartInfo.FileName = "openssl";
            a.StartInfo.Arguments = $"cms -sign -binary -stream -engine gost -inkey {KEY_FILE} -signer {CRT_FILE} -nodetach -outform pem";

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                a.StartInfo.FileName = "wsl";
                a.StartInfo.Arguments = "openssl " + a.StartInfo.Arguments;
            }

            a.StartInfo.RedirectStandardInput = true;
            a.StartInfo.RedirectStandardOutput = true;
            a.StartInfo.UseShellExecute = false;

            a.Start();
            a.StandardInput.Write(Encoding.UTF8.GetString(data)); // просто передавать массив байтов не получается - ломает подпись
            a.StandardInput.Close();

            StringBuilder resultData = new StringBuilder();
            bool isKeyProcessing = false;
            while (!a.StandardOutput.EndOfStream)
            {
                string line = a.StandardOutput.ReadLine();
                if (line == "-----BEGIN CMS-----")
                {
                    isKeyProcessing = true;
                }
                else if (line == "-----END CMS-----")
                {
                    isKeyProcessing = false;
                }
                else if (isKeyProcessing)
                {
                    resultData.Append(line);
                }
            }
            return resultData.ToString();
        }

19 Source : ManagedAes.cs
with Apache License 2.0
from ajuna-network

public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;

            // Create an Aes object
            // with the specified key and IV.
            using (var aesAlg = Aes.Create())
            {
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create an encryptor to perform the stream transform.
                var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (var swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }

                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return encrypted;
        }

19 Source : CancerspaceInspector.cs
with GNU General Public License v3.0
from AkaiMage

public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props) {
		if (!initialized) {
			customRenderQueue = (materialEditor.target as Material).shader.renderQueue;
			rng = new System.Random();
			initialized = true;
		}
		cancerfree = (materialEditor.target as Material).shader.name.Contains("Cancerfree");
		
		GUIStyle defaultStyle = new GUIStyle(EditorStyles.foldout);
		defaultStyle.fontStyle = FontStyle.Bold;
		defaultStyle.onNormal = EditorStyles.boldLabel.onNormal;
		defaultStyle.onFocused = EditorStyles.boldLabel.onFocused;
		
		List<CSCategory> categories = new List<CSCategory>();
		categories.Add(new CSCategory(Styles.falloffSettingsreplacedle, defaultStyle, me => {
			CSProperty falloffCurve = FindProperty("_FalloffCurve", props);
			CSProperty falloffDepth = FindProperty("_DepthFalloff", props);
			CSProperty falloffColor = FindProperty("_ColorFalloff", props);
			
			DisplayRegularProperty(me, falloffCurve);
			if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_MinFalloff", props));
			DisplayRegularProperty(me, FindProperty("_MaxFalloff", props));
			DisplayRegularProperty(me, falloffDepth);
			if (falloffDepth.prop.floatValue > .5) {
				CSProperty falloffDepthCurve = FindProperty("_DepthFalloffCurve", props);
				
				DisplayRegularProperty(me, falloffDepthCurve);
				if (falloffDepthCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_DepthMinFalloff", props));
				DisplayRegularProperty(me, FindProperty("_DepthMaxFalloff", props));
			}
			DisplayRegularProperty(me, falloffColor);
			if (falloffColor.prop.floatValue > .5) {
				CSProperty falloffColorCurve = FindProperty("_ColorFalloffCurve", props);

				DisplayRegularProperty(me, FindProperty("_ColorChannelForFalloff", props));
				DisplayRegularProperty(me, falloffColorCurve);
				if (falloffColorCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_ColorMinFalloff", props));
				DisplayRegularProperty(me, FindProperty("_ColorMaxFalloff", props));
			}
		}));
		categories.Add(new CSCategory(Styles.particleSystemSettingsreplacedle, defaultStyle, me => {
			CSProperty falloffCurve = FindProperty("_LifetimeFalloffCurve", props);
			CSProperty falloff = FindProperty("_LifetimeFalloff", props);
			
			DisplayRegularProperty(me, FindProperty("_ParticleSystem", props));
			DisplayRegularProperty(me, falloff);
			if (falloff.prop.floatValue > .5) {
				DisplayRegularProperty(me, falloffCurve);
				if (falloffCurve.prop.floatValue > .5) DisplayRegularProperty(me, FindProperty("_LifetimeMinFalloff", props));
				DisplayRegularProperty(me, FindProperty("_LifetimeMaxFalloff", props));
			}
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.screenShakeSettingsreplacedle, defaultStyle, me => {
			DisplayFloatWithSliderMode(me, FindProperty("_XShake", props));
			DisplayFloatWithSliderMode(me, FindProperty("_YShake", props));
			DisplayFloatWithSliderMode(me, FindProperty("_XShakeSpeed", props));
			DisplayFloatWithSliderMode(me, FindProperty("_YShakeSpeed", props));
			DisplayFloatWithSliderMode(me, FindProperty("_ShakeAmplitude", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.wobbleSettingsreplacedle, defaultStyle, me => {
			DisplayFloatRangeProperty(me, FindProperty("_XWobbleAmount", props));
			DisplayFloatRangeProperty(me, FindProperty("_YWobbleAmount", props));
			DisplayFloatRangeProperty(me, FindProperty("_XWobbleTiling", props));
			DisplayFloatRangeProperty(me, FindProperty("_YWobbleTiling", props));
			DisplayFloatWithSliderMode(me, FindProperty("_XWobbleSpeed", props));
			DisplayFloatWithSliderMode(me, FindProperty("_YWobbleSpeed", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.blurSettingsreplacedle, defaultStyle, me => {
			DisplayFloatWithSliderMode(me, FindProperty("_BlurRadius", props));
			DisplayIntSlider(me, FindProperty("_BlurSampling", props), 1, 5);
			DisplayRegularProperty(me, FindProperty("_AnimatedSampling", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.distortionMapSettingsreplacedle, defaultStyle, me => {
			CSProperty distortionType = FindProperty("_DistortionType", props);
			CSProperty distortionMapRotation = FindProperty("_DistortionMapRotation", props);
			CSProperty distortionAmplitude = FindProperty("_DistortionAmplitude", props);
			CSProperty distortionRotation = FindProperty("_DistortionRotation", props);
			CSProperty distortFlipbook = FindProperty("_DistortFlipbook", props);
			
			DisplayRegularProperty(me, distortionType);
			DisplayRegularProperty(me, FindProperty("_DistortionTarget", props));
			
			switch ((int) distortionType.prop.floatValue) {
				case 0:
					DisplayRegularProperty(me, FindProperty("_BumpMap", props));
					DisplayFloatWithSliderMode(me, distortionMapRotation);
					DisplayFloatWithSliderMode(me, distortionAmplitude);
					DisplayFloatWithSliderMode(me, distortionRotation);
					DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedX", props));
					DisplayFloatWithSliderMode(me, FindProperty("_BumpMapScrollSpeedY", props));
					break;
				case 1:
					DisplayRegularProperty(me, FindProperty("_MeltMap", props));
					DisplayFloatWithSliderMode(me, distortionMapRotation);
					DisplayFloatWithSliderMode(me, distortionAmplitude);
					DisplayFloatWithSliderMode(me, distortionRotation);
					DisplayFloatWithSliderMode(me, FindProperty("_MeltController", props));
					DisplayFloatWithSliderMode(me, FindProperty("_MeltActivationScale", props));
					break;
			}
			
			DisplayRegularProperty(me, distortFlipbook);
			
			if (distortFlipbook.prop.floatValue != 0) {
				DisplayIntField(me, FindProperty("_DistortFlipbookTotalFrames", props));
				DisplayIntField(me, FindProperty("_DistortFlipbookStartFrame", props));
				DisplayIntField(me, FindProperty("_DistortFlipbookRows", props));
				DisplayIntField(me, FindProperty("_DistortFlipbookColumns", props));
				DisplayFloatProperty(me, FindProperty("_DistortFlipbookFPS", props));
			}
				
		}));
		categories.Add(new CSCategory(Styles.overlaySettingsreplacedle, defaultStyle, me => {
			CSProperty overlayImageType = FindProperty("_OverlayImageType", props);
			CSProperty overlayImage = FindProperty("_MainTex", props);
			CSProperty overlayRotation = FindProperty("_MainTexRotation", props);
			CSProperty overlayPixelate = FindProperty("_PixelatedSampling", props);
			CSProperty overlayScrollSpeedX = FindProperty("_MainTexScrollSpeedX", props);
			CSProperty overlayScrollSpeedY = FindProperty("_MainTexScrollSpeedY", props);
			CSProperty overlayBoundary = FindProperty("_OverlayBoundaryHandling", props);
			CSProperty overlayColor = FindProperty("_OverlayColor", props);
			
			if (!cancerfree) BlendModePopup(me, FindProperty("_BlendMode", props));
			
			DisplayRegularProperty(me, overlayImageType);
			switch ((int) overlayImageType.prop.floatValue) {
				// TODO: replace these with proper enums so there's no magic numbers
				case 0:
					DisplayRegularProperty(me, overlayBoundary);
					DisplayRegularProperty(me, overlayPixelate);
					me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
					me.TextureScaleOffsetProperty(overlayImage.prop);
					DisplayFloatWithSliderMode(me, overlayRotation);
					if (overlayBoundary.prop.floatValue != 0) {
						DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
						DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
					}
					break;
				case 1:
					DisplayRegularProperty(me, overlayBoundary);
					DisplayRegularProperty(me, overlayPixelate);
					me.TexturePropertySingleLine(Styles.overlayImageText, overlayImage.prop, overlayColor.prop);
					me.TextureScaleOffsetProperty(overlayImage.prop);
					DisplayFloatWithSliderMode(me, overlayRotation);
					if (overlayBoundary.prop.floatValue != 0) {
						DisplayFloatWithSliderMode(me, overlayScrollSpeedX);
						DisplayFloatWithSliderMode(me, overlayScrollSpeedY);
					}
					DisplayIntField(me, FindProperty("_FlipbookTotalFrames", props));
					DisplayIntField(me, FindProperty("_FlipbookStartFrame", props));
					DisplayIntField(me, FindProperty("_FlipbookRows", props));
					DisplayIntField(me, FindProperty("_FlipbookColumns", props));
					DisplayFloatProperty(me, FindProperty("_FlipbookFPS", props));
					break;
				case 2:
					DisplayRegularProperty(me, FindProperty("_OverlayCubemap", props));
					DisplayColorProperty(me, overlayColor);
					DisplayVec3WithSliderMode(
						me,
						"Rotation",
						FindProperty("_OverlayCubemapRotationX", props),
						FindProperty("_OverlayCubemapRotationY", props),
						FindProperty("_OverlayCubemapRotationZ", props)
					);
					DisplayVec3WithSliderMode(
						me,
						"Rotation Speed",
						FindProperty("_OverlayCubemapSpeedX", props),
						FindProperty("_OverlayCubemapSpeedY", props),
						FindProperty("_OverlayCubemapSpeedZ", props)
					);
					break;
			}
			
			DisplayFloatRangeProperty(me, FindProperty("_BlendAmount", props));
		}));
		if (cancerfree) categories.Add(new CSCategory(Styles.blendSettingsreplacedle, defaultStyle, me => {
			DisplayRegularProperty(me, FindProperty("_BlendOp", props));
			DisplayRegularProperty(me, FindProperty("_BlendSource", props));
			DisplayRegularProperty(me, FindProperty("_BlendDestination", props));
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.screenColorAdjustmentsreplacedle, defaultStyle, me => {
			CSProperty colorBurningToggle = FindProperty("_Burn", props);
			
			DisplayVec3WithSliderMode(
				me,
				"HSV Add",
				FindProperty("_HueAdd", props),
				FindProperty("_SaturationAdd", props),
				FindProperty("_ValueAdd", props)
			);
			DisplayVec3WithSliderMode(
				me,
				"HSV Multiply",
				FindProperty("_HueMultiply", props),
				FindProperty("_SaturationMultiply", props),
				FindProperty("_ValueMultiply", props)
			);
			
			DisplayFloatRangeProperty(me, FindProperty("_InversionAmount", props));
			DisplayColorProperty(me, FindProperty("_Color", props));
			
			BlendModePopup(me, FindProperty("_ScreenColorBlendMode", props));
			
			DisplayRegularProperty(me, colorBurningToggle);
			if (colorBurningToggle.prop.floatValue == 1) {
				DisplayFloatRangeProperty(me, FindProperty("_BurnLow", props));
				DisplayFloatRangeProperty(me, FindProperty("_BurnHigh", props));
			}
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.screenTransformreplacedle, defaultStyle, me => {
			DisplayRegularProperty(me, FindProperty("_ScreenBoundaryHandling", props));
			DisplayRegularProperty(me, FindProperty("_ScreenReprojection", props));
			DisplayFloatWithSliderMode(me, FindProperty("_Zoom", props));
			DisplayRegularProperty(me, FindProperty("_Pixelation", props));
			
			CSProperty screenXOffsetR = FindProperty("_ScreenXOffsetR", props);
			CSProperty screenXOffsetG = FindProperty("_ScreenXOffsetG", props);
			CSProperty screenXOffsetB = FindProperty("_ScreenXOffsetB", props);
			CSProperty screenXOffsetA = FindProperty("_ScreenXOffsetA", props);
			CSProperty screenYOffsetR = FindProperty("_ScreenYOffsetR", props);
			CSProperty screenYOffsetG = FindProperty("_ScreenYOffsetG", props);
			CSProperty screenYOffsetB = FindProperty("_ScreenYOffsetB", props);
			CSProperty screenYOffsetA = FindProperty("_ScreenYOffsetA", props);
			CSProperty screenXMultiplierR = FindProperty("_ScreenXMultiplierR", props);
			CSProperty screenXMultiplierG = FindProperty("_ScreenXMultiplierG", props);
			CSProperty screenXMultiplierB = FindProperty("_ScreenXMultiplierB", props);
			CSProperty screenXMultiplierA = FindProperty("_ScreenXMultiplierA", props);
			CSProperty screenYMultiplierR = FindProperty("_ScreenYMultiplierR", props);
			CSProperty screenYMultiplierG = FindProperty("_ScreenYMultiplierG", props);
			CSProperty screenYMultiplierB = FindProperty("_ScreenYMultiplierB", props);
			CSProperty screenYMultiplierA = FindProperty("_ScreenYMultiplierA", props);
			
			if (sliderMode) {
				DisplayFloatRangeProperty(me, screenXOffsetA);
				DisplayFloatRangeProperty(me, screenYOffsetA);
				DisplayFloatRangeProperty(me, screenXOffsetR);
				DisplayFloatRangeProperty(me, screenYOffsetR);
				DisplayFloatRangeProperty(me, screenXOffsetG);
				DisplayFloatRangeProperty(me, screenYOffsetG);
				DisplayFloatRangeProperty(me, screenXOffsetB);
				DisplayFloatRangeProperty(me, screenYOffsetB);
				DisplayFloatRangeProperty(me, screenXMultiplierA);
				DisplayFloatRangeProperty(me, screenYMultiplierA);
				DisplayFloatRangeProperty(me, screenXMultiplierR);
				DisplayFloatRangeProperty(me, screenYMultiplierR);
				DisplayFloatRangeProperty(me, screenXMultiplierG);
				DisplayFloatRangeProperty(me, screenYMultiplierG);
				DisplayFloatRangeProperty(me, screenXMultiplierB);
				DisplayFloatRangeProperty(me, screenYMultiplierB);
			} else {
				DisplayVec4Field(me, "Screen X Offset (RGB)", screenXOffsetR, screenXOffsetG, screenXOffsetB, screenXOffsetA);
				DisplayVec4Field(me, "Screen Y Offset (RGB)", screenYOffsetR, screenYOffsetG, screenYOffsetB, screenYOffsetA);
				DisplayVec4Field(me, "Screen X Multiplier (RGB)", screenXMultiplierR, screenXMultiplierG, screenXMultiplierB, screenXMultiplierA);
				DisplayVec4Field(me, "Screen Y Multiplier (RGB)", screenYMultiplierR, screenYMultiplierG, screenYMultiplierB, screenYMultiplierA);
			}
			DisplayFloatRangeProperty(me, FindProperty("_ScreenRotationAngle", props));
		}));
		categories.Add(new CSCategory(Styles.targetObjectSettingsreplacedle, defaultStyle, me => {
			DisplayVec4Field(
				me,
				"Position",
				FindProperty("_ObjectPositionX", props),
				FindProperty("_ObjectPositionY", props),
				FindProperty("_ObjectPositionZ", props),
				FindProperty("_ObjectPositionA", props)
			);
			DisplayVec3Field(
				me,
				"Rotation",
				FindProperty("_ObjectRotationX", props),
				FindProperty("_ObjectRotationY", props),
				FindProperty("_ObjectRotationZ", props)
			);
			DisplayVec4Field(
				me,
				"Scale",
				FindProperty("_ObjectScaleX", props),
				FindProperty("_ObjectScaleY", props),
				FindProperty("_ObjectScaleZ", props),
				FindProperty("_ObjectScaleA", props)
			);
			DisplayRegularProperty(me, FindProperty("_Puffiness", props));
		}));
		categories.Add(new CSCategory(Styles.stencilreplacedle, defaultStyle, me => {
			DisplayIntSlider(me, FindProperty("_StencilRef", props), 0, 255);
			DisplayRegularProperty(me, FindProperty("_StencilComp", props));
			DisplayRegularProperty(me, FindProperty("_StencilPreplacedOp", props));
			DisplayRegularProperty(me, FindProperty("_StencilFailOp", props));
			DisplayRegularProperty(me, FindProperty("_StencilZFailOp", props));
			DisplayIntSlider(me, FindProperty("_StencilReadMask", props), 0, 255);
			DisplayIntSlider(me, FindProperty("_StencilWriteMask", props), 0, 255);
		}));
		categories.Add(new CSCategory(Styles.maskingreplacedle, defaultStyle, me => {
			if (!cancerfree) {
				DisplayRegularProperty(me, FindProperty("_DistortionMask", props));
				DisplayFloatRangeProperty(me, FindProperty("_DistortionMaskOpacity", props));
			}
			
			DisplayRegularProperty(me, FindProperty("_OverlayMask", props));
			DisplayFloatRangeProperty(me, FindProperty("_OverlayMaskOpacity", props));
			
			DisplayRegularProperty(me, FindProperty("_OverallEffectMask", props));
			DisplayFloatRangeProperty(me, FindProperty("_OverallEffectMaskOpacity", props));
			BlendModePopup(me, FindProperty("_OverallEffectMaskBlendMode", props));

			EditorGUILayout.Space();
			
			DisplayRegularProperty(me, FindProperty("_OverallAmplitudeMask", props));
			DisplayFloatRangeProperty(me, FindProperty("_OverallAmplitudeMaskOpacity", props));
		}));
		categories.Add(new CSCategory(Styles.miscSettingsreplacedle, defaultStyle, me => {
			DisplayRegularProperty(me, FindProperty("_CullMode", props));
			DisplayRegularProperty(me, FindProperty("_ZTest", props));
			DisplayRegularProperty(me, FindProperty("_ZWrite", props));
			ShowColorMaskFlags(me, FindProperty("_ColorMask", props));
			DisplayRegularProperty(me, FindProperty("_MirrorMode", props));
			DisplayRegularProperty(me, FindProperty("_EyeSelector", props));
			DisplayRegularProperty(me, FindProperty("_PlatformSelector", props));
			CSProperty projectionType = FindProperty("_ProjectionType", props);
			DisplayRegularProperty(me, projectionType);
			if (projectionType.prop.floatValue != 2) {
				DisplayVec3WithSliderMode(
					me,
					Styles.projectionRotationText,
					FindProperty("_ProjectionRotX", props),
					FindProperty("_ProjectionRotY", props),
					FindProperty("_ProjectionRotZ", props)
				);
			}
		}));
		if (!cancerfree) categories.Add(new CSCategory(Styles.renderQueueExportreplacedle, defaultStyle, me => {
			Material material = me.target as Material;
			
			customRenderQueue = EditorGUILayout.IntSlider(Styles.customRenderQueueSliderText, customRenderQueue, 0, 5000);
			if (GUILayout.Button(Styles.exportCustomRenderQueueButtonText)) {
				int relativeQueue = customRenderQueue - ((int) UnityEngine.Rendering.RenderQueue.Transparent);
				string newQueueString = "Transparent" + (relativeQueue >= 0 ? "+" : "") + relativeQueue;
				string shaderName = "RedMage/Cancer" + (cancerfree ? "free" : "space");
				string newShaderPath = shaderName + " Queue " + customRenderQueue;
				
				string shaderPath = replacedetDatabase.GetreplacedetPath(material.shader.GetInstanceID());
				string outputLocation = shaderPath.Substring(0, shaderPath.Replace("\\", "/").LastIndexOf('/') + 1) + "CancerspaceQueue" + customRenderQueue + ".shader";
				
				try {
					using (StreamWriter sw = new StreamWriter(outputLocation)) {
						using (StreamReader sr = new StreamReader(shaderPath)) {
							string line;
							while ((line = sr.ReadLine()) != null) {
								if (line.Contains("\"Transparent+")) {
									Regex rx = new Regex(@"Transparent[+-]\d+", RegexOptions.Compiled);
									MatchCollection matches = rx.Matches(line);
									foreach (Match match in matches) {
										line = line.Replace(match.Value, newQueueString);
									}
								} else if (line.Contains(shaderName)) {
									Regex rx = new Regex("\"[^\"]+\"", RegexOptions.Compiled);
									MatchCollection matches = rx.Matches(line);
									foreach (Match match in matches) {
										line = line.Replace(match.Value, "\"" + newShaderPath + "\"");
									}
								}
								if (!cancerfree) line = line.Replace("_Garb", "_Garb" + customRenderQueue);
								sw.Write(line);
								sw.WriteLine();
							}
						}
					}
				} catch (Exception e) {
					Debug.Log("AAAGAGHH WHAT? HOW? WHY??? WHAT ARE YOU DOING? Shader file could not be read / written.");
					Debug.Log(e.Message);
					return;
				}
				
				replacedetDatabase.Refresh();
				
				material.shader = Shader.Find(newShaderPath);
				
				replacedetDatabase.Savereplacedets();
			}
		}));
		
		EditorGUIUtility.labelWidth = 0f;
		
		sliderMode = EditorGUILayout.ToggleLeft(Styles.sliderModeCheckboxText, sliderMode);
		showRandomizerOptions = EditorGUILayout.ToggleLeft(Styles.randomizerOptionsCheckboxText, showRandomizerOptions);
		if (showRandomizerOptions) {
			randomizingCurrentPreplaced = GUILayout.Button("Randomize Values");
		}
		
		int oldflags = GetExpansionFlags();
		int newflags = 0;
		for (int i = 0; i < categories.Count; ++i) {
			bool expanded = EditorGUILayout.Foldout((oldflags & (1 << i)) != 0, categories[i].name, true, categories[i].style);
			newflags |= (expanded ? 1 : 0) << i;
			if (expanded) {
				EditorGUI.indentLevel++;
				categories[i].setupDelegate(materialEditor);
				EditorGUI.indentLevel--;
			}
		}
		SetExpansionFlags(newflags);
		
		
		if (!cancerfree) GUI.enabled = false;
		materialEditor.RenderQueueField();
		
		randomizingCurrentPreplaced = false;
	}

See More Examples