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...
I am using C# implementation of netsuite api from web reference com.netsuite.webservices
I released filter fileSearch.basic by name (you can see it commented) it is working fine.
Please help to write function to achieve all attached files for current user. Something is wrong in this code, it filters nothing and showing me all files as it is without any filter. Please help me.
public static void GetFileAttachmentByCustomerId(string customerId)
{
using (NetSuiteService netSuiteService = GetNetSuiteService())
{
FileSearch fileSearch = new FileSearch();
// this works fine (filter files by name)
//SearchStringField nameSearchParams = new SearchStringField
//{
// #operator = SearchStringFieldOperator.contains,
// operatorSpecified = true,
// searchValue = "some name",
//};
//fileSearch.basic = new FileSearchBasic() { name = nameSearchParams };
// this code not filter files at all
{
RecordRef nsCustomerRef = new RecordRef
{
internalId = customerId,
type = RecordType.customer,
typeSpecified = true,
};
SearchMultiSelectField shopperSearchParam = new SearchMultiSelectField
{
#operator = SearchMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new RecordRef[] { nsCustomerRef }
};
fileSearch.shopperJoin = new CustomerSearchBasic { internalId = shopperSearchParam };
}
SearchResult result = netSuiteService.search(fileSearch);
// Get connected objects
{
Customer customer = GetCustomerById(netSuiteService, customerId);
Account account = GetAccountById(netSuiteService, "301395"); //
Folder folder = GetFolderById(netSuiteService, "3962");
}
File file = (File)result.recordList.First();
byte[] fileContent = GetFileContentByInternalId(file.internalId);
}
}
.
Try this:
var nsCustomerRef = new RecordRef
{
internalId = "4",
type = RecordType.employee,
typeSpecified = true,
};
var currentUser = new SearchMultiSelectField()
{
operatorSpecified = true,
#operator = SearchMultiSelectFieldOperator.anyOf,
searchValue = new List<RecordRef>() {nsCustomerRef}.ToArray()
};
var fileSearchBasic = new FileSearchBasic() {owner = currentUser};
var fileSearch = new FileSearch() { basic = fileSearchBasic };
var result = netSuiteService.search(fileSearch);
var file = (File)result.recordList.First();
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.
How i can search by profile property? MSDN say use ProfileSearchManager, but it not working.
I want search users by MobilePhone property.
SPServiceContext serviceContext = SPServiceContext.GetContext(site);
UserProfileManager upm = new UserProfileManager(serviceContext);
ProfileSearchManager sp = ProfileSearchManager.GetProfileSearchManager(serviceContext);
string[] searchPattern = { "123" };
ProfileBase[] searchResults = sp.Search(searchPattern, ProfileSearchFlags.User);
foreach (ProfileBase profile in searchResults)
{
Console.WriteLine(profile.DisplayName);
}
using (SPSite site = new SPSite(siteUrl))
{
using (var qRequest = new KeywordQuery(site)
{
QueryText = "MobilePhone:*" +"123" ,
EnableQueryRules = true,
EnableSorting = false,
SourceId = new Guid("Enter here Result Source Guid"),
TrimDuplicates = false
})
{
//Get properties you want here
qRequest.SelectProperties.Add("FirstName");
qRequest.SelectProperties.Add("LastName");
SearchExecutor e = new SearchExecutor();
ResultTableCollection rt = e.ExecuteQuery(qRequest);
var tab = rt.Filter("TableType", KnownTableTypes.RelevantResults);
var result = tab.FirstOrDefault();
DataTable resultTable = result.Table;
}
}
I'm trying to get bit locker recovery information for all users from active directory via below functions.
I've tried many different solution but none of them solved my problem.
I can get most of the computer properties like Operation System,Service Pack expect bit locker info.
Is there any special permission or method to search with msFVE-RecoveryInformation ?
Method 1:
DirectoryEntry child = new DirectoryEntry("LDAP://XXXXX");
DirectoryEntries enteries = child.Children;
DirectorySearcher ds = new DirectorySearcher(child);
ds.Filter = "(&(objectCategory=Computer)(cn=computerName))";
ds.SearchScope = SearchScope.Subtree;
SearchResultCollection item = ds.FindAll();
//string dn = item.GetDirectoryEntry().Properties["distinguishedname"].Value.ToString();
string temp1 = System.DirectoryServices.AccountManagement.UserPrincipal.Current.DistinguishedName;
child = new DirectoryEntry(("LDAP://" + temp1), "XXXXX", "XXXXX");
enteries = child.Children;
ds = new DirectorySearcher(child);
ds.Filter = "(objectClass=msFVE-RecoveryInformation)";
ds.SearchScope = SearchScope.Subtree;
SearchResultCollection result = ds.FindAll();
if (result.Count > 0)
{
foreach (SearchResult sr in result)
{
string recoveryKeyPackage = sr.GetDirectoryEntry().Properties["msFVE-KeyPackage"].Value.ToString();
string recoveryGUID = sr.GetDirectoryEntry().Properties["msFVE-RecoveryGuid"].Value.ToString();
string recoveryPassword = sr.GetDirectoryEntry().Properties["msFVE-RecoveryPassword"].Value.ToString();
string recoveryVolumeGUID = sr.GetDirectoryEntry().Properties["msFVE-VolumeGuid"].Value.ToString();
}
}
else
{
Console.Write ("No recovery information found!");
}
Method 2:
public Dictionary<string, string> GetBitlockerKeys(string computerName)
{
DirectoryEntry dEntry = new DirectoryEntry("LDAP://XXXX");
var keys = new Dictionary<string, string>();
using (var computerObject = dEntry)
{
var children = computerObject.Children;
var schemaFilter = children.SchemaFilter;
schemaFilter.Add("msFVE-RecoveryInformation");
foreach (DirectoryEntry child in children) using (child)
{
var recoveryGuid = new Guid((byte[])child.Properties["msFVE-RecoveryGuid"].Value).ToString();
var recoveryPassword = child.Properties["msFVE-RecoveryPassword"].Value.ToString();
if (!keys.ContainsKey(recoveryGuid))
{
keys.Add(recoveryGuid, recoveryPassword);
}
}
}
return keys;
}