My SQL query retrieves one row of multiple columns. I have stored that in string with '|' separator to differentiate between columns.
And then prints that string in <textarea> field of .aspx page.
My question is there any way in which after that | separator next column comes in next line in textarea? Just like pressing Enter key?
Code:
dtOutput = Generix.getData("dbo.EventMsg E Left Join dbo.ATMStatusHistory A On E.Code=A.Fault", "Distinct E.Fault_Short_Name", "A.Code In (" + sFaultNumber + ") And IsNull(Fault_Short_Name,'')<>''", "", "", 1);
sOtherFaults = "";
foreach (DataRow drOutput in dtOutput.Rows)
{
foreach (DataColumn dcOutput in dtOutput.Columns)
{
sOtherFaults += ((sOtherFaults == "") ? "" : ":") + Convert.ToString(drOutput[dcOutput]);
}
}
sOutput += "|" + sOtherFaults + "|" + sClosedFault + "|" + sTemp + "|";
Response.Write(sOutput);
Try:
string.Join(#"|\r\n", sOutput, sOtherFaults, sClosedFault, sTemp);
I dont really understand what you mean but try this
sOutput += "|" + sOtherFaults + "|" + sClosedFault + "|" + sTemp + "|";
Response.Write(sOutput.Replace("|", "\r\n"));
Or
sOutput += "|" + sOtherFaults + "|" + sClosedFault + "|" + sTemp + "\r\n";
Response.Write(sOutput);
I think you'd be better off using a StringBuilder here, like this.
var responseString = new StringBuilder(sOutput);
resposeString.AppendLine("|");
foreach (DataRow drOutput in dtOutput.Rows)
{
foreach (DataColumn dcOutput in dtOutput.Columns)
{
resposeString.AppendFormat("{0}:", Convert.ToString(drOutput[dcOutput]));
}
}
// Remove last : delimiter
responseString.Remove(responseString.Length - 1, 1);
resposeString.AppendLine("|");
resposeString.Append(sClosedFault);
resposeString.AppendLine("|");
resposeString.Append(sTemp);
Response.Write(responseString.ToString());
Like String.Format this will save lots of intermediate string instantiations but, also fits nicely in the loop structure.
Related
I have a file containing text and I can get it to populate a textbox on page load but it always adds a blank first line. Any ideas? I've tried skipping the first line in the array in case it was blank (both 0 and 1) but 0 does nothing and 1 skips the first line in the text file.
I've also tried to set the textbox to null and "" first in case it was appending to the textbox in some way.
//Populating the contents box
string[] str = null;
if (File.Exists(docPath + prefix + libIDPath + "\\" + oldFileName))
{
str = File.ReadAllLines(docPath + prefix + libIDPath + "\\" + oldFileName);
//str = str.Skip(0).ToArray();
//FDContentsBox.Text = null;
}
foreach (string s in str)
{
FDContentsBox.Text = FDContentsBox.Text + "\n" + s;
}
In your foreach you are appending the "\n" before appending the string itself. Try
FDContentsBox.Text = FDContentsBox.Text + s + "\n";
instead.
Please try this, there is no need to read all lines nor a foreach loop
var filePath = docPath + prefix + libIDPath + "\\" + oldFileName;
if (File.Exists(filePath))
{
FDContentsBox.Text = File.ReadAllText(filePath);
}
I am using C# Script in Tabular Editor to read a Power BI file and use clipboard to get information to Excel. Totally newbie to both so my code isn't great but works. My code is below.
For the Expression field I am using .Replace("\n"," ") to replace the line breaks with a blank space.
Otherwise the line broken text moves into the next row in Excel and doesn't align with the corresponding column anymore.
Is there a way I can achieve both
i.e. replace the line breaks with something in Excel that is recognized as a multiple line but still remains with in an Excel Cell.
I have googled and read multiple threads and tried \r, \x0A, CHAR(10), WrapText in Excel etc.
var tsv = "Table_Name\tTable_MeasureCount\tMeasure_Name\tMeasure_Description\tMeasure_DisplayFolder\tMeasure_IsHidden\tMeasure_DataType\tMeasure_FormatString\tMeasure_DataCategory\tMeasure_ErrorMessage\tMeasure_Expression";
foreach(var Table in Model.Tables)
foreach(var Measure in Table.Measures)
{
tsv += "\r\n" + Table.Name
+ "\t" + Table.Measures.Count
+ "\t" + Measure.Name
+ "\t" + Measure.Description
+ "\t" + Measure.DisplayFolder
+ "\t" + Measure.IsHidden
+ "\t" + Measure.DataType
+ "\t" + Measure.FormatString
+ "\t" + Measure.DataCategory
+ "\t" + Measure.ErrorMessage.Replace("\n"," ")
+ "\t" + Measure.Expression.Replace("\n"," ");
}
tsv.Output();
This is the logic I ended up with (I couldn't get a function to work in Tabular Editor)
var csv = "\"Table_Name\",\"Table_MeasureCount\",\"Measure_Name\",\"Measure_Description\",\"Measure_DisplayFolder\",\"Measure_IsHidden\",\"Measure_DataType\",\"Measure_FormatString\",\"Measure_DataCategory\",\"Measure_ErrorMessage\",\"Measure_Expression\"";
string str1 = "\r\n\"";
string str2 = "\",\"";
string str3 = "\"";
//foreach(var Measure in Model.AllMeasures)
foreach(var Table in Model.Tables)
{
foreach(var Measure in Table.Measures)
{
csv += str1 + Table.Name
+ str2 + Table.Measures.Count
+ str2 + Measure.Name
+ str2 + Measure.Description
+ str2 + Measure.DisplayFolder
+ str2 + Measure.IsHidden
+ str2 + Measure.DataType
+ str2 + Measure.FormatString.Replace("\"","\"\"")
+ str2 + Measure.DataCategory
+ str2 + Measure.ErrorMessage.Replace("\"","\"\"")
+ str2 + Measure.Expression.Replace("\"","\"\"")
+ str3;
}
}
csv.Output();
Now we have established CSV is the best option as it allows for line-breaks, I'd suggest the following:
First create a simple function to parse a string into a safe format:
public string stringToCsvSafe(string str)
{
return "\"" + str.Replace("\"", "\"\"") + "\"";
}
Then in your loop build your output string, something like this:
var newRow = new List<object>() {
Table.Name,
Table.Measures.Count,
stringToCsvSafe(Measure.Name),
stringToCsvSafe(Measure.Description),
...
};
csv += string.Join(",", newRow) + "\n";
Hi i have problems getting my foreach to work. It only picks one node, in my simpel linq query. i actly dont no what the problem is, because i usede to be using Xmldocument and xmlnodelist. But i really want to learn do it using Linq, i cannot find anything on google why its not working, i allso tryede the expmales on these links.
http://www.dotnetcurry.com/linq/564/linq-to-xml-tutorials-examples
Simple LINQ to XML is not working
https://forums.asp.net/t/1378244.aspx?Linq+to+XML+query+how+to+get+all+elements+but+excluding+some+
http://www.c-sharpcorner.com/UploadFile/de41d6/learning-linq-made-easy-linq-to-xml-tutorial-3/
Both these examples only return, one xml node.
XElement ele = XElement.Load(filePath);
String aXmlString = ele.ToString(SaveOptions.DisableFormatting) + ele.Value;
foreach (XElement xNode in ele.Descendants("lakeringsdel"))
{
//litTest.Text = xNode.Element("lakeringsMetode").Value;
strData = "<table style='width:100%;' >"
+ "<tr>"
+ "<th>Nr.</th>"
+ "<th>Arbejdsbeskrivelse/Omfang</th>"
+ "<th>Metode</th>"
+ "<th>Ae</th>"
+ "</tr>"
+ "<tr>"
+ "<td>" + xNode.Element("ledenr").Value + "</td>"
+ "<td>" + xNode.Element("lakeringsDel").Value + "</td> "
+ "<td>" + xNode.Element("lakeringsMetode").Value + "</td> "
+ "<td>" + xNode.Element("arbejdsEnheder").Value + "</td> "
+ "</tr>"
+
"</table>";
}
next example
var test = "";
var q = from c in ele.Descendants("lakeringsdel")
select c.Element("lakeringsDel").Value;
foreach (string item in q)
{
test = item;
}
My xml document
<lakRapportDetaljer>
<aePrTime>10</aePrTime>
<fabrikatModelTekst>FORD FOCUS (CEW)</fabrikatModelTekst>
<kilometerStand>28205</kilometerStand>
<lakArbejde>2745.0</lakArbejde>
<lakIaltTotal>3610.05</lakIaltTotal>
<lakIndex>134</lakIndex>
<lakMaterialer>865.05</lakMaterialer>
<lakTimepris>450.0</lakTimepris>
<lakeringsMetode>2-LAGS METALLIC</lakeringsMetode>
<lakeringsMetode>DØRGREB LEVERES LAKE</lakeringsMetode>
<lakeringsdel>
<arbejdsEnheder>10.0</arbejdsEnheder>
<lakeringsDel>KOFANGER H B</lakeringsDel>
<lakeringsMetode>REPARATION LAK.PLAST</lakeringsMetode>
<ledenr>2584</ledenr>
</lakeringsdel>
<lakeringsdel>
<arbejdsEnheder>15.0</arbejdsEnheder>
<lakeringsDel>BAGSKÆRM HØJRE</lakeringsDel>
<lakeringsMetode>REP.LAK. <50%, METAL</lakeringsMetode>
<ledenr>3482</ledenr>
</lakeringsdel>
<lakeringsdel>
<arbejdsEnheder>5.0</arbejdsEnheder>
<lakeringsDel>SPECIALAFDÆKNING</lakeringsDel>
<lakeringsMetode>OVERFLADE LAKERING</lakeringsMetode>
<ledenr>1000</ledenr>
</lakeringsdel>
<miljoeLakMaterialerProcent>6</miljoeLakMaterialerProcent>
</lakRapportDetaljer>
I've tested your code,but I can't see any problem: it returns three nodes:
if you want to select all elements inside the 3 Xelement nodes "lakeringsdel", you could do :
var q = from c in ele.Descendants("lakeringsdel")
select c;
foreach (XElement item in q)
{
test = item.Value;
}
which gives :
or directly:
var q = ele.Descendants("lakeringsdel");
foreach (XElement item in q)
{
test = item.Value;
}
which gives the same result
or in 1 line:
ele.Descendants("lakeringsdel").ToList().ForEach(elem=>test =elem.Value);
but as said Reniuz in comment : you store only the last result in your "test" variable
if you want to store all results you could do:
List<string> test = new List<string>();
var q = from c in ele.Descendants("lakeringsdel")
select c.Element("lakeringsDel").Value;
foreach (string item in q)
{
test.Add(item);
}
or in 1 line:
test.AddRange(q);
In both examples you set the output strData and test every time you loop through your items. That results in handling nly the last item in your list.
Assuming you want to show a table with the results on your homepage you should change your first example to this
XElement ele = XElement.Load(filePath);
String aXmlString = ele.ToString(SaveOptions.DisableFormatting) + ele.Value;
strData = "<table style='width:100%;' >"
+ "<tr>"
+ "<th>Nr.</th>"
+ "<th>Arbejdsbeskrivelse/Omfang</th>"
+ "<th>Metode</th>"
+ "<th>Ae</th>"
+ "</tr>"
foreach (XElement xNode in ele.Descendants("lakeringsdel"))
{
//litTest.Text = xNode.Element("lakeringsMetode").Value;
strData += "<tr>"
+ "<td>" + xNode.Element("ledenr").Value + "</td>"
+ "<td>" + xNode.Element("lakeringsDel").Value + "</td> "
+ "<td>" + xNode.Element("lakeringsMetode").Value + "</td> "
+ "<td>" + xNode.Element("arbejdsEnheder").Value + "</td> "
+ "</tr>";
}
strData += "</table>";
I would recommend using a StringBuilder to build the string instead of +; whcih could look like this example.
StringBuilder strData = new StringBuilder("<table style='width:100%;'>");
strData.AppendLine("<tr>");
strData.AppendLine("<th>Nr.</th>");
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);
I read data from a text file which is 27 MB file and contains 10001 rows, I need to handle large data. I perform some kind of processing in each row of data and then write it back to a text file. This is the code I have am using
StreamReader streamReader = System.IO.File.OpenText("D:\\input.txt");
string lineContent = streamReader.ReadLine();
int count = 0;
using (StreamWriter writer = new StreamWriter("D:\\ft1.txt"))
{
do
{
if (lineContent != null)
{
string a = JsonConvert.DeserializeObject(lineContent).ToString();
string b = "[" + a + "]";
List<TweetModel> deserializedUsers = JsonConvert.DeserializeObject<List<TweetModel>>(b);
var CreatedAt = deserializedUsers.Select(user => user.created_at).ToArray();
var Text = deserializedUsers.Where(m => m.text != null).Select(user => new
{
a = Regex.Replace(user.text, #"[^\u0000-\u007F]", string.Empty)
.Replace(#"\/", "/")
.Replace("\\", #"\")
.Replace("\'", "'")
.Replace("\''", "''")
.Replace("\n", " ")
.Replace("\t", " ")
}).ToArray();
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
writer.WriteLine(TextWithTimeStamp);
}
lineContent = streamReader.ReadLine();
}
while (streamReader.Peek() != -1);
streamReader.Close();
This code helps does well up to 54 iterations as I get 54 lines in the output file. After that it gives error "Index was outside the bounds of the array." at line
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
I am not very clear about the issue if the maximum capacity of array has been violated, if so how can I increase it or If I can write the individual line encountered in loop through
writer.WriteLine(TextWithTimeStamp);
And clean the storage or something that can solve this issue. I tried using list insead of array , still issue is the same.Please help.
Change this line
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
to
var TextWithTimeStamp = (Text.Any() ? Text.First().a : string.Empty) +
" (timestamp:" + (CreatedAt.Any() ? CreatedAt.First() : string.Empty) + ")";
As you are creating Text and CreatedAt collection objects, they might be empty (0 total item) based on some scenarios and conditions.
Those cases, Text[0] and CreatedAt[0] will fail. So, before using the first element, check if there are any items in the collection. Linq method Any() is used for that purpose.
Update
If you want to skip the lines that do not contain text, change this lines
var TextWithTimeStamp = Text[0].a + " (timestamp:" + CreatedAt[0] + ")";
writer.WriteLine(TextWithTimeStamp);
to
if (Text.Any())
{
var TextWithTimeStamp = Text.First().a + " (timestamp:" + CreatedAt.First() + ")";
writer.WriteLine(TextWithTimeStamp);
}
Update 2
To include all the stringss from CreatedAt rather than only the first one, you can add all the values in comma separated strings. A general example
var strings = new List<string> { "a", "b", "c" };
var allStrings = string.Join(",", strings); //"a,b,c"