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()".
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
}
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 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!