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!.
Related
I am trying to create dynamic syntax function and function syntax is like below:
MyFunction( arg1,arg2,ar3.....);
I have string like this:
str = Previousvalue.Value1,Previousvalue.Value2
Now I would like to create syntax like this in final variable :
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);
str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
This is how I am trying to achieve with string.join (without using loop) but not getting how to do it and this seems like impossible to do without using loop:
final = string.Join("MyFunction(", str.Split(','));
Case 1:
Input : string str =Previousvalue.Value1,Previousvalue.Value2
Output:
string final=MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 2 :
Input : str = Previousvalue.Value1,Previousvalue.Value2,Previousvalue.Value3;
output:
String final = MyFunction(Previousvalue.Value1,',',Previousvalue.Value2,',',Previousvalue.Value3);
Case 3:
string input = " Previousvalue.Value1";
Output:
String final = Previousvalue.Value1; //No function
From what I understand, you want to generate a string like this:
"MyFunction(Previousvalue.Value1,',',Previousvalue.Value2);"
^..........^...................^....^...................^.
prefix arg1 sep arg2 suffix
or in other words
prefix = "MyFunction(";
separator = ",',',";
suffix = ");"
which can be achieved by moving the prefix and suffix out of the string.Join and using the above separator value:
string final = "MyFunction(" + string.Join(",',',", str.Split(',')) + ");";
Also instead of Split / Join you could simply use string.Replace:
string final = "MyFunction(" + str.Replace(",", ",',',") + ");";
From my understanding of the problem you want to call the MyFunction method with n string parameters, but also with string[]. You can do it like this:
public static void Main(string[] args)
{
string str = "Test1,Test2,Test3";
string test1 = MyFunction("Test1", "Test2", "Test3");
string test2 = MyFunction(str.Split(','));
}
public static string MyFunction(params string[] parameters)
{
StringBuilder sb = new StringBuilder();
foreach(var item in parameters)
{
sb.AppendLine(item);
}
return sb.ToString();
}
Try :
public string MyJoin(params string[] vars)
{
return "MyFunction(" + string.Join(",", vars) + ");";
}
I am attempting to get the 'Id' property of the Parameter element to be enclosed in double quotes. I first attempted to simply escape the quotations and this is the first thing I tried to achieve this:
buffer = String.Format("{0}" + "<Parameter Id=" + "{1}" + ">" + "{2}" + "</Parameter>", buffer, id, param);
With the above code I get this back, as you can see the escape characters are showing up, along with the quotation:
<Conquest><User>ArchElf</User><Token>0123456789012345678901234567890</Token><Command>validate</Command><Parameter Id=\"1\">Gemstone3</Parameter>
My second attempt is based on advised I received on IRC, a fellow advised that I may be able to use '"' to get my quotations, ala:
buffer = String.Format("{0}" + "<Parameter Id=" + """ + "{1}" + """ + ">" + "{2}" + "</Parameter>", buffer, id, param);
This method only yielded the literal '"' string in the end result:
<Conquest><User>ArchElf</User><Token>0123456789012345678901234567890</Token><Command>validate</Command><Parameter Id="1">Gemstone3</Parameter>
In desperation I went ahead and just added the literal double quotes baked into the string.
I did this because I read at This Codeproject Article that the only characters in a String.Format that I need to worry about escaping are curly braces and(surprise, surprise) this isn't even compile-able, WITH and WITHOUT the preceding #. Shouting at me a bunch of errors including:
Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
; Expected
) Expected
...and so on
Any help on this matter would be greatly appreciated. I know this has got to be something trivial I am missing, the best kind of conundrums. :/
Here is the entire BuildCommand method:
public string BuildCommand(string _command, string[] _parameters = null)
{
int id = 1;
string buffer = String.Format("<Conquest><User>"+"{0}"+"</User><Token>"+"{1}"+"</Token><Command>"+"{2}"+"</Command>", _playerName, _token, _command);
if (_parameters != null)
{
foreach (string param in _parameters)
{
if (param.Length < 1 || param == null)
break;
buffer = String.Format("{0}" + "<Parameter Id=" + "{1}" + ">" + "{2}" + "</Parameter>", buffer, id, param);
// buffer = String.Format(#"""{0}""<Parameter Id=""{1}"">""{2}""</Parameter>", buffer, id, param);
id += 1;
}
}
You could do it the right way
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//<Conquest><User>ArchElf</User><Token>0123456789012345678901234567890</Token><Command>validate</Command><Parameter Id=\"1\">Gemstone3</Parameter>
string user = "ArchElf";
string token = "0123456789012345678901234567890";
string command = "validate";
int id = 1;
string value = "Gemstrone3";
XElement conquest = new XElement("Conquest");
conquest.Add(new XElement("User", user));
conquest.Add(new XElement("Token", token));
conquest.Add(new XElement("Command", command));
XElement e_parameter = new XElement("Parameter", value);
e_parameter.Add(new XAttribute("Id", id));
conquest.Add(e_parameter);
}
}
}
You have to escape " with \:
String.Format("\"{0}\"<Parameter Id=\"{1}\">\"{2}\"</Parameter>", buffer, id, param);
You could also use a verbatim string literal, then you have to use double quotes:
String.Format(#"""{0}""<Parameter Id=""{1}"">""{2}""</Parameter>", buffer, id, param);
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 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);
}
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 "";
}
}