I have created an application that checks how many users are logged into a machine and performs a count. I have used Cassia to get the usernames, however I would like to put those usernames in a list and send to my database.
I am having a problem with putting those usernames into the list.
Here is my code:
static void Main(string[] args)
{
while (!Console.KeyAvailable)
{
List<string> list = new List<string>();
string host = Dns.GetHostName();
ITerminalServicesManager manager = new TerminalServicesManager();
using (ITerminalServer server = manager.GetRemoteServer(host))
{
server.Open();
foreach (ITerminalServicesSession session in server.GetSessions())
{
NTAccount account = session.UserAccount;
if (account != null)
{
list.Add(account.ToString());
Console.WriteLine(list);
Console.WriteLine("Count: " + list.Count);
Thread.Sleep(10000);
}
}
}
}
}
When I run the application, the count is performed correctly, but the list is not displayed in my application. System.Collection.Generic.List``1[System.String] is displayed instead of the list.
Is there a way to place those usernames in a list? Or maybe an array would be better? Any suggestions?
Thank you.
Try printing out your list using following
list.ForEach(Console.WriteLine);
That will print all the list elements. One per line.
I see couple of issues here.
First one: place list creation and printing outisde your loop, otherwise you're creating new list for each session object and I really doubt it was intended.
Second one: you can't print the list using one WirteLine since in this cast it tries to use .ToString() method of list inherited from object and gives you result like System.Collection.Generic.List``1[System.String].
Instead you have to use another loop to traverse the list and print it:
List<string> list = new List<string>();
foreach (ITerminalServicesSession session in server.GetSessions())
{
NTAccount account = session.UserAccount;
if (account != null)
{
list.Add(account.ToString());
}
}
foreach (var item in list)
Console.WriteLine(item);
Console.WriteLine("Count: " + list.Count);
Thread.Sleep(10000);
This line is printing the value of list.ToString() to the console:
Console.WriteLine(list);
Your accounts are in there, but the default behavior of ToString will print information about the object's type. Try replacing that line with:
Console.WriteLine(account.ToString());
You can use this code block:
foreach (var item in list)
Console.WriteLine(item);
Console.WriteLine(list) is the same Console.WriteLine(list.ToString()).
ToString() method returns system name of the List object.
Related
I have to print all the text of the web elements, so i am storing the web elements in list "test" and then getting text of each web element and keep them adding to other list "Title".
Now when i am trying to print all the elements of list "Title".But only the text of 1st element is printed.
Please help me to find where i am going wrong.
public void PrintText()
{
var Title = new List<string>();
IList <IWebElement> test=Controls.GetWebElementList(X-path);
foreach (var g in test)
{
Title.Add(Controls.GetText(x-path));
}
foreach (var h in Title)
{
Console.WriteLine(h);
}
}
It's not that clear how Controls.GetWebElementList() is defined.
Ideally to extract the texts you have to induce WebDriverWait for VisibilityOfAllElementsLocatedBy() and you can use the following Locator Strategy:
IList <IWebElement> test = new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.XPath("X-path")));
Your code looks fine.
Try to verify the first list to print their values.
And then run again, maybe your first line had only one value.
I have a list of strings that I would like to iterate through and change the values if certain items in the list if they match up to a string value in a separate list of objects.
User inputs an email address into an Event object that contains a list of EventMembers:
List<string> EventMembers
I would then like to check through all users in the database to find the username(e-mail address) that matches with the inputted e-mail address
i understand I cannot change values in a list using a foreach loop, but i'm lost with what to do with linq. Basically i'm trying to do something like this:
var allUsers = _userManager.Users
foreach (var a in allUsers)
{
foreach (var e in #event.EventMembers)
{
if (e == a.UserName)
{
e = a.FirstName + a.LastName;
}
}
}
The best thing would be to define an initial collection of members so you don't keep modifying the list while the foreach is still running. You could then check if EventMembers contain the username and then replace it by accessing the value with the index.
var allUsers = _userManager.Users;
List<string> Members;
foreach (var a in allUsers)
{
if (#event.EventMembers.Contains(a.UserName))
{
var index = #event.Members.IndexOf(a.UserName);
Members[index] = a.FirstName + a.LastName;
}
}
EventMembers = Members;
I'm having some issues with my programm in c#.
Basically I have a list called mainList with 3 items in it. First two items are integers, but third one is another list containing more items.
mainList[0] = 8;
mainList[1] = 1;
mainList[2] = list;
By using foreach loop I'm able to print all of those items.
foreach (var i in (dynamic)(mainList[2]))
{
Console.WriteLine(i);
}
However I don't know how to access them. The thing is that I can't use indexes, because it is not an array. I would like to do something like this:
foreach (var i in (dynamic)(mainList[2]))
{
// First item is in datetime type, so I would like to change it to int
Console.WriteLine(Convert.ToInt64(i[1]));
}
Is there a way to access items inside list like we do it in arrays with a help of indexes?
Lists support the same index-based access as arrays, so you can use
mainList[n]
to access the nth entry in mainList.
I guess you are looking for something like this, although it is really unclear what you're asking:
foreach(var item in mainList)
{
if(item is System.Collections.IEnumerable)
{
foreach(var obj in ((System.Collections.IEnumerable)item))
{
Console.WriteLine(obj);
}
}
}
I want to store user input of server names once saved from inside an application. I get an error in the settings for index out of bounds in my SettingsForm class (error line indicated below). I believe my ServerName property is only of size one so how would I go about changing this? Or is something else need to be changed in my code?
I am unsure about storing the multiple strings to one property. I have been trying different things but I am new to C# and WinForms applications. Here is the code I have been trying to work out:
UserSettings class:
[UserScopedSetting()]
[DefaultSettingValue("Enter Server Name")]
public String[] ServerName
{
get
{
return (String[])this["ServerName"];
}
set
{
this["ServerName"] = (String[])value;
}
}
SettingsForm class:
private void saveSettingsButton_Click(object sender, EventArgs e)
{
//loop through all servers
for (int i=0; i<serverCounter.Value; i++)
{
TextBox currentTextBox = (TextBox)servers[i, 0];
us.ServerName[i] = currentTextBox.Text; //ERROR
currentTextBox.DataBindings.Add("Text", us, "ServerName");
}
us.Save();
this.Close();
}
Potential issues: what value does serverCounter.Value have? How is us.ServerName[] instantiated? ServerName returns a string array, but to me it looks like each serverName should be a string, and then put into an array (or list).
From the code snippet you show, my guess is that serverCounter has a certain value >1 and us.ServerName always is an array with 1 item (or it is never instantiated). This will give you an index out of range error.
Try using public string ServerName instead of public String[] ServerName and then each time you get a return value, put that value into an array--or if you don't know how many servers will be inputted, a List would be better.
List<string> serverNames = new List<string>();
// Get currentName from user--I don't understand how your code is supposed to work
serverNames.Add(currentName); // this is the name entered by the user
Then use a foreach loop:
foreach (string name in serverNames)
{
//do something
}
If you know in advance how many servers there are, you can use a string array:
string[] serverNames = new string[serverCounter];
and still use a foreach loop to iterate over it.
I am fairly new to C#
I am trying to retrieve some information from an external data source and store it in array, once it is in an array I wish to sort it by time.
I know how to do this for just one column in a row, however the information I require has multiple columns.
For example:
foreach (Appointment Appoint in fapts)
{
// Store Appoint.Subject, Appoint.Start, Appoint.Organiser.Name.ToString(), Appoint.Location in an array
}
// Sort my array by Appoint.Start
foreach ( item in myNewArray )
{
//print out Appoint.Subject - Appoint.Start, Appoint.Organiser.Name.ToString() and Appoint.location
}
Many thanks for your help.
EDIT:
I have multiple data sources which pull in this:
foreach (Appointment Appoint in fapts)
{
// Store Appoint.Subject, Appoint.Start, Appoint.Organiser.Name.ToString(), Appoint.Location in an array
}
Hence the need to sort the items in a new array, I know this isn't very efficent but there is no way of getting the information I need in any other way.
You can sort a list using the LINQ sorting operators OrderBy and ThenBy, as shown below.
using System.Linq;
and then...
var appointments = new List<Appointment>();
var sortedAppointments = list.OrderBy(l => l.Subject).ThenBy(l => l.Name).ToList();
This will create a new list of appointments, sorted by subject and then by name.
It's unclear what your final aim is but:
Use a generic List instead of an array:
See this SO question for more information as to why using a List is prefered.
List<Appointment> appointments = new List<Appointment>();
foreach (Appointment Appoint in fapts)
{
appointments.Add(Appoint);
}
foreach (var item in appointments)
{
Console.WriteLine(item.Subject);
Console.WriteLine(item.Foo);
// Here you could override ToString() on Appointment to print eveything in one Console.WriteLine
}
If the aim of your code is to order by time, try the following:
var sortedAppointments = fapts.OrderBy(a => a.Start); // assuming Start is a DateTime property of `Appointment`.
Consider a Dictionary Object instead of an array if the data is conceptually one row multiple columns.
foreach(KeyValuePair<string, string> entry in MyDic)
{
// do something with entry.Value or entry.Key
}
You already have a list of objects in fpts, sort that list itself:
fpts.OrderBy(x => x.Subject).ThenBy(x => x.Location).ToList();
LINQ is your friend here.
fapts appears to already be a collection so you could just operate on it.
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start).ToArray()
I've used the ToArray() call to force immediate evaluation and means that myNewArray is already sorted so that if you use it more than once you don't have to re-evaluate the sort.
Alternatively if you are only using this once you can just as easily miss the ToArray() portion out and then execution of the sort will be deferred until you try and enumerate through myNewArray.
This solution puts the source objects into the array, but if you are just wanting to store the specific fields you mention then you will need to use a select. You have two choices for the array item type, you can either use an anonymous class which provides difficulties if you are returning this array from a function or define a class.
For anonymous:
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start)
.Select(Appoint => new {
Start = Appoint.Start,
Organiser = Appoint.Organiser.Name.ToString(),
Location = Appoint.Location
}).ToArray();
For named class assuming class is MyClass:
var myNewArray = fapts.OrderBy(Appoint => Appoint.Start)
.Select(Appoint => new MyClass {
Start = Appoint.Start,
Organiser = Appoint.Organiser.Name.ToString(),
Location = Appoint.Location
}).ToArray();
You have a wide range of options. The 2 most common are:
1) Create a class, then define an array or list of that class, and populate that
2) Create a structure that matches the data format and create an array or list of that
Of course, you could put the data into an XML format or dataset, but that's probably more work than you need.
public List<foo> appointments = new List<foo>();
public struct foo
{
public string subject ;
public DateTime start ;
public string name ;
public string location ;
}
public void foo1()
{
// parse the file
while (!File.eof())
{
// Read the next line...
var myRecord = new foo() ;
myRecord.subject = data.subject ;
myRecord.start = data.Start ;
myRecord.name = data.Name ;
//...
appointments.Add(myRecord);
}
}
Enjoy
(Since I can't comment and reply to the comment - it wasn't clear if he had a class, etc. or was just showing us what he wanted to do. I assumed it was just for demonstration purposes since there wasn't any info as to how the data was being read. If he could already put it into a class, than the first answer applied anyway. I just tossed the last 2 in there because they were options for getting the data first.)