setting system time based on the calculated datetime in c# - c#

i have copied the code , i have a variable ("Modifiedtime_1.Modifiedtime") i want to change system time with the datetime available in (Modifiedtime_1.Modifiedtime) whenever
if (compare == 0 || compare > 0)
{
Modifiedtime_1.Modifiedtime = Max.AddMinutes(5);
Console.WriteLine("----------");
Console.WriteLine("modifiedtime");
Console.WriteLine(Modifiedtime_1.Modifiedtime);
Console.WriteLine("----------");
}
Loop is executed.
Thanks in adavnce.
using System;
using System.Management;
using System.Threading;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace datetime_1
{
public class RemoteConnect
{
public class Modifiedtime_1
{
public static DateTime? Modifiedtime = null;
}
public static void Main()
{
while (true)
{
Console.WriteLine(DateTime.Now.ToString());
Console.WriteLine("\a");
Thread.Sleep(1000);
Console.Clear();
ConnectionOptions options = new ConnectionOptions();
options.EnablePrivileges = true;
options.Impersonation = ImpersonationLevel.Impersonate;
options.Authentication = AuthenticationLevel.Packet;
options.Authority = "ntlmdomain:node1.local";
options.Username = "user1";
options.Password = "xxxxxx";
ManagementScope scope = new ManagementScope(string.Format(#"\\node1\root\cimv2"), options);
scope.Connect();
if (scope.IsConnected == true)
{
Console.WriteLine("node1 Connection Succeeded");
}
else
{
Console.WriteLine("node1 Connection Failed");
}
ConnectionOptions options1 = new ConnectionOptions();
options1.EnablePrivileges = true;
options1.Impersonation = ImpersonationLevel.Impersonate;
options1.Authentication = AuthenticationLevel.Packet;
options1.Authority = "ntlmdomain:node2.local";
options1.Username = "user2";
options1.Password = "xxxxxx";
ManagementScope scope1 = new ManagementScope(string.Format(#"\\node2\root\cimv2"), options1);
scope1.Connect();
if (scope1.IsConnected == true)
{
Console.WriteLine("node2 Connection Succeeded");
}
else
{
Console.WriteLine("node2 Connection Failed");
}
ConnectionOptions options3 = new ConnectionOptions();
options3.EnablePrivileges = true;
options3.Impersonation = ImpersonationLevel.Impersonate;
options3.Authentication = AuthenticationLevel.Packet;
options3.Authority = "ntlmdomain:WORKGROUP";
options3.Username = "user2";
options3.Password = "xxxx";
ManagementScope scope3 = new ManagementScope(string.Format(#"\\node3\root\cimv2"), options3);
scope3.Connect();
if (scope3.IsConnected == true)
{
Console.WriteLine("node3 Connection Succeeded");
}
else
{
Console.WriteLine("node3 Connection Failed");
}
ConnectionOptions options4 = new ConnectionOptions();
options4.EnablePrivileges = true;
options4.Impersonation = ImpersonationLevel.Impersonate;
options4.Authentication = AuthenticationLevel.Packet;
options4.Authority = "ntlmdomain:Workgroup";
options4.Username = "user4";
options4.Password = "xxxxxx";
ManagementScope scope4 = new ManagementScope(string.Format(#"\\node4\root\cimv2"), options4);
scope4.Connect();
if (scope4.IsConnected == true)
{
Console.WriteLine("node4 Connection Succeeded");
}
else
{
Console.WriteLine("node4 Connection Failed");
}
DateTime Localdatetime = DateTime.Now;
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_LocalTime");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node1");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj["Year"], queryObj["Month"], queryObj["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj["Hour"], queryObj["Minute"], queryObj["Second"]);
String node1_Hour_TEMP = queryObj["Hour"].ToString();
String node1_Minute_TEMP = queryObj["Minute"].ToString();
String node1_SECOND_TEMP = queryObj["Second"].ToString();
String node1_Year_TEMP = queryObj["Year"].ToString();
String node1_Month_TEMP = queryObj["Month"].ToString();
String node1_Day_TEMP = queryObj["Day"].ToString();
ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(scope1, query);
foreach (ManagementObject queryObj1 in searcher1.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node2");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj1["Year"], queryObj1["Month"], queryObj1["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj1["Hour"], queryObj1["Minute"], queryObj1["Second"]);
String node2_Hour_TEMP = queryObj1["Hour"].ToString();
String node2_Minute_TEMP = queryObj1["Minute"].ToString();
String node2_SECOND_TEMP = queryObj1["Second"].ToString();
String node2_Year_TEMP = queryObj1["Year"].ToString();
String node2_Month_TEMP = queryObj1["Month"].ToString();
String node2_Day_TEMP = queryObj1["Day"].ToString();
ManagementObjectSearcher searcher2 =
new ManagementObjectSearcher(scope3, query);
foreach (ManagementObject queryObj2 in searcher2.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node3");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj2["Year"], queryObj2["Month"], queryObj2["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj2["Hour"], queryObj2["Minute"], queryObj2["Second"]);
String node3_Hour_TEMP = queryObj2["Hour"].ToString();
String node3_Minute_TEMP = queryObj2["Minute"].ToString();
String node3_SECOND_TEMP = queryObj2["Second"].ToString();
String node3_Year_TEMP = queryObj2["Year"].ToString();
String node3_Month_TEMP = queryObj2["Month"].ToString();
String node3_Day_TEMP = queryObj2["Day"].ToString();
ObjectQuery query4 = new ObjectQuery("SELECT * FROM Win32_LocalTime");
ManagementObjectSearcher searcher4 = new ManagementObjectSearcher(scope4, query);
foreach (ManagementObject queryObj4 in searcher4.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("node4");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Date: {0}-{1}-{2}", queryObj4["Year"], queryObj4["Month"], queryObj4["Day"]);
Console.WriteLine("Time: {0}:{1}:{2}", queryObj4["Hour"], queryObj4["Minute"], queryObj4["Second"]);
String node4_Hour_TEMP = queryObj4["Hour"].ToString();
String node4_Minute_TEMP = queryObj4["Minute"].ToString();
String node4_SECOND_TEMP = queryObj4["Second"].ToString();
String node4_Year_TEMP = queryObj4["Year"].ToString();
String node4_Month_TEMP = queryObj4["Month"].ToString();
String node4_Day_TEMP = queryObj4["Day"].ToString();
//Convert DATE Time String to INT
int node1_Hour;
int.TryParse(node1_Hour_TEMP, out node1_Hour);
int node1_Minute;
int.TryParse(node1_Minute_TEMP, out node1_Minute);
int node1_SECOND;
int.TryParse(node1_SECOND_TEMP, out node1_SECOND);
int node1_YEAR;
int.TryParse(node1_Year_TEMP, out node1_YEAR);
int node1_MONTH;
int.TryParse(node1_Month_TEMP, out node1_MONTH);
int node1_DAY;
int.TryParse(node1_Day_TEMP, out node1_DAY);
DateTime node1_DATE = new DateTime(node1_YEAR, node1_MONTH, node1_DAY, node1_Hour, node1_Minute, node1_SECOND);
//Convert DATE Time String to INT
int node2_Hour;
int.TryParse(node2_Hour_TEMP, out node2_Hour);
int node2_Minute;
int.TryParse(node2_Minute_TEMP, out node2_Minute);
int node2_SECOND;
int.TryParse(node2_SECOND_TEMP, out node2_SECOND);
int node2_YEAR;
int.TryParse(node2_Year_TEMP, out node2_YEAR);
int node2_MONTH;
int.TryParse(node2_Month_TEMP, out node2_MONTH);
int node2_DAY;
int.TryParse(node2_Day_TEMP, out node2_DAY);
DateTime node2_DATE = new DateTime(node2_YEAR, node2_MONTH, node2_DAY, node2_Hour, node2_Minute, node2_SECOND);
//Convert DATE Time String to INT
int node3_Hour;
int.TryParse(node3_Hour_TEMP, out node3_Hour);
int node3_Minute;
int.TryParse(node3_Minute_TEMP, out node3_Minute);
int node3_SECOND;
int.TryParse(node3_SECOND_TEMP, out node3_SECOND);
int node3_YEAR;
int.TryParse(node3_Year_TEMP, out node3_YEAR);
int node3_MONTH;
int.TryParse(node3_Month_TEMP, out node3_MONTH);
int node3_DAY;
int.TryParse(node3_Day_TEMP, out node3_DAY);
DateTime node3_DATE = new DateTime(node3_YEAR, node3_MONTH, node3_DAY, node3_Hour, node3_Minute, node3_SECOND);
//Convert DATE Time String to INT
int node4_Hour;
int.TryParse(node4_Hour_TEMP, out node4_Hour);
int node4_Minute;
int.TryParse(node4_Minute_TEMP, out node4_Minute);
int node4_SECOND;
int.TryParse(node4_SECOND_TEMP, out node4_SECOND);
int node4_YEAR;
int.TryParse(node4_Year_TEMP, out node4_YEAR);
int node4_MONTH;
int.TryParse(node4_Month_TEMP, out node4_MONTH);
int node4_DAY;
int.TryParse(node4_Day_TEMP, out node4_DAY);
DateTime node4_DATE = new DateTime(node4_YEAR, node4_MONTH, node4_DAY, node4_Hour, node4_Minute, node4_SECOND);
Console.WriteLine("LocalDateTime");
Console.WriteLine(Localdatetime);
Console.WriteLine("=====LINQ=====");
var Max = new[] { node1_DATE, node2_DATE, node3_DATE, node4_DATE }.Max();
Console.WriteLine(Max);
Console.WriteLine("=====LINQEND=====");
//compare datetime with local.
int compare = DateTime.Compare(Max, Localdatetime);
if (compare == 0 || compare > 0)
{
Modifiedtime_1.Modifiedtime = Max.AddMinutes(5);
Console.WriteLine("----------");
Console.WriteLine("modifiedtime");
Console.WriteLine(Modifiedtime_1.Modifiedtime);
Console.WriteLine("----------");
}
else
{
Modifiedtime_1.Modifiedtime = Localdatetime;
Console.WriteLine("----------");
Console.WriteLine("modifiedtime");
Console.WriteLine(Modifiedtime_1.Modifiedtime);
Console.WriteLine("----------");
}
}
}
}
}
}
}
}
}

Why not just do something like this
Before your infinite loop.
bool firstPass = true;
Inside your loop
... Work out what Modifiedtime_1.Modifiedtime value is.
and at the end of the loop
if ( firstPass || (..times deviated to much calculation))
{
firstPass = false;
SetLocalMachineTimeMethod(Modifiedtime_1.Modifiedtime);
}
where SetLocalMachineTimeMethod is some routine you call to set the time locally. There is also a possibility of the added refinement of checking the modified time and (local system time) to see if they have drifted apart by too much and then allow the call be be made again.

Related

Get ids on windows

I have an error that I cannot solve, not even searching the internet.
My code:
public static void GetClasses(ref List<ListViewItem> items)
{
ManagementPath path = new ManagementPath(string.Format("\\\\{0}\\ROOT\\CIMV2", SystemInformation.ComputerName.ToUpperInvariant()));
ConnectionOptions options = new ConnectionOptions
{
EnablePrivileges = true,
Impersonation = ImpersonationLevel.Impersonate,
Authentication = AuthenticationLevel.Default,
Username = null,
SecurePassword = null
};
ManagementScope managementScope = new ManagementScope(path, options);
managementScope.Connect();
ObjectGetOptions options2 = new ObjectGetOptions();
new ManagementScope(new ManagementObject(managementScope, path, options2).Path, options);
ObjectQuery query = new ObjectQuery("SELECT * FROM meta_class WHERE __Class LIKE \"%%%\" AND NOT __Class LIKE \"[_][_]%\" AND NOT __Class LIKE \"Win32_Perf%\" AND NOT __Class LIKE \"MSFT[_]%\"");
EnumerationOptions options3 = new EnumerationOptions
{
EnumerateDeep = true,
UseAmendedQualifiers = true
};
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(managementScope, query, options3);
new List<WMIClass>();
foreach (ManagementClass managementClass in from ManagementClass currentClass in managementObjectSearcher.Get()
orderby currentClass.ClassPath.ClassName
select currentClass)
{
bool flag = false;
// using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())
using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
{
while (enumerator2.MoveNext())
{
if (enumerator2.Current.Type == CimType.String)
{
flag = true;
}
}
}
if (flag)
{
WMIClass wmiclass = new WMIClass(managementClass);
ListViewItem listViewItem = new ListViewItem
{
Name = wmiclass.DisplayName,
Text = wmiclass.DisplayName,
ToolTipText = wmiclass.Description,
Tag = wmiclass
};
listViewItem.SubItems.Add(wmiclass.Description);
items.Add(listViewItem);
}
}
}
Error line:
using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
// using (ManagementObjectCollection.ManagementObjectEnumerator enumerator2 = disks.GetEnumerator())
I don't know what the mistake is. If you can help me please I don't understand the language very well.
I would greatly appreciate your help.
Try changing
using (PropertyDataCollection.PropertyDataEnumerator enumerator2 = ManagementClass.Properties.GetEnumerator())
{
while (enumerator2.MoveNext())
{
if (enumerator2.Current.Type == CimType.String)
{
flag = true;
}
}
}
to
PropertyDataCollection.PropertyDataEnumerator enumerator2 = managementClass.Properties.GetEnumerator();
while (enumerator2.MoveNext())
{
if (enumerator2.Current.Type == CimType.String)
{
flag = true;
}
}
First, "using" must be removed because GetEnumerator() does not return a disposable object and second, use "managementClass.Properties.GetEnumerator()" instead of "ManagementClass.Properties.GetEnumerator()".

Bindling User details from AD using LDAP (in c#) takes time --13mins for 7500 records approx .Need advice for code to improve the performance

I have got a request from a client to fetch all client user details from AD and finally dump to a db so that they can use it for reporting.
I have used DirectoryEntry and PrincipalContext class to retrieve all the information.The user volume is approx 7500 and and for each user i am binding 35 AD attributes in a list of object.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.IO;
using AccountCheck;
using Microsoft.ActiveDirectory.Management.Commands;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.ComponentModel;
namespace testproj1
{
class Class1
{
//private static DateTime LonTS1;
//static void Main(string[] args)
// public static int LoadADUsers()
static void Main(string[] args)
{
int userCount = 0;
int maxPasswordAge = 90;
string LDAP_QUERY = "LDAP://DC=xyz,DC=com";
string LDAP_FILTER = "(&(objectClass=user)(objectCategory=person))";
//string LDAP_FILTER = "(&(objectCategory=person)(objectClass=user)(!userAccountControl:1.2.840.113556.1.4.803:=2))";
DirectoryEntry objDirEntry = new DirectoryEntry(LDAP_QUERY);
string[] aryPropertiesToRetrieve =
{"sAMAccountName","Company","whenCreated","department","description","Enabled","displayName","distinguishedName","mail","employeeID","accountExpires", "extensionAttribute11", "extensionAttribute12",
"extensionAttribute13", "extensionAttribute14","extensionAttribute7", "extensionAttribute9","givenName" ,"Initials","title","location","sn","LastLogoff","LastLogon","manager","ChangePasswordAtLogon",
"physicalDeliveryOfficeName", "pwdLastSet","PasswordNeverExpires","PasswordNotRequired","nTSecurityDescriptor","ProtectedFromAccidentalDeletion","usercannotchangepassword","userAccountControl","userPrincipalName","lastlogontimestamp",
};
List<string> adPropertyList = new List<string>(aryPropertiesToRetrieve);
DirectorySearcher objSearch = new DirectorySearcher(objDirEntry, LDAP_FILTER, aryPropertiesToRetrieve);
objSearch.Asynchronous = true;
objSearch.PageSize = 500;
objSearch.SizeLimit = 1000;
objSearch.SearchScope = SearchScope.Subtree;
SearchResultCollection objResults = objSearch.FindAll();
User adUser = new User();
List<User> allUsers = new List<User>();
//NewADObjectParameterSet na = new NewADObjectParameterSet();
//string SQL = string.Empty;
int userAccountControl = 0;
DateTime accountExpiration = DateTime.Now;
//DateTime? accountExpiration;
DateTime passwordLastSet = DateTime.Now;
int daysUntilPasswordExpiration = 0;
DateTime passwordExpiration = DateTime.Now;
int daysUntilAccountExpiration = 0;
double passwordAge = 0;
DateTime? LLon=null;
string Mgr;
bool MCPANL;
string pfcd;
foreach (SearchResult result in objResults)
{
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, GetPropertyValue(result, "sAMAccountName").ToString());
//accountExpiration = (DateTime)GetPropertyValue_name(result, "accountExpires", "displayName", "sAMAccountName");
//accountExpiration = (DateTime)GetPropertyValue(result, "accountExpires");
accountExpiration = (DateTime)GetPropertyValue(result, "accountExpires");
//accountExpiration = user.AccountExpirationDate.HasValue ? (DateTime)user.AccountExpirationDate : (DateTime?)null;
daysUntilAccountExpiration = accountExpiration.Subtract(DateTime.Now).Days;
userAccountControl = (int)GetPropertyValue(result, "userAccountControl");
passwordLastSet = (DateTime)GetPropertyValue(result, "pwdLastSet");
pfcd = (string)GetPropertyValue(result, "ProtectedFromAccidentalDeletion");
if (passwordLastSet == null)
{ MCPANL = true; }
else { MCPANL = false; }
Mgr = GetPropertyValue(result, "manager").ToString();
if (Mgr == "" || Mgr == null)
{ Mgr = ""; }
else
{ Mgr = Mgr.Substring(3, Mgr.IndexOf(",") - 3); }
//LLoff = (string)GetPropertyValue(result, "LastLogoff");
// LLon = user.LastLogon.HasValue ? (DateTime)user.LastLogon : (DateTime?) null;
LLon = user.LastLogon;
if (userAccountControl > 10000) //password never expires
{
daysUntilPasswordExpiration = daysUntilAccountExpiration;
passwordExpiration = accountExpiration;
}
else
{
passwordAge = DateTime.Now.Subtract(passwordLastSet).TotalDays;
daysUntilPasswordExpiration = maxPasswordAge - (int)Math.Round(passwordAge + 1);
passwordExpiration = DateTime.Now.AddDays(daysUntilPasswordExpiration);
}
adUser = new User()
{
Name = GetPropertyValue(result, "sAMAccountName").ToString(),
Company = GetPropertyValue(result, "Company").ToString(),
Creation_Date = GetPropertyValue(result, "whenCreated").ToString(),
Department = GetPropertyValue(result, "department").ToString(),
Description = GetPropertyValue(result, "description").ToString(),
Enabled = user.Enabled,
Display_Name = GetPropertyValue(result, "displayName").ToString(),
Distinguished_Name = GetPropertyValue(result, "distinguishedName").ToString(),
Email = GetPropertyValue(result, "mail").ToString(),
EmployeeID = GetPropertyValue(result, "employeeID").ToString(),
Expiration_Date = accountExpiration,
extensionAttribute11 = GetPropertyValue(result, "extensionAttribute11").ToString(),
extensionAttribute12 = GetPropertyValue(result, "extensionAttribute12").ToString(),
extensionAttribute13_Room = GetPropertyValue(result, "extensionAttribute13").ToString(),
extensionAttribute14_Ext = GetPropertyValue(result, "extensionAttribute14").ToString(),
extensionAttribute7_IAM_ID = GetPropertyValue(result, "extensionAttribute7").ToString(),
extensionAttribute9_CostCenter = GetPropertyValue(result, "extensionAttribute9").ToString(),
First_Name = GetPropertyValue(result, "givenName").ToString(),
Initials = GetPropertyValue(result, "Initials").ToString(),
Job_Title = GetPropertyValue(result, "title").ToString(),
//Last_Known_Location = GetPropertyValue(result, "location").ToString(),
Last_Name = GetPropertyValue(result, "sn").ToString(),
// lastLogoff = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddTicks(LLoff),
//lastLogoff=
lastLogon = LLon,
Manager = Mgr,
Must_Change_Password_At_Next_Logon = MCPANL,
Office = GetPropertyValue(result, "physicalDeliveryOfficeName").ToString(),
Password_Age_In_Days = passwordAge,
Password_Expiration_Date = passwordExpiration,
Password_Last_Changed = passwordLastSet,
Password_Never_Expire = user.PasswordNeverExpires,
Password_Not_Required = user.PasswordNotRequired,
physicalDeliveryOfficeName = GetPropertyValue(result, "physicalDeliveryOfficeName").ToString(),
//Protected_From_Accidental_Deletion = GetPropertyValue(result, "ProtectedFromAccidentalDeletion").ToString(),
User_Cannot_Change_Password = user.UserCannotChangePassword,
userAccountControl = GetPropertyValue(result, "userAccountControl").ToString(),
Username = GetPropertyValue(result, "userPrincipalName").ToString(),
Username_pre_2000 = GetPropertyValue(result, "sAMAccountName").ToString(),
//lastLogon_value= LLonTS1
};
allUsers.Add(adUser);
userCount++;
//Console.WriteLine("the count is" + userCount);
// Console.ReadLine();
} // end foreach SearchResult loop
string connectionstring = ConfigurationManager.ConnectionStrings["LDAP_ALLUSER"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
string query = "truncate table [dbo].[adlook] ";
SqlCommand cmd1 = new SqlCommand(query, conn);
cmd1.ExecuteNonQuery();
SqlCommand cmd =
new SqlCommand(
"INSERT INTO [dbo].[ADlook] (name, company, creation_date,department,description,enabled,display_name,distinguished_name,email,employeeid,expiration_date,extensionattribute11,extensionattribute12,extensionattribute13_room,extensionattribute14_ext,extensionattribute7_iam_id,extensionattribute9_costcenter,first_name,initials,job_title,last_name,lastlogon,manager,must_change_password_at_next_logon,office,password_age_in_days,password_expiration_date,password_last_changed,password_never_expire,password_not_required,physicaldeliveryofficename,user_cannot_change_password,useraccountcontrol,username,username_pre_2000) " +
" VALUES (#name,#company,#creation_date,#department,#description,#enabled,#display_name,#distinguished_name,#email,#employeeid,#expiration_date,#extensionattribute11,#extensionattribute12,#extensionattribute13_room,#extensionattribute14_ext,#extensionattribute7_iam_id,#extensionattribute9_costcenter,#first_name,#initials,#job_title,#last_name,#lastlogon,#manager,#must_change_password_at_next_logon,#office,#password_age_in_days,#password_expiration_date,#password_last_changed,#password_never_expire,#password_not_required,#physicaldeliveryofficename,#user_cannot_change_password,#useraccountcontrol,#username,#username_pre_2000)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.Add("#name",DbType.String); cmd.Parameters.Add("#company",DbType.String); cmd.Parameters.Add("#creation_date",DbType.DateTime); cmd.Parameters.Add("#department",DbType.String); cmd.Parameters.Add("#description",DbType.String); cmd.Parameters.Add("#enabled",DbType.Boolean);
cmd.Parameters.Add("#display_name",DbType.String); cmd.Parameters.Add("#distinguished_name",DbType.String); cmd.Parameters.Add("#email",DbType.String); cmd.Parameters.Add("#employeeid",DbType.String); cmd.Parameters.Add("#expiration_date",DbType.DateTime); cmd.Parameters.Add("#extensionattribute11",DbType.String);
cmd.Parameters.Add("#extensionattribute12",DbType.String); cmd.Parameters.Add("#extensionattribute13_room",DbType.String); cmd.Parameters.Add("#extensionattribute14_ext",DbType.String); cmd.Parameters.Add("#extensionattribute7_iam_id",DbType.String); cmd.Parameters.Add("#extensionattribute9_costcenter",DbType.String); cmd.Parameters.Add("#first_name",DbType.String);
cmd.Parameters.Add("#initials",DbType.String); cmd.Parameters.Add("#job_title",DbType.String); cmd.Parameters.Add("#last_name",DbType.String); cmd.Parameters.Add("#lastlogon",DbType.DateTime); cmd.Parameters.Add("#manager",DbType.String); cmd.Parameters.Add("#must_change_password_at_next_logon",DbType.Boolean);
cmd.Parameters.Add("#office",DbType.String); cmd.Parameters.Add("#password_age_in_days",DbType.Int32); cmd.Parameters.Add("#password_expiration_date",DbType.DateTime); cmd.Parameters.Add("#password_last_changed",DbType.DateTime); cmd.Parameters.Add("#password_never_expire",DbType.Boolean); cmd.Parameters.Add("#password_not_required",DbType.Boolean);
cmd.Parameters.Add("#physicaldeliveryofficename",DbType.String); cmd.Parameters.Add("#user_cannot_change_password",DbType.Boolean); cmd.Parameters.Add("#useraccountcontrol",DbType.String); cmd.Parameters.Add("#username",DbType.String); cmd.Parameters.Add("#username_pre_2000",DbType.String);
foreach (var item in allUsers)
{
cmd.Parameters[0].Value = item.Name; cmd.Parameters[1].Value = item.Company; cmd.Parameters[2].Value = item.Creation_Date; cmd.Parameters[3].Value = item.Department; cmd.Parameters[4].Value = item.Description;
cmd.Parameters[5].Value = item.Enabled; cmd.Parameters[6].Value = item.Display_Name; cmd.Parameters[7].Value = item.Distinguished_Name; cmd.Parameters[8].Value = item.Email; cmd.Parameters[9].Value = item.EmployeeID;
cmd.Parameters[10].Value = item.Expiration_Date; cmd.Parameters[11].Value = item.extensionAttribute11; cmd.Parameters[12].Value = item.extensionAttribute12; cmd.Parameters[13].Value = item.extensionAttribute13_Room; cmd.Parameters[14].Value = item.extensionAttribute14_Ext;
cmd.Parameters[15].Value = item.extensionAttribute7_IAM_ID; cmd.Parameters[16].Value = item.extensionAttribute9_CostCenter; cmd.Parameters[17].Value = item.First_Name; cmd.Parameters[18].Value = item.Initials; cmd.Parameters[19].Value = item.Job_Title;
cmd.Parameters[20].Value = item.Last_Name;cmd.Parameters[21].Value = (object)item.lastLogon ?? DBNull.Value;cmd.Parameters[22].Value = item.Manager; cmd.Parameters[23].Value = item.Must_Change_Password_At_Next_Logon; cmd.Parameters[24].Value = item.Office;
cmd.Parameters[25].Value = item.Password_Age_In_Days; cmd.Parameters[26].Value = item.Password_Expiration_Date; cmd.Parameters[27].Value = item.Password_Last_Changed; cmd.Parameters[28].Value = item.Password_Never_Expire; cmd.Parameters[29].Value = item.Password_Not_Required;
cmd.Parameters[30].Value = item.physicalDeliveryOfficeName; cmd.Parameters[31].Value = item.User_Cannot_Change_Password; cmd.Parameters[32].Value = item.userAccountControl; cmd.Parameters[33].Value = item.Username; cmd.Parameters[34].Value = item.Username_pre_2000;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
///////////////////////////////////////// 1st method starts
private static object GetPropertyValue(SearchResult result, string propertyName)
{
object propValue = null;
if (result.Properties.Contains(propertyName))
{
if (result.Properties[propertyName].Count > 0)
{
propValue = result.Properties[propertyName][0];
if (propertyName == "accountExpires" || propertyName == "pwdLastSet")
{
long dateValue = (long)propValue;
long maxDate = DateTime.MaxValue.ToFileTime();
if (dateValue == 0 || dateValue > maxDate || dateValue == null) //never expires
{
propValue = Convert.ToDateTime("12/31/2100"); //new DateTime(2100, 12, 31);
}
else //expires
{
propValue = DateTime.FromFileTime(dateValue);
}
}
}
}
else
{
propValue = string.Empty;
}
return propValue;
}
////////////////////////////// 1st method ends
}
}
there are no errors as of now and it is just code that takes long to retrieve information.`
The code iterates each user and adds the to the object allUsers.
It takes approximately 13mins to add all users to this object which seems like a long time and will appreciate if someone can help me if i am doing anything wrong in coding part.
i have wrote a User class where all the property definitions are there and connection string to dump into db is being inherited from App.Config.
In the below code *****allUsers.Add(adUser)*****; is the part where it will add one by one user details and until it adds all users (almost 7500) , it takes at-least 14 mins of time.
Please help so that i can do any changes to code to make this process faster and i can add all user data in the object faster.
There is more than One way to Access LDAP Data and They perform diffrent in Diffrent enviorments. I use This Method and its pretty fast. May be you wanna give it a try.
var context = new PrincipalContext(ContextType.Domain, "yourdomainasaString");
var qbeUser = new UserPrincipal(context);
var searcher = new PrincipalSearcher(qbeUser);
foreach (DirectoryEntry de in searcher.FindAll().Select(x => x.GetUnderlyingObject()))
{
var tmpsid = de.Properties["objectSid"].Value;
var tmproles = de.Properties["memberof"].Value;
var IsActive = de.Properties["userAccountControl"][0].ToString() != "514";
//And So on
}

Wpf WMI Win32_Service Query

In my WPF application I need to get a list of Windows Services(~200) with a specific properties.
var result = new List<ServicesModel>();
ConnectionOptions connOptions = new ConnectionOptions
{
Impersonation = ImpersonationLevel.Impersonate,
EnablePrivileges = true,
};
ManagementScope manScope = new ManagementScope($#"\\{System.Environment.MachineName}\ROOT\CIMV2",
connOptions);
manScope.Connect();
SelectQuery query = new SelectQuery("SELECT * FROM Win32_Service");
using (var searcher = new ManagementObjectSearcher(manScope, query))
foreach (var o in searcher.Get())
{
var obj = (ManagementObject) o;
ServicesModel service = new ServicesModel
{
Name = obj["DisplayName"] as string,
Path = obj["PathName"] as string,
Description = obj["Description"] as string,
Pid = Convert.ToInt32(obj["ProcessId"]),
Status = obj["State"] as string,
StartMode = obj["StartMode"] as string,
LogOnAs = obj["StartName"] as string
};
result.Add(service);
}
return result;
It takes approximately ~1 minute to execute this method and return data which is unacceptable.
Looks like searcher.Get() takes all that time...
What I can do to improve execute/return time/performance?
Thanks
Based on the comments I came up with following, hope it might help someone:
public List<string> GetWindowsServicesList()
{
var result = new List<string>();
foreach (ServiceController service in ServiceController.GetServices())
{
string serviceName = service.ServiceName;
result.Add(serviceName);
}
return result;
}
public ServicesModel GetServiceProperties(string serviceName)
{
ServicesModel service = null;
string path = $"Win32_Service.Name=\"{serviceName}\"";
using (ManagementObject mngObj = new ManagementObject(path))
{
service = new ServicesModel
{
Name = mngObj.GetPropertyValue("Name") as string,
Path = mngObj.GetPropertyValue("PathName") as string,
Description = mngObj.GetPropertyValue("Description") as string,
Pid = Convert.ToInt32(mngObj.GetPropertyValue("ProcessId")),
Status = mngObj.GetPropertyValue("State") as string,
StartMode = mngObj.GetPropertyValue("StartMode") as string,
LogOnAs = mngObj.GetPropertyValue("StartName") as string
};
}
return service;
}
public List<ServicesModel> WindowsServicesCollection()
{
var result = new List<ServicesModel>();
try
{
var windowsServicesNames = GetWindowsServicesList();
for (int i = 0; i < windowsServicesNames.Count(); i++)
{
result.Add(GetServiceProperties(windowsServicesNames[i]));
}
}
catch (System.Management.ManagementException ex)
{
}
catch (System.TimeoutException ex)
{
}
return result;
}
Works much, much faster than previous solution although it seems like performance is not super consistent and it depends from some various factors that I did not identified...

A prepared String is not being saved completely when not debugging

I have a Program which should save permanently values to a .txt file. When I debug it by putting a breakpoint into the code it works fine. But when letting it work for a while it only saves the last value caught instead of the last 3.
The method ExecuteStrategy is being executed every minute.
Here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Bot_V1._0
{
public class SaveAllMinuteBarsStrategy : IStrategy
{
public Guid StrategyGuid { get; set; }
//private static string[] Data = new string[8];
private string DataDax { get; set; }
private string DataDow { get; set; }
private string DataOil { get; set; }
private string DataGold { get; set; }
private string DataSpy { get; set; }
private string DataEsd { get; set; }
private string DataEgp { get; set; }
private string DataUpy { get; set; }
private string xPath = #"G:\TradingBot\Saved Candles folder";
private DateTime firstEnter;
const char LF = '\n';
public SaveAllMinuteBarsStrategy (Guid StrategyCGuid)
{
this.StrategyGuid = StrategyGuid;
}
public List<ShareAndTimeRange> InitStrategy (Guid stratGuid)
{
firstEnter = DateTime.Now;
var Dax = new ShareAndTimeRange("DAX", 1, stratGuid, null, false);
var Dow = new ShareAndTimeRange("DOW", 1, stratGuid, null, false);
var Oil = new ShareAndTimeRange("OIL", 1, stratGuid, null, false);
var Gold = new ShareAndTimeRange("GOLD", 1, stratGuid, null, false);
var Spy = new ShareAndTimeRange("SPY", 1, stratGuid, null, false);
var Esd = new ShareAndTimeRange("EUR/USD", 1, stratGuid, null, false);
var Egb = new ShareAndTimeRange("EUR/GBP", 1, stratGuid, null, false);
var Ujp = new ShareAndTimeRange("USD/JPY", 1, stratGuid, null, false);
var ElementList = new List<ShareAndTimeRange>();
ElementList.Add(Dax);
ElementList.Add(Dow);
ElementList.Add(Oil);
ElementList.Add(Gold);
ElementList.Add(Spy);
ElementList.Add(Esd);
ElementList.Add(Egb);
ElementList.Add(Ujp);
return ElementList;
}
public void ExecuteStrategy(ShareAndTimeRange Share)
{
SaveDataHourly(Share);
}
private void SaveDataHourly(ShareAndTimeRange Share)
{
if (Share.Candle == null)
return;
var PreparedString = Share.Candle.Time.ToString("yyyyMMdd HHmmss") + ";";
PreparedString = PreparedString + Share.Candle.Open + ";" + Share.Candle.High + ";";
PreparedString = PreparedString + Share.Candle.Low + ";" + Share.Candle.Close;
PreparedString = PreparedString + LF;
switch (Share.ShareName)
{
case ("DAX"):
{
DataDax = DataDax + PreparedString;
//Data[0] = Data[0] +
bool reset = HDMYSaving(Share, DataDax);
if (reset)
DataDax = "";
break;
}
case ("DOW"):
{
DataDow = DataDow + PreparedString;
bool reset = HDMYSaving(Share, DataDow);
if (reset)
DataDow = "";
break;
}
case ("OIL"):
{
DataOil = DataOil + PreparedString;
bool reset = HDMYSaving(Share, DataOil);
if (reset)
DataOil = "";
break;
}
case ("GOLD"):
{
DataGold = DataGold + PreparedString;
bool reset = HDMYSaving(Share, DataGold);
if (reset)
DataGold = "";
break;
}
case ("SPY"):
{
DataSpy = DataSpy + PreparedString;
bool reset = HDMYSaving(Share, DataSpy);
if (reset)
DataSpy = "";
break;
}
case ("EUR/USD"):
{
DataEsd = DataEsd + PreparedString;
bool reset = HDMYSaving(Share, DataEsd);
if (reset)
DataEsd = "";
break;
}
case ("EUR/GBP"):
{
DataEgp = DataEgp + PreparedString;
bool reset = HDMYSaving(Share, DataEgp);
if (reset)
DataEgp = "";
break;
}
case ("USD/JPY"):
{
DataUpy = DataUpy + PreparedString;
bool reset = HDMYSaving(Share, DataUpy);
if (reset)
DataUpy = "";
break;
}
}
}
private void SavePersistentData (string FolderName , string FileName, string Share )
{
if (!System.IO.File.Exists(FolderName))
{
Directory.CreateDirectory(FolderName);
}
string fullPath = System.IO.Path.Combine(FolderName, FileName);
if (!System.IO.File.Exists(fullPath))
{
FileStream fs = File.Create(fullPath);
fs.Dispose();
}
using (StreamWriter sw = new StreamWriter(fullPath, false))
{
sw.Write(Share);
sw.Dispose();
}
//System.IO.File.WriteAllText(fullPath, Share);
}
private void SavePersistent (string ReadFolder , string WriteFolder , string WriteFolderFile)
{
DirectoryInfo ParDir = new DirectoryInfo(ReadFolder);
string dat = "";
foreach (var item in ParDir.GetFiles())
{
var elem = System.IO.Path.Combine(ReadFolder, item.Name);
dat += System.IO.File.ReadAllText(elem);
}
SavePersistentData(WriteFolder, WriteFolderFile, dat);
foreach (var item in ParDir.GetFiles())
{
var del = System.IO.Path.Combine(ReadFolder, item.Name);
File.Delete(del);
}
}
private bool HDMYSaving(ShareAndTimeRange Share, string Values)
{
if (Share.Candle == null)
return false;
bool toReset = false;
string SharePath = System.IO.Path.Combine(xPath, Share.ShareName);//c:\TradingBot\Saved Candles folder\"Sharename"\
string HourPath = System.IO.Path.Combine(SharePath, "Hour Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Hour Data
int res;
int resuzt = Math.DivRem(Share.Candle.Time.Minute,3,out res);
if ( res == 0) //0 Share.Candle.Time.Minute == 0
{
DateTime DateToWriteH = Share.Candle.Time;
string HourFilePath = DateToWriteH.ToString("yyyyMMddHHmm") + ".txt";
SavePersistentData(HourPath, HourFilePath, Values);
toReset = true;
}
DateTime DateToWriteD = Share.Candle.Time.AddDays(-1);
string DayPath = System.IO.Path.Combine(SharePath, "Day Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Day Data
string DayFilePath = System.IO.Path.Combine(DayPath, DateToWriteD.ToString("yyyyMMdd") + ".txt");
if (Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(DayFilePath))
{
SavePersistent(HourPath, DayPath, DateToWriteD.ToString("yyyyMMdd") + ".txt");
}
DateTime DateToWriteM = Share.Candle.Time.AddMonths(-1);
string MonthPath = System.IO.Path.Combine(SharePath, "Month Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Month Data
string MonthFilePath = System.IO.Path.Combine(MonthPath, DateToWriteM.ToString("yyyyMM") + ".txt");
if (Share.Candle.Time.Day == 1 && Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(MonthFilePath))
{
SavePersistent(DayPath, MonthPath, DateToWriteM.ToString("yyyyMM") + ".txt");
}
DateTime DateToWriteY = Share.Candle.Time.AddYears(-1);
string YearPath = System.IO.Path.Combine(SharePath, "Year Data");//c:\TradingBot\Saved Candles folder\"Sharename"\Year Data
string YearFilePath = System.IO.Path.Combine(YearPath, DateToWriteY.ToString("yyyy") + ".txt");
if (Share.Candle.Time.Month == 1 && Share.Candle.Time.Day == 1 && Share.Candle.Time.Hour == 0 && Share.Candle.Time.Minute == 0 && !System.IO.File.Exists(YearFilePath))
{
SavePersistent(MonthPath, YearPath, DateToWriteY.ToString("yyyy") + ".txt");
}
return toReset;
}
}
Is there a problem having a lot of Events which are fired every 2 seconds or every minute?
Thanks!!
i found the problem. It was on another Class. The Fault was firing an event every time the program colleted a new value, but the program schould wait for the other "WebsTakenInCare".
Here is the Code before:
if (DataList.Count() == WebsTakenInCare)
{
FinalizedData = ShortenUpData(DataList);
DataList.Clear();
}
BuildCandles(FinalizedData);
and after changing:
if (DataList.Count() == WebsTakenInCare)
{
FinalizedData = ShortenUpData(DataList);
DataList.Clear();
BuildCandles(FinalizedData);
}
else
return;
regards!

how to refresh management object

i had written a code to display the description(Name) of connected USB devices.once i removed a device,then i need to refresh the ManagementObject and have to display the connected device description.
Here is my Code,
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice");
foreach (ManagementObject mo in searcher.Get())
{
string str1 = mo["CurrentRefreshRate"].ToString();
Console.WriteLine(str1);
string dependent = mo["Dependent"].ToString();
string deviceId = dependent.Split('=')[1];
deviceId = deviceId.Replace('\"', '\'');
ManagementObjectSearcher searcher2 =
new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity Where DeviceID = " + deviceId);
foreach (ManagementObject mo2 in searcher2.Get())
{
HardwareDetails Detail = new HardwareDetails();
Detail.Description = mo2["Description"].ToString();
Detail.DeviceId = mo2["DeviceId"].ToString();
string[] str = Detail.DeviceId.Split('\\');
string Id = str[1];
if (Id.Contains('&'))
{
string[] separate = Id.Split('&');
Detail.Vid = separate[0].Contains('_') ? separate[0].Split('_')[1] : separate[0].Split('D')[1];
Detail.Pid = separate[1].Contains('_') ? separate[1].Split('_')[1] : separate[1].Split('D')[1];
//Detail.Pid = pid1[1];
}
else
{
Detail.Vid = "";
Detail.Pid = "";
}
if (list.Count > 0)
{
foreach (HardwareDetails h in list)
{
if (!(h.Description == Detail.Description))
{
list.Add(Detail);
break;
}
}
}
else
list.Add(Detail);
}
}
// remove duplicates, sort alphabetically and convert to array
HardwareDetails[] usbDevices = list.ToArray();
return usbDevices;
Did you try this?
WqlEventQuery query = new WqlEventQuery(
"SELECT * FROM Win32_DeviceChangeEvent");
ManagementEventWatcher watcher = new ManagementEventWatcher(query);
watcher.EventArrived +=
new EventArrivedEventHandler(HandleEvent);
// Start listening for events
watcher.Start();
.........
// Stop listening for events
watcher.Stop();
And in the HandleEvent add or remove device from the list
Hope this helps!

Categories