Convert Text To Code ( Put it in a string variable )

covert a text block to code ( text stored in a variable ) with an option to produce C# or VB.NET code using String or StringBuilder .

Usage : When you want to display a large text message or send an email with specific template you will need to format your text in a text editor like notepad or what ever you use but when you start to copy this text to your code editor to deal with you will need this utility

The Code :

create as GUI like the bellow



Then add the following code to the input text ( TextChanged ) Event
if (this.cmbLanguage.SelectedIndex == 1)
{
 txtTextToCodeResult.Text= this.convertToVBCode(txtTextToCodeInput.Lines, this.chkUseStringBuilder.Checked,this.chkAddLineBreak.Checked);
}
else
{
 txtTextToCodeResult.Text= this.convertToCSharpCode(txtTextToCodeInput.Lines, this.chkUseStringBuilder.Checked,this.chkAddLineBreak.Checked);
}

Then add the following methods to your form :

private string convertToCSharpCode(string[] lines, bool useStringBuilder, bool addNewLineSymbole)
{
    StringBuilder output = new StringBuilder(0x400);
    if (useStringBuilder)
    {
       output.Append("StringBuilder str = new StringBuilder(1024);\r\n\r\n");
       foreach (string l in lines)
       {
          output.Append(string.Format("str.Append (@\"{0}\"{1}); {2}", l.Replace("\"", "\"\""), addNewLineSymbole ? " + Environment.NewLine " : "", "\r\n"));
       }
    }
    else
    {
       output.Append("String str = \"\";\r\n\r\n");
       foreach (string l in lines)
       {
           output.Append(string.Format("str += @\"{0}\"{1}; {2}", l.Replace("\"", "\"\""), addNewLineSymbole ? " + Environment.NewLine " : "", "\r\n"));
       }
    }
    return output.ToString();
}

private string convertToVBCode(string[] lines, bool useStringBuilder, bool addNewLineSymbole)
{
    StringBuilder output = new StringBuilder(0x400);
    if (useStringBuilder)
    {
      output.Append("Dim str As New System.Text.StringBuilder(1024)\r\n\r\n");
      foreach (string l in lines)
      {
         output.Append(string.Format("str.Append (\"{0}\"{1}) {2}", l.Replace("\"", "\"\""), addNewLineSymbole ? " & Environment.NewLine " : "", "\r\n"));
       }
    }
    else
    {
       output.Append("Dim str As String = \"\"\r\n\r\n");
       foreach (string l in lines)
       {
           output.Append(string.Format("str &= \"{0}\"{1} {2}", l.Replace("\"", "\"\""), addNewLineSymbole ? " & Environment.NewLine " : "", "\r\n"));
       }
    }
    return output.ToString();
}


No comments:

Post a Comment