/// <summary> /// Deletes the specified data. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data">The data.</param> /// <returns>a task</returns> public async Task Delete <T>(T data) where T : BaseModel { try { // Change local await DataHandler.Delete(data); AssassinCache.Remove(data); // send data to server if (QuantWebClient != null && observingTypes.Any(p => p.TypeDescritor == typeof(T).AssemblyQualifiedName)) { await CheckConnection(); if (IsConnected) { await QuantWebClient?.Delete(data); } } // delete image CheckForImage(data, true); } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error updating data."), LogLevel.Error); } }
/// <summary> /// Gets data from server in seperate yielded results. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="takeCount">The number of entites that need to returned</param> /// <param name="skip">The number of entities that need to be skiped.</param> /// <param name="includeAll">if set to <c>true</c> all relations will be loaded too.</param> /// <returns>a yielded result of the requested type</returns> public System.Collections.Async.IAsyncEnumerable <T> GetFromServer <T>(int takeCount, int skip, string query, bool includeAll) where T : BaseModel { return(new AsyncEnumerable <T>(async yield => { try { await Task.Delay(1); var BaseModelList = await this.QuantWebClient.GetFirst(typeof(T).AssemblyQualifiedName, takeCount, skip, query, includeAll); var result = BaseModelList.Select(p => p.CastAs <T>()); foreach (var item in result) { item.Synced = true; await DataHandler.Update(item); await item.RequestImageFromServer(this); await yield.ReturnAsync(item); } } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error getting data."), LogLevel.Error); } })); }
public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { Charge charge = null; try { try { OnNotify?.Invoke(this, $"Расчёт начат в {DateTime.Now.ToString("G")}"); if (IsCorrect(volumes, tariff)) { charge = new Charge { Value = volumes.Value * tariff.Value, Month = volumes.Month, HouseId = tariff.HouseId, ServiceId = tariff.ServiceId }; } OnNotify?.Invoke(this, $"Расчёт успешно завершён в {DateTime.Now.ToString("G")}"); } catch { OnException?.Invoke(this, new Tuple <string, Exception>("Исключение", new Exception("Возникло Исключение"))); throw; } } catch (Exception e) { Console.WriteLine(e.Message); OnException?.Invoke(this, new Tuple <string, Exception>("Исключение", e)); } return(charge); }
/// <summary> /// Updates the specified data. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data">The data.</param> /// <param name="updateImage">if set to <c>true</c> the image entity will also be updated.</param> /// <returns>a task</returns> public async Task Update <T>(T data, bool updateImage = false) where T : BaseModel { try { data.ModifiedDT = DateTime.UtcNow; data.Synced = false; // change local data await DataHandler.Update(data); AssassinCache.AddOrUpdate(data); // send to server if observed if (QuantWebClient != null && observingTypes.Any(p => p.TypeDescritor == typeof(T).AssemblyQualifiedName)) { await CheckConnection(); if (IsConnected) { await QuantWebClient?.Update(data); } } // update image if (updateImage) { CheckForImage(data); } } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error updating data."), LogLevel.Error); } }
/// <summary> /// Adds, updates or deletes the specific data from the server /// </summary> /// <param name="data">The data.</param> /// <returns>true if successful</returns> private bool AddUpdateDelete(BaseModel data, BaseModel currentData) { bool okay = true; try { data.Synced = true; var newObject = data.CastAs(Type.GetType(data.TypeDiscriptor)); if (newObject != null && currentData == null) { DataHandler.Insert(newObject); AssassinCache.AddOrUpdate(data); } else if (newObject != null && currentData != null && currentData.ModifiedDT < newObject.ModifiedDT) { if ((newObject as BaseModel).Archived) { DataHandler.Delete(newObject); AssassinCache.Remove(data); } else { DataHandler.Update(newObject); AssassinCache.AddOrUpdate(data); } } } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error updating data received from server."), LogLevel.Error); okay = false; } return(okay); }
/// <summary> /// Initializes a new instance of the <see cref="AssassinDataService" /> class. /// </summary> /// <param name="appId">The application identifier.</param> /// <param name="remoteEndPoint">The remote end point.</param> /// <param name="apiConnectionType">Type of the API connection.</param> public AssassinDataService(string appId, string remoteEndPoint, ApiConnectionType apiConnectionType, int syncIntervalInSeconds) : this(appId) { this.QuantWebClient = new AssassinWebClient(remoteEndPoint, apiConnectionType); this.IsConnected = false; // If an entity was send to the server it will be marked as synced StreamQueueWorker <WebPackage> .OnPackageSend = async(package) => { try { OnNotify?.Invoke(this, "Package send" + package.Method, LogLevel.Debug); if (package.Method == PackageMethod.Insert || package.Method == PackageMethod.Update && package.EntityData != null) { var unknownObject = package.EntityData.CastAs(Type.GetType(package.EntityData.TypeDiscriptor)) as BaseModel; unknownObject.Synced = true; await DataHandler.Update(unknownObject); } } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Package error."), LogLevel.Error); } }; // Start the observer new Thread(() => { this.DataObserver = new Timer(RunTimer, null, 2000, syncIntervalInSeconds * 1000); }).Start(); }
//--------------------------------------------------------------------------------- /// <summary> /// Get stacks for the current repository /// </summary> //--------------------------------------------------------------------------------- private void Notify(object notification) { OnNotify?.Invoke(new ShortStackNotification(notification) { DisplayText = notification.ToString() }); }
public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { OnNotify?.Invoke(this, $"Расчёт начат в {DateTime.Now}"); Charge charge = new Charge(); try { this.volume = volumes; this.tariff = tariff; ValidServiceID(); ValidHouseID(); ValidMonth(); ValidValue(); charge.ServiceId = volume.ServiceId; charge.HouseId = volume.HouseId; charge.Month = volume.Month; charge.Value = volume.Value * tariff.Value; } catch (Exception ex) { OnException?.Invoke(this, new Tuple <string, Exception>(ex.Message, ex)); throw; } OnNotify?.Invoke(this, $"Расчёт успешно завершён в {DateTime.Now}"); return(charge); }
public Charge CalculateSubsidy(Volume volume, Tariff tariff) { Charge charge = null; try { OnNotify?.Invoke(this, $"Расчёт начат в {DateTime.UtcNow:G}"); if (!DataValidator(volume, tariff, out string message)) { OnException?.Invoke(this, new Tuple <string, Exception>(message, new Exception(message))); } charge = new Charge() { HouseId = volume.HouseId, ServiceId = volume.ServiceId, Month = volume.Month, Value = volume.Value * tariff.Value }; OnNotify?.Invoke(this, $"Расчёт успешно завершён в {DateTime.UtcNow:G}"); } catch (Exception ex) { OnException?.Invoke(this, new Tuple <string, Exception>(ex.Message, ex)); throw; } return(charge); }
/// <summary> /// Notifies the specified data. /// </summary> /// <param name="data">The data.</param> public virtual void Notify(T data) { if (Subscribed) { OnNotify?.Invoke(data); NotificationQueue.Add(data); } }
/// <summary> /// Notifies the specified data. /// </summary> /// <param name="data">The data.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public virtual async Task NotifyAsync(T data) { if (Subscribed) { OnNotify?.Invoke(data); await NotificationQueue.AddAsync(data); } }
Task ISamsungStockNotifier.NotifyAsync(StockPriceModel stockPriceModel) { return(Task.Run(() => { OnNotify?.Invoke(this, (listObserver) => { listObserver.ForEach((observer) => observer.GetUpdatePrice(stockPriceModel)); }); })); }
/// <summary> /// Gets a data object by the identifier. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id">The identifier.</param> /// <param name="includeAll">if set to <c>true</c> all relations will be loaded too.</param> /// <returns>the specific entity of the given type</returns> public async Task <T> GetById <T>(Guid id, bool includeAll) where T : BaseModel { try { await Task.Delay(1); return(DataHandler.GetById <T>(id, includeAll)); } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error getting data."), LogLevel.Error); } return(default(T)); }
/// <summary> /// Gets a specific data range defined by the specific parameters. Can be used for paging. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="takeCount">The number of entites that need to returned</param> /// <param name="skip">The number of entities that need to be skiped.</param> /// <param name="includeAll">if set to <c>true</c> all relations will be loaded too.</param> /// <returns>a result list of the requested type</returns> public async Task <IEnumerable <T> > GetPage <T>(int takeCount, int skip, bool includeAll, string query = null) where T : BaseModel { try { await Task.Delay(1); return(DataHandler.GetFirst <T>(takeCount, skip, query, includeAll)); } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error getting data."), LogLevel.Error); } return(new List <T>()); }
/// <summary> /// Gets all entities of a specific type defined by a specific query (where part of sql) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query">The where clause in sql notation, e.g "MODIFIED > GETDATE()".</param> /// <param name="includeAll">if set to <c>true</c> all relations will be loaded too.</param> /// <returns> /// a result list of the requested type /// </returns> public async Task <IEnumerable <T> > GetByQuery <T>(string query, bool includeAll) where T : BaseModel { try { await Task.Delay(1); return(DataHandler.GetByQuery <T>(query, includeAll)); } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error getting data."), LogLevel.Error); } return(new List <T>()); }
public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { string msg = null; Charge charge = null; try { OnNotify?.Invoke(this, $"Расчёт начат в {DateTime.Now}"); if (volumes.ServiceId != tariff.ServiceId) { msg += "Не совпадают ID услуг объема и тарифа!\n"; } if (volumes.HouseId != tariff.HouseId) { msg += "Не совпадают ID домов объема и тарифа!\n"; } if (tariff.PeriodBegin > volumes.Month || volumes.Month > tariff.PeriodEnd) { msg += "Месяц объема не входит в период тарифа!\n"; } if (tariff.Value <= 0) { msg += "Значение тарифа не должно быть <= 0!\n"; } if (volumes.Value < 0) { msg += "Значение объема не может быть < 0!\n"; } if (msg != null) { OnException?.Invoke(this, new Tuple <string, Exception>(msg, new Exception(msg))); return(null); } charge = new Charge() { HouseId = volumes.HouseId, ServiceId = volumes.ServiceId, Month = volumes.Month, Value = volumes.Value * tariff.Value }; OnNotify?.Invoke(this, $"Расчёт успешно завершён в {DateTime.Now}"); } catch (Exception e) { OnException?.Invoke(this, new Tuple <string, Exception>(e.Message, e)); } return(charge); }
/// <summary> /// Вычислении субсидии на дом по указанному объёму и указанному тарифу /// </summary> /// <param name="volumes"></param> /// <param name="tariff"></param> /// <returns>charge</returns> public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { /// Начало проверок соответствия условиями OnNotify?.Invoke(this, "Расчет начат в " + DateTime.Now.ToString("HH:mm:ss dd.MM.yyyy")); if (volumes.ServiceId != tariff.ServiceId) { NoCorrect("Не совпадают идентификаторы Услуг!"); } if (volumes.HouseId != tariff.HouseId) { NoCorrect("Не совпадают идентификаторы Домов!"); } if (volumes.Month.Month < tariff.PeriodBegin.Month || tariff.PeriodEnd.Month < volumes.Month.Month) { NoCorrect("Период действия тарифа не распространяется на месяц начисления объема!"); } if (tariff.Value <= 0) { NoCorrect("Не допускается использование нулевых или отрицательных значений тарифа!"); } if (volumes.Value < 0) { NoCorrect("Значение объема не может быть отрицательным!"); } /// Конец проверок соответствия условиями /// Нахождение значения начисления Charge charge = new Charge(); try { charge.ServiceId = volumes.ServiceId; charge.HouseId = volumes.HouseId; charge.Month = volumes.Month; charge.Value = volumes.Value * tariff.Value; } catch (Exception e) { NoCorrect("Произошла ошибка при нахождении значения начисления", e); } OnNotify?.Invoke(this, "Расчет успешно закончен в " + DateTime.Now.ToString("HH:mm:ss dd.MM.yyyy")); return(charge); }
///<summary> ///Метод расчета субсидии ///</summary> public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { OnNotify?.Invoke(this, "Расчет начат в " + DateTime.Now); if (volumes.HouseId != tariff.HouseId) { InvalidInput(new ValidationException("House ID's does't match, code: 1"), "Идентификаторы домов не совпадают"); } if (volumes.ServiceId != tariff.ServiceId) { InvalidInput(new ValidationException("Service ID's does't match, code: 2"), "Идентификаторы сервисов не совпадают"); } if (!(tariff.PeriodBegin.Month <= volumes.Month.Month && volumes.Month.Month <= tariff.PeriodEnd.Month)) { InvalidInput(new ValidationException("discrepancy between the terms of using the volume and the tariff, code: 3"), "месяц объёма должен входить в период действия тарифа"); } if (tariff.Value <= 0) { InvalidInput(new ValidationException("Zero or negative tariff values are not allowed, code: 4"), "Не допускается нулевых или отрицательных значений тарифа"); } if (volumes.Value < 0) { InvalidInput(new ValidationException("Negative volume values are not allowed, code: 5"), "Не допускается отрицательных значений объема"); } var charge = new Charge(); try { charge.HouseId = volumes.HouseId; charge.ServiceId = tariff.ServiceId; charge.Month = volumes.Month; charge.Value = volumes.Value * tariff.Value; } catch (Exception e) { OnException?.Invoke(this, Tuple.Create("Calculating unexpected error: ", e)); throw; } OnNotify?.Invoke(this, "Расчет успешно закончен в " + DateTime.Now); return(charge); }
public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { Charge change = new Charge(); OnNotify?.Invoke(this, $"Start counting ({DateTime.Now})"); if (volumes.HouseId == tariff.HouseId) { if (volumes.ServiceId == tariff.ServiceId) { if (volumes.Month.Month <= tariff.PeriodEnd.Month && volumes.Month.Month >= tariff.PeriodBegin.Month) { if (tariff.Value > 0) { if (volumes.Value >= 0) { change.ServiceId = tariff.ServiceId; change.HouseId = tariff.HouseId; change.Value = tariff.Value * volumes.Value; change.Month = DateTime.Today; } else { ExceptionCall("incorrect volumes value"); } } else { ExceptionCall("incorrect tariss value"); } } else { ExceptionCall("incorrect period"); } } else { ExceptionCall("incorrect service ID"); } } else { ExceptionCall("incorrect house ID"); } OnNotify?.Invoke(this, $"End counting ({DateTime.Now})"); return(change); }
public Charge CalculateSubsidy(Volume volume, Tariff tariff) { var currentCharge = new Charge(); if (IsDataCorrect(tariff, volume) == true) { OnNotify?.Invoke(this, $"Расчёт начат в {DateTime.Now}"); currentCharge.Value = volume.Value * tariff.Value; currentCharge.HouseId = tariff.HouseId; currentCharge.ServiceId = tariff.ServiceId; currentCharge.Month = volume.Month; OnNotify?.Invoke(this, $"Расчёт успешно завершён в {DateTime.Now}"); return(currentCharge); } OnException?.Invoke(this, new Tuple <string, Exception>("some message", _ex)); return(null); }
public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { OnNotify?.Invoke(this, $"Расчёт начат в {DateTime.UtcNow:G}"); if (volumes.ServiceId != tariff.ServiceId) { InvalidInput("ServiceId", new Exception("Идентификаторы услуг у объёма и у тарифа не совпадают!")); } if (volumes.HouseId != tariff.HouseId) { InvalidInput("HouseId", new Exception("Идентификаторы домов у объёма и у тарифа не совпадают!")); } if (!(tariff.PeriodBegin.Month <= volumes.Month.Month && volumes.Month.Month <= tariff.PeriodEnd.Month)) { InvalidInput("Month", new Exception("Месяц объёма не входит в период действия тарифа!")); } if (tariff.Value <= 0) { InvalidInput("Tariff Value", new Exception("Нулевое или отрицательное значение тарифа!")); } if (volumes.Value < 0) { InvalidInput("Volumes Value", new Exception("Отрицательное значение объема!")); } Charge charge = null; try { charge = new Charge(); charge.ServiceId = volumes.ServiceId; charge.HouseId = volumes.HouseId; charge.Month = volumes.Month; charge.Value = volumes.Value * tariff.Value; } catch (Exception ex) { OnException?.Invoke(this, new Tuple <string, Exception>("Subsidy calculation error! Message: ", ex)); throw; } OnNotify?.Invoke(this, $"Расчёт успешно завершён в {DateTime.UtcNow:G}"); return(charge); }
public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { OnNotify?.Invoke(this, $"Расчёт начат {DateTime.Now}"); if (volumes.HouseId != tariff.HouseId) { OnException?.Invoke(this, new Tuple <string, Exception>(null, new Exception("Error in HouseId"))); throw new Exception("Error in HouseId"); } else if (volumes.ServiceId != tariff.ServiceId) { OnException?.Invoke(this, new Tuple <string, Exception>(null, new Exception("Error in ServiceId"))); throw new Exception("Error in ServiceId"); } else if (volumes.Month <= tariff.PeriodBegin || volumes.Month >= tariff.PeriodEnd) { OnException?.Invoke(this, new Tuple <string, Exception>(null, new Exception("Error in Mounth"))); throw new Exception("Error in Mounth"); } else if (tariff.Value <= 0) { OnException?.Invoke(this, new Tuple <string, Exception>(null, new Exception("Error in tariff"))); throw new Exception("Error in tariff value"); } else if (volumes.Value < 0) { OnException?.Invoke(this, new Tuple <string, Exception>(null, new Exception("Error in volume"))); throw new Exception("Error in volume value"); } else { OnNotify?.Invoke(this, $"Расчёт закончен {DateTime.Now}"); return(new Charge() { ServiceId = volumes.ServiceId, HouseId = volumes.HouseId, Month = volumes.Month, Value = volumes.Value * tariff.Value }); } }
bool NeoRuntimeNotify(IExecutionEngine engine) { using (var ctx = engine.CurrentContext) { if (ctx == null) { return(false); } if (!ctx.EvaluationStack.TryPop(out IStackItem it)) { return(false); } using (it) { OnNotify?.Invoke(this, new NotifyEventArgs(engine.MessageProvider, ctx?.ScriptHash, it)); } } return(true); }
public Charge CalculateSubsidy(Volume volumes, Tariff tariff) { try { Check(volumes, tariff); OnNotify.Invoke(this, $"Расчет начат в {DateTime.Now:T}"); Charge charge = new Charge { HouseId = volumes.HouseId, Month = volumes.Month, ServiceId = volumes.ServiceId, Value = volumes.Value * tariff.Value }; OnNotify.Invoke(this, $"Расчет успешно завершен в {DateTime.Now:T}"); return(charge); } catch (Exception e) { OnException.Invoke(this, new Tuple <string, Exception>("Ошибка", e)); throw; } }
/// <summary> /// Checks the connection. /// </summary> /// <returns>a task</returns> private async Task CheckConnection() { try { if (this.QuantWebClient != null) { this.IsConnected = this.QuantWebClient.CheckConnetion(); if (!this.IsConnected) { try { this.IsConnected = await this.QuantWebClient.Connect(this.AppId); } catch (Exception ex) { } } } } catch (Exception ex) { OnNotify?.Invoke(this, ex.ToText("Error creating data."), LogLevel.Error); } }
protected void StateChanged(DeviceStateChangeEventArgs args) => OnNotify?.Invoke(this, args);
public void NotifyMetrics(CommunicationMetrics metrics) { OnNotify?.Invoke(this, new MetricNotificationEventArgs(metrics)); }
public async void RaiseAsync(EventHandlerEnum @event) { var simpleEventArgs = new SimpleEventArgs(@event); await OnNotify?.Invoke(simpleEventArgs); }
public void Notify(PutNotifyEvent arg) { OnNotify?.Invoke(this, arg); }
public void RaiseOnNotify(NotifyEventArgs e) => OnNotify?.Invoke(this, e);