public AlertFunctionResult DefaultAlert(AlertSettings settings) { var afr = new AlertFunctionResult(); foreach (var target in settings.Targets) { var ar = new AlertResult(); try { var targetSettings = settings.TargetSettings[target]; var recipient = new HaleAlertPushbulletRecipient() { AccessToken = targetSettings["accessToken"], Target = targetSettings["target"], TargetType = (PushbulletPushTarget)Enum.Parse(typeof(PushbulletPushTarget), targetSettings["targetType"]), Name = targetSettings["name"], Id = Guid.NewGuid() }; var response = _api.Push("Hale Alert", string.Format("{0}\n{1}", settings.SourceString, settings.Message), recipient); ar.Message = response.Type; ar.RanSuccessfully = true; } catch (Exception x) { ar.RanSuccessfully = false; ar.ExecutionException = x; } afr.AlertResults.Add(target, ar); } afr.RanSuccessfully = true; return afr; }
public AlertResultActionResult GetAlertResult([FromBody] AlertApiRequest request) { try { if (!ModelState.IsValid) { return(new AlertResultActionResult( new AlertApiResonse { Exception = new Exception("InValid Input") })); } AlertResult result = GetSingleAlert(request); var response = new AlertApiResonse { AlertResult = result, Exception = result.Success ? null : new Exception(result.ErrorMessage) }; return(new AlertResultActionResult(response)); } catch (Exception ex) { return(new AlertResultActionResult(new AlertApiResonse { Exception = ex, AlertResult = new AlertResult { Success = false, ErrorMessage = "Errors in execute your request, please retry later." } })); } }
public AlertFunctionResult DefaultAlert(AlertSettings settings) { AlertFunctionResult functionResult = new AlertFunctionResult(); functionResult.RanSuccessfully = true; foreach (string target in settings.Targets) { AlertResult result = new AlertResult(); try { Dictionary<string, string> targetSettings = settings.TargetSettings[target]; HaleAlertSlackRecipient recipient = CreateRecipient(targetSettings); SlackMessage msg = CreateSlackMessage(recipient, settings); SendSlackMessage(msg, recipient); result.RanSuccessfully = true; result.Message = "OK"; } catch (Exception x) { functionResult.RanSuccessfully = result.RanSuccessfully = false; functionResult.FunctionException = result.ExecutionException = x; } functionResult.AlertResults.Add(target, result); } return functionResult; }
private void OnQuitHandle(AlertResult result) { if (result == AlertResult.OK) { Application.Quit(); } }
public void FinishAlertMessage(AlertResult result) { lock (alertResults) { alertResults.Enqueue(result); alertCount = alertCount - 1 >= 0 ? alertCount - 1 : 0; } }
private string ExHandler(Exception ex) { AlertResult Result = new AlertResult(); Result.Success = false; Result.Message = "WS Error: " + ex.Message.ToString(); return(new JavaScriptSerializer().Serialize(Result)); }
public AlertBuilder Action(string label, bool isPrimary = true, AlertResult alertResult = AlertResult.Ok) { _actions.Add(new AlertAction() { Label = label, IsPrimary = isPrimary, AlertResult = alertResult }); return(this); }
private static IAlertResult SetKeyValuePairsInAlertResult(Dictionary <string, object> alert) { var result = new AlertResult(); foreach (var valuePair in alert) { result.AddResult(valuePair.Key, valuePair.Value as string); } return(result); }
/// <summary> /// Processes the alert. /// </summary> /// <param name="alert">The alert.</param> /// <param name="force">if set to <c>true</c> [force].</param> /// <returns></returns> public void ProcessAlert(Alert alert, int tradingDate) { VerifyResult result = null; AlertResult aResult = this.CheckAlert(alert, tradingDate); if (aResult != null) { new AlertResultBLL(_unit).Create(aResult); } }
void SellItem(AlertResult result) { if (result == AlertResult.OK) { int getCoin = bagItem.sellPrice * sellNum; PlayerDataMgr.Instance.playerData.AddCoin(getCoin); BagDataManager.Instance.DeleteItem(bagItem.ID, sellNum, true); gameObject.SetActive(false); UIManager.Instance.ShowTips(string.Format("获得{0}金币", getCoin)); } }
private void OnAlert(AlertResult result) { if (result == AlertResult.OK) { PlayerDataMgr.Instance.playerData.StartBattle(); CloseSelf(); SceneMgr.Instance.EnterScene("Battle1", () => { UIManager.Instance.ShowWindow("UIBattle"); }); } }
public string DeleteAlert(string AlertID, string SessionID) { //don't allow iOS 6 (or any browsers) to cache responses System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); AlertResult Result = new AlertResult(); Result.Success = false; //first, validate session if (!ValidateSession(SessionID)) { Result.Message = sInvalidSession; } else { //validate user can save if (!ValidateUser()) { Result.Message = "Permission denied."; } else { try { //Convert JSON string to object list using (SqlConnection oCN = new SqlConnection(ConfigurationManager.ConnectionStrings["CN_INSIDER"].ConnectionString)) { oCN.Open(); using (SqlCommand oCMD = new SqlCommand()) { oCMD.Connection = oCN; oCMD.CommandText = "DELETE FROM DataAlerts_Alert WHERE AlertID = @AlertID"; oCMD.Parameters.Add("@AlertID", AlertID); int iAffected = oCMD.ExecuteNonQuery(); if (iAffected > 0) { Result.Success = true; } } } } catch (Exception ex) { return(ExHandler(ex)); } } } //return proper status return(new JavaScriptSerializer().Serialize(Result)); }
public void OnAlert(AlertResult result) { if (result == AlertResult.OK) { PlayerDataMgr.Instance.playerData.AddGem(-10); Reborn(); } else { Debug.Log("取消复活"); UIManager.Instance.Dispatcher.SendEvent <HeroController>(UIEventType.ON_CANCEL_REBORN, this); } }
void UpdateAlertMessageReceiver() { if (alertResults.Count > 0) { int itemsInQueue = alertResults.Count; lock (alertResults) { for (int i = 0; i < itemsInQueue; i++) { AlertResult alertResult = alertResults.Dequeue(); alertResult.callback(alertResult.result); } } } }
public AlertFunctionResult DefaultAlert(AlertSettings settings) { var afr = new AlertFunctionResult(); foreach (var target in settings.Targets) { var result = new AlertResult(); var mbresult = MessageBox.Show(settings.Message, settings.SourceString, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); result.RanSuccessfully = true; result.Message = $"{target} -> {mbresult.ToString()}"; result.Target = target; afr.AlertResults.Add(target, result); } afr.RanSuccessfully = true; return afr; }
public CustomLogHanderResultDto CheckCustomLog(string AlertName, string HostName, string InstanceName, string Description, JObject table, JArray row, string rowPayload, ILogger log) { CustomLogHanderResultDto result = new CustomLogHanderResultDto(); string resourceHostName = HostName; if (resourceHostName.Contains(".")) { resourceHostName = resourceHostName.Substring(0, resourceHostName.IndexOf('.') - 1); } string regexString = regex; regexString = regexString.Replace("{HOSTNAME}", resourceHostName); log.LogInformation($"DB regex - check for alert {AlertName}: {regexString} on {rowPayload}"); // Check if body contains a database, then report incident Regex rx = new Regex(regexString, RegexOptions.IgnoreCase); // Find matches. MatchCollection matches = rx.Matches(rowPayload); if (matches.Count > 0) { result.Handled = true; // If we have a match with databases foreach (Match match in matches) { log.LogInformation($"DB regex - found match for alert {AlertName} and regex {regexString}: {match.Value}!"); AlertResult dbResult = new AlertResult() { ResourceName = HostName, InstanceName = match.Value.Replace($"{resourceHostName}\\", "") }; dbResult.PartitionKey = dbResult.ResourceName + " - " + dbResult.InstanceName; dbResult.Type = type; dbResult.Description = Description; result.Results.Add(dbResult); } } else { log.LogInformation($"DB regex - No matches found!"); } return(result); }
public string LoadProductClasses(string SessionID) { //don't allow iOS 6 (or any browsers) to cache responses System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); AlertResult Result = new AlertResult(); Result.Success = false; //first, validate session if (!ValidateSession(SessionID)) { Result.Message = sInvalidSession; } else { try { using (SqlConnection oCN = new SqlConnection(ConfigurationManager.ConnectionStrings["CN_MAS_RDP"].ConnectionString)) { oCN.Open(); using (SqlCommand oCMD = new SqlCommand("", oCN)) { oCMD.CommandText = "SELECT CATEGORY1 FROM CI_ITEM WHERE UDF_IS_ACTIVE = 'y' AND COALESCE(CATEGORY1, '') <> '' GROUP BY CATEGORY1 ORDER BY COUNT(*) DESC"; using (SqlDataReader oDR = oCMD.ExecuteReader()) { Result.Message = ""; while (oDR.Read()) { Result.Message += (Result.Message.ToString() == "") ? oDR["CATEGORY1"].ToString() : "," + oDR["CATEGORY1"].ToString(); } } Result.Success = true; Result.Message = Result.Message; } } } catch (Exception ex) { return(ExHandler(ex)); } } return(new JavaScriptSerializer().Serialize(Result)); }
public static void SaveSuggestion(AlertResult result) { using var da = new SuggestionDa(); da.SaveSuggestion(new Data.Definitions.Entities.Suggestion { SuggestedActions = string.Join(", ", result.SuggestedActions), CurrentChaikinOSCValue = result.CurrentChaikinOSCValue, CurrentRSIValue = result.CurrentRSIValue, Success = result.Success, ErrorMessage = result.ErrorMessage, FinalSuggestion = result.FinalSuggestion, CurrentPrice = result.CurrentPrice, InsertTimeStamp = DateTime.Now, SuggestionMessage = result.SuggestionMessage, Symbol = result.Symbol }); }
public async Task <AlertResult> SendAlertsAsync(IdentityUser user, Alert alert, Status tweet) { Task <bool> emailSuccessTask = null, smsSuccessTask = null; bool? emailSuccess = null, smsSuccess = null; var result = new AlertResult(); if (alert.Email && user.EmailConfirmed) { var message = $"{tweet.User.ScreenNameResponse} tweeted:\n\n{tweet.Text}"; if (alert.IncludeLink) { message += $"\n\nhttps://twitter.com/{tweet.User.ScreenNameResponse}/status/{tweet.StatusID}"; } //emailSuccessTask = SendEmailAsync(user.Email, message); } if (alert.SMS && user.PhoneNumberConfirmed) { var message = $"{tweet.User.ScreenNameResponse} tweeted:\n\n{tweet.Text}"; if (alert.IncludeLink) { message += $"\n\nhttps://twitter.com/{tweet.User.ScreenNameResponse}/status/{tweet.StatusID}"; } if (_logger != null) { _logger.LogInformation($"Sending an SMS to {alert.UserId}"); } smsSuccessTask = SendSMSAsync(user.PhoneNumber, message); } if (emailSuccessTask != null) { result.EmailSuccess = await emailSuccessTask; } if (smsSuccessTask != null) { result.SMSSuccess = await smsSuccessTask; } return(result); }
public AlertResult GetAlertResult() { var result = new AlertResult(); try { result = new AlertResult { SuggestionMessage = GetSuggestionForCurrentSticker(), Success = true, Symbol = CurrentSticker, CurrentRSIValue = Factory.IndicatorSuggestions.GetRSIIndicator(RsiResults), CurrentChaikinOSCValue = Factory.IndicatorSuggestions.GetChaikinOSCValue(ChaikinOscResults), CurrentPrice = Math.Round(CurrentQuote.Close, 2) }; var secondSuggestion = CheckForSecondAlert(); result.SuggestedActions.Add(secondSuggestion.ToString()); var indicatorSuggestions = CheckForIndicatorSuggestions(); List <string> suggestions = GetStringSuggestions(indicatorSuggestions); result.SuggestedActions.AddRange(suggestions); FinalSuggestion = GetFinalSuggestion(indicatorSuggestions, secondSuggestion); result.FinalSuggestion = FinalSuggestion.ToString(); } catch (Exception ex) { result = new AlertResult { Success = false, ErrorMessage = "Failed to get Alert and Suggestion." + ex.Message }; } finally { if (result.Success) { SuggestionMgr.SaveSuggestion(result); } } return(result); }
public AlertResult CheckAlert(Alert alert, int tradingDate) { VerifyResult result = null; AlertResult aResult = null; int latestTradingDate = new TickerBLL(_unit).GetLatestTradingDateByShareZone(alert.ShareId, alert.ZoneId); if (latestTradingDate >= tradingDate) { result = VerifyAlert(alert); aResult = new AlertResult { AlertId = alert.Id, IsMatch = result.IsMatch, Message = result.ErrorMessage, TradingDate = result.TradingDate, ShareId = alert.ShareId, ZoneId = alert.ZoneId, ProcessDT = DateTime.Now }; } return(aResult); }
public List <OutStockSearchResult> SearchAlert(string userId, int tradingDate, bool force, int?zoneId) { List <OutStockSearchResult> searchResult = new List <OutStockSearchResult>(); List <AlertResult> arList = this.GetAlertResultDB(tradingDate, zoneId); if (arList.Count == 0) { force = true; } if (force) { arList = new List <AlertResult>(); var alertList = _unit.DataContext.Alert.Where(a => a.IsActive && a.Owner == userId && a.ZoneId == zoneId).ToList(); foreach (Alert a in alertList) { AlertResult aResult = CheckAlert(a, tradingDate); arList.Add(aResult); } var arBll = new AlertResultBLL(_unit); // remove and add result arBll.DeleteAlertResultByAlert(tradingDate, zoneId); arBll.AddAlertResultBatch(arList); } arList = arList.Where(c => c.IsMatch).ToList(); string shareListString = GetShareListString(arList); searchResult = new IndicatorBLL(_unit).SearchShareByShareString(shareListString, tradingDate); return(searchResult); }
private void OnBtnCancelClick() { _alertResult = AlertResult.CANCEL; CloseSelf(); }
public string SaveAlert(string jsAlert, string SessionID) { //don't allow iOS 6 (or any browsers) to cache responses System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); AlertInstance a = new JavaScriptSerializer().Deserialize <AlertInstance>(jsAlert); AlertResult Result = new AlertResult(); Result.Success = false; //first, validate session if (!ValidateSession(SessionID)) { Result.Message = sInvalidSession; } else { //validate user can save if (!ValidateUser()) { Result.Message = "Permission denied."; } else { try { //Convert JSON string to object list using (SqlConnection oCN = new SqlConnection(ConfigurationManager.ConnectionStrings["CN_INSIDER"].ConnectionString)) { oCN.Open(); using (SqlCommand oCMD = new SqlCommand()) { oCMD.Connection = oCN; oCMD.Parameters.Add("@AlertID", a.AlertID); oCMD.Parameters.Add("@Name", a.Name); oCMD.Parameters.Add("@SendTo", a.SendTo); oCMD.Parameters.Add("@Active", a.Active); oCMD.Parameters.Add("@DaysToRun", a.DaysToRun); oCMD.Parameters.Add("@Frequency", a.Frequency); oCMD.Parameters.Add("@AlertTypeClass", a.AlertTypeClass); oCMD.Parameters.Add("@ParamJSON", a.ParamJSON); oCMD.Parameters.Add("@SessionID", clsJW_Encrypt.fnDecrypt(SessionID)); if (a.AlertID == 0) { oCMD.CommandText = "INSERT INTO DataAlerts_Alert (" + "Name,SendTo,Active,DaysToRun,Frequency,AlertTypeID,ParamJSON,CreatedBy,CreatedDate,LastModifiedBy,LastModifiedDate" + ")" + " SELECT @Name,@SendTo,@Active,@DaysToRun,@Frequency" + ",(SELECT AlertTypeID FROM DataAlerts_AlertType WHERE AlertClass = @AlertTypeClass)" + ",@ParamJSON" + ",Contact.ContactID,GetDate(),Contact.ContactID,GetDate()" + " FROM Contact" + " WHERE CAST(Contact.sSessionID As nvarchar(max)) = @SessionID"; } else { oCMD.CommandText = "UPDATE DataAlerts_Alert" + " SET Name=@Name" + ",SendTo=@SendTo" + ",Active=@Active" + ",DaysToRun=@DaysToRun" + ",Frequency=@Frequency" + ",AlertTypeID=DataAlerts_AlertType.AlertTypeID" + ",ParamJSON=@ParamJSON" + ",LastModifiedBy=(SELECT contactID FROM Contact WHERE CAST(Contact.sSessionID As nvarchar(max)) = @SessionID)" + ",LastModifiedDate=GetDate()" + " FROM DataAlerts_AlertType" + " WHERE AlertID = @AlertID" + " AND DataAlerts_AlertType.AlertClass = @AlertTypeClass"; } int ResultRows = oCMD.ExecuteNonQuery(); Result.Success = (ResultRows == 0) ? false : true; if (a.AlertID != 0) { Result.Message = (ResultRows == 0) ? "Alert ID could not be found." : "Alert saved successfully."; } else { Result.Message = (ResultRows == 0) ? "New Alert could not be added." : "Alert saved successfully"; } } } } catch (Exception ex) { return(ExHandler(ex)); } } } //return proper status return(new JavaScriptSerializer().Serialize(Result)); }
protected AlertResult[] GetAlertResults(string alertName, string payload, Newtonsoft.Json.Linq.JObject payloadObj, ILogger log) { List <AlertResult> results = new List <AlertResult>(); foreach (JObject table in payloadObj["data"]["SearchResult"]["tables"]) { int resourceIndex = GetColumnIndex(alertName, "Computer", table, log); int instanceIndex = GetColumnIndex(alertName, "InstanceName", table, log); int renderedDescriptionIndex = GetColumnIndex(alertName, "RenderedDescription", table, log); if (resourceIndex != -1) { foreach (JArray row in table["rows"]) { AlertResult result = new AlertResult() { ResourceName = row[resourceIndex].ToString(), PartitionKey = row[resourceIndex].ToString() }; // Set instance info, if available if (instanceIndex != -1 && !String.IsNullOrEmpty(row[instanceIndex].ToString())) { result.InstanceName = row[instanceIndex].ToString(); result.PartitionKey = result.ResourceName + " - " + result.InstanceName; } // Set rendered description info, if available if (renderedDescriptionIndex != -1 && !String.IsNullOrEmpty(row[renderedDescriptionIndex].ToString())) { result.Description = row[renderedDescriptionIndex].ToString(); } bool handled = false; List <AlertResult> localResults = new List <AlertResult>(); log.LogInformation($"Starting handler check for Alert Rule {alertName}"); foreach (string customHandlerKey in customLogHandlers.Keys) { ICustomLogHandler handler = customLogHandlers[customHandlerKey]; CustomLogHanderResultDto logHandlerResult = handler.CheckCustomLog(alertName, result.ResourceName, result.InstanceName, result.Description, table, row, Newtonsoft.Json.JsonConvert.SerializeObject(row), log); if (logHandlerResult.Handled) { log.LogInformation($"Handler {handler.LogType} was successful for alert {alertName}"); handled = true; } localResults.AddRange(logHandlerResult.Results); } if (handled) { // Custom handlers matched, add them results.AddRange(localResults); } else { log.LogInformation($"No handlers matched {alertName}, adding OTHER alert."); // No custom handler results, just add main alert results.Add(result); } } } } return(results.ToArray()); }
public CustomLogHanderResultDto CheckCustomLog(string AlertName, string HostName, string InstanceName, string Description, JObject table, JArray row, string rowPayload, ILogger log) { CustomLogHanderResultDto result = new CustomLogHanderResultDto(); try { // Check if body contains disk info, then report incident Regex rx = new Regex(regex, RegexOptions.IgnoreCase); // Find matches in the instance text. MatchCollection matches = rx.Matches(InstanceName); if (matches.Count > 0) { result.Handled = true; log.LogInformation($"DISK regex {regex} successful, found {matches.Count} matches"); // If we have a match with disks foreach (Match match in matches) { bool createIncident = true; int freeSpacePercentIndex = GetColumnIndex("Free_Space_Percent", table); int freeMegabytesIndex = GetColumnIndex("Free_MB", table); decimal freeSpacePercent = 0, freeMegabytes = 0, diskSize = 0; if (freeSpacePercentIndex != -1) { freeSpacePercent = Math.Round(Convert.ToDecimal(row[freeSpacePercentIndex].ToString())); } if (freeMegabytesIndex != -1) { freeMegabytes = Convert.ToDecimal(row[freeMegabytesIndex].ToString()); } if (freeSpacePercent > 0 && freeMegabytes > 0) { diskSize = Math.Round(freeMegabytes / (freeSpacePercent / 100)); } if (diskSize > 500000 && freeSpacePercent > 5) { // Don't create incident if disk is large (> 500 GB) and free space percent is greater than 5 createIncident = false; } if (createIncident) { AlertResult diskResult = new AlertResult() { ResourceName = HostName, InstanceName = match.Value }; diskResult.PartitionKey = diskResult.ResourceName + " - " + diskResult.InstanceName; diskResult.Type = type; if (!String.IsNullOrEmpty(Description)) { diskResult.Description = Description; } else { diskResult.Description = $"Disk alert for drive: {diskResult.InstanceName} - size: {diskSize} - free percent: {freeSpacePercent} - free mb: {freeMegabytes}"; } result.Results.Add(diskResult); } } } else { log.LogInformation($"DISK regex - No matches found!"); } } catch (Exception ex) { log.LogError(ex, "Error in CustomLogServiceDISK"); } return(result); }
private void OnBtnOkClick() { _alertResult = AlertResult.OK; CloseSelf(); }
public string LoadAlert(string AlertID, string SessionID) { //don't allow iOS 6 (or any browsers) to cache responses System.Web.HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); AlertResult Result = new AlertResult(); Result.Success = false; //first, validate session if (!ValidateSession(SessionID)) { Result.Message = sInvalidSession; } else { try { using (SqlConnection oCN = new SqlConnection(ConfigurationManager.ConnectionStrings["CN_INSIDER"].ConnectionString)) { oCN.Open(); using (SqlCommand oCMD = new SqlCommand("", oCN)) { oCMD.CommandText = "SELECT AlertID, DA.Name, DAT.Name As AlertTypeName, DAT.AlertClass As AlertTypeClass, DA.AlertTypeID, Active, SendTo, Frequency, DaysToRun, '' As LastRun, '' As NextRun, ParamJSON" + " FROM DataAlerts_Alert DA" + " INNER JOIN DataAlerts_AlertType DAT" + " ON DAT.AlertTypeID = DA.AlertTypeID" + " WHERE AlertID = @AlertID" + " ORDER BY AlertID"; oCMD.Parameters.Add("@AlertID", AlertID); AlertInstance Alert = new AlertInstance(); using (SqlDataReader oDR = oCMD.ExecuteReader()) { while (oDR.Read()) { Alert.AlertID = Convert.ToInt32(oDR["AlertID"].ToString()); Alert.Name = oDR["Name"].ToString(); Alert.AlertTypeClass = oDR["AlertTypeClass"].ToString(); Alert.AlertTypeName = oDR["AlertTypeName"].ToString(); Alert.Active = Convert.ToBoolean(oDR["Active"]); Alert.SendTo = oDR["SendTo"].ToString(); Alert.Frequency = oDR["Frequency"].ToString(); Alert.DaysToRun = oDR["DaysToRun"].ToString(); Alert.LastRun = oDR["LastRun"].ToString(); Alert.NextRun = oDR["NextRun"].ToString(); Alert.ParamJSON = oDR["ParamJSON"].ToString(); } } Result.Success = true; Result.Message = new JavaScriptSerializer().Serialize(Alert); } } } catch (Exception ex) { return(ExHandler(ex)); } } return(new JavaScriptSerializer().Serialize(Result)); }
/// <summary> /// Initializes a new instance of the <see cref="iFactr.UI.AlertResultEventArgs"/> class. /// </summary> /// <param name="result">The result of the alert dialog.</param> public AlertResultEventArgs(AlertResult result) { Result = result; }
public AlertResultActionResult(AlertApiResonse alertResult) { StatusCode = alertResult.AlertResult.Success ? HttpStatusCode.OK: HttpStatusCode.BadRequest; AlertResult = alertResult.AlertResult; }