String concatenation - c#

string res1 = "CalcAPI.GetXElementValue(" + "\"" + res[0] + "\"" + "," + "\"" + res[1] + "\"" + "," + false + ")"
in
res[0] = "IRS5555"
res[1] = "IRS001"
Output of this code is:
CalcAPI.GetXElementValue("IRS5555","IRS001",False)
but I want
CalcAPI.GetXElementValue("IRS5555","IRS001",false)
false in lower case.
Sorry for not providing full code...
false is not static...
public static object GetElementDataType(string DataType)
{
///Write here methos for fetching data type of current element.
object res = null;
switch (DataType.ToLower())
{
case "int":
res = 0;
break;
case "double":
res = 0.0;
break;
case "string":
res = "";
break;
case "myboolean":
res = false;
break;
default:
res = "";
break;
}
return res;
}
string res1 =
"CalcAPI.GetXElementValue(" + "\"" + res[0] + "\"" + ","
+ "\"" + res[1] + "\"" + ","
+ GetElementDataType("myboolean") + ")"
then result is
CalcAPI.GetXElementValue("IRS5555","IRS001",False)
but i want
CalcAPI.GetXElementValue("IRS5555","IRS001",false)
if i pass double
string res1 = "CalcAPI.GetXElementValue(" + "\"" + res[0] + "\"" + "," + "\"" + res[1] + "\"" + "," + GetElementDataType("double") + ")"
then result is
CalcAPI.GetXElementValue("IRS5555","IRS001",0)
but i want
CalcAPI.GetXElementValue("IRS5555","IRS001",0.0)
if i pass string
string res1 = "CalcAPI.GetXElementValue(" + "\"" + res[0] + "\"" + "," + "\"" + res[1] + "\"" + "," + GetElementDataType("string") + ")"
then result is
CalcAPI.GetXElementValue("IRS5555","IRS001",)
but i want
CalcAPI.GetXElementValue("IRS5555","IRS001","")

If your false is constant there, then you can use simple string. And it`s better to use string format:
string res1 = string.Format("CalcAPI.GetXElementValue(\"{0}\",\"{1}\",false)", res[0], res[1]);

Use false.ToString().ToLower().

try with
false.ToString().ToLower()

use ToLower() function like this
string res1 = "CalcAPI.GetXElementValue(" + "\"" + res[0] + "\"" + "," + "\"" + res[1] + "\"" + "," + false.ToString().ToLower() + ")"

Related

adding first row to to a csv

Having the following function:
string chargeMonth = DateTime.Now.ToString("yyyyMM");
var fileCreationDate = DateTime.Now.ToString("yyyyMMdd");
string fileCreationTime = DateTime.Now.ToString("HHmmss");
string constVal = "MLL";
string fileType = "HIYUV-CHEVRA";
string[] values;
string header, sumRow;
string line, compId;
string inputFile = "records.CSV";
Dictionary<string, System.IO.StreamWriter> outputFiles = new Dictionary<string, System.IO.StreamWriter>();
using (System.IO.StreamReader file = new System.IO.StreamReader("D:\\" + inputFile, Encoding.Default))
{
header = file.ReadLine();
while ((line = file.ReadLine()) != null)
{
values = line.Split(",".ToCharArray());
compId = values[3];
if (!outputFiles.ContainsKey(compId))
{
sumRow = constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime;
string outputFileName = constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV";
outputFiles.Add(compId, new System.IO.StreamWriter("D:\\" + outputFileName));
outputFiles[compId].WriteLine(header);
}
outputFiles[compId].WriteLine(line);
}
}
foreach (System.IO.StreamWriter outputFile in outputFiles.Values)
{
outputFile.Close();
}
Which will create csvs based on dictionary's keys/values.
anyways, for each CSV I want to add a row in the FIRST line which is not in a format of the other rows..
somehting like:
line1 aaaabbbbcccc
line2 1 2 3 10 100
line3 2 2 3 10 100
I have no idea how to do that since Im "pulling" data from a dictionary and the line has nothing to do with it. Thanks for any kind of help.
outputFiles[compId].WriteLine(constVal + "-" + fileType + "-" + (String.Format("{0:00000}", Int32.Parse(compId))) + "-" + chargeMonth + "-" + fileCreationDate + "-" + fileCreationTime + ".CSV");
added the following line, it works now. thanks.

C# roslyn - How to obtain the type information in the syntax tree

How to obtain the type information of "t"?
How to get the type name of t
class Test
{
void main()
{
var t = new Test();
t.Equals(null);// object.Equals
//How do I get the type of "t" ?
}
}
private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var invocationExpr = (InvocationExpressionSyntax)context.Node;
var memberAccessExpr = invocationExpr.Expression as MemberAccessExpressionSyntax;
if (memberAccessExpr == null)
return;
if (memberAccessExpr.Name.ToString() != nameof(object.Equals))
return;
var memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol as IMethodSymbol;
if (memberSymbol == null)
return;
_ = memberSymbol.ContainingType.SpecialType;// Object
}
I don't know why, but I cannot enter the breakpoint when debugging with vs.
So I can only debug in this way, but I can't find the correct method.
var str = memberSymbol.ContainingSymbol?.Name + Environment.NewLine
+ memberSymbol.AssociatedSymbol?.Name + Environment.NewLine
+ memberSymbol.ContainingType?.Name + Environment.NewLine
+ memberSymbol.ContainingType?.SpecialType + Environment.NewLine
+ memberSymbol.ContainingType?.ContainingType?.Name + Environment.NewLine
+ memberSymbol.ContainingType?.TypeKind + Environment.NewLine
+ memberSymbol.ContainingType?.OriginalDefinition?.Name + Environment.NewLine
+ memberSymbol.ContainingType?.BaseType?.Name + Environment.NewLine
+ memberSymbol.ContainingType?.MetadataName + Environment.NewLine
+ memberSymbol.ContainingType?.ContainingAssembly?.Name + Environment.NewLine
+ string.Join(" ", memberSymbol.ContainingType?.MemberNames ?? Enumerable.Empty<string>()) + Environment.NewLine
+ "***************" + Environment.NewLine
+ invocationExpr.FullSpan.ToString() + Environment.NewLine
;
File.WriteAllText(#"xxxxxxx", str);
I want to obtain "Test" type information or type string

Azure REST API - Create, through programming, a database within an elasticPoll

I need to create, through programming, a database in an elasticPoll.
To do this, I'm using the API version 2014-04-01, indicated in "Azure REST APIs > SQL Database > Databases > Create Or Update".
I create a new HttpWebRequest object and launch the .Create() method
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Sql/servers/{2}/databases/{3}?api-version={4}", VariabiliGlobali.SubscriptionID, VariabiliGlobali.ResourceGroup, VariabiliGlobali.SqlServerName, databaseName, VariabiliGlobali.APIVersion));
and compile the properties:
request.Headers["Authorization"] = "Bearer" + token;
request.ContentType = "application/json; charset = utf-8";
request.Method = "PUT"
I create a new StreamWriter object
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
//streamWriter.Close();
}
and the .Write() mothod parameter, assign the complete Json code of the model shown in the "Databases - Create Or Update" example as below.
string json =
"{" +
"\"parameters\": {" +
"\"subscriptionId\": \"" + VariabiliGlobali.SubscriptionID + "\"," +
"\"resourceGroupName\": \"" + VariabiliGlobali.ResourceGroup + "\"," +
"\"serverName\": \"" + VariabiliGlobali.SqlServerName + "\"," +
"\"databaseName\": \"" + databaseName + "\"," +
"\"api-version\": \"" + VariabiliGlobali.APIVersion + "\"," +
"\"parameters\": {" +
"\"properties\": {" +
"\"elasticPoolName\": \"" + elasticPoolName + "\"" +
"}," +
"\"location\": \"West Europe\"" +
"}" +
"}," +
"\"responses\": {" +
"\"200\": {" +
"\"body\": {" +
"\"id\": \"/subscriptions/" + VariabiliGlobali.SubscriptionID + "/resourceGroups/" + VariabiliGlobali.ResourceGroup + "/providers/Microsoft.Sql/servers/" + VariabiliGlobali.SqlServerName + "/databases/" + databaseName + "\"," +
"\"name\": \"" + databaseName + "\"," +
"\"type\": \"Microsoft.Sql/servers/databases\"," +
"\"location\": \"West Europe\"," +
"\"kind\": \"v12.0,user\"," +
"\"properties\": {" +
"\"edition\": \"Standard\"," +
"\"status\": \"Online\"," +
"\"serviceLevelObjective\": \"S0\"," +
"\"collation\": \"SQL_Latin1_General_CP1_CI_AS\"," +
"\"creationDate\": \"2017-02-24T22:39:46.547Z\"," +
"\"maxSizeBytes\": \"268435456000\"," +
"\"currentServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveName\": \"S0\"," +
"\"sampleName\": null," +
"\"defaultSecondaryLocation\": \"Japan West\"," +
"\"earliestRestoreDate\": \"2017-02-10T01:52:52.923Z\"," +
"\"elasticPoolName\": null," +
"\"containmentState\": 2," +
"\"readScale\": \"Disabled\"," +
"\"failoverGroupId\": null" +
"}" +
"}" +
"}," +
"\"201\": {" +
"\"body\": {" +
"\"id\": \"/subscriptions/" + VariabiliGlobali.SubscriptionID + "/resourceGroups/" + VariabiliGlobali.ResourceGroup + "/providers/Microsoft.Sql/servers/" + VariabiliGlobali.SqlServerName + "/databases/" + databaseName + "\"," +
"\"name\": \"" + databaseName + "\"," +
"\"type\": \"Microsoft.Sql/servers/databases\"," +
"\"location\": \"West Europe\"," +
"\"kind\": \"v12.0,user\"," +
"\"properties\": {" +
"\"edition\": \"Standard\"," +
"\"status\": \"Online\"," +
"\"serviceLevelObjective\": \"S0\"," +
"\"collation\": \"SQL_Latin1_General_CP1_CI_AS\"," +
"\"creationDate\": \"2017-02-24T22:39:46.547Z\"," +
"\"maxSizeBytes\": \"268435456000\"," +
"\"currentServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveId\": \"f1173c43-91bd-4aaa-973c-54e79e15235b\"," +
"\"requestedServiceObjectiveName\": \"S0\"," +
"\"sampleName\": null," +
"\"defaultSecondaryLocation\": \"Japan West\"," +
"\"earliestRestoreDate\": \"2017-02-10T01:52:52.923Z\"," +
"\"elasticPoolName\": null," +
"\"containmentState\": 2," +
"\"readScale\": \"Disabled\"," +
"\"failoverGroupId\": null" +
"}" +
"}" +
"}," +
"\"202\": { }" +
"}" +
"}";
Launch the .GetResponse() method of the HttpWebRequest object
var httpResponse = (HttpWebResponse)request.GetResponse();
and in response I get the following error:
{'Error': {"code": "InvalidRequestContent", "message": "The request content was invalid and could not be deserialized: 'Could not find member' parameters on object of type 'ResourceDefinition' , Line 1, position 14. '. "}}
Where am I wrong?
Thanks in advance.
I believe the documentation is incorrect. Correct request payload should be:
{"properties": {"elasticPoolName": "XXXXX"},"location": "West Europe"}

Bool does not exist in current context but declared in same way as other variables

I have a bool that the compiler says does not exist in the current scope, however all the other variable are declared and used in the same place/way. Code below, some class names changed and code simplified but the structure remains the same.
iDReq does not exist in the current context
if (button.Click) {
string sourceFileName = "";
string destPathFileName = "";
int exportCount = 0;
bool iDReq = true;
iDReq = (System.Windows.Forms.MessageBox.Show("Include ID in file names?", "ID",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes);
foreach (KeyValueCollection item in SearchControl.SelectedItems)
{
Class.Document doc = Class.Document.GetDocument((long)item["id"].Value);
{
sourceFileName = #"\\server\share" + #"\" + Convert.ToString(doc.GetExtraInfo("docFileName"));
string fileExtension = System.IO.Path.GetExtension(sourceFileName);
//Line below is the one that the compiler does not like.
iDReq = true ? destPathFileName = destPath + #"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension : destPathFileName = destPath + #"" + doc.Description + fileExtension;
try {
System.IO.Directory.CreateDirectory(destPath);
System.IO.File.Copy(sourceFileName,destPathFileName,true);
System.Windows.Forms.Clipboard.SetText(destPathFileName);
exportCount ++;
}
catch(Exception ex)
{
ErrorBox.Show(ex);
}
}
}
}
Is it because it's a boolean value or am I missing something else?
I think your ternary is badly written, but I am not sure about what you want. I would rewrite you this as a plain if/else. I love ternary operator, but it is just sugar.
I think you are looking for this:
destPathFileName = iDReq == true
? (destPath + #"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension)
: (destPath + #"" + doc.Description + fileExtension);
and iDReq == true is superflous.
also you can write:
destPathFileName = destPath + #"" + doc.Description
+ (iDReq ? " (" + doc.ID + ")" : string.Empty)
+ fileExtension;
by the way, #"" is string.Empty.
and with string interpolation:
destPathFileName = destPath + doc.Description
+ (iDReq ? $" ({doc.ID})" : string.Empty)
+ fileExtension;
try this:
destPathFileName = iDReq ? destPath + #"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension : destPath + #"" + doc.Description + fileExtension;

How to trim within a loop

I am trying to output to a text file, with the following C# code. The problem is that my outputted information has a comma at the end of it and this won't work with the program that uses the file after. I'm trying to figure out how to get rid of this comma...
var toFile = Path.Combine(GetTextPath(),
string.Format(heatname + "_{0}.txt", DateTime.Now.ToString("yyyyMMdd")));
string ElementsNum = RoundedValues.Count.ToString();
DateTime dt = System.DateTime.Now;
var year = dt.ToString("yy");
var month = dt.ToString("MM");
var day = dt.ToString("dd");
var minute = dt.ToString("mm");
using (var fs = File.OpenWrite(toFile))
using (TextWriter sw = new StreamWriter(fs))
{
sw.Write("NA" + "," + dt.Hour.ToString() + "," + minute + "," + day + ","
+ month + "," + year + "," + "ALTEST " + "," +
"ALTEST " + "," + heatgrade + " " + "," + " " + "," + heatname + "," +
DT2.Rows[0][3].ToString() + "," + heatgrade + "," + "OE2" + "," + "," +
"," + "," + "," + "," + "," + " " + ElementsNum);
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
}
}
You can use TrimEnd, for example:
var theString = "abcd,";
var trimmedString = theString.TrimEnd(new[]{','});
In your case, if I'm not mistaken, this is where you want it to happen:
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
If so, you can do this:
var pairs = pair.B.ToString() + ", " + pair.A.ToString() + ",";
sw.Write(pairs.Trim().TrimEnd(new[]{','}));
Here is a linqy way to do it. This would use the Aggregate function of linq.
var x = RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b })
.Aggregate("", (old, item) => {
return old + (old == "" ? "" : ", ") +
item.B.ToSTring() + ", " + item.A.ToString();
});
sw.Write(x);
Version two (go go join!) uses linq to make a array of strings containing the pairs and then combine those pairs seperated by a comma using join.
string [] x = RoundedValues.Zip(Elements,
(a, b) => b.ToSTring() + ", " + a.ToString() ).ToArray();
sw.Write(String.Join(", ",x));
It might be that the following would work, but I'm not where I can test it ... this sure looks sexy (mostly because it is one line and everyone loves one line solutions):
sw.Write(String.Join(", ",
RoundedValues.Zip(Elements,
(a, b) => b.ToSTring() + ", " + a.ToString() )
));
Which would replace
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sw.Write(pair.B.ToString() + ", " + pair.A.ToString() + ",");
}
Another option is to use the StringBuilder.
...
StringBuilder sb = new StringBuilder();
foreach (var pair in RoundedValues.Zip(Elements, (a, b) => new { A = a, B = b }))
{
sb.AppendFormat("{0}, {1},", pair.B, pair.A);
}
sw.Write(sb.ToString().TrimEnd(new[] { ' ', ',' });

Categories

Resources