ASP.NET StreamWriter - new line after x commas - asp.net

I've got a JS array which is writing to a text file on the server using StreamWriter. This is the line that does it:
sw.WriteLine(Request.Form["seatsArray"]);
At the moment one line is being written out with the entire contents of the array on it. I want a new line to be written after every 5 commas. Example array:
BN,ST,A1,303,601,BN,ST,A2,303,621,BN,WC,A3,303,641,
Should output:
BN,ST,A1,303,601,
BN,ST,A2,303,621,
BN,WC,A3,303,641,
I know I could use a string replace but I only know how to make this output a new line after every comma, and not after a specified amount of commas.
How can I get this to happen?
Thanks!

Well, here's the simplest answer I can think of:
string[] bits = Request.Form["seatsArray"].Split(',');
for (int i = 0; i < bits.Length; i++)
{
sw.Write(bits[i]);
sw.Write(",");
if (i % 5 == 4)
{
sw.WriteLine();
}
}
It's not terribly elegant, but it'll get the job done, I believe.
You may want this afterwards to finish off the current line, if necessary:
if (bits[i].Length % 5 != 0)
{
sw.WriteLine();
}
I'm sure there are cleverer ways... but this is simple.
One question: are the values always three characters long? Because if so, you're basically just breaking the string up every 20 characters...

Something like:
var input = "BN,ST,A1,303,601,BN,ST,A2,303,621,BN,WC,A3,303,641,";
var splitted = input.Split(',');
var cols = 5;
var rows = splitted.Length / cols;
var arr = new string[rows, cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
arr[row, col] = splitted[row * cols + col];
I will try find a more elegant solution. Properly with some functional-style over it.
Update: Just find out it is not actually what you needs. With this you get a 2D array with 3 rows and 5 columns.
This however will give you 3 lines. They do not have a ending ','. Do you want that? Do you always want to print it out? Or do you want to have access to the different lines?:
var splitted = input.Split(new [] { ','}, StringSplitOptions.RemoveEmptyEntries);
var lines = from item in splitted.Select((part, i) => new { part, i })
group item by item.i / 5 into g
select string.Join(",", g.Select(a => a.part));
Or by this rather large code. But I have often needed a "Chunk" method so it may be reusable. I do not know whether there is a build-in "Chunk" method - couldn't find it.
public static class LinqExtensions
{
public static IEnumerable<IList<T>> Chunks<T>(this IEnumerable<T> xs, int size)
{
int i = 0;
var curr = new List<T>();
foreach (var x in xs)
{
curr.Add(x);
if (++i % size == 0)
{
yield return curr;
curr = new List<T>();
}
}
}
}
Usage:
var lines = input.Split(',').Chunks(5).Select(list => string.Join(",", list));

Related

Faster database access by index

I have this code
using (var contents = connection.CreateCommand())
{
contents.CommandText = "SELECT [subject],[note] FROM tasks";
var r = contents.ExecuteReader();
int zaehler = 0;
int zielzahl = 5;
while (r.Read())
{
if (zaehler == zielzahl)
{
//access r["subject"].ToString()
}
zaehler++;
}
}
I want to make it faster by accessing zielzahl directly like r[zielzahl] instead of iterating through all entries. But
r[zielzahl]["subject"]
does not work aswell as
r["subject"][zielzahl]
How do I access the column subject of result number zielzahl?
To get only the sixth record, use the OFFSET clause:
SELECT subject, note
FROM tasks
LIMIT 1 OFFSET 5
Please note that the order of returned records is not guaranteed unless you use the ORDER BY clause.

checkboxlist selection issue

There are 5 goals and 5 employees. Each goal can be assigned to any number of these 5 employees. So I have 5 CheckBoxLists for each of the goals, each CheckBoxList having the names of these 5 employees as items.
I want to retrieve from the database which employees have been assigned which goals. I have the following piece of code:
List<CheckBoxList> checkboxlists = new List<CheckBoxList>();
checkboxlists.Add(CheckBoxList1);
checkboxlists.Add(CheckBoxList2);
checkboxlists.Add(CheckBoxList3);
checkboxlists.Add(CheckBoxList4);
checkboxlists.Add(CheckBoxList5);
for (int z = 1; z <= checkboxlists.Count; z++)
{
SqlCommand check = new SqlCommand("SELECT ISGoal1, ISGoal2,ISGoal3, ISGoal4,ISGoal5 FROM PRM2011_EMPLOYEE_GOAL WHERE EmployeeID = '" + employeeid[z - 1] + "'", con);
SqlDataReader y = check.ExecuteReader();
y.Read();
for (int j = 1; j <= 5; j++)
{
if (null != y && y.HasRows)
{
string yes_or_no = y["ISGoal" + j].ToString().Trim();
if (yes_or_no == "Yes")
{
checkboxlists[j-1].Items[z-1].Selected = true;
}
//else checkboxlists[j - 1].Items[z - 1].Selected = false;
}
}
y.Close();
}
My problem is that even if I select one goal for an employee, all the checkboxes corresponding to that particular employee get selected. Why is this happening?
Correspondingly, if I comment out the else portion in the code posted, and if any of the goals are not selected, then all the checkboxes corresponding to that employee goes unselected. Please help.
A few thoughts:
Have your for loops go from 0 to less than checkboxlists.Count and from 0 to less than 5. That way you can avoid having to deal with all the subtractions everywhere.
On the line checkboxlists[j-1].Items[z-1].Selected = true, shouldn't it be checkboxlists[z-1].Items[j-1].Selected = true since I am assuming you are using z to iterate over your CheckBoxLists.
Its late here, so my brain may be a bit fuzzy, but it seems that #2 could be your issue. Give those thoughts a shot and I will follow up with you if you are still having issues.
You have many issues in your code I'll tell you the main problem and then I'll list the other flaws of your code.
What's causing this is:
the existence of the method y.Read(); out side of the for loop.
since the function of Read(); is to read the next row in the database. so basically your code reads the first value, Let's assume the value will be "Yes" so it will cause the ListBox to check the employee and instead of calling the y.Read(); again so it moves to the next row it DOES NOT! .. so the value is kept "Yes" and hense all the CheckBoxes in the List will be checked.
The Solution:
It's as simple as just moving the y.Read(); from out side the loop into it.
Like this:
List<CheckBoxList> checkboxlists = new List<CheckBoxList>();
checkboxlists.Add(CheckBoxList1);
checkboxlists.Add(CheckBoxList2);
checkboxlists.Add(CheckBoxList3);
checkboxlists.Add(CheckBoxList4);
checkboxlists.Add(CheckBoxList5);
for (int z = 1; z <= checkboxlists.Count; z++)
{
SqlCommand check = new SqlCommand("SELECT ISGoal1, ISGoal2,ISGoal3, ISGoal4,ISGoal5 FROM PRM2011_EMPLOYEE_GOAL WHERE EmployeeID = '" + employeeid[z - 1] + "'", con);
SqlDataReader y = check.ExecuteReader();
for (int j = 1; j <= 5; j++)
{
y.Read();
if (null != y && y.HasRows)
{
string yes_or_no = y["ISGoal" + j].ToString().Trim();
if (yes_or_no == "Yes")
{
checkboxlists[j-1].Items[z-1].Selected = true;
}
//else checkboxlists[j - 1].Items[z - 1].Selected = false;
}
}
y.Close();
}
Extra Notes on your code
First of all
You need to edit your SqlCommand to use SqlParameters
SqlCommand check = new SqlCommand("SELECT ISGoal1, ISGoal2,ISGoal3, ISGoal4,ISGoal5 FROM PRM2011_EMPLOYEE_GOAL WHERE EmployeeID = #EmpID", con);
check.Parameters.AddWithValue("#ImpID", employeeid[z - 1]);
Second
If you are trying to build a real application then this is a very bad practice. Even if you are not building this application for real I don't think this is the way to practice.
for (int j = 1; j <= 5; j++)
your Loop should look like this:
for (int j = 1; j <= checkboxlists.Count; j++)
Third
Using a string to represent a Yes/No value is a also a bad practice .. You should use for all your ISGoal columns database, the DataType BIT. and consequently you'll change the local variable's DateType in your C# code from string to bool.
Fourth
checkboxlists[j-1].Items[z-1].Selected = true;
You should switch as Ryan said, because z denotes to the CheckBoxLists and j denotes to the items of a given CheckBoxList
so it could be like this:
checkboxlists[z-1].Items[j-1].Selected = true;
N.B: I wasn't paying attention at first I thougth [z-1] is some kind of LINQ expression :D!! .. It's my fault but I mean I used to do this when I first started programming and I still couldn't recognize it .. It's not the best practice I think! .. my advice respect the used Zero-Based numbering.
Finally
You don't have to check everytime if y.Read(); is null or not. So I think this piece of code would make more sense and also hard coding the condition of the loop is a very bad practice, so we'll use a while loop and add local variable of type int, then we'll increment it within our loop code so you could use it to access the CheckBoxList items
int j = 1;
while (y.Read())
{
string yes_or_no = y["ISGoal" + j].ToString().Trim();
if (yes_or_no == "Yes")
{
checkboxlists[j-1].Items[z-1].Selected = true;
//use our counter "j" here
}
//else checkboxlists[j - 1].Items[z - 1].Selected = false;
//use our counter "j" here
j++;
}
..Good Luck ;)

Flex Newbie XMLList question - Sorting XML and XMLList

Is it possible to sort an XMLList? All the examples I can find on it create a new XMLListCollection like this:
MyXMLListCol = new XMLListCollection(MyXMLList);
I don't think the XMLListCollection in this case has any reference to the XMLList so sorting it would leave my XMLList unsorted, is this correct?
How can I sort the XMLList directly?
Thanks
~Mike
So I finally got my search terms altered enough I actually churned up an answer to this.
Using the technique I got from here:
http://freerpad.blogspot.com/2007/07/more-hierarchical-sorting-e4x-xml-for.html
I was able to come up with this:
public function sortXMLListByAttribute(parentNode:XML,xList:XMLList,attr:String):void{
//attr values must be ints
var xListItems:int = xList.length();
if(xListItems !=0){
var sortingArray:Array = new Array();
var sortAttr:Number = new Number();
for each (var item:XML in xList){
sortAttr = Number(item.attribute(attr));
if(sortingArray.indexOf(sortAttr)==-1){
sortingArray.push(sortAttr);
}
//piggy back the removal, just have to remove all of one localName without touching items of other localNames
delete parentNode.child(item.localName())[0];
}
if( sortingArray.length > 1 ) {
sortingArray.sort(Array.NUMERIC);
}
var sortedList:XMLList = new XMLList();
for each(var sortedAttr:Number in sortingArray){
for each (var item2:XML in xList){
var tempVar:Number = Number(item2.attribute(attr));
if(tempVar == sortedAttr){
sortedList += item2
}
}
}
for each(var item3:XML in sortedList){
parentNode.appendChild(item3);
}
}
}
Works pretty fast and keeps my original XML variable updated. I know I may be reinventing the wheel just to not use an XMLListCollection, but I think the ability to sort XML and XMLLists can be pretty important
While there is no native equivalent to the Array.sortOn function, it is trivial enough to implement your own sorting algorithm:
// Bubble sort.
// always initialize variables -- it save memory.
var ordered:Boolean = false;
var l:int = xmlList.length();
var i:int = 0;
var curr:XML = null;
var plus:XML = null;
while( !ordered )
{
// Assume that the order is correct
ordered = true;
for( i = 0; i < l; i++ )
{
curr = xmlList[ i ];
plus = xmlList[ i + 1 ];
// If the order is incorrect, swap and set ordered to false.
if( Number( curr.#order ) < Number( plus.#order ) )
{
xmlList[ i ] = plus;
xmlList[ i + 1 ] = curr;
ordered = false;
}
}
}
but, realistically, it is far easier and less buggy to use XMLListCollection. Further, if someone else is reading your code, they will find it easier to understand. Please do yourself a favor and avoid re-inventing the wheel on this.

How to simplify adding multiple text inputs

i have an application in which i have around 100 textinputs all are numbers
i want to simplify the addition ie. any other way than saying txt1.text+txt2.text.....
that would increase my code a lot
is it possible to have (n+=txt*.text) or some thing like that
any help would be appreciated have to get the application done in two days thank you
If txt1, txt2 etc are public properties of the class representing this, you can use the following code to get the sum of the numbers in the text inputs.
var n:Number = 0;
for(i = 1; i <= total; i++)
n += Number(this["txt" + i].text);
To get a concatenated string:
var s:String = "";
for(i = 1; i <= total; i++)
s += this["txt" + i].text;
If the text inputs are properties of a different class, use the instance name of the object instead of this. For example:
instanceName["txt" + i].text;
Another solution that is more clean is to store them in an array and loop through them. But that might require changes in other parts of your code.

Use Take() to get a limited number of results but also get the potential total

Given the following...
int maxResults = 25;
string code = "Thailand";
var q = from i in images where i.component_code == code select i;
var images = q.OrderByDescending(x => x.image_rating).Take(maxResults);
if (images.Count() > 0)
{
...
lblResult = string.Format("Viewing {0} Images Of A Possible {1}", images.Count(), ?);
}
How do I get the potential total number of images that would have been returned if Take() had not been used
Can't you use q.Count() for this?

Resources