public bool DeleteDailyMail(int userID) { using (var dataContext = DataContextFactory.CreateDataContext()) { var mail = (from p in dataContext.Email where p.ID == userID select p).FirstOrDefault(); if (mail == null) { Logger.Instance.WriteEntry("Mailer_DeleteDailyMail: Cannot find mail to be added.", LogType.Warning); return(false); } mail.DailMail = false; try { dataContext.SubmitChanges(); dailyMails.Remove(new MailAddress(mail.Address, mail.ReceiverName)); return(true); } catch { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("Mailer_DeleteDailyMail: "); messageEx1.Append("Deleting of emailadress " + userID + " from DailyMail List failed."); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(false); } } }
public bool AddDailyMail(int mailID) { using (var db = DataContextFactory.CreateDataContext()) { Database.Email mail; try { mail = (from p in db.Email where p.ID == mailID select p).FirstOrDefault(); if (mail == null) { Logger.Instance.WriteEntry("Mailer_AddDailyMail: Cannot find mail to be added.", LogType.Warning); return(false); } mail.DailMail = true; db.SubmitChanges(); return(true); } catch { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("Mailer_AddDailyMail: "); messageEx1.Append("Adding of emailadress " + mailID + " to DailyMail List failed."); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(false); } } }
/// <summary> /// Changes the mail adress and the username of a given mail adress /// </summary> /// <param name="mailAdressOld"></param> /// <param name="userNameNew"></param> /// <param name="mailAdressNew"></param> /// <returns>true if the execution was done without errors.</returns> public bool ChangeEmail(int userID, string userNameNew, string mailAdressNew) { try { using (var dataContext = DataContextFactory.CreateDataContext()) { var user = (from q in dataContext.Email where q.ID == userID select q).FirstOrDefault(); if (user == null) { Logger.Instance.WriteEntry("Mailer_ChangeEmail: Cannot find the user.", LogType.Warning); return(false); } user.ReceiverName = userNameNew; user.Address = mailAdressNew; dataContext.SubmitChanges(); } return(true); } catch (Exception e) { Logger.Instance.WriteEntry("Mailer_ChangeEmail: Can't change email: " + e.StackTrace, LogType.Exception); return(false); } }
/* COMMENT by Yannic: This method is never used because there is a method MoveMonitoredSystemo*/ public bool AssignToOU(string monitoredSystemMAC, int newOUID) { using (var dataContext = DataContextFactory.CreateDataContext()) { try { var workstation = (from p in dataContext.MonitoredSystem where p.MacAddress == monitoredSystemMAC select p).FirstOrDefault(); if (workstation != null) { workstation.OrganizationalUnit.ID = newOUID; dataContext.SubmitChanges(); return(true); } else { return(false); } } catch (Exception e) { //logging exception var messageEx = new StringBuilder(); messageEx.Append("ClientWebService_AssignToOU: "); messageEx.Append("Can't assign" + monitoredSystemMAC + "to OU" + newOUID + ". " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception); return(false); } } }
/// <summary> /// 生成自动编号 /// </summary> /// <param name="prefix">自动生成编号的前缀</param> /// <param name="numberFormat">自动生成的编号中自增序列号的长度</param> /// <param name="type">自动编号的类型</param> /// <returns></returns> public string CreateNumber(string prefix, int serialLen, string type) { try { DataContext dc = DataContextFactory.CreateDataContext(ConnectStr, _MappingSource); AutoCreateNumber num = dc.GetTable <AutoCreateNumber>().SingleOrDefault(item => item.Prefix == prefix && item.NumberType == type); if (num == null) { num = new AutoCreateNumber() { Prefix = prefix, Number = 1, NumberType = type }; dc.GetTable <AutoCreateNumber>().InsertOnSubmit(num); } else { num.Number += 1; } dc.SubmitChanges(); return(num.Prefix + num.Number.ToString("D" + serialLen)); } catch (Exception ex) { LJH.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex); } return(null); }
public int?AddEMail(string emailAdress, string userName) { using (var dataContext = DataContextFactory.CreateDataContext()) { MISD.Server.Database.Email mail = new MISD.Server.Database.Email(); mail.Address = emailAdress; mail.ReceiverName = userName; mail.DailMail = false; dataContext.Email.InsertOnSubmit(mail); try { dataContext.SubmitChanges(); return(mail.ID); } catch { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("Mailer_AddEMail: "); messageEx1.Append("Adding of emailadress " + emailAdress + " of " + userName + " to MailList failed."); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(null); } } }
/// <summary> /// Create a new organisation unit, if the given parent exist. /// </summary> /// <param name="name">Name of the new organisation unit</param> /// <param name="parentFQDN">FQDN of the parent of this organisation unit</param> public int CreateOU(string name, string parentFQDN, DateTime updateTime) { using (var dataContext = DataContextFactory.CreateDataContext()) { try { var newOU = new OrganizationalUnit(); newOU.Name = name; newOU.LastUpdate = updateTime.Ticks; if (parentFQDN == null || parentFQDN.Length < 1) { newOU.Parent = null; newOU.LastUpdate = null; newOU.FQDN = newOU.Name; } else { var existParent = (from p in dataContext.OrganizationalUnit let parent = p.FQDN == parentFQDN where parent orderby p.Parent ascending select p).FirstOrDefault(); if (existParent == null) { newOU.Parent = null; newOU.LastUpdate = null; newOU.FQDN = newOU.Name; } else { newOU.FQDN = existParent.FQDN + "." + name; newOU.Parent = existParent.ID; } } dataContext.OrganizationalUnit.InsertOnSubmit(newOU); dataContext.SubmitChanges(); return(newOU.ID); } catch (Exception e) { //parentFQDN isn't in the db var messageEx1 = new StringBuilder(); messageEx1.Append("OUManager_CreateOU: "); messageEx1.Append("creating OU" + name + " with parent " + parentFQDN + " failed. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); // exception is used in the Client-Webservice to return that this OU isn't available throw new InvalidOperationException("Create OU. The parent FQDN dosn't exist."); } } }
/// <summary> /// Changes the parent ou of a given ou. /// </summary> /// <param name="ouID"></param> /// <param name="ouIDParent"></param> /// <returns></returns> public bool ChangeParent(int ouID, int?ouIDParent, DateTime updateTime) { try { using (var dataContext = DataContextFactory.CreateDataContext()) { var ou = (from q in dataContext.OrganizationalUnit where q.ID == ouID select q).FirstOrDefault(); if (ou != null && (ou.LastUpdate == null || ou.LastUpdate < updateTime.Ticks)) { ou.LastUpdate = updateTime.Ticks; if (ou != null && ouIDParent != null) { var parentOU = (from p in dataContext.OrganizationalUnit where p.ID == ouIDParent select p.ID).ToList(); if (parentOU.Count == 1) { ou.Parent = ouIDParent; dataContext.SubmitChanges(); } else { throw new ArgumentException("Parent OU deosn't exists"); } } else { ou.Parent = null; dataContext.SubmitChanges(); } } else if (ou == null) { Logger.Instance.WriteEntry("OUManager_ChangeParent: Can't find the OU to be changed.", LogType.Warning); return(false); } else { Logger.Instance.WriteEntry("OUManager_ChangeParent: Can't change parent OU. The UpdateTime is to late.", LogType.Warning); return(false); } } return(true); } catch (Exception e) { Logger.Instance.WriteEntry("OUManager_ChangeParent: Can't change parent OU. " + e.StackTrace + " " + e.Message + " " + e, LogType.Exception); return(false); } }
public bool AddMailObserver(int userID, List <string> mac) { if (mac == null) { return(false); } try { using (var dataContext = DataContextFactory.CreateDataContext()) { foreach (string i in mac) { var msID = (from q in dataContext.MonitoredSystem where q.MacAddress == i select q.ID).FirstOrDefault(); EmailObserver observer = new EmailObserver() { EmailID = userID, MonitoredSystemID = msID }; dataContext.EmailObserver.InsertOnSubmit(observer); dataContext.SubmitChanges(); // local caching. #region caching if (warningMails.ContainsKey(msID)) { List <MailAddress> list; if (warningMails.TryGetValue(msID, out list)) { warningMails.Remove(msID); } else { list = new List <MailAddress>(); } list.Add(new MailAddress(observer.Email.Address, observer.Email.ReceiverName)); warningMails.Add(msID, list); } #endregion } return(true); } } catch (Exception e) { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("Mailer_AddMailObserver: "); messageEx1.Append("Adding of MailObserver failed. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(false); } }
/// <summary> /// Updates the mapping state of a monitored system, if the mapping duration of this monitored system is out of date /// </summary> /// <param name="monitoredSystemID">MAC Adress of the monitored system to update</param> public void UpdateMappingState(string monitoredSystemMac) { try { using (var dataContext = DataContextFactory.CreateDataContext()) { var monitoredSystem = PrecompiledQueries.GetMonitoredSystemByMAC(dataContext, monitoredSystemMac); MappingState newState = MappingState.Critical; // Critical state if (monitoredSystem.CriticalEnd != null) { if (monitoredSystem.CriticalEnd < DateTime.Now.Ticks) { newState = MappingState.Warning; } } else { newState = MappingState.Warning; } // Warning state if (monitoredSystem.WarningEnd != null) { if (monitoredSystem.WarningEnd < DateTime.Now.Ticks) { newState = MappingState.OK; } } else { newState = MappingState.OK; } // Maintenance state if (PrecompiledQueries.GetMonitoredSystemMaintenanceModeByID(dataContext, monitoredSystem.ID)) { newState = MappingState.Maintenance; } monitoredSystem.Status = (byte)newState; dataContext.SubmitChanges(); } } catch (Exception e) { Logger.Instance.WriteEntry("ValueManager_UpdateMappingState: Can't update the mapping of workstation (MAC: " + monitoredSystemMac + "). " + e.StackTrace, LogType.Exception); } }
private OUManager() { //set root name rootName = "System"; #region check root organisation unit using (var dataContext = DataContextFactory.CreateDataContext()) { //create organisation unit root if necessary var root = (from ou in dataContext.OrganizationalUnit let name = ou.Name == "System" let parent = ou.Parent == null where name & parent select ou).ToList(); if (root.Count == 0) { //create root Database.OrganizationalUnit ouRoot = new OrganizationalUnit() { Name = "System", FQDN = "System", Parent = null }; dataContext.OrganizationalUnit.InsertOnSubmit(ouRoot); dataContext.SubmitChanges(); var messageInfo1 = new StringBuilder(); messageInfo1.Append("WorkstationWebservice_WorkstationWebservice: "); messageInfo1.Append("Organisation unit root created."); MISD.Core.Logger.Instance.WriteEntry(messageInfo1.ToString(), LogType.Info); } else if (root.Count > 1) { //logging warning. There are two roots var messageW1 = new StringBuilder(); messageW1.Append("WorkstationWebservice_WorkstationWebservice: "); messageW1.Append("Two organisation unit root in the database."); MISD.Core.Logger.Instance.WriteEntry(messageW1.ToString(), LogType.Warning); } //logging. Webservice start. var messageInfo2 = new StringBuilder(); messageInfo2.Append("Workstation webservice started."); MISD.Core.Logger.Instance.WriteEntry(messageInfo2.ToString(), LogType.Info); } #endregion }
static void Main(string[] args) { // These tasks are usually handled by my IoC bootstrapper new QueryExtensionsUtil().OnStartup(); new SumAsyncExtensionsUtil().OnStartup(); new AverageAsyncExtensionsUtil().OnStartup(); new DbSetExtensionsUtil().OnStartup(); new DataContextFactoryStartupTask().OnStartup(); // this would normally be injected on the constructor IDispatcher dispatcher = new Dispatcher(); using (var context = DataContextFactory.CreateDataContext()) { var query = new GetPeopleByFirstNameQuery("Alan"); PrintPeople(dispatcher.Get(query)); var command = new AddCommand <Person>(new Person { FirstName = "Alan", LastName = "Turing" }); dispatcher.QueueCommand(command); var mutableAlan = new Person { FirstName = "Alan", LastName = "Shepard" }; dispatcher.Add(mutableAlan); // Using an IDispatcher extension method context.SaveChanges(); PrintPeople(dispatcher.Get(query)); mutableAlan.LastName = "Alda"; dispatcher.QueueCommand(new UpdateCommand <Person>(mutableAlan)); // Not strictly needed PrintPeople(dispatcher.Get(query)); dispatcher.QueueCommand(new RemoveCommand <Person>(mutableAlan)); context.SaveChanges(); PrintPeople(dispatcher.Get(query)); } Console.Read(); }
public bool RemoveEMail(int userID) { using (var dataContext = DataContextFactory.CreateDataContext()) { var mail = (from p in dataContext.Email where (p.ID == userID) select p).FirstOrDefault(); if (mail == null) { Logger.Instance.WriteEntry("Mailer_RemoveEMail: Cannot find the email to be removed.", LogType.Warning); return(false); } //save user to delete from local cache MailAddress m = new MailAddress(mail.Address, mail.ReceiverName); // delete on database dataContext.Email.DeleteOnSubmit(mail); // remove from local cache dailyMails.Remove(m); for (int i = 0; i < warningMails.Count; i++) { warningMails.ElementAt(i).Value.Remove(m); } try { dataContext.SubmitChanges(); return(true); } catch { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("Mailer_RemoveEMail: "); messageEx1.Append("Removing of emailadress " + m.Address + " of " + m.User + " from MailList failed."); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(false); } } }
public bool RemoveMailObserver(int userID, List <string> monitoredSystemMACs) { using (var dataContext = DataContextFactory.CreateDataContext()) { try { foreach (string mac in monitoredSystemMACs) { var mail = (from p in dataContext.EmailObserver where (p.EmailID == userID && p.MonitoredSystem.MacAddress == mac) select p).FirstOrDefault(); if (mail != null) { dataContext.EmailObserver.DeleteOnSubmit(mail); dataContext.SubmitChanges(); #region caching for (int i = 0; i < warningMails.Count; i++) { warningMails.ElementAt(i).Value.Remove(new MailAddress(mail.Email.Address, mail.Email.ReceiverName)); } #endregion } else { Logger.Instance.WriteEntry("Mailer_RemoveMailObserver: Cannot find mail to be removed", LogType.Warning); } } return(true); } catch (Exception e) { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("Mailer_RemoveMailObserver: "); messageEx1.Append("Removing of MailObserver failed. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(false); } } }
/// <summary> /// 获取服务器时间,如果执行失败,serverDT 返回null /// </summary> /// <param name="serverDT"></param> /// <returns></returns> public CommandResult GetServerDateTime(out DateTime?serverDT) { try { serverDT = null; DataContext dc = DataContextFactory.CreateDataContext(_ConnStr, _MapSource); var ret = dc.ExecuteQuery <DateTime>("select Now from View_Now").ToList(); if (ret != null && ret.Count == 1) { serverDT = ret[0]; return(new CommandResult(ResultCode.Successful, string.Empty)); } return(new CommandResult(ResultCode.Fail, "获取数据库时间失败")); } catch (Exception ex) { serverDT = null; LJH.GeneralLibrary.ExceptionHandling.ExceptionPolicy.HandleException(ex); return(new CommandResult(ResultCode.Fail, ex.Message)); } }
private void CleanValueX(DataType dataType) { using (var dataContext = DataContextFactory.CreateDataContext()) { try { string queryIndicator = "SELECT [ID] FROM [MISD].[dbo].[Indicator] WHERE [ValueType] =" + (byte)dataType; var query = new StringBuilder(); query.Append("DELETE FROM [MISD].[dbo].[Value" + dataType.ToString() + "]"); query.Append("WHERE [ID] NOT IN "); query.Append("(SELECT [ValueID] FROM [MISD].[dbo].[IndicatorValue] AS iv JOIN (" + queryIndicator + ") AS i ON iv.IndicatorID = i.ID)"); dataContext.ExecuteQuery <bool>(query.ToString()); } catch (Exception e) { Logger.Instance.WriteEntry("CleanerJob_CleanValueX: Problem cleaning values: " + e.ToString(), LogType.Exception); } } }
public bool ChangeOUName(int ouID, string newName, DateTime updateTime) { using (var dataContext = DataContextFactory.CreateDataContext()) { var ou = (from p in dataContext.OrganizationalUnit where p.ID == ouID select p).FirstOrDefault(); if (ou != null && (ou.LastUpdate == null || ou.LastUpdate < updateTime.Ticks)) { ou.Name = newName; ou.LastUpdate = updateTime.Ticks; try { dataContext.SubmitChanges(); return(true); } catch (Exception e) { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("ClientWebService_ChangeOUName: "); messageEx1.Append("Name of OU" + ouID + "to" + newName + " failed. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(false); } } else { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("ClientWebService_ChangeOUName: "); messageEx1.Append("Name of OU" + ouID + "to" + newName + " failed. " + "UpdateTime to late or OU not found."); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Warning); return(false); } } }
/// <summary> /// Sets a single update interval for a specific indicator of a system. /// </summary> /// <param name="monitoredSystemID">The ID of the system to set the update interval.</param> /// <param name="pluginName">The plugin to set the update interval.</param> /// <param name="indicator">The indicator to set the update interval of.</param> /// <param name="time">The new update interval.</param> /// <returns>A list containing all indicators in combination with the update interval for each indicator.</returns> public List <Tuple <string, TimeSpan> > SetUpdateIntervals(int monitoredSystemID, string pluginName, string indicator, TimeSpan time) { using (var dataContext = DataContextFactory.CreateDataContext()) { var interval = (from ind in dataContext.Indicator let system = ind.MonitoredSystem.ID == monitoredSystemID let plugin = ind.PluginMetadata.Name == pluginName let indicatorname = ind.Name == indicator where system && plugin && indicatorname select ind).FirstOrDefault(); if (interval == null) { Logger.Instance.WriteEntry("UpdateIntervalManager_SetUpdateIntervals: Cound not find the indicator (name: " + indicator + "), returning empty list.", LogType.Warning); return(new List <Tuple <string, TimeSpan> >()); } interval.UpdateInterval = time.Ticks; dataContext.SubmitChanges(); // update server-sided scheduling try { MISD.Server.Manager.MetaClusterManager.Instance.RefreshUpdateIntervals(monitoredSystemID, pluginName, new List <Tuple <string, TimeSpan> > { new Tuple <string, TimeSpan>(indicator, time) }); MISD.Server.Scheduling.GlobalScheduler.Instance.RefreshIntervals(monitoredSystemID, pluginName, new List <Tuple <string, TimeSpan> > { new Tuple <string, TimeSpan>(indicator, time) }); } catch (Exception e) { Logger.Instance.WriteEntry("UpdateIntervalManager_SetUpdateInverals: Problem updating server-sided scheudling intervals, " + e.ToString(), LogType.Exception); } return(this.GetUpdateIntervals(monitoredSystemID, pluginName)); } }
/// <summary> /// Rests the mapping of a workstation /// </summary> /// <param name="macList">List of MACs</param> /// <returns></returns> public bool ResetMapping(List <Tuple <string, DateTime> > macList) { try { using (var dataContext = DataContextFactory.CreateDataContext()) { foreach (Tuple <string, DateTime> tuple in macList) { bool returnValue = true; var ms = (from q in dataContext.MonitoredSystem where q.MacAddress == tuple.Item1 select q).First(); if (ms != null && (ms.LastUpdate == null || ms.LastUpdate < tuple.Item2.Ticks)) { ms.LastUpdate = tuple.Item2.Ticks; ms.CriticalEnd = null; ms.WarningEnd = null; ms.Status = (byte)MappingState.OK; } else { returnValue = false; Logger.Instance.WriteEntry("ValueManager_ResetMapping: Can't reset mapping. The update time is too late or the ms doesn't exist.", LogType.Warning); } } dataContext.SubmitChanges(); return(true); } } catch (Exception e) { Logger.Instance.WriteEntry("ValueManager_ResetMapping: Can't reset mapping. " + e.StackTrace, LogType.Exception); return(false); } }
public List <Tuple <int, string, string, int?, DateTime?> > GetAllOUs() { using (var dataContext = DataContextFactory.CreateDataContext()) { try { List <Tuple <int, string, string, int?, DateTime?> > returnList = new List <Tuple <int, string, string, int?, DateTime?> >(); var organisationalUnits = (from p in dataContext.OrganizationalUnit where p.Name != "IgnoredOuForInternalUsageOfIgnoredSystems" select p).ToList(); foreach (var ou in organisationalUnits) { if (ou.LastUpdate != null) { returnList.Add(new Tuple <int, string, string, int?, DateTime?>(ou.ID, ou.Name, ou.FQDN, ou.Parent, new DateTime((long)ou.LastUpdate))); } else { returnList.Add(new Tuple <int, string, string, int?, DateTime?>(ou.ID, ou.Name, ou.FQDN, ou.Parent, null)); } } return(returnList); } catch (Exception e) { //logging exception var messageEx = new StringBuilder(); messageEx.Append("ClientWebService_GetAllOUs: "); messageEx.Append("Can't select all OUs. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception); return(null); } } }
/// <summary> /// Sets the filter for a specific monitored system and an indicator. /// </summary> /// <param name="monitoredSystemID">The ID of the monitored system whose filter should be set.</param> /// <param name="pluginName">The plugins for the filter.</param> /// <param name="indicator">The indicator for the filter.</param> /// <param name="filterValue">The expression for the filter.</param> public void SetFilter(int monitoredSystemID, string pluginName, string indicator, string filterValue) { using (var dataContext = DataContextFactory.CreateDataContext()) { var indi = (from p in dataContext.Indicator let a = p.MonitoredSystemID == monitoredSystemID let b = p.PluginMetadata.Name == pluginName let c = p.Name == indicator where a && b && c select p).FirstOrDefault(); if (indi != null) { indi.FilterStatement = filterValue; dataContext.SubmitChanges(); UpdateFilter(monitoredSystemID, pluginName, indicator, filterValue); } else { Logger.Instance.WriteEntry("FilterManager_SetFilter: Could not find the indicator (name: " + indicator + ")", LogType.Warning); } } }
/// <summary> /// Sets the metric for a specific monitored system and an indicator. /// </summary> /// <param name="monitoredSystemID">The ID of the system whose metric should be set.</param> /// <param name="pluginName">The plugins for the metric.</param> /// <param name="indicator">The indicator for the metric.</param> /// <param name="valueWarn">The expression for mapping values to "warning".</param> /// <param name="valueCrit">The expression for mapping values to "critical".</param> public void SetMetric(int monitoredSystemID, string pluginName, string indicator, string valueWarn, string valueCrit) { try { using (var dataContext = DataContextFactory.CreateDataContext()) { var indi = (from p in dataContext.Indicator let a = p.MonitoredSystemID == monitoredSystemID let b = p.PluginMetadata.Name == pluginName let c = p.Name == indicator where a && b && c select p).FirstOrDefault(); if (indi != null) { indi.StatementWarning = valueWarn; indi.StatementCritical = valueCrit; dataContext.SubmitChanges(); // update local cache string key = monitoredSystemID.ToString() + "." + pluginName + "." + indicator; Tuple <string, string> value = new Tuple <string, string>(valueWarn, valueCrit); cacheMan.Add(key, value); } else { Logger.Instance.WriteEntry("MetricManager_SetMetric: Could not find the indicator to be updated (name: " + indicator + ")", LogType.Warning); } } } catch (Exception e) { Logger.Instance.WriteEntry("MetricManager_SetMetric: Problem setting metric for system " + monitoredSystemID + " and plugin " + pluginName + " and indicator " + indicator + ". " + e.ToString(), LogType.Exception); } }
public UnitWork(string connStr, MappingSource ms) { _Inventory = DataContextFactory.CreateDataContext(connStr, ms); }
public List <WorkstationInfo> GetWorkstationInfo(List <Tuple <int, TimeSpan> > workstationsWithReset) { List <WorkstationInfo> returns = new List <WorkstationInfo>(); using (var dataContext = DataContextFactory.CreateDataContext()) { dataContext.Log = Console.Out; try { foreach (Tuple <int, TimeSpan> current in workstationsWithReset) { //update mapping state UpdateMappingState(current.Item1); var monitoredSystem = PrecompiledQueries.GetMonitoredSystemByID(dataContext, current.Item1); WorkstationInfo workstationInfo; if (monitoredSystem.LastUpdate != null) { //create result workstationInfo = new WorkstationInfo() { Name = monitoredSystem.Name, ID = monitoredSystem.ID, FQDN = monitoredSystem.FQDN, OuID = monitoredSystem.OrganizationalUnitID, IsAvailable = monitoredSystem.IsAvailable, CurrentOS = ((MISD.Core.Platform)monitoredSystem.OperatingSystem).ToString(), MacAddress = monitoredSystem.MacAddress, State = monitoredSystem.Status.HasValue ? (MappingState)monitoredSystem.Status : MappingState.OK, LastUpdate = new DateTime((long)monitoredSystem.LastUpdate) }; } else { //create result workstationInfo = new WorkstationInfo() { Name = monitoredSystem.Name, ID = monitoredSystem.ID, FQDN = monitoredSystem.FQDN, OuID = monitoredSystem.OrganizationalUnitID, IsAvailable = monitoredSystem.IsAvailable, CurrentOS = ((MISD.Core.Platform)monitoredSystem.OperatingSystem).ToString(), MacAddress = monitoredSystem.MacAddress, State = monitoredSystem.Status.HasValue ? (MappingState)monitoredSystem.Status : MappingState.OK, LastUpdate = null }; } returns.Add(workstationInfo); } return(returns); } catch (Exception e) { //logging exception var messageEx = new StringBuilder(); messageEx.Append("Can't create List of WorkstationInfos" + ". " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx.ToString(), LogType.Exception); return(null); } } }
/// <summary> /// Registers a new node in the database. /// </summary> /// <param name="node">The node to be registered.</param> /// <param name="OUName">The name of the OU for the node.</param> private void RegisterNode(WorkstationInfo node, string OUName) { using (var dataContext = DataContextFactory.CreateDataContext()) { Database.MonitoredSystem monitoredSystem = null; try { try { monitoredSystem = PrecompiledQueries.GetMonitoredSystemByID(dataContext, PrecompiledQueries.GetMonitoredSystemIDByMAC(dataContext, node.MacAddress)); } catch (Exception) { monitoredSystem = null; } // monitored system is not yet known in the db if (monitoredSystem == null) { monitoredSystem = new MonitoredSystem(); monitoredSystem.OrganizationalUnitID = this.OUID; monitoredSystem.Name = node.Name; monitoredSystem.FQDN = node.FQDN; monitoredSystem.IsAvailable = node.IsAvailable; monitoredSystem.IsIgnored = false; monitoredSystem.OperatingSystem = (byte)PlatformHelper.ParsePlatform(node.CurrentOS); monitoredSystem.MacAddress = node.MacAddress; dataContext.MonitoredSystem.InsertOnSubmit(monitoredSystem); dataContext.SubmitChanges(); //logging info var messageOK = new StringBuilder(); messageOK.Append("ClusterManager_RegisterNode: "); messageOK.Append("Cluster node " + monitoredSystem.Name + " "); messageOK.Append("(" + monitoredSystem.OperatingSystem.ToString() + ") "); messageOK.Append("is now added to the system."); MISD.Core.Logger.Instance.WriteEntry(messageOK.ToString(), LogType.Info); } else { if (node.IsAvailable) { monitoredSystem.IsAvailable = node.IsAvailable; monitoredSystem.Name = node.Name; monitoredSystem.FQDN = node.FQDN; monitoredSystem.OperatingSystem = (byte)PlatformHelper.ParsePlatform(node.CurrentOS); monitoredSystem.OrganizationalUnitID = this.OUID; } else { // no changes necessary as the node might be booted under a different cluster } dataContext.SubmitChanges(); } node.ID = monitoredSystem.ID; } catch (Exception e) { //logging exception string workstationLogName; string osLogName; if (monitoredSystem != null) { workstationLogName = monitoredSystem.Name; osLogName = monitoredSystem.OperatingSystem.ToString(); } else { workstationLogName = "[unkown]"; osLogName = "system unkown"; } var messageEx2 = new StringBuilder(); messageEx2.Append("ClusterManager_RegisterNode: "); messageEx2.Append("Cluster node" + workstationLogName + " "); messageEx2.Append("(" + osLogName + ") "); messageEx2.Append("sign in has failed. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx2.ToString(), LogType.Exception); } } }
protected DataContext CreateDataContext() => factory.CreateDataContext();
public bool DeleteOU(int ouID) { using (var dataContext = DataContextFactory.CreateDataContext()) { var ou = (from p in dataContext.OrganizationalUnit where p.ID == ouID select p).FirstOrDefault(); if (ou == null) { Logger.Instance.WriteEntry("OUManager_DeleteOU: Cannot find OU to be deleted.", LogType.Warning); return(false); } var children = (from q in dataContext.OrganizationalUnit where q.Parent == ouID select q.ID).ToList(); foreach (int c in children) { this.DeleteOU(c); } List <Tuple <string, DateTime> > monitoredSystemMACAddresses = new List <Tuple <string, DateTime> >(); var ws = (from p in dataContext.MonitoredSystem where p.OrganizationalUnit.ID == ouID select p).ToList(); //new Tuple<string, long?> (p.MacAddress, p.LastUpdate)).ToList(); foreach (var ms in ws) { monitoredSystemMACAddresses.Add(new Tuple <string, DateTime>(ms.MacAddress, new DateTime((long)ms.LastUpdate))); } MISD.Server.Manager.WorkstationManager.Instance.AddWorkstationsToIgnoreList(monitoredSystemMACAddresses); using (var dataContext2 = DataContextFactory.CreateDataContext()) { int id; ws = (from p in dataContext2.MonitoredSystem where p.OrganizationalUnit.ID == ouID select p).ToList(); foreach (var ms in ws) { var ignoredou = (from p in dataContext2.OrganizationalUnit where p.Name == "IgnoredOuForInternalUsageOfIgnoredSystems" select p).ToList(); if (ignoredou.Count == 0) { id = this.AddOU("IgnoredOuForInternalUsageOfIgnoredSystems", null, System.DateTime.Now); } else { id = ignoredou.FirstOrDefault().ID; } ms.OrganizationalUnitID = id; ms.OrganizationalUnit = (from p in dataContext2.OrganizationalUnit where p.ID == id select p).ToList().FirstOrDefault(); try { dataContext2.SubmitChanges(); } catch (Exception e) { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("ClientWebService_DeleteOU: "); messageEx1.Append("Deletion of References from" + ouID + " failed. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); } } } } using (var dataContext3 = DataContextFactory.CreateDataContext()) { var ou = (from p in dataContext3.OrganizationalUnit where p.ID == ouID select p).FirstOrDefault(); dataContext3.OrganizationalUnit.DeleteOnSubmit(ou); try { dataContext3.SubmitChanges(); return(true); } catch (Exception e) { //logging exception var messageEx1 = new StringBuilder(); messageEx1.Append("ClientWebService_DeleteOU: "); messageEx1.Append("Deletion of OU" + ouID + " failed. " + e.ToString()); MISD.Core.Logger.Instance.WriteEntry(messageEx1.ToString(), LogType.Exception); return(false); } } }
/// <summary> /// Do the cleaning job. /// </summary> protected override void TimerTickAsync() { long valuesDeleted = 0; using (var dataContext = DataContextFactory.CreateDataContext()) { //logging StringBuilder messageStart = new StringBuilder(); messageStart.Append("CleanterJob_TimerTickAsync: "); messageStart.Append("Start cleaning."); Logger.Instance.WriteEntry(messageStart.ToString(), LogType.Info); long now = DateTime.Now.Ticks; // Find storage durations to remove. var indicators = (from p in dataContext.Indicator select p.Name).ToList(); //Find indicator value to remove #region delete indicator values for all indicators foreach (var ind in indicators) { bool newValues = true; //delete the first's values. while (newValues) { //get some indicator values to remove of this indicator. // The cleaner deletes only some values to decrease the runtime of the folowing sql statement. var indicatorValueToRemove = (from q in dataContext.Indicator where q.Name == ind from r in q.IndicatorValue let storageDuration = q.StorageDuration == null ? 864000000000 : q.StorageDuration let deadLineTicks = now - storageDuration let indicatorValueTicks = r.Timestamp where indicatorValueTicks <= deadLineTicks select r.ID).Take(Properties.Settings.Default.CleanerTakeCount).ToList(); if (indicatorValueToRemove.Count > 0) { newValues = true; } else { newValues = false; } valuesDeleted = valuesDeleted + indicatorValueToRemove.Count; // Remove indicator value if necessary #region delete indicator value try { //build delete indicatorvalute query var deleteQuery = new StringBuilder(); deleteQuery.Append("DELETE FROM [MISD].[dbo].[IndicatorValue] "); deleteQuery.Append("WHERE [ID] IN ("); foreach (var current in indicatorValueToRemove) { deleteQuery.Append(current + ","); } deleteQuery.Length--; deleteQuery.Append(")"); //delete indicatorvalue if (indicatorValueToRemove.Count > 0) { dataContext.ExecuteQuery <bool>(deleteQuery.ToString()); } } catch (Exception e) { MISD.Core.Logger.Instance.WriteEntry("CleanerJob_TimerTickAsync: Can't delete IndicatorValue. " + e.ToString(), LogType.Exception); } #endregion } } #endregion } // Clean valueX tables CleanValueX(DataType.String); CleanValueX(DataType.Int); CleanValueX(DataType.Float); #region end logging StringBuilder messageEnd = new StringBuilder(); messageEnd.Append("CleanterJob_TimerTickAsync: "); messageEnd.Append("End cleaning. " + valuesDeleted + " values deleted."); Logger.Instance.WriteEntry(messageEnd.ToString(), LogType.Info); #endregion }