Rich Text Box - text coloring error - c#

I wrote this function
private void richAdd(string who, string what)
{
string colorstring = who + " ( " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " ) :";
richTextBox1.Text += colorstring + " " + what + "\r\n\r\n";
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Find(colorstring), colorstring.Length);
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.DeselectAll();
}
which is supposed to color who+time in blue and what in black.
Yet after the second time it makes all the text blue... any ideas what could be wrong with it?
Thanks!

try
private void richAdd(string who, string what)
{
string colorstring = who + " ( " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " ) :";
richTextBox1.AppendText(colorstring + " " + what + "\r\n\r\n");
richTextBox1.Select(richTextBox1.Text.LastIndexOf(colorstring), colorstring.Length);
richTextBox1.SelectionColor = Color.Blue;
}

Related

Add pause to Alexa without using SSML

Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.
Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."
I am using C# and my own https endpoint, not AWS Lambda.
Any suggestions? Otherwise I will add it as SSML. Thanks.
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("here are works of art for " + m_artist + ". ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available.";
}
else
{
m_location = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n"); // It is located on the " + dr["CurrentLocation"].ToString());
}
sql_conn_data.Close();
response.Response.OutputSpeech.Text = output.ToString();
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
UPDATE
OK. Ended up going the SSML route which looks like this:
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_location_card;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("<speak>");
output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available. <break time='1s' />";
m_location_card = "The location is not available. ";
}
else
{
m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
m_location_card = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");
}
output.Append("</speak>");
sql_conn_data.Close();
response.Response.OutputSpeech.Ssml = output.ToString();
response.Response.OutputSpeech.Type = "SSML";
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
}
There is not a way to introduce a pause in Alexa without SSML. You will need to build the ssml string and return it back to Alexa using the pause, or the cadence strings.

C# Creating white space lines between assembled .text

private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + txtFirstName.Text[0] + txtMiddle.Text + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
I'm trying to get 1 character white space inbetween cboTitle.Text, txtFirname.Text, txtMiddle.Text, and txtLastName, but they all output the information together, but I want them spaced evenly. what do I need to do? thanks in advance.
I'm going to post some other code thats below the one above in my project, just in case it might be relevant.
string AssembleText(string Title, string FirstName, string MiddleInitial, string LastName, string AddressLines, string City )
{
string Result = "";
Result += Title + " ";
Result += FirstName.Substring(0, 2) + " ";
// Only append middle initial if it is entered
if (MiddleInitial != "")
{
Result += MiddleInitial + " ";
}
Result += LastName + "\r\n";
// Only append items from the multiline address box
// if they are entered
if ( AddressLines != "")
{
Result += AddressLines + "\r\n";
}
//if (AddressLines.Length > 0 && AddressLines.ToString() != "")
//{
// Result += AddressLines + "\r\n";
//}
Result += City;
return Result;
}
}
}
If you just want a space between those specific fields in btnAssemble_Click, you can just insert them like this:
string myStr = foo + " " + bar + " " + baz;
So your first function would be modified to read:
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " + txtMiddle.Text + " " + txtLastName.Text + "\r\n" + txtStreet.Text + "\r\n" + cboCity.Text);
}
A few other comments:
It's not clear to me what the AssembleText() function you posted has to do with this. I am confused though, as I see a few lines appending spaces at the end just like I mentioned above.
Using the String.Format() function may make this code easier to read and maintain.
Using Environment.NewLine instead of "\r\n" will make the string contain the newline character defined for that specific environment.
Using a StringBuilder object may be faster over concatenation when building strings inside of a loop (which may not apply here).
Using String.format() should feet the bill. It also make your code easy to read.
txt.assembled.text = String.Format("{0} {1} {2} {3}",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text
);
It would be like this
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " +txtMiddle.Text + " " + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
It seems that you want String.Join; whenever you want to combine strings with a delimiter, say, " " (space) all you need is to put
String combined = String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text);
Complete implementation (joining by space and new line) could be
txtAssembled.Text = String.Join(Environment.NewLine,
String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text),
txtStreet.Text,
cboCity.Text);

NUnit: To get Error message

