I'm trying to make an app where I could see the process, path, user, and description like Task Manager Details, which I have made but I want a filter to search from the source code where the image path contains 'Chrome' for example or If you could help me to get the Description like the task manager image and filter with this column. If you can help me to get the username of the process without using the another method will be nice.
Thank you.
This is what i have improved.
DataTable dt = null;
private void Form1_Load(object sender, EventArgs e)
{
var wmiQueryString = "SELECT * FROM Win32_Process";
// var wmiQueryString = "SELECT * FROM Win32_ComputerSystem";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var query = from p in Process.GetProcesses()
join mo in results.Cast<ManagementObject>()
on p.Id equals (int)(uint)mo["ProcessId"]
select new
{
Process = p.ProcessName,
Path = (string)mo["ExecutablePath"],
CommandLine = (string)mo["CommandLine"],
User = GetProcessOwner(p.Id),
Description = mo["Description"]
};
dt = ConvertToDataTable(query);
dataGridView1.DataSource = dt;
}
}
DataTable ConvertToDataTable<TSource>(IEnumerable<TSource> source)
{
var props = typeof(TSource).GetProperties();
var dt = new DataTable();
dt.Columns.AddRange(
props.Select(p => new DataColumn(p.Name, p.PropertyType)).ToArray()
);
source.ToList().ForEach(
i => dt.Rows.Add(props.Select(p => p.GetValue(i, null)).ToArray())
);
Array a = source.ToArray();
for (int i = 0; i < a.Length; i++)
{
var x = a.GetValue(i);
//if (true)
//{
// DataRow r = dt.NewRow();
// r.
//}
a.ToString();
}
return dt;
}
public string GetProcessOwner(int processId)
{
string query = "Select * From Win32_Process Where ProcessID = " + processId; ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); ManagementObjectCollection processList = searcher.Get(); foreach (ManagementObject obj in processList)
{
string[] argList = new string[] { string.Empty, string.Empty }; int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList)); if (returnVal == 0)
{
// return DOMAIN\user
return argList[0];
}
}
return "NO OWNER";
}
What I have
TaskManager what I want
The process description comes from the file description. You can grab it like so:
private void Form1_Load(object sender, EventArgs e)
{
var wmiQueryString = "SELECT * FROM Win32_Process";
// var wmiQueryString = "SELECT * FROM Win32_ComputerSystem";
using (var searcher = new ManagementObjectSearcher(wmiQueryString))
using (var results = searcher.Get())
{
var query = from p in Process.GetProcesses()
join mo in results.Cast<ManagementObject>()
on p.Id equals (int)(uint)mo["ProcessId"]
select new
{
Process = p.ProcessName,
Path = (string)mo["ExecutablePath"],
CommandLine = (string)mo["CommandLine"],
User = GetProcessOwner(p.Id),
Description = GetDescription((string)mo["ExecutablePath"])
};
dt = ConvertToDataTable(query);
dataGridView1.DataSource = dt;
}
}
string GetDescription(string executablePath)
{
if (!File.Exists(executablePath))
{
return "No Description";
}
return FileVersionInfo.GetVersionInfo(executablePath).FileDescription;
}
You'll probably need to run your program as an administrator to show the details of all processes.
Why would you like to get the username with another method?
Related
I am trying to get result from DataTable but I am stuck and have no idea what to do.
I have public static DataTable VratiKorisnike() which needs to return DataTable resultTable as result because my result is store in resultTable.
SO far my function is here
public static DataTable VratiKorisnike()
{
List<Korisnik> lstADUsers = new List<Korisnik>();
string sDomainName = "saos";
string DomainPath = "LDAP://" + sDomainName;
string output = #"C:\output.txt";
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname");
search.PropertiesToLoad.Add("usergroup");
search.PropertiesToLoad.Add("displayname");
search.PropertiesToLoad.Add("userAccountControl");
search.PropertiesToLoad.Add("PasswordExpirationDate");
//search.PropertiesToLoad.Add("DomainGroup");
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("samaccountname");
resultsTable.Columns.Add("usergroup");
resultsTable.Columns.Add("displayname");
resultsTable.Columns.Add("userAccountControl");
resultsTable.Columns.Add("PasswordExpirationDate");
//resultsTable.Columns.Add("DomainGroup");
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter <= (resultCol.Count - 1); counter++)
{
string UserNameEmailString = string.Empty;
result = search.FindOne();
if ((result.Properties.Contains("samaccountname") && result.Properties.Contains("usergroup")))
{
Korisnik korisnik = new Korisnik();
korisnik.Ime = ((string)(result.Properties["samaccountname"][0]));
korisnik.Prezime = ((string)(result.Properties["displayname"][0]));
korisnik.AccountExpired = (DateTime)result.Properties["userAccountControl"][0];
korisnik.PassNevExp = ((bool)result.Properties["PasswordExpirationDate"][0]);
korisnik.DomenskaGrupa = ((string)(result.Properties["DomainGroup"][0]));
DataRow dr = resultsTable.NewRow();
dr["samaccountname"] = korisnik.Ime;
dr["displayname"] = korisnik.Prezime;
dr["userAccountControl"] = korisnik.AccountExpired;
dr["PasswordExpirationDate"] = korisnik.PassNevExp;
dr["DomainGroup"] = korisnik.DomenskaGrupa;
resultsTable.Rows.Add(dr);
lstADUsers.Add(korisnik);
}
}
var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
var res = json;
Console.WriteLine(resultCol);
Console.ReadLine();
File.WriteAllText(output, json);
}
return resultsTable;
}
When I call function to Main I get error
Foreach statement cannot operate on variables of type 'DataTable'
because 'DataTable' does not contain a public instance definition for
'GetEnumerator'
foreach (Korisnik korisnik in VratiKorisnike())
{
Console.WriteLine(korisnik);
}
I try something like this:
foreach(DataTable dt in VratiKorisnike())
{
Console.WriteLine(dt);
}
The error is VratiKorisnike()
Any idea how to resolve this issue ?
To use a DataTable as an IEnumerable<DataRow>, you need to use Linq To DataSet, in perticular AsEnumerable
foreach (DataRow row in VratiKorisnike().AsEnumerable())
{
string displayName = row.Field<string>("displayname")
...
}
You need to use the Rows property:
foreach (var korisnik in VratiKorisnike().Rows)
It Represents a collection of rows for a DataTable, and . Actually it will compiles like this and as you can see, because of GetEnumerator you can use your loop with that:
IEnumerator enumerator = VratiKorisnike().Rows.GetEnumerator();
try
{
while (enumerator.MoveNext())
{
DataRow value = (DataRow)enumerator.Current;
Console.WriteLine(value);
}
}
finally
{
IDisposable disposable = enumerator as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
I would like to write the result of a SELECT query in Cassandra into a CSV file. Any help, please. I am just new to C#. Here is what I did. Any help to write the result into CSV file? Thanks
Cluster cluster = Cluster.Builder().AddContactPoint("127.0.0.1").Build();
List<string> lstOfKeyspaces = cluster.Metadata.GetKeyspaces().ToList<string>();
ISession session = cluster.Connect("test");
//get tables in the keysapce
List<string> lstString = cluster.Metadata.GetTables("test").ToList<string>();
Console.WriteLine("Connection succeeded");
// Console.ReadLine();
// RowSet resultRequest = session.Execute(" select * from integrationobjects.emp");
//Execute a query on a connection synchronously
var rs = session.Execute("SELECT * FROM emp");
Here is the solution
List<string> lstColumnName = new List<string>();
string strPath = System.IO.Directory.GetCurrentDirectory();
try
{
Cluster cassandraCluster = Cluster.Builder().AddContactPoint(strIpAddress).Build();
ISession session = cassandraCluster.Connect(strKeyspace);
string strCqlRequest = "SELECT * FROM" + " " + strTable;
RowSet rs = session.Execute(strCqlRequest);
using (var w = new StreamWriter(strPathToSave))
{
//get table columns with types
TableMetadata t = cassandraCluster.Metadata.GetTable(strKeyspace,strTable);
TableColumn[] arrcol = t.TableColumns;
foreach (var strCol in arrcol)
{
lstColumnName.Add(strCol.Name);
}
IDictionary<string,TableColumn> dic =t.ColumnsByName;
//Add column liste to the file
var strColumnLine = String.Join(",", lstColumnName.ToArray());
w.WriteLine(strColumnLine);
//Iterate through the RowSet and add rows to the file
foreach (Row row in rs)
{
List<string> values = new List<string>();
IEnumerator<Object> colEnumerator = row.GetEnumerator();
while (colEnumerator.MoveNext())
{
values.Add(colEnumerator.Current.ToString());
}
var line = String.Join(",", values.ToArray());
w.WriteLine(line);
w.Flush();
}
}
How to get a list users in Task Manager with status?
I found only how to get a list of domain users
var usersSearcher = new ManagementObjectSearcher(#"SELECT * FROM Win32_UserAccount");
var users = usersSearcher.Get();
You can try this code to get the list of users:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_UserAccount");
var managementObjects = usersSearcher.Get();
List<string> result = new List<string>();
foreach (ManagementObject item in managementObjects)
{
foreach (var pr in item.Properties)
{
if (pr.Name == "Caption")
{
result.Add(pr.Value?.ToString());
}
}
}
var users = result.Distinct().ToList();
Also you may try this:
var usersSearcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Process");
var managementObjects = usersSearcher.Get();
List<string> allUsers = new List<string>();
foreach (ManagementObject obj in managementObjects)
{
string[] argList = new string[] { string.Empty, string.Empty };
int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));
if (returnVal == 0)
{
// return DOMAIN\user
allUsers.Add(argList[1] + "\\" + argList[0]);
}
}
var result = allUsers.Distinct().ToList();
I have two list (1st with values from a website, 2nd with values from a .csv file) and I'd like to join them in another list, starting two equals values, and display it in a datagridview.
Before to post the code, I'd like to say that I tried to fill my datagridview with these two lists separately and they work.
I didn't get any error, but I can't see my datagridview with values.
I'm going to post my code and explain it.
First List Code:
var url = textBox5.Text;
//var url = "http://www.betexplorer.com/soccer/norway/tippeligaen/results/";
var web = new HtmlWeb();
var doc = web.Load(url);
Bets = new List<Bet>();
// Lettura delle righe
var Rows = doc.DocumentNode.SelectNodes("//tr");
foreach (var row in Rows)
{
if (!row.GetAttributeValue("class", "").Contains("rtitle"))
{
if (string.IsNullOrEmpty(row.InnerText))
continue;
var rowBet = new Bet();
foreach (var node in row.ChildNodes)
{
var data_odd = node.GetAttributeValue("data-odd", "");
if (string.IsNullOrEmpty(data_odd))
{
if (node.GetAttributeValue("class", "").Contains("first-cell"))
{
rowBet.Match = node.InnerText.Trim();
var matchTeam = rowBet.Match.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
rowBet.Home = matchTeam[0];
rowBet.Host = matchTeam[1];
}
if (node.GetAttributeValue("class", "").Contains("result"))
{
rowBet.Result = node.InnerText.Trim();
var matchPoints = rowBet.Result.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
int help;
if (int.TryParse(matchPoints[0], out help))
{
rowBet.HomePoints = help;
}
if (matchPoints.Length == 2 && int.TryParse(matchPoints[1], out help))
{
rowBet.HostPoints = help;
}
}
if (node.GetAttributeValue("class", "").Contains("last-cell"))
rowBet.Date = node.InnerText.Trim();
}
else
{
rowBet.Odds.Add(data_odd);
}
}
if (!string.IsNullOrEmpty(rowBet.Match))
Bets.Add(rowBet);
}
}
Second List & Combined List Code:
string FileName = #"C:\mydir\testcsv.csv";
OleDbConnection conn = new OleDbConnection
("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " +
Path.GetDirectoryName(FileName) +
"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter
("SELECT * FROM " + Path.GetFileName(FileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
conn.Close();
// DataTable dt = new DataTable();
DataTable dt = ds.Tables[0];
//dataGridView2.DataSource = dt;
// dataGridView2.DataMember = "Table";
List<HT> matchlist = new List<HT>();
matchlist = (from DataRow dr in dt.Rows
select new HT()
{
Home = dr["Home"].ToString().Replace("Milan", "AC Milan").Replace("Roma", "AS Roma"),
Host = dr["Host"].ToString().Replace("Milan", "AC Milan").Replace("Roma", "AS Roma"),
ScoreHome = dr["ScoreHome"].ToString(),
ScoreAway = dr["ScoreAway"].ToString(),
//Segno = dr["Segno"].ToString(),
//odd1 = dr["odd1"].ToString(),
//oddx = dr["oddx"].ToString(),
//odd2 = dr["odd2"].ToString()
}).ToList();
// dataGridView2.DataSource = matchlist;
var combinedDataList = (from d1 in Bets
//join d2 in dataList2 on d1.Home equals d2.Home
join d2 in matchlist on new { d1.Home, d1.Host } equals new { d2.Home, d2.Host }
select new CombinedData
{
Data = d1.Date,
Home = d1.Home,
Away = d1.Host,
HSFT = d1.HomePoints,
ASFT = d1.HostPoints,
HSHT = d2.ScoreHome,
ASHT = d2.ScoreAway,
HODD = d1.odd1,
XODD = d1.oddX,
AODD = d1.odd2,
RisFin = d1.RisFin,
Over05SH = d1.over05sh,
Over05FT = d1.Over05FT,
Over15FT = d1.Over15FT,
Over25FT = d1.Over25FT,
Over35FT = d1.Over35FT,
Over45FT = d1.Over45FT
}).OrderBy(p => p.HODD);
dataGridView2.DataSource = combinedDataList;
Thank you for your attention. Have a fantastic sunday!
EDIT: I delete unnecessary code
EDIT2: I add the screen of my single list output. Let's see:
First List:
Second List:
So, I'd like to merge "ScoreHome" and "ScoreAway" from the second list in my first list based on "Home" and "Host" that I have in both lists.
I though the following code would work but every time I look at file.Item; it is null. Should I be doing something different?
Microsoft.Office.Server.Search.Query.FullTextSqlQuery query = new Microsoft.Office.Server.Search.Query.FullTextSqlQuery(siteCollection);
query.QueryText = "SELECT Title, Path, Description, Write, Rank, Size from scope() where \"scope\" = 'SocialNetworking'";
query.ResultTypes = Microsoft.Office.Server.Search.Query.ResultType.RelevantResults;
//query.RowLimit = Int32.MaxValue;
query.TrimDuplicates = true;
query.EnableStemming = false;
query.IgnoreAllNoiseQuery = true;
query.KeywordInclusion = Microsoft.Office.Server.Search.Query.KeywordInclusion.AllKeywords;
query.Timeout = 0x2710;
query.HighlightedSentenceCount = 3;
query.SiteContext = new Uri(siteCollection.Url);
query.AuthenticationType = Microsoft.Office.Server.Search.Query.QueryAuthenticationType.NtAuthenticatedQuery;
Microsoft.Office.Server.Search.Query.ResultTableCollection queryResults = query.Execute();
Microsoft.Office.Server.Search.Query.ResultTable queryResultsTable = queryResults[Microsoft.Office.Server.Search.Query.ResultType.RelevantResults];
DataTable queryDataTable = new DataTable();
queryDataTable.Load(queryResultsTable, LoadOption.OverwriteChanges);
foreach (DataRow dr in queryDataTable.Rows)
{
//if (dr["ContentType"].ToString() == "Item")
//{
using (SPSite lookupSite = new SPSite(dr["Path"].ToString()))
{
using (SPWeb web = lookupSite.OpenWeb())
{
SPFile file = web.GetFile(dr["Path"].ToString());
SPListItem li = file.Item;
}
}
//}
}
If you know it is an item try SPWeb.GetListItem
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spweb.getlistitem.aspx
The file might also not exist, check SPFile.Exists before using any of SPFile's properties
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfile.exists.aspx