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);
}
Related
I cannot understand why this code is behaving like this. I have to return a string on a specific format. It looks like when I include the "|" character on the string, the numbers that come after it get modified.
Why would this happen? Is "|" somehow converting the double values again?
static int Main(string[] args) {
.........
connectionString = connectionString.Replace("'master'", databaseName);
var watch = System.Diagnostics.Stopwatch.StartNew();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
}
watch.Stop();
string spentTimeString = String.Format("{0:0.##}", watch.ElapsedMilliseconds / 1000f);
string msg = $"Connection Time " + spentTimeString + "s.";
string perfData = "'connection_time'=" + String.Format("{0:0.##}", watch.ElapsedMilliseconds / 1000f);
string result = Ok(msg, perfData);
......
}
public static string Ok(string message, string perfData)
{
Console.WriteLine($"Msg: {message}");
Console.WriteLine($"PerfData: {perfData}");
string result = string.Concat("OK: ", message, "|", perfData);
Console.WriteLine($"Result: {result}");
return result;
}
Here is the Console output that I see:
Msg: Connection Time 0.42s.
PerfData: 'connection_time'=0.42
Result: OK: Connection Time 0.42s.|'connection_time'=0.41999
You can clearly see how 0.42 get's converted to 0.41999 after the concatenation takes place. How do I fix this?
I'm closing this post for now since it does not seem to be an issue with c#. It looks like NSClient++ is changing this value after it is returned.
I'm not sure though, I will post it on the proper section.
Thank you all!.
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.
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 am fairly new to c# and am working on a little project but got stuck on this. I have a file that contains some assembly code. I want my program to search this file for a string, actually a value right after my string. One of the strings i am searching for is:
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint
My search code is this:
private void searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
if (Regex.IsMatch(text, searchText))
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
}
}
//when i click a button//
searchFile(#"setproperty QName(PackageNamespace(""""), ""font"")
getlocal 4
pushint ");
I know that the string is in the file but the result comes up with not found. I don't know if it is the quotes or tabs or both that is causing this.
Here is part of the file:
getlocal 4
pushstring "Verdana"
setproperty QName(PackageNamespace(""), "font")
getlocal 4
pushint 16764170
setproperty QName(PackageNamespace(""), "color")
getlocal 4
pushbyte 12
setproperty QName(PackageNamespace(""), "size")
My second question is how can i get the value of the first int after my search result?
Thanks in advance.
-Leen
You should change your method like this:
private static string searchFile(String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader("test.txt");
String text = reader.ReadToEnd();
int poz = text.IndexOf(searchText);
if (poz >= 0)
{
int start = poz + searchText.Length;
int end = text.IndexOf("\n", start);
Console.WriteLine(searchText + " was found in the given file", "Finally!!");
return text.Substring(start, end - start);
}
else
{
Console.WriteLine("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return string.Empty;
}
}
The call:
string val = searchFile("setproperty QName(PackageNamespace(\"\"), \"font\")\r\n\r\n getlocal 4\r\n pushint ");
So I think you may be use to VB.net. C-based languages (like c#) used the backslash character "\" as an escape character.
So in a searching for a double-quote in a string you would need to escape it using \".
I believe what you're looking for is:
searchFile(#"setproperty QName(PackageNamespace(\"\"), \"font\")
getlocal 4
pushint ");
But this isn't really a regular expression, which is what the Regex class is meant for. So I would (well not really, I would clean it up a bit, like not mix my UI and bizlogic) do this:
// Added String as the function type so you can return the matched "Integer" as a string, you could always do a Int32.TryParse(...)
private String searchFile(String file, String searchText)
{
System.IO.StreamReader reader = new System.IO.StreamReader(file);
String text = reader.ReadToEnd();
int32 index = text.IndexOf(searchText);
if (index >= 0) //We could find it at the very beginning
{
MessageBox.Show(searchText + " was found in the given file", "Finally!!");
int32 start = index + searchText.Length;
int32 end = Regex.Match(text, "[\n\r\t]", index).Index; // This will search for whitespace
String value = text.Substring(start, end - start);
// Now you can do something with your value, like...
return value;
}
else
{
MessageBox.Show("Sorry, but " + searchText + " could not be found in the given file", "No Results");
return "";
}
}