I would like to know Is it possible to get error message (reason of why my testcase failed). For instance, below is my code of I am trying to find an element it will fail my test. Error message will display in NUnit. How to get that error message in my text file.
private DateTime _timestamp1;
private DateTime _timestamp2;
private string _TestNum;
private string _TestDetails;
[Test]
public void Initialize()
{
_timestamp1 = DateTime.Now;
_TestNum = "12345";
_TestDetails = "For test purpose";
TWebDriver driver = new TWebDriver();
{
driver.Navigate().GoToUrl("http://www.google.com");
driver.FindElement(By.Id("q"));
}
}
[TearDown]
public void cleanup()
{
string path = (#"..\..\Result\");
_timestamp2 = DateTime.Now;
TimeSpan timediff = (_timestamp2) - (_timestamp1);
string TotalTime = timediff.Minutes + " minutes and " + timediff.Seconds + " seconds";
if ((TestContext.CurrentContext.Result.Status == TestStatus.Passed) || (TestContext.CurrentContext.Result.State == TestState.Success))
{
string status = "Passed";
File.WriteAllText(Path.Combine(path, "Passed" + ".txt"), "Test Case No.: " + _TestNum + string.Format(Environment.NewLine) + "Test Details: " + _TestDetails + string.Format(Environment.NewLine) + "Start Time: " + _timestamp1 + string.Format(Environment.NewLine) + "End Time: " + _timestamp2 + string.Format(Environment.NewLine) + "Total Time: " + TotalTime + string.Format(Environment.NewLine) + "Status: " + status);
}
else
{
string status = "Failed";
File.WriteAllText(Path.Combine(path, "Passed" + ".txt"), "Test Case No.: " + _TestNum + string.Format(Environment.NewLine) + "Test Details: " + _TestDetails + string.Format(Environment.NewLine) + "Start Time: " + _timestamp1 + string.Format(Environment.NewLine) + "End Time: " + _timestamp2 + string.Format(Environment.NewLine) + "Total Time: " + TotalTime + string.Format(Environment.NewLine) + "Status: " + status);
}
}
NUnit Version: 2.6.4

ASP.NET C# Form Submission Problems

I have built a form with jqueryui-date picker - basically if the end date is less than or equal to start time it needs to display a message saying it must be greater than the start time before allowing the user to submit the form. Cannot see where i am going wrong.
Code Below on Submit
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime startDate = Convert.ToDateTime(txtStartDate.Text + " " + ddlTime.SelectedValue);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text + " " + ddlTime2.SelectedValue);
if (startDate >= DateTime.Now)
{
if (endDate <= startDate)
{
usrComment.Visible = true;
//usrComment.Text = "Return time needs to be greater than pickup time IF same day";
usrComment.Text = "Date =" + startDate + "Date 2 =" + endDate;
}
else
{
if (Page.IsValid)
{
string EmailServer = WebConfigurationManager.AppSettings["Email.Server"];
int ServerPort = Int32.Parse(WebConfigurationManager.AppSettings["Email.ServerPort"]);
string EmailServerUser = (WebConfigurationManager.AppSettings["Email.UserName"]);
string EmailServerPass = (WebConfigurationManager.AppSettings["Email.Password"]);
string EmailFrom = (WebConfigurationManager.AppSettings["Email.From"]);
string EmailTo = (WebConfigurationManager.AppSettings["Email.To"]);
string EmailToUser = txtEmail.Text;
string EmailSubject = "Quote Form submitted";
****.****.*****.Email m = new ****.****.Helpers.Email(EmailServer, ServerPort, EmailServerUser, EmailServerPass);
StringBuilder html = new StringBuilder();
html.AppendLine("<ul>");
html.AppendLine("<li>" + lblName.Text + ": " + txtName.Text + "</li>");
html.AppendLine("<li>" + lblEmail.Text + ": " + txtEmail.Text + "</li>");
html.AppendLine("<li>" + lblPhone.Text + ": " + txtPhone.Text + "</li>");
html.AppendLine("<li>" + lblVehicleType.Text + ": " + ddlVehicleType.SelectedValue + "</li>");
html.AppendLine("<li>" + lblPickupDate.Text + ": " + txtStartDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime.SelectedValue + "</li>");
html.AppendLine("<li>" + lblReturnDate.Text + ": " + txtEndDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime2.SelectedValue + "</li>");
html.AppendLine("</ul>");
m.SendHTMLEmail(EmailFrom, EmailTo, EmailSubject, html.ToString());
//Response.Redirect("/contact-us/quote-form-submitted.aspx");
}
usrComment.Text = "SUBMIT IT NOW!!!!!";
}
}
}
jQuery for the date picker
$(function () {
function getDiff() {
var from = $(".start").val();
var till = $(".fin").val();
var c = from.split("/");
beg = new Date(c[2], c[1] - 1, c[0]);
var d = till.split("/");
en = new Date(d[2], d[1] - 1, d[0]);
var rest = (en - beg) / 86400000;
var txt = rest == 0 ? "" : rest + " days"
$("#res").text(txt);
}
$(".start").datepicker({
changeMonth: false,
changeYear: false,
showAnim: "fadeIn",
gotoCurrent: true,
minDate: 0, //change this to +3 to start 3 days from now
dateFormat: "dd/mm/yy",
onSelect: function (dateText, inst) {
$(".fin").val(dateText);
$(".fin").datepicker("option", "minDate", dateText);
getDiff();
}
});
$(".fin").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true,
showAnim: "fadeIn",
onSelect: getDiff
});
//Disabling Copy, Paste, Cut
$('.start').bind('paste', function (e) {
e.preventDefault();
//alert("You cannot paste text into this textbox!");
window.alert = function () { };
});
$('.fin').bind('paste', function (e) {
e.preventDefault();
//alert("You cannot paste text into this textbox!");
window.alert = function () { };
});
});
So if you have a pickup date of 17/09/2013 and pickup time as 08:00 and the same for return date and time it should alert you with the message and if the return date is greater than or equal to start time the return pickup time needs to be greater than 08:00 if that makes sense?
It would be nice to have a useful, constructive comment. It doesn't matter if this is the "right way" to do it. I believe this is what you're trying to do. I've just added an else to the initial if statement to inform the user to choose a Start date later than now and altered the text of the other else statement to inform the user to pick a return date later than the start date.
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime startDate = Convert.ToDateTime(txtStartDate.Text + " " + ddlTime.SelectedValue);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text + " " + ddlTime2.SelectedValue);
if (startDate >= DateTime.Now)
{
if (endDate <= startDate)
{
usrComment.Visible = true;
usrComment.Text = "Please enter a Return date later than " + startDate;
}
else
{
if (Page.IsValid)
{
string EmailServer = WebConfigurationManager.AppSettings["Email.Server"];
int ServerPort = Int32.Parse(WebConfigurationManager.AppSettings["Email.ServerPort"]);
string EmailServerUser = (WebConfigurationManager.AppSettings["Email.UserName"]);
string EmailServerPass = (WebConfigurationManager.AppSettings["Email.Password"]);
string EmailFrom = (WebConfigurationManager.AppSettings["Email.From"]);
string EmailTo = (WebConfigurationManager.AppSettings["Email.To"]);
string EmailToUser = txtEmail.Text;
string EmailSubject = "Quote Form submitted";
****.****.*****.Email m = new ****.****.Helpers.Email(EmailServer, ServerPort, EmailServerUser, EmailServerPass);
StringBuilder html = new StringBuilder();
html.AppendLine("<ul>");
html.AppendLine("<li>" + lblName.Text + ": " + txtName.Text + "</li>");
html.AppendLine("<li>" + lblEmail.Text + ": " + txtEmail.Text + "</li>");
html.AppendLine("<li>" + lblPhone.Text + ": " + txtPhone.Text + "</li>");
html.AppendLine("<li>" + lblVehicleType.Text + ": " + ddlVehicleType.SelectedValue + "</li>");
html.AppendLine("<li>" + lblPickupDate.Text + ": " + txtStartDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime.SelectedValue + "</li>");
html.AppendLine("<li>" + lblReturnDate.Text + ": " + txtEndDate.Text + "</li>");
html.AppendLine("<li>" + ddlTime2.SelectedValue + "</li>");
html.AppendLine("</ul>");
m.SendHTMLEmail(EmailFrom, EmailTo, EmailSubject, html.ToString());
//Response.Redirect("/contact-us/quote-form-submitted.aspx");
}
usrComment.Text = "SUBMIT IT NOW!!!!!";
}
}
else
{
usrComment.Visible = true;
usrComment.Text = "Please enter a Start date later than " + DateTime.Now;
}
}
I suggest you not to use any kind of custom function.
JquerUI-date picker have inbuilt functionality for comparing end date with start date.
Please try this
http://jqueryui.com/datepicker/#date-range

RichTextBox new Text append on top

I have a RichtTextBox in my C# application that shows a log to the user. The problem is that newly inserted text appends below the old text, but I want to append it on top of the old text.
For example, When I append the text "Newtext" it looks like this:
RichtTextBox:
|---------------------
|Oldtext |
|Newtext |
|---------------------
But it needs to look like this:
RichTextBox:
|---------------------
|Newtext |
|Oldtext |
|---------------------
This is the code I'm using for filling my RichTextBox:
public void DisplayLog(string logtext)
{
if (logtext != "")
{
if (this.txtLog.InvokeRequired && !txtLog.IsDisposed)
{
Invoke(new MethodInvoker(delegate()
{
txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n");
}));
}
else if (!txtLog.IsDisposed)
{
txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n");
}
}
}
Can somebody help me out please?
Answer:
Inserting at top of richtextbox
Use Insert
txtLog.Text = txtLog.Text.Insert(0,DateTime.UtcNow + ": " + logtext + "\n");
I think txtlog is the RichTextBox and you should prepend this.
To do this go at start using
txtlog .SelectionStart = 0;
txtlog .SelectionLength = 0;
txtlog .SelectedText = (DateTime.UtcNow + ": " + logtext + "\n");

Categories