Compare data from ActiveDirectory and store to db - c#

Currently I create that ActiveDirectory user is store to file and it's working perfect. What I want for now is that I need to comapre data from ActiveDirectory and data from database and if status is 0 change it and store to database result. It means if account is active = 1 is not active = 0.
So far I create this
using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.IO;
namespace ActiverDirectory
{
public class Korisnik
{
public int Id { get; set; }
public string Username { get; set; } //samaccountname
public string DisplayName { get; set; } //displayname
public bool isEnabled { get; set; } //AccountExpires
public bool PassNevExp { get; set; } //PassExpires
}
class Program
{
static void Main(string[] args)
{
foreach (Korisnik korisnik in VratiKorisnike())
{
Console.WriteLine(korisnik);
}
}
public static List<Korisnik> VratiKorisnike()
{
List<Korisnik> lstADUsers = new List<Korisnik>();
string sDomainName = "saoos";
string DomainPath = "LDAP://" + sDomainName;
string constring = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
string Query = "SELECT * FROM tblZaposleni_AD";
DataTable table = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter(Query, constring);
adapter.Fill(table);
string txt = "";
string fileLoc = #"C:\output.txt";
foreach (DataRow row in table.Rows)
{
string line = "";
foreach (DataColumn column in table.Columns)
{
line += "," + row[column.ColumnName].ToString();
}
txt += line.Substring(1);
}
using (var sw = new StreamWriter(fileLoc))
{
sw.WriteLine(txt);
}
Console.WriteLine("Ok");
DirectoryEntry searchRoot = new DirectoryEntry(DomainPath);
DirectorySearcher search = new DirectorySearcher(searchRoot);
search.Filter = "(&(objectClass=user)(objectCategory=person))";
search.PropertiesToLoad.Add("samaccountname"); // Username
search.PropertiesToLoad.Add("displayname"); // display name
search.PropertiesToLoad.Add("userAccountControl"); // isEnabled
search.PropertiesToLoad.Add("pwdLastSet"); //passwordExpires
DataTable resultsTable = new DataTable();
resultsTable.Columns.Add("samaccountname");
resultsTable.Columns.Add("displayname");
resultsTable.Columns.Add("Neaktivan");
resultsTable.Columns.Add("dontexpirepassword");
SearchResult result;
SearchResultCollection resultCol = search.FindAll();
if (resultCol != null)
{
for (int counter = 0; counter < resultCol.Count; counter++)
{
string UserNameEmailString = string.Empty;
result = resultCol[counter];
if (result.Properties.Contains("samaccountname")
&& result.Properties.Contains("displayname"))
{
int userAccountControl = Convert.ToInt32(result.Properties["userAccountControl"][0]);
string samAccountName = Convert.ToString(result.Properties["samAccountName"][0]);
int isEnable;
int Dont_Expire_Password;
if (userAccountControl > 0)
{
isEnable = 0;
}
else
{
isEnable = 1;
}
if ((userAccountControl & 65536) != 0)
{
Dont_Expire_Password = 1;
}
else
{
Dont_Expire_Password = 0;
}
Korisnik korisnik = new Korisnik();
korisnik.Username = (result.Properties["samaccountname"][0]).ToString();
korisnik.DisplayName = result.Properties["displayname"][0].ToString();
korisnik.isEnabled = Convert.ToBoolean(result.Properties["userAccountControl"][0]);
//long value = (long)result.Properties["pwdLastSet"][0];
//DateTime pwdLastSet = DateTime.FromFileTimeUtc(value);
DataRow dr = resultsTable.NewRow();
dr["samaccountname"] = korisnik.Username.ToString();
dr["displayname"] = korisnik.DisplayName.ToString();
dr["neaktivan"] = Math.Abs(isEnable);
dr["dontexpirepassword"] = Dont_Expire_Password;
resultsTable.Rows.Add(dr);
lstADUsers.Add(korisnik);
}
}
var json = JsonConvert.SerializeObject(resultCol, Formatting.Indented);
var res = json;
Console.WriteLine("Ispis uspjesno obavljen");
Console.ReadLine();
File.WriteAllText(fileLoc, json);
}
return lstADUsers;
}
}
}
So far everything is here, I just need to store this to [db].[table]
This is some peace of code which check from ActiveDirectory if UserAccount is active or disable
If account is active in ActiveDirectory and in [db].[table] is inactive change status to 1 and store data. When I run this I get properly output, but status is not changed.
Any ideas

Try something like this :
public class Korisnik
{
public int Id { get; set; }
public string Username { get; set; } //samaccountname
public string DisplayName { get; set; } //displayname
private bool _isEnabled { get; set; } //AccountExpires
public int isEnabled {
get { return (_isEnabled == true)? 1 : 0;}
set { _isEnabled = (value == 0) ? false : true; }
} //AccountExpires
public bool PassNevExp { get; set; } //PassExpires
}

Related

How to read google sheet as a datatable in c#?

I searched on the Internet, but I didn’t find much, I need to read a Google sheet and get a datatable at the output. Please tell me how can I do this (I'm just learning)
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Dynamic;
namespace GoogleSheetsHelper
{
public class GoogleSheetsHelper
{
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
static string ApplicationName = "GoogleSheetsHelper";
private readonly SheetsService _sheetsService;
private readonly string _spreadsheetId;
public GoogleSheetsHelper(string credentialFileName, string spreadsheetId)
{
var credential = GoogleCredential.FromStream(new FileStream(credentialFileName, FileMode.Open)).CreateScoped(Scopes);
_sheetsService = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
_spreadsheetId = spreadsheetId;
}
public List<ExpandoObject> GetDataFromSheet(GoogleSheetParameters googleSheetParameters)
{
googleSheetParameters = MakeGoogleSheetDataRangeColumnsZeroBased(googleSheetParameters);
var range = $"{googleSheetParameters.SheetName}!{GetColumnName(googleSheetParameters.RangeColumnStart)}{googleSheetParameters.RangeRowStart}:{GetColumnName(googleSheetParameters.RangeColumnEnd)}{googleSheetParameters.RangeRowEnd}";
SpreadsheetsResource.ValuesResource.GetRequest request =
_sheetsService.Spreadsheets.Values.Get(_spreadsheetId, range);
var numberOfColumns = googleSheetParameters.RangeColumnEnd - googleSheetParameters.RangeColumnStart;
var columnNames = new List<string>();
var returnValues = new List<ExpandoObject>();
if (!googleSheetParameters.FirstRowIsHeaders)
{
for (var i = 0;i<=numberOfColumns;i++)
{
columnNames.Add($"Column{i}");
}
}
var response = request.Execute();
int rowCounter = 0;
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
foreach (var row in values)
{
if (googleSheetParameters.FirstRowIsHeaders && rowCounter == 0)
{
for (var i = 0; i <= numberOfColumns; i++)
{
columnNames.Add(row[i].ToString());
}
rowCounter++;
continue;
}
var expando = new ExpandoObject();
var expandoDict = expando as IDictionary<String, object>;
var columnCounter = 0;
foreach (var columnName in columnNames)
{
expandoDict.Add(columnName, row[columnCounter].ToString());
columnCounter++;
}
returnValues.Add(expando);
rowCounter++;
}
}
return returnValues;
}
public void AddCells(GoogleSheetParameters googleSheetParameters, List<GoogleSheetRow> rows)
{
var requests = new BatchUpdateSpreadsheetRequest {Requests = new List<Request>()};
var sheetId = GetSheetId(_sheetsService, _spreadsheetId, googleSheetParameters.SheetName);
GridCoordinate gc = new GridCoordinate
{
ColumnIndex = googleSheetParameters.RangeColumnStart - 1,
RowIndex = googleSheetParameters.RangeRowStart - 1,
SheetId = sheetId
};
var request = new Request {UpdateCells = new UpdateCellsRequest {Start = gc, Fields = "*"}};
var listRowData = new List<RowData>();
foreach (var row in rows)
{
var rowData = new RowData();
var listCellData = new List<CellData>();
foreach (var cell in row.Cells)
{
var cellData = new CellData();
var extendedValue = new ExtendedValue {StringValue = cell.CellValue};
cellData.UserEnteredValue = extendedValue;
var cellFormat = new CellFormat {TextFormat = new TextFormat()};
if (cell.IsBold)
{
cellFormat.TextFormat.Bold = true;
}
cellFormat.BackgroundColor = new Color { Blue = (float)cell.BackgroundColor.B/255, Red = (float)cell.BackgroundColor.R/255, Green = (float)cell.BackgroundColor.G/255 };
cellData.UserEnteredFormat = cellFormat;
listCellData.Add(cellData);
}
rowData.Values = listCellData;
listRowData.Add(rowData);
}
request.UpdateCells.Rows = listRowData;
// It's a batch request so you can create more than one request and send them all in one batch. Just use reqs.Requests.Add() to add additional requests for the same spreadsheet
requests.Requests.Add(request);
_sheetsService.Spreadsheets.BatchUpdate(requests, _spreadsheetId).Execute();
}
private string GetColumnName(int index)
{
const string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var value = "";
if (index >= letters.Length)
value += letters[index / letters.Length - 1];
value += letters[index % letters.Length];
return value;
}
private GoogleSheetParameters MakeGoogleSheetDataRangeColumnsZeroBased(GoogleSheetParameters googleSheetParameters)
{
googleSheetParameters.RangeColumnStart = googleSheetParameters.RangeColumnStart - 1;
googleSheetParameters.RangeColumnEnd = googleSheetParameters.RangeColumnEnd - 1;
return googleSheetParameters;
}
private int GetSheetId(SheetsService service, string spreadSheetId, string spreadSheetName)
{
var spreadsheet = service.Spreadsheets.Get(spreadSheetId).Execute();
var sheet = spreadsheet.Sheets.FirstOrDefault(s => s.Properties.Title == spreadSheetName);
int sheetId = (int)sheet.Properties.SheetId;
return sheetId;
}
}
public class GoogleSheetCell
{
public string CellValue { get; set; }
public bool IsBold { get; set; }
public System.Drawing.Color BackgroundColor { get; set; } = System.Drawing.Color.White;
}
public class GoogleSheetParameters
{
public int RangeColumnStart { get; set; }
public int RangeRowStart { get; set; }
public int RangeColumnEnd { get; set; }
public int RangeRowEnd { get; set; }
public string SheetName { get; set; }
public bool FirstRowIsHeaders { get; set; } }
public class GoogleSheetRow
{
public GoogleSheetRow() => Cells = new List<GoogleSheetCell>();
public List<GoogleSheetCell> Cells { get; set; }
}
}

List of online AD users in domain network C#

There is a domain network with are connected computers.
Need a code that will display a list of Active Directory users connected to it now (using them / connected remotely).
Something similar to the "Users" tab in Task Manager, only for a domain network.
I tried to do this with WMI.
Classes Win32_LogonSession, Win32_LoggedOnUser, Win32_Account
The principle is this:
From active Win32_LogonSession weeded out LogonType = 2, 10 и 11.
By LogonId from Win32_LoggedOnUser get name and domain, search it in Win32_Account (to weed out system sessions) (Below there will be a code, maybe someone will come in handy)
But I ran into a problem : the event Session_onEnd is triggered far from 100% of cases, and LogOff seems not to be recorded at all, or is recorded incorrectly.
As a result, I get a lot of "hanging" sessions that users connect to, or create new ones when they log in. Analysis of the Windows event log in this regard does not give anything useful either. (LogOff is still incorrect)
So, if I can connect to a computer and get all the information out of it, how to extract - is it in use now and who is using it?
using System;
using System.Collections.Generic;
using System.Data;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.Linq;
using System.Management;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace UserManager
{
public partial class LogOnSession : Form
{
List<LogOnSessionR> SessionsList = new List<LogOnSessionR>();
List<LoggedOnUser> LoggedList = new List<LoggedOnUser>();
List<PC> CompList = new List<PC>();
public LogOnSession()
{
InitializeComponent();
}
private void LogOnSession_Load(object sender, EventArgs e)
{
if (Form1.SelfRef != null)
{
CBDomain.Items.Add("All Forest");
foreach (object a in Form1.SelfRef.CBDomain.Items)
{
CBDomain.Items.Add(a);
}
CBDomain.SelectedIndex = Form1.SelfRef.CBDomain.SelectedIndex;
}
GetComputersInDomain(CBDomain.SelectedIndex);
CBComputers.SelectedIndex = 0;
}
private void CBDomain_SelectedIndexChanged(object sender, EventArgs e)
{
LogOnListView.Items.Clear();
GetComputersInDomain(CBDomain.SelectedIndex);
}
public void GetComputersInDomain(int I)
{
CompList.Clear();
CBComputers.Items.Clear();
if (I == 0)
{
DirectoryEntry de = new DirectoryEntry();
DirectorySearcher myADSearcher = new DirectorySearcher(de);
myADSearcher.Filter = "(&(objectClass=computer))";
foreach (SearchResult sr in myADSearcher.FindAll())
{
PC pc = new PC();
pc.Name = removeCN(sr.GetDirectoryEntry().Name);
pc.IP = getPCIP(pc.Name);
CompList.Add(pc);
}
}
else
{
DirectoryEntry de = new DirectoryEntry("LDAP://" + Form1.ListDomain[I-1].Name);
DirectorySearcher myADSearcher = new DirectorySearcher(de);
myADSearcher.Filter = "(&(objectClass=computer))";
foreach (SearchResult sr in myADSearcher.FindAll())
{
PC pc = new PC();
pc.Name = removeCN(sr.GetDirectoryEntry().Name);
pc.IP = getPCIP(pc.Name);
CompList.Add(pc);
}
}
CBComputers.Items.Add("All");
foreach (PC pc in CompList)
{
CBComputers.Items.Add(pc.Name);
}
}
public string removeCN(string str)
{
if (str.Contains("CN="))
{
return str.Replace("CN=", "");
}
else
{
return str;
}
}
public string getPCIP(string hostName)
{
IPHostEntry hostEntry;
hostEntry = Dns.GetHostEntry(hostName);
if (hostEntry.AddressList.Length > 0)
{
return hostEntry.AddressList[0].ToString();
//you might get more than one ip for a hostname since
//DNS supports more than one record
}
return null;
}
private void RefreshL_Click(object sender, EventArgs e)
{
ViewResult(getInfo());
}
public void ViewResult(List<LogonUser> results)
{
LogOnListView.Items.Clear();
if (results.Count == 0) { return; }
int i = 0;
foreach (LogonUser result in results)
{
LogOnListView.Items.Add(i.ToString());
LogOnListView.Items[i].SubItems.Add(result.SamAccountName);
LogOnListView.Items[i].SubItems.Add(result.FullName);
LogOnListView.Items[i].SubItems.Add(result.Computer);
LogOnListView.Items[i].SubItems.Add(result.Domain);
LogOnListView.Items[i].SubItems.Add(result.StartTime.ToLocalTime().ToString());
LogOnListView.Items[i].SubItems.Add(cAD.LastLastLogon(getDN(result.SamAccountName)).ToLocalTime().ToString());
LogOnListView.Items[i].SubItems.Add(cAD.LastLastLogoff(getDN(result.SamAccountName)).ToLocalTime().ToString());
i++;
}
}
private string getDN(string samAccountName)
{
DirectoryEntry myADEntry = new DirectoryEntry();
DirectorySearcher myADSearcher = new DirectorySearcher(myADEntry);
myADSearcher.Filter = "(&(objectClass=user)(sAMAccountName=" + samAccountName + ")(!(objectClass=computer)))";
return myADSearcher.FindOne().GetDirectoryEntry().Properties["distinguishedName"].Value.ToString();
}
private List<LogonUser> getInfo()
{
List<LogonUser> LogonUserList = new List<LogonUser>();
ConnectionOptions options;
options = new ConnectionOptions();
//options.Username = "administrator";
//options.Password = "Parol-Admin";
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
if (CBComputers.SelectedIndex == 0)
{
foreach (PC pc in CompList)
{
if (pc.Name == Environment.MachineName)
{
LogonUserList.AddRange(getLogonUserList(pc, options, LocalWMIRequestLogOnSession(), LocalWMIRequestLoggedOnUser()));
}
else
{
LogonUserList.AddRange(getLogonUserList(pc, options, WMIRequestLogOnSession(pc.IP, options), WMIRequestLoggedOnUser(pc.IP, options)));
}
}
}
else
{
PC pc = CompList[CBComputers.SelectedIndex - 1];
if (pc.Name == Environment.MachineName)
{
LogonUserList.AddRange(getLogonUserList(pc, options, LocalWMIRequestLogOnSession(), LocalWMIRequestLoggedOnUser()));
}
else
{
LogonUserList.AddRange(getLogonUserList(pc, options, WMIRequestLogOnSession(pc.IP, options), WMIRequestLoggedOnUser(pc.IP, options)));
}
}
return LogonUserList;
}
private LogonUser FindInDomainController(PC pc, ConnectionOptions options, LoggedOnUser lou, LogOnSessionR losr)
{
try
{
List<PC> Controllers = new List<PC>();
if (CBDomain.SelectedIndex == 0)
{
foreach (GlobalCatalog contr in Form1.DsDomain.Forest.GlobalCatalogs)
{
PC Con = new PC();
Con.Name = contr.Name;
Con.IP = contr.IPAddress;
Controllers.Add(Con);
}
}
else
{
foreach (DomainController contr in Form1.ListDomain[CBDomain.SelectedIndex - 1].DomainControllers)
{
PC Con = new PC();
Con.Name = contr.Name;
Con.IP = contr.IPAddress;
Controllers.Add(Con);
}
}
LogonUser getlg;
foreach (PC Controller in Controllers)
{
ManagementScope scope;
if (Controller.Name == Environment.MachineName)
{
scope = new ManagementScope("\\root\\cimv2");
}
else
{
scope = new ManagementScope("\\\\" + Controller.IP + "\\root\\cimv2", options);
scope.Connect(); //
}
String queryString = "SELECT * FROM Win32_UserAccount WHERE Domain=\"" + getDomain(lou.Antecedent) + "\" AND Name=\"" + getsAmAccountName(lou.Antecedent) + "\"";
ObjectQuery query;
query = new ObjectQuery(queryString);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
var Temp = searcher.Get()
.Cast<ManagementObject>()
.Select(mo => new
{
Name = Convert.ToString(mo["Name"]),
FullName = Convert.ToString(mo["FullName"]),
AccountType = Convert.ToUInt32(mo["AccountType"]),
Caption = Convert.ToString(mo["Caption"]),
Description = Convert.ToString(mo["Description"]),
Disabled = Convert.ToBoolean(mo["Disabled"]),
Domain = Convert.ToString(mo["Domain"]),
InstallDate = Convert.ToDateTime(mo["InstallDate"]),
LocalAccount = Convert.ToBoolean(mo["LocalAccount"]),
Lockout = Convert.ToBoolean(mo["Lockout"]),
PasswordChangeable = Convert.ToBoolean(mo["PasswordChangeable"]),
PasswordExpires = Convert.ToBoolean(mo["PasswordExpires"]),
PasswordRequired = Convert.ToBoolean(mo["PasswordRequired"]),
SID = Convert.ToString(mo["SID"]),
SIDType = Convert.ToByte(mo["SIDType"]),
Status = Convert.ToString(mo["Status"])
}
).ToList();
if (Temp.Count == 0) { continue; }
// if (Temp.Count > 1) { throw new Exception("Найденно " + Temp.Count + " одинаковых пользователя"); }
getlg = new LogonUser()
{
AuthenticationPackage = losr.AuthenticationPackage,
Name = Temp[0].Name,
Domain = Temp[0].Domain,
Caption = Temp[0].Caption,
Description = Temp[0].Description,
InstallDate = Temp[0].InstallDate,
LogonId = losr.LogonId,
LogonType = losr.LogonType,
StartTime = losr.StartTime,
Status = Temp[0].Status,
Computer = pc.Name,
SamAccountName = getsAmAccountName(lou.Antecedent),
FullName = Temp[0].FullName,
AccountType = Temp[0].AccountType,
Enabled = !Temp[0].Disabled,
LocalAccount = Temp[0].LocalAccount,
Lockout = Temp[0].Lockout,
PasswordChangeable = Temp[0].PasswordChangeable,
PasswordExpires = Temp[0].PasswordExpires,
PasswordRequired = Temp[0].PasswordRequired,
SID = Temp[0].SID,
SIDType = Temp[0].SIDType
};
return getlg;
}
return null;
}
catch
{
}
return null;
}
public List<LogOnSessionR> LocalWMIRequestLogOnSession()
{
List<LogOnSessionR> ReqList = new List<LogOnSessionR>();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LogonSession WHERE LogonType = '2' OR LogonType = '10' OR LogonType = '11'");
var Temp = searcher.Get()
.Cast<ManagementObject>()
.Select(mo => new
{
AuthenticationPackage = Convert.ToString(mo["AuthenticationPackage"]),
Name = Convert.ToString(mo["Name"]),
Caption = Convert.ToString(mo["Caption"]),
Description = Convert.ToString(mo["Description"]),
InstallDate = (mo["InstallDate"] == null ? Convert.ToDateTime(mo["InstallDate"]) : ManagementDateTimeConverter.ToDateTime(mo["InstallDate"].ToString())),
LogonId = Convert.ToString(mo["LogonId"]),
LogonType = Convert.ToUInt32(mo["LogonType"]),
StartTime = (mo["StartTime"] == null ? Convert.ToDateTime(mo["StartTime"]) : ManagementDateTimeConverter.ToDateTime(mo["StartTime"].ToString())),
Status = Convert.ToString(mo["Status"])
}
).ToList();
foreach (var obj in Temp)
{
LogOnSessionR req = new LogOnSessionR();
req.AuthenticationPackage = obj.AuthenticationPackage;
req.Name = obj.Name;
req.Caption = obj.Caption;
req.Description = obj.Description;
req.InstallDate = obj.InstallDate;
req.LogonId = obj.LogonId;
req.LogonType = obj.LogonType;
req.StartTime = obj.StartTime;
req.Status = obj.Status;
ReqList.Add(req);
}
return ReqList;
}
public List<LoggedOnUser> LocalWMIRequestLoggedOnUser()
{
List<LoggedOnUser> ReqList = new List<LoggedOnUser>();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_LoggedOnUser");
var Temp = searcher.Get()
.Cast<ManagementObject>()
.Select(mo => new
{
Antecedent = Convert.ToString(mo["Antecedent"]),
Dependent = Convert.ToString(mo["Dependent"])
}
).ToList();
foreach (var obj in Temp)
{
LoggedOnUser req = new LoggedOnUser();
req.Antecedent = obj.Antecedent;
req.Dependent = obj.Dependent;
ReqList.Add(req);
}
return ReqList;
}
private string getLogonId(string dependent)
{
var start = "LogonId=\"";
var end = "\"";
var regEx = new Regex(String.Format("{0}(.*){1}", Regex.Escape(start), Regex.Escape(end)));
var match = regEx.Match(dependent);
return match.Groups[1].Value;
// "\\\\.\\root\\cimv2:Win32_LogonSession.LogonId=\"997\""
}
private string getDomain(string antecedent)
{
var start = "Domain=\"";
var end = "\",";
var regEx = new Regex(String.Format("{0}(.*){1}", Regex.Escape(start), Regex.Escape(end)));
var match = regEx.Match(antecedent);
return match.Groups[1].Value;
// "\\\\.\\root\\cimv2:Win32_Account.Domain=\"LAB\" AND Name=\"Administrator\""
}
private string getsAmAccountName(string antecedent)
{
var start = "Name=\"";
var end = "\"";
var regEx = new Regex(String.Format("{0}(.*){1}", Regex.Escape(start), Regex.Escape(end)));
var match = regEx.Match(antecedent);
return match.Groups[1].Value;
//
}
private List<LogonUser> getLogonUserList(PC pc, ConnectionOptions options, List<LogOnSessionR> sessionsList, List<LoggedOnUser> loggedList)
{
List<LogonUser> getList = new List<LogonUser>();
foreach (LoggedOnUser lou in loggedList)
{
foreach(LogOnSessionR losr in sessionsList)
{
if (losr.LogonId == getLogonId(lou.Dependent))
{
LogonUser temp = FindInDomainController(pc, options, lou, losr);
if (temp != null)
{
getList.Add(temp);
}
}
}
}
return getList;
}
public List<LogOnSessionR> WMIRequestLogOnSession(string ip, ConnectionOptions options)
{
List<LogOnSessionR> ReqList = new List<LogOnSessionR>();
try
{
ManagementScope scope;
scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", options);
scope.Connect();
String queryString = "SELECT * FROM Win32_LogonSession WHERE LogonType = '2' OR LogonType = '10' OR LogonType = '11'";
ObjectQuery query;
query = new ObjectQuery(queryString);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
var Temp = searcher.Get()
.Cast<ManagementObject>()
.Select(mo => new
{
AuthenticationPackage = Convert.ToString(mo["AuthenticationPackage"]),
Name = Convert.ToString(mo["Name"]),
Caption = Convert.ToString(mo["Caption"]),
Description = Convert.ToString(mo["Description"]),
InstallDate = (mo["InstallDate"] == null ? Convert.ToDateTime(mo["InstallDate"]) : ManagementDateTimeConverter.ToDateTime(mo["InstallDate"].ToString())),
LogonId = Convert.ToString(mo["LogonId"]),
LogonType = Convert.ToUInt32(mo["LogonType"]),
StartTime = (mo["StartTime"] == null ? Convert.ToDateTime(mo["StartTime"]) : ManagementDateTimeConverter.ToDateTime(mo["StartTime"].ToString())),
Status = Convert.ToString(mo["Status"])
}
).ToList();
foreach (var obj in Temp)
{
LogOnSessionR req = new LogOnSessionR();
req.AuthenticationPackage = obj.AuthenticationPackage;
req.Name = obj.Name;
req.Caption = obj.Caption;
req.Description = obj.Description;
req.InstallDate = obj.InstallDate;
req.LogonId = obj.LogonId;
req.LogonType = obj.LogonType;
req.StartTime = obj.StartTime;
req.Status = obj.Status;
ReqList.Add(req);
}
return ReqList;
}
catch
{
}
return new List<LogOnSessionR>();
}
public List<LoggedOnUser> WMIRequestLoggedOnUser(string ip, ConnectionOptions options)
{
List<LoggedOnUser> ReqList = new List<LoggedOnUser>();
try
{
ManagementScope scope;
scope = new ManagementScope("\\\\" + ip + "\\root\\cimv2", options);
scope.Connect();
String queryString = "SELECT * FROM Win32_LoggedOnUser";
ObjectQuery query;
query = new ObjectQuery(queryString);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
var Temp = searcher.Get()
.Cast<ManagementObject>()
.Select(mo => new
{
Antecedent = Convert.ToString(mo["Antecedent"]),
Dependent = Convert.ToString(mo["Dependent"])
}
).ToList();
foreach (var obj in Temp)
{
LoggedOnUser req = new LoggedOnUser();
req.Antecedent = obj.Antecedent;
req.Dependent = obj.Dependent;
ReqList.Add(req);
}
return ReqList;
}
catch
{
}
return new List<LoggedOnUser>();
}
private void label2_Click(object sender, EventArgs e)
{
}
}
public class PC
{
public string Name { get; set; }
public string IP { get; set; }
}
public class LoggedOnUser
{
public string Antecedent { get; set; }
public string Dependent { get; set; }
}
public class LogOnSessionR
{
public string AuthenticationPackage { get; set; }
public string Name { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
public System.DateTime InstallDate { get; set; }
public string LogonId { get; set; }
public UInt32 LogonType { get; set; }
public System.DateTime StartTime { get; set; }
public string Status { get; set; }
}
public class LogonUser
{
public string AuthenticationPackage { get; set; }
public string Name { get; set; }
public string Domain { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
public System.DateTime InstallDate { get; set; }
public string LogonId { get; set; }
public UInt32 LogonType { get; set; }
public System.DateTime StartTime { get; set; }
public string Status { get; set; }
public string Computer { get; set; }
public string SamAccountName { get; set; }
public string FullName { get; set; }
public uint AccountType { get; set; }
public bool? Enabled { get; set; }
public bool LocalAccount { get; set; }
public bool Lockout { get; set; }
public bool PasswordChangeable { get; set; }
public bool PasswordExpires { get; set; }
public bool PasswordRequired { get; set; }
public string SID { get; set; }
public byte SIDType { get; set; }
}
}
If you can connect to any computer in your domain network and get any info from it - this is security issue, that must be solved.
First of all, you must understand a security problem of your solution. Any computer than you can connect to may be attacked by hacker. There are similar precedents in my experience.
So, if you need to get any info from computer or server in your domain network - you must install some agent on every computer and server, where you want to get internal data of it state. This agent will be monitor computer/server by your rule sets and send information to some database or collecting system.
Microsoft has System Center Operations Manager with this architecture and purpose. You can develop own agents, or use powershell scrips + windows scheduler to collect any data from computer.
Do not implement your solution in domain network - it's bad. A better solution is to check which computers are included in the domain and which have agents from the monitoring database. And install agents on those computers on which they do not yet exist.
Any user account or group, that has a lot of rignts on domain objects (for example, all computers) - is security issue, that must be solved.
If you want to get any logged on users - you can check process explorer.exe - which user starts it.
So, if you use powershell script as agent to collect data, you can run
query user
It will display, for expample:
user |seance |ID |Staus |Idle time | logon time |
-----|----------|---|-------|----------|----------------|
user1|rdp-tcp |2 |Active | . |12/07/2020 10:20|
then you can store this data in you database, or another storage.
If you want to develop some agent, you can use Windows API, System.Runtime.InteropServices, like this, because your agent will can access this API.
Also, you can get users, which logged on computer by this
foreach (System.Management.ManagementObject Process in Processes.Get())
{
if (Process["ExecutablePath"] != null &&
System.IO.Path.GetFileName(Process["ExecutablePath"].ToString()).ToLower() == "explorer.exe" )
{
string[] OwnerInfo = new string[2];
Process.InvokeMethod("GetOwner", (object[])OwnerInfo);
Console.WriteLine(string.Format("Windows Logged-in Interactive UserName={0}", OwnerInfo[0]));
break;
}
}
Every user start process explorer.exe, and own it.
Also, you not need to store any sp

MVC Controller Action/dll only works in localhost

I have an MVC that takes values from a form, sends them to a dll, to have logic performed on them & assigned to a model. The model is then returned to the view. In localhost it is successful and I get the following result:
However when I publish the webapp to an azure instance, it doesn't return any of the values. You can see it here: http://levelupsite.azurewebsites.net/ or see the image here
Does anyone know what could cause this? I will attach the code below:
Controller:
[HttpPost]
public ActionResult CBC(System.Web.Mvc.FormCollection form, FFAC model)
{
//recieve values from form
var email = escapeCharactersspace((form["email"].ToString()));
var Gender = Convert.ToString(model.UserGender);
var UserID = escapeCharactersspace((form["username"].ToString()));
var Neutrophils = escapeCharactersspace(form["Neutrophils"]);
var Lymphocytes = escapeCharactersspace(form["Lympthocytes"]);
var Monocytes = escapeCharactersspace(form["Monocytes"]);
var Eosinophils = escapeCharactersspace(form["Eosinophils"]);
var Basophils = escapeCharactersspace(form["Basophils"]);
var Platelets = (escapeCharactersspace(form["Platelets"]));
var Haematocrit = escapeCharactersspace(form["Haematocrit"]);
var Haemoglobin = escapeCharactersspace(form["Haemoglobin"]);
var MCV = escapeCharactersspace(form["MCV"]);
var MCH = (escapeCharactersspace(form["MCH"]));
var MCHC = escapeCharactersspace(form["MCHC"]);
//turn form to array
decimal[] cbcInputs = { Convert.ToDecimal(Neutrophils), Convert.ToDecimal(Lymphocytes), Convert.ToDecimal(Monocytes), Convert.ToDecimal(Eosinophils), Convert.ToDecimal(Basophils), Convert.ToDecimal(Platelets), Convert.ToDecimal(Haematocrit), Convert.ToDecimal(Haemoglobin), Convert.ToDecimal(MCV), Convert.ToDecimal(MCH), Convert.ToDecimal(MCHC) };
//create instance of model
var scfiae = new FIAECBC();
//create instance of external class library
var fiae = new FIAEngine();
//send inputs & model instance to external class library to perform logic
fiae.setcbcvals(cbcInputs, UserID, Gender, scfiae);
//return the get results page
return View("GetResults", scfiae);
}
FIAEngine - dll that performs the logic
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SharedComponents;
using static SharedComponents.FIAECBC;
namespace FIAE
{
public class FIAEngine
{
decimal d_Neutrophils;
decimal d_Lymphocytes;
decimal d_Monocytes;
decimal d_Eosinophils;
decimal d_Basophils;
decimal d_Platelets;
decimal d_Haematocrit;
decimal d_Haemoglobin;
decimal d_MCV;
decimal d_MCH;
decimal d_MCHC;
string UserID;
string Gender;
string Neutrophils;
string Lymphocytes;
string Monocytes;
string Eosinophils;
string Basophils;
string Platelets;
string Haematocrit;
string Haemoglobin;
string MCV;
string MCH;
string MCHC;
string rag_Neutrophils;
string rag_Lymphocytes;
string rag_Monocytes;
string rag_Eosinophils;
string rag_Basophils;
string rag_Platelets;
string rag_Haematocrit;
string rag_Haemoglobin;
string rag_MCV;
string rag_MCH;
string rag_MCHC;
public void Setcbcfilevals(FIAECBC cbcmodel)
{
}
public void setcbcvals(decimal[] inputs, string _UserID, string _Gender, FIAECBC cbcmodel)
{
d_Neutrophils = inputs[0];
d_Lymphocytes = inputs[1];
d_Monocytes = inputs[2];
d_Eosinophils = inputs[3];
d_Basophils = inputs[4];
d_Platelets = inputs[5];
d_Haematocrit = inputs[6];
d_Haemoglobin = inputs[7];
d_MCV = inputs[8];
d_MCH = inputs[9];
d_MCHC = inputs[10];
UserID = _UserID;
Gender = _Gender;
Neutrophils = "Neutrophils";
Lymphocytes = "Lymphocytes";
Monocytes = "Monocytes";
Eosinophils = "Eosinophils";
Basophils = "Basophils";
Platelets = "Platelets";
Haematocrit = "Haematocrit";
Haemoglobin = "Haemoglobin";
MCV = "MCV";
MCH = "MCH";
MCHC = "MCHC";
rag_Neutrophils = "i";
rag_Lymphocytes = "i";
rag_Monocytes = "i";
rag_Eosinophils = "i";
rag_Basophils = "i";
rag_Platelets = "i";
rag_Haematocrit = "i";
rag_Haemoglobin = "i";
rag_MCV = "i";
rag_MCH = "i";
rag_MCHC = "i";
try
{
//male calculations
if (Gender == "Male")
{
rag_Neutrophils = FindMaleRAG(d_Neutrophils, 1);
rag_Lymphocytes = FindMaleRAG(d_Lymphocytes, 2);
rag_Monocytes = FindMaleRAG(d_Monocytes, 3);
rag_Eosinophils = FindMaleRAG(d_Eosinophils, 4);
rag_Basophils = FindfeMaleRAG(d_Basophils, 5);
rag_Platelets = FindMaleRAG(d_Platelets, 6);
rag_Haematocrit = FindMaleRAG(d_Haematocrit, 7);
rag_Haemoglobin = FindMaleRAG(d_Haemoglobin, 8);
rag_MCV = FindMaleRAG(d_MCV, 9);
rag_MCH = FindMaleRAG(d_MCH, 10);
rag_MCHC = FindMaleRAG(d_MCHC, 11);
//set view model values to the form values
cbcmodel.d_Neutrophils = d_Neutrophils;
cbcmodel.d_Lymphocytes = d_Lymphocytes;
cbcmodel.d_Monocytes = d_Monocytes;
cbcmodel.d_Eosinophils = d_Eosinophils;
cbcmodel.d_Basophils = d_Basophils;
cbcmodel.d_Platelets = d_Platelets;
cbcmodel.d_Haematocrit = d_Haematocrit;
cbcmodel.d_Haemoglobin = d_Haemoglobin;
cbcmodel.d_MCV = d_MCV;
cbcmodel.d_MCH = d_MCH;
cbcmodel.d_MCHC = d_MCHC;
cbcmodel.Neutrophils = Neutrophils;
cbcmodel.Lymphocytes = Lymphocytes;
cbcmodel.Monocytes = Monocytes;
cbcmodel.Eosinophils = Eosinophils;
cbcmodel.Basophils = Basophils;
cbcmodel.Platelets = Platelets;
cbcmodel.Haematocrit = Haematocrit;
cbcmodel.Haemoglobin = Haemoglobin;
cbcmodel.MCV = MCV;
cbcmodel.MCH = MCH;
cbcmodel.MCHC = MCHC;
cbcmodel.rag_Neutrophils = rag_Neutrophils;
cbcmodel.rag_Lymphocytes = rag_Lymphocytes;
cbcmodel.rag_Monocytes = rag_Monocytes;
cbcmodel.rag_Eosinophils = rag_Eosinophils;
cbcmodel.rag_Basophils = rag_Basophils;
cbcmodel.rag_Platelets = rag_Platelets;
cbcmodel.rag_Haematocrit = rag_Haematocrit;
cbcmodel.rag_Haemoglobin = rag_Haematocrit;
cbcmodel.rag_MCV = rag_MCV;
cbcmodel.rag_MCH = rag_MCH;
cbcmodel.rag_MCHC = rag_MCHC;
}
else if (Gender == "Female")
{
rag_Neutrophils = FindfeMaleRAG(d_Neutrophils, 1);
rag_Lymphocytes = FindfeMaleRAG(d_Lymphocytes, 2);
rag_Monocytes = FindfeMaleRAG(d_Monocytes, 3);
rag_Eosinophils = FindfeMaleRAG(d_Eosinophils, 4);
rag_Basophils = FindfeMaleRAG(d_Basophils, 5);
rag_Platelets = FindfeMaleRAG(d_Platelets, 6);
rag_Haematocrit = FindfeMaleRAG(d_Haematocrit, 7);
rag_Haemoglobin = FindfeMaleRAG(d_Haemoglobin, 8);
rag_MCV = FindfeMaleRAG(d_MCV, 9);
rag_MCH = FindfeMaleRAG(d_MCH, 10);
rag_MCHC = FindfeMaleRAG(d_MCHC, 11);
//set view model values to the form values
cbcmodel.d_Neutrophils = d_Neutrophils;
cbcmodel.d_Lymphocytes = d_Lymphocytes;
cbcmodel.d_Monocytes = d_Monocytes;
cbcmodel.d_Eosinophils = d_Eosinophils;
cbcmodel.d_Basophils = d_Basophils;
cbcmodel.d_Platelets = d_Platelets;
cbcmodel.d_Haematocrit = d_Haematocrit;
cbcmodel.d_Haemoglobin = d_Haemoglobin;
cbcmodel.d_MCV = d_MCV;
cbcmodel.d_MCH = d_MCH;
cbcmodel.d_MCHC = d_MCHC;
cbcmodel.Neutrophils = Neutrophils;
cbcmodel.Lymphocytes = Lymphocytes;
cbcmodel.Monocytes = Monocytes;
cbcmodel.Eosinophils = Eosinophils;
cbcmodel.Basophils = Basophils;
cbcmodel.Platelets = Platelets;
cbcmodel.Haematocrit = Haematocrit;
cbcmodel.Haemoglobin = Haemoglobin;
cbcmodel.MCV = MCV;
cbcmodel.MCH = MCH;
cbcmodel.MCHC = MCHC;
cbcmodel.rag_Neutrophils = rag_Neutrophils;
cbcmodel.rag_Lymphocytes = rag_Lymphocytes;
cbcmodel.rag_Monocytes = rag_Monocytes;
cbcmodel.rag_Eosinophils = rag_Eosinophils;
cbcmodel.rag_Basophils = rag_Basophils;
cbcmodel.rag_Platelets = rag_Platelets;
cbcmodel.rag_Haematocrit = rag_Haematocrit;
cbcmodel.rag_Haemoglobin = rag_Haematocrit;
cbcmodel.rag_MCV = rag_MCV;
cbcmodel.rag_MCH = rag_MCH;
cbcmodel.rag_MCHC = rag_MCHC;
}
}
catch (Exception ex)
{
}
//return inputs;
}
public string FindMaleRAG(decimal i, int x)
{
String connString = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLServerCon"]);
//for each row, do this
//find the threshld values
String thresholdquery = #"select * from dbo.malethreshold where ID = " + x;
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(thresholdquery, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//compare threshold values t posted values from form
string composite = Convert.ToString(reader[1]);
decimal redlow = Convert.ToDecimal(reader[2]);
decimal greenlow = Convert.ToDecimal(reader[3]);
decimal greenhigh = Convert.ToDecimal(reader[4]);
decimal redhigh = Convert.ToDecimal(reader[5]);
if (i < redlow)
{
// Red low
return ("red");
}
else if (i > redlow && i < greenlow)
{
// Amber Low
return ("orange");
}
else if (i >= greenlow && i <= greenhigh)
{
//green
return ("green");
}
else if (i > greenhigh && i < redhigh)
{
//amber high
return ("orange");
}
else if (i > redhigh)
{
// Redhigh
return ("red");
}
else
{
//sorting error
return ("error in sorting");
}
}
}
}
}
return ("sorting error");
}
public string FindfeMaleRAG(decimal i, int x)
{
String connString = Convert.ToString(ConfigurationManager.ConnectionStrings["SQLServerCon"]);
//for each row, do this
//find the threshld values
String thresholdquery = #"select * from dbo.malethreshold where ID = " + x;
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand command = new SqlCommand(thresholdquery, conn))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
//compare threshold values t posted values from form
string composite = Convert.ToString(reader[1]);
decimal redlow = Convert.ToDecimal(reader[2]);
decimal greenlow = Convert.ToDecimal(reader[3]);
decimal greenhigh = Convert.ToDecimal(reader[4]);
decimal redhigh = Convert.ToDecimal(reader[5]);
if (i < redlow)
{
// Red low
return ("red");
}
else if (i > redlow && i < greenlow)
{
// Amber Low
return ("orange");
}
else if (i >= greenlow && i <= greenhigh)
{
//green
return ("green");
}
else if (i > greenhigh && i < redhigh)
{
//amber high
return ("orange");
}
else if (i > redhigh)
{
// Redhigh
return ("red");
}
else
{
//sorting error
return ("error in sorting");
}
}
}
}
}
return ("sorting error");
}
}
}
FIAECBC model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace SharedComponents
{
public class FIAECBC
{
public string Neutrophils { get; set; }
public string Lymphocytes { get; set; }
public string Monocytes { get; set; }
public string Eosinophils { get; set; }
public string Basophils { get; set; }
public string Platelets { get; set; }
public string Haematocrit { get; set; }
public string Haemoglobin { get; set; }
public string MCV { get; set; }
public string MCH { get; set; }
public string MCHC { get; set; }
public decimal d_Neutrophils { get; set; }
public decimal d_Lymphocytes { get; set; }
public decimal d_Monocytes { get; set; }
public decimal d_Eosinophils { get; set; }
public decimal d_Basophils { get; set; }
public decimal d_Platelets { get; set; }
public decimal d_Haematocrit { get; set; }
public decimal d_Haemoglobin { get; set; }
public decimal d_MCV { get; set; }
public decimal d_MCH { get; set; }
public decimal d_MCHC { get; set; }
public string rag_Neutrophils { get; set; }
public string rag_Lymphocytes { get; set; }
public string rag_Monocytes { get; set; }
public string rag_Eosinophils { get; set; }
public string rag_Basophils { get; set; }
public string rag_Platelets { get; set; }
public string rag_Haematocrit { get; set; }
public string rag_Haemoglobin { get; set; }
public string rag_MCV { get; set; }
public string rag_MCH { get; set; }
public string rag_MCHC { get; set; }
public Gender UserGender { get; set; }
public static IEnumerable<SelectListItem> GetSelectItems()
{
yield return new SelectListItem { Text = "Male", Value = "Male" };
yield return new SelectListItem { Text = "Female", Value = "Female" };
}
public bool Bookkeeping { get; set; }
}
public enum Gender
{
Male,
Female
}
}

Insufficient Memory error being thrown

namespace Calendar
{
public partial class MainCalendar : Form
{
private JArray items;
private List<String> AMList = new List<String>();
private List<String> PMList = new List<String>();
private List<String> accessToCalendarFilepath = new List<String>();
private List<CalendarModel> people;
private List<List<CalendarModel>> managers = new List<List<CalendarModel>>();
private List<String> userSelection = new List<String>();
private bool authorizedAccess = false;
private String javaScriptFileContainingJSONObject = "";
public MainCalendar()
{
InitializeComponent();
var locationInformation = System.Environment.CurrentDirectory + Path.DirectorySeparatorChar + "location.json";
using (StreamReader file = File.OpenText(locationInformation))
using (JsonTextReader reader = new JsonTextReader(file))
{
JArray o = (JArray)JToken.ReadFrom(reader);
items = o;
}
foreach (var item in items.Children())
{
var itemProperties = item.Children<JProperty>();
// you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "name");
var myElementValue = myElement.Value; ////This is a JValue type
if(myElementValue.ToString().Contains("AM"))
{
AMList.Add(myElementValue.ToString());
}
if (myElementValue.ToString().Contains("PM"))
{
PMList.Add(myElementValue.ToString());
}
}
mondayAM.DataSource = AMList.ToArray();
tuesdayAM.DataSource = AMList.ToArray();
wednesdayAM.DataSource = AMList.ToArray();
thursdayAM.DataSource = AMList.ToArray();
fridayAM.DataSource = AMList.ToArray();
mondayPM.DataSource = PMList.ToArray();
tuesdayPM.DataSource = PMList.ToArray();
wednesdayPM.DataSource = PMList.ToArray();
thursdayPM.DataSource = PMList.ToArray();
fridayPM.DataSource = PMList.ToArray();
loadAccessControl("accesscontrol.json");
dateTimePicker1.AlwaysChooseMonday(dateTimePicker1.Value);
String dateSelected = dateTimePicker1.Value.ToShortDateString();
findManagerForSelectedDate(dateSelected);
}
public void loadAccessControl(String fileName)
{
var accessControlInformation = Environment.CurrentDirectory + Path.DirectorySeparatorChar + fileName;
List<AccessControl> accounts = JsonConvert.DeserializeObject<List<AccessControl>>(File.ReadAllText(accessControlInformation));
foreach (AccessControl account in accounts)
{
Console.WriteLine(account.accountName);
if (account.accountName.ToLower().Contains(Environment.UserName.ToLower()))
{
foreach (CalendarFile file in account.files)
{
// Console.WriteLine(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
accessToCalendarFilepath.Add(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "content" + Path.DirectorySeparatorChar + file.Filename);
}
break;
}
}
contentsOfFile();
}
private void contentsOfFile()
{
String line;
foreach(var file in accessToCalendarFilepath)
{
StreamReader contentsOfJSONFile = new StreamReader(file);
while((line = contentsOfJSONFile.ReadLine()) != null)
{
if(line.Contains("var "))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "[";
}
else if(line.Contains("];"))
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + "]";
}
else
{
javaScriptFileContainingJSONObject = javaScriptFileContainingJSONObject + line;
}
}
people = JsonConvert.DeserializeObject<List<CalendarModel>>((string)javaScriptFileContainingJSONObject);
managers.Add(people);
javaScriptFileContainingJSONObject = "";
}
}
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
List<String> managerNames = new List<String>();
foreach(var item in managers)
{
foreach (var subitem in item)
{
CalendarModel c = subitem;
Console.WriteLine(c.date);
c.name = new CultureInfo("en-US", false).TextInfo.ToTitleCase(c.name);
if (userSelection.Count > 0)
{
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name); // CRASHING HERE
//{"Exception of type 'System.OutOfMemoryException' was thrown."}
}
}
}
else
{
userSelection.Add(c.name);
}
}
}
Console.WriteLine();
}
I keep running out of memory.
The CalendarModel class:
namespace Calendar
{
class CalendarModel
{
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date")]
public string date { get; set; }
[JsonProperty("title")]
public string title { get; set; }
[JsonProperty("mondayAM")]
public string mondayAM { get; set; }
[JsonProperty("mondayPM")]
public string mondayPM { get; set; }
[JsonProperty("tuesdayAM")]
public string tuesdayAM { get; set; }
[JsonProperty("tuesdayPM")]
public string tuesdayPM { get; set; }
[JsonProperty("wednesdayAM")]
public string wednesdayAM { get; set; }
[JsonProperty("wednesdayPM")]
public string wednesdayPM { get; set; }
[JsonProperty("thursdayAM")]
public string thursdayAM { get; set; }
[JsonProperty("thursdayPM")]
public string thursdayPM { get; set; }
[JsonProperty("fridayAM")]
public string fridayAM { get; set; }
[JsonProperty("fridayPM")]
public string fridayPM { get; set; }
[JsonProperty("saturdayAM")]
public string saturdayAM { get; set; }
[JsonProperty("saturdayPM")]
public string saturdayPM { get; set; }
}
}
I keep crashing at
userSelection.Add(c.name)
Take a close look at what you are doing
foreach (var addedUser in userSelection.ToArray())
{
if (!addedUser.Contains(c.name))
{
userSelection.Add(c.name);
}
}
You are adding to userSelection in the userSelection loop
The test is on !addedUser.Contains
You should not even be able to do that but I think the ToArrray() is letting it happen
So you add Sally
Then then Mark
Then you add Mark again because in the loop Mark != Sally
You are not using List<String> managerNames = new List<String>();
private void findManagerForSelectedDate(String dateSelected)
{
dateSelected = dateTimePicker1.Value.ToShortDateString();
You pass in dateSelected, then overright with dateTimePicker1, and then you don't even use it
Most of you code makes very little sense to me

How to split data into datagridview

I need to split values from two columns into a datagridview.
You can see a screenshot of my values here:
I need to split match and result columns to have a column for every value.
This is my code:
Class:
using System;
using System.Collections.Generic;
namespace bexscraping
{
public class Bet
{
public string Match { get; set; }
public string Result { get; set; }
public List<string> Odds { get; set; }
public string Date { get; set; }
public Bet()
{
Odds = new List<string>();
}
public override string ToString()
{
String MatchInfo = String.Format("{0}: {1} -> {2}", Date, Match, Result);
String OddsInfo = String.Empty;
foreach (string d in Odds)
OddsInfo += " | " + d;
return MatchInfo + "\n" + OddsInfo;
}
}
}
form1:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace bexscraping
{
public partial class Form1 : Form
{
private List<Bet> Bets;
private Bet SelectedBet { get; set; }
public Form1()
{
InitializeComponent();
dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0) {
SelectedBet = (Bet)dataGridView1.SelectedRows[0].DataBoundItem;
if (SelectedBet.Odds.Count > 0) {
textBox1.Text = SelectedBet.Odds[0].ToString();
textBox2.Text = SelectedBet.Odds[1].ToString();
textBox3.Text = SelectedBet.Odds[2].ToString();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
LoadInfo();
if (Bets.Count > 0)
{
SelectedBet = Bets[0];
dataGridView1.DataSource = Bets;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0].ToString();
textBox2.Text = SelectedBet.Odds[1].ToString();
textBox3.Text = SelectedBet.Odds[2].ToString();
}
}
}
private void LoadInfo()
{
string url = "http://www.betexplorer.com/soccer/australia/northern-nsw/results/";
HtmlWeb web = new HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = web.Load(url);
Bets = new List<Bet>();
// Lettura delle righe
var Rows = doc.DocumentNode.SelectNodes("//tr");
foreach (HtmlNode row in Rows)
{
if (!row.GetAttributeValue("class", "").Contains("rtitle"))
{
if (string.IsNullOrEmpty(row.InnerText))
continue;
Bet rowBet = new Bet();
foreach (HtmlNode node in row.ChildNodes)
{
string 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("-", 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(":", StringSplitOptions.RemoveEmptyEntries);
rowBet.HomePoints = int.Parse(matchPoints[0];
rowBet.HostPoints = int.Parse(matchPoints[1];
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);
}
}
}
}
}
I hope you can help me. Thanks!
Ok after I try it this is working solution for me.
Probably its diferent namespace but all components have same name.
Form1 class
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HtmlAgilityPack;
namespace Test
{
public partial class Form1 : Form
{
private List<Bet> Bets;
public Form1()
{
InitializeComponent();
Form1_Load_1();
dataGridView1.SelectionChanged += DataGridView1_SelectionChanged;
}
private Bet SelectedBet { get; set; }
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
SelectedBet = (Bet) dataGridView1.SelectedRows[0].DataBoundItem;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0];
textBox2.Text = SelectedBet.Odds[1];
textBox3.Text = SelectedBet.Odds[2];
}
}
}
private void LoadInfo()
{
var url = "http://www.betexplorer.com/soccer/australia/northern-nsw/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);
}
}
}
private void Form1_Load_1()
{
LoadInfo();
if (Bets.Count > 0)
{
SelectedBet = Bets[0];
dataGridView1.DataSource = Bets;
if (SelectedBet.Odds.Count > 0)
{
textBox1.Text = SelectedBet.Odds[0];
textBox2.Text = SelectedBet.Odds[1];
textBox3.Text = SelectedBet.Odds[2];
}
}
}
}
}
Bets class
using System;
using System.Collections.Generic;
namespace Test
{
class Bet
{
public string Match { get; set; }
public string Result { get; set; }
public List<string> Odds { get; set; }
public string Date { get; set; }
public string Home { get; set; }
public string Host { get; set; }
public int HomePoints { get; set; }
public int HostPoints { get; set; }
public Bet()
{
Odds = new List<string>();
}
public override string ToString()
{
String MatchInfo = String.Format("{0}: {1} -> {2}", Date, Match, Result);
String OddsInfo = String.Empty;
foreach (string d in Odds)
OddsInfo += " | " + d;
return MatchInfo + "\n" + OddsInfo;
}
}
}

Categories