I'm trying to write some code for unity in c#. I am having a problem wring \n into a List. Heres my code.
public static List<string> ChatHeads = null;
public void Start()
{
ChatHeads = new List<string>();
}
void Update()
{
ChatBoxMessage.text = GetChatHead();
}
string GetChatHead()
{
return string.Join(System.Environment.NewLine, ChatHeads.ToArray());
}
public void MainFunc()
{
string FinalMessage = "";
if (FinalMessage.Length >= 82 || !.inWorld)
{
FinalMessage = Message + "\n";
ChatHeads.Add(FinalMessage);
}
else
{
FinalMessage = "[" + username + "] " + MainWorld.ChatTag + Message + "\n";
ChatHeads.Add(FinalMessage);
}
}
The issue is GetChatHead() only returns the first array string if \n isnt the last part of the string. code works fine as long as the \n appears but it NEVER does always disappears.
thanks.
Pic to List array, No \n at end of any lines.
[2
Solved. Apparently Encoding.Default.GetString() wont allow you to add anything to the string.
Message = Encoding.Default.GetString(packet.ReadBytes((int)Length));
No Good
Message = packet.ReadString();
Worked.
Related
My code searches through a list and then if it finds a match, it displays the object in my listbox. My problem is that if there is more than 1 object in the list (if im searching for Alex and there is two objects with the name Alex), it returns it all on the same line instead of separating them to separate lines.
I coulda swore match += request + "\n"; was how to do it correctly, but it's not working.
Edit: One thing I dont understand is that if i just have match += request; it will allow me to use the horizontal scroll bar on my listbox to see everything written. And if i use match += request + "\n"; or match += request + Environment.NewLine; it doesn't let me use the scroll box and just cuts off.
public string SearchRequest(string keyword)
{
bool found = false;
string noMatch = "No requests with the name " + "'" + keyword + "'" + " were found";
string match = "";
foreach (ServiceRequest request in Requests)
{
if (request.searchKeywords(keyword))
{
match += request + "\n";
found = true;
}
}
if (found)
return match;
else
return noMatch;
}
/
public bool searchKeywords(string keyword)
{
if (keyword == name)
return true;
else
return false;
}
/
private void btnSearch_Click(object sender, EventArgs e)
{
lstSearch.Items.Clear();
lstSearch.Items.Add(myRequest.SearchRequest(txtSearch.Text));
}
Try
match += request + Environment.NewLine;
If you put all the results in a single string then it will still be a single item in the list.
Return an array of strings from the method instead of a single string:
public string[] SearchRequest(string keyword) {
List<string> match = new List<string>();
foreach (ServiceRequest request in Requests) {
if (request.searchKeywords(keyword)) {
match.Add(request.ToString());
}
}
if (match.Count > 0) {
return match.ToArray();
} else {
return new string[] { "No requests with the name " + "'" + keyword + "'" + " were found" };
}
}
Then use AddRange to add the strings as separate items in the list:
lstSearch.Items.AddRange(myRequest.SearchRequest(txtSearch.Text));
In Windows OS, the new line is two characters, the Carriage Return \r followed by Line Feed: \n. You can use Environment.NewLine as a shortcut (preferred) or append "\r\n" yourself. See further wikipedia entry on newline
Use one of these:
match += request + "\r\n";
Use an string literal:
match += request + #"
";
OR only at runtime will this resolve:
match += request + System.Environment.NewLine;
On Unix "\n"
You can't add a string with newlines to a listbox and expect it to show up as multiple items. Either split the string on newline and add each line separately to the listbox, or return a list of strings from your search function to begin with, avoiding the need for a split afterwards.
Struggling with a C# Component. What I am trying to do is take a column that is ntext in my input source which is delimited with pipes, and then write the array to a text file. When I run my component my output looks like this:
DealerID,StockNumber,Option
161552,P1427,Microsoft.SqlServer.Dts.Pipeline.BlobColumn
Ive been working with the GetBlobData method and im struggling with it. Any help with be greatly appreciated! Here is the full script:
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
string vehicleoptionsdelimited = Row.Options.ToString();
//string OptionBlob = Row.Options.GetBlobData(int ;
//string vehicleoptionsdelimited = System.Text.Encoding.GetEncoding(Row.Options.ColumnInfo.CodePage).GetChars(OptionBlob);
string[] option = vehicleoptionsdelimited.Split('|');
string path = #"C:\Users\User\Desktop\Local_DS_CSVs\";
string[] headerline =
{
"DealerID" + "," + "StockNumber" + "," + "Option"
};
System.IO.File.WriteAllLines(path + "OptionInput.txt", headerline);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + "OptionInput.txt", true))
{
foreach (string s in option)
{
file.WriteLine(Row.DealerID.ToString() + "," + Row.StockNumber.ToString() + "," + s);
}
}
Try using
BlobToString(Row.Options)
using this function:
private string BlobToString(BlobColumn blob)
{
string result = "";
try
{
if (blob != null)
{
result = System.Text.Encoding.Unicode.GetString(blob.GetBlobData(0, Convert.ToInt32(blob.Length)));
}
}
catch (Exception ex)
{
result = ex.Message;
}
return result;
}
Adapted from:
http://mscrmtech.com/201001257/converting-microsoftsqlserverdtspipelineblobcolumn-to-string-in-ssis-using-c
Another very easy solution to this problem, because it is a total PITA, is to route the error output to a derived column component and cast your blob data to a to a STR or WSTR as a new column.
Route the output of that to your script component and the data will come in as an additional column on the pipeline ready for you to parse.
This will probably only work if your data is less than 8000 characters long.
I tried to split a String into a parts array and combine them at the end into a result String.
But while I tested a little bit, I get a message.
By pressing convert_click:
"NullRefenceException was unhandeled"
Object reference not set to an instance of an object.
Here the main code:
public string []parts { get; set; }
public string inputStr { get; set; }
private void inputText_TextChanged(object sender, EventArgs e)
{
String inputStr = inputText.ToString();
//example
//inputStr = "984, fenceshit2, 0, 1994.56025813, -1592.16428141, 16.105, 0.653280779782, 0.270598520636, 0.653281646552, 0.270598879665, -1";
}
private void convert_Click(object sender, EventArgs e)
{
String creObj = "CreateObject(";
String result;
String[] parts = inputStr.Split(new char[] { ',' });
result = creObj +
parts[0] + "," +
parts[2] + "," +
parts[3] + "," +
//...up to "parts[10"
");";
outputText.Text = result;
//output(should be in this case):
//"CreateObject(984, 1994.56025813, -1592.16428141, 16.105, 0.653280779782, 0.270598520636, 0.653281646552, 0.270598879665, -1);"
}
//If I need to creat a code line in the main Designer.cs, please let me know.
I just want to split a String and combine them in the end into 1 string and send this into a text box.
If someone wants the sourcecode, pm me.
Because you are assigning inputText.toString() to local inputStr. Inside function inputText_TextChanged, just write
inputStr = inputText.Text;
You are declaring a local copy of input string, when you really want to be assigning to the public one.
Instead of
String inputStr = inputText.ToString();
Just do this:
inputStr = inputText.ToString();
I am trying to display part of a string using a MessageBox, for this I use the String.SubString method. However when I run the code the MessageBox is not displayed and no error is thrown.
For troubleshooting purposes I display the entire string in a MessageBox before trying to display the substring.
This displays the following (Received |<BID>22|):
I want to display the number part of the string, however when I try doing this nothing is displayed. Can anyone see what is going wrong please? Here is the code:
public void parseMessage(string theMessage)
{
String message = theMessage.Replace("\n", String.Empty);
MessageBox.Show("Received |" + message + "|");
String zoneNumber = message.Substring(5, message.Length);
if (message.StartsWith("<BID>"))
{
MessageBox.Show("Bid received for zone " + zoneNumber);
}
}
I can't access your linked image, so I don't know for certain what message contains, but
String zoneNumber = message.Substring(5, message.Length);
should throw an exception as it would overflow the length of the string by 5 characters.
Use
String zoneNumber = message.Substring(5);
instead.
How about changing
String zoneNumber = message.Substring(5, message.Length);
to
String zoneNumber = message.Substring(5);
I want to display the number part of the string, however when I try doing this nothing is displayed
That's because, looking at your message, it has leading whitespace and you are trying to do StartsWith("<BID>")
First, TrimStart, then try StartsWith, or just do Contains.
StartsWith:
if (message.TrimStart().StartsWith("<BID>"))
{
MessageBox.Show("Bid received for zone " + zoneNumber);
}
so the problem is that if (message.StartsWith("<BID>")) does not return true?
does this help?
public void parseMessage(string theMessage)
{
String message = theMessage.Replace("\r", String.Empty).Replace("\n", String.Empty).Replace("\r\n", String.Empty);
MessageBox.Show("Received |" + message + "|");
String zoneNumber = message.Substring(5, message.Length);
if (message.TrimStart().StartsWith("<BID>"))
{
MessageBox.Show("Bid received for zone " + zoneNumber);
}
}
You could use rplace instead of SubString
if (message.StartsWith("<BID>"))
{
MessageBox.Show("Bid received for zone " + message.Replace("<BID>",""));
}
Try this:
String bidMarker = "<BID>";
int startLoc = message.IndexOf(bid);
if (startLoc != -1)
{
String zoneNumber = message.Substring(startLoc + bidMarker.Length).Trim();
MessageBox.Show("Bid received for zone " + zoneNumber);
}
Currently I am building an agenda with extra options.
for testing purposes I store the data in a simple .txt file
(after that it will be connected to the agenda of a virtual assistant.)
To change or delete text from this .txt file I have a problem.
Although the part of the content that needs to be replaced and the search string are exactly the same it doesn't replace the text in content.
code:
Change method
public override void Change(List<object> oldData, List<object> newData)
{
int index = -1;
for (int i = 0; i < agenda.Count; i++)
{
if(agenda[i].GetType() == "Task")
{
Task t = (Task)agenda[i];
if(t.remarks == oldData[0].ToString() && t.datetime == (DateTime)oldData[1] && t.reminders == oldData[2])
{
index = i;
break;
}
}
}
string search = "Task\r\nTo do: " + oldData[0].ToString() + "\r\nDateTime: " + (DateTime)oldData[1] + "\r\n";
reminders = (Dictionary<DateTime, bool>) oldData[2];
if(reminders.Count != 0)
{
search += "Reminders\r\n";
foreach (KeyValuePair<DateTime, bool> rem in reminders)
{
if (rem.Value)
search += "speak " + rem.Key + "\r\n";
else
search += rem.Key + "\r\n";
}
}
// get new data
string newRemarks = (string)newData[0];
DateTime newDateTime = (DateTime)newData[1];
Dictionary<DateTime, bool> newReminders = (Dictionary<DateTime, bool>)newData[2];
string replace = "Task\r\nTo do: " + newRemarks + "\r\nDateTime: " + newDateTime + "\r\n";
if(newReminders.Count != 0)
{
replace += "Reminders\r\n";
foreach (KeyValuePair<DateTime, bool> rem in newReminders)
{
if (rem.Value)
replace += "speak " + rem.Key + "\r\n";
else
replace += rem.Key + "\r\n";
}
}
Replace(search, replace);
if (index != -1)
{
remarks = newRemarks;
datetime = newDateTime;
reminders = newReminders;
agenda[index] = this;
}
}
replace method
private void Replace(string search, string replace)
{
StreamReader reader = new StreamReader(path);
string content = reader.ReadToEnd();
reader.Close();
content = Regex.Replace(content, search, replace);
content.Trim();
StreamWriter writer = new StreamWriter(path);
writer.Write(content);
writer.Close();
}
When running in debug I get the correct info:
content "-- agenda --\r\n\r\nTask\r\nTo do: test\r\nDateTime: 16-4-2012 15:00:00\r\nReminders:\r\nspeak 16-4-2012 13:00:00\r\n16-4-2012 13:30:00\r\n\r\nTask\r\nTo do: testing\r\nDateTime: 16-4-2012 9:00:00\r\nReminders:\r\nspeak 16-4-2012 8:00:00\r\n\r\nTask\r\nTo do: aaargh\r\nDateTime: 18-4-2012 12:00:00\r\nReminders:\r\n18-4-2012 11:00:00\r\n" string
search "Task\r\nTo do: aaargh\r\nDateTime: 18-4-2012 12:00:00\r\nReminders\r\n18-4-2012 11:00:00\r\n" string
replace "Task\r\nTo do: aaargh\r\nDateTime: 18-4-2012 13:00:00\r\nReminders\r\n18-4-2012 11:00:00\r\n" string
But it doesn't change the text. How do I make sure that the Regex.Replace finds the right piece of content?
PS. I did check several topics on this, but none of the solutions mentioned there work for me.
You missed a : right after Reminders. Just check it again :)
You could try using a StringBuilder to build up you want to write out to the file.
Just knocked up a quick example in a console app but this appears to work for me and I think it might be what you are looking for.
StringBuilder sb = new StringBuilder();
sb.Append("Tasks\r\n");
sb.Append("\r\n");
sb.Append("\tTask 1 details");
Console.WriteLine(sb.ToString());
StreamWriter writer = new StreamWriter("Tasks.txt");
writer.Write(sb.ToString());
writer.Close();