public IEnumerable <string> GetVisitedPersons(Int32 sinceHours) { List <string> persons = new List <string>(); try { using (SqliteConnection db = new SqliteConnection(SqliteConnectionString)) { db.Open(); string sql = $"SELECT distinct(VisitorId) FROM Keg_Visitor WHERE strftime('%s', datetime(VisitedDateTime,'{sinceHours} hour')) >= strftime('%s', datetime('now', 'localtime'));"; // Commit results. using (SqliteCommand command = new SqliteCommand(sql, db)) { var reader = command.ExecuteReader(); while (reader.HasRows && reader.Read()) { persons.Add(reader[0].ToString()); } } } } catch (Exception ex) { KegLogger.KegLogException(ex, "SqLiteHelper:GetVisitedPersons", SeverityLevel.Error); throw; } return(persons); }
public Int32 GetVisitedPersonsCount(Int32 sinceHours) { try { using (SqliteConnection db = new SqliteConnection(SqliteConnectionString)) { db.Open(); string sql = $"SELECT count(distinct(VisitorId)) FROM Keg_Visitor WHERE strftime('%s', datetime(VisitedDateTime,'{sinceHours} hour')) >= strftime('%s', datetime('now', 'localtime'));"; // Commit results. using (SqliteCommand command = new SqliteCommand(sql, db)) { var count = command.ExecuteScalar(); //return 0 or number return(Int32.Parse(count.ToString())); } } } catch (Exception ex) { KegLogger.KegLogException(ex, "SqLiteHelper:GetVisitedPersonsCount", SeverityLevel.Error); throw; } }
/// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { //Exception ex = new Exception("Failed to load Page " + e.SourcePageType.FullName); KegLogger.KegLogException(e.Exception, "App:OnNavigationFailed", SeverityLevel.Critical); KegLogger.KegLogTrace(e.Exception.Message, "App:OnNavigationFailed", SeverityLevel.Critical, new Dictionary <string, string>() { { "SourcePage", e.SourcePageType.FullName } }); throw e.Exception; }
private static bool CheckValidUrl() { try { //TODO: Add Validation //Constants.COSMOSAzureFunctionsURL return(true); } catch (Exception ex) { KegLogger.KegLogException(ex, "GlobalSettings:GetKegSetting", SeverityLevel.Critical); throw ex; } }
public static async void AddUserAsync(User item) { try { var client = new System.Net.Http.HttpClient(); string url = $"{GlobalSettings.UrlCombine(Constants.COSMOSAzureFunctionsURL, "keguser")}?code={Constants.AF_KEGKEY}"; //string url = $"https://kegocnizerfunctions.azurewebsites.net/api/keguser"; StringContent content = new StringContent(JsonConvert.SerializeObject(item)); var response = await client.PostAsync(url, content); var body = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { KegLogger.KegLogException(ex, "User:AddUserAsync", SeverityLevel.Critical); } }
internal async void OnFlowControlChanged(object sender, FlowControlChangedEventArgs e) { await Page2Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { try { Debug.WriteLine($"{e.GetType().Name}: {e.Flowing}"); } catch (Exception ex) { KegLogger.KegLogException(ex, "Page2:OnFlowConrolChanged", SeverityLevel.Warning); // new Dictionary<string, string>() { // {"Flowing", e.Flowing.ToString() } //}); } }); }
public static async Task <User> GetUserByHashcode(string hashcode) { try { var client = new System.Net.Http.HttpClient(); string url = $"{GlobalSettings.UrlCombine(Constants.COSMOSAzureFunctionsURL, "keguser", hashcode)}?code={Constants.AF_KEGKEY}"; var response = await client.GetAsync(url); var body = await response.Content.ReadAsStringAsync(); List <User> list = JsonConvert.DeserializeObject <List <User> >(body); return(list.FirstOrDefault()); } catch (Exception ex) { KegLogger.KegLogException(ex, "User:GetUserByHashcode", SeverityLevel.Critical); return(null); } }
public static async Task <KegConfig> GetKegSetting(string id) { if (!CheckValidUrl()) { return(null); } var myClientHandler = new HttpClientHandler { Credentials = System.Net.CredentialCache.DefaultCredentials }; var client = new HttpClient(myClientHandler) { Timeout = TimeSpan.FromSeconds(60) }; //var client = new Windows.Web.Http.HttpClient(); string url = $"{UrlCombine(Constants.COSMOSAzureFunctionsURL, "kegconfig", id)}?code={Constants.AF_KEGKEY}"; try { var response = await client.GetAsync(new Uri(url)); var body = await response.Content.ReadAsStringAsync(); List <KegConfig> list = JsonConvert.DeserializeObject <List <KegConfig> >(body); return(list.FirstOrDefault()); } catch (TaskCanceledException tEx) { KegLogger.KegLogException(tEx, "GlobalSettings:GetKegSetting", SeverityLevel.Critical); throw tEx; } catch (HttpRequestException hEx) { KegLogger.KegLogException(hEx, "GlobalSettings:GetKegSetting", SeverityLevel.Critical); throw hEx; } }
//public static string SqliteConnectionString = $"Filename= {System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "KegSqLite.sds") }"; public static void InitializeSqLiteDatabase() { try { using (SqliteConnection db = new SqliteConnection(SqliteConnectionString)) { db.Open(); String kegVisitorCommand = "CREATE TABLE IF NOT " + "EXISTS Keg_Visitor (Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, VisitorId TEXT NOT NULL, Ounces REAL NOT NULL, VisitedDateTime TEXT NOT NULL)"; SqliteCommand kebVisitorTable = new SqliteCommand(kegVisitorCommand, db); kebVisitorTable.ExecuteReader(); } } catch (Exception ex) { KegLogger.KegLogException(ex, "SqLiteHelper:InitializeSqLiteDatabase", SeverityLevel.Critical); throw; } }
//public static TelemetryClient telemetryClient; /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; try { Task.Run(() => Common.GetKegSettings()).Wait(); } catch (Exception ex) { //Azure Down //TODO Debug.WriteLine($"Exception:{ex.Message}"); KegLogger.KegLogException(ex, "App:App", SeverityLevel.Critical); throw ex; } InitializeCallibrations(); }
internal void InitializeCallibrations() { calibration = new Dictionary <string, object>(); try { // to initialize a sensor measurement object, we pass it a calibration object // eventually, these will come from a specific Cosmos document that the app will passthru foreach (var c in Weight.GetDefaultCalibrationSettings()) { calibration[c.Key] = c.Value; } foreach (var c in FlowControl.GetDefaultCalibrationSettings()) { calibration[c.Key] = c.Value; } foreach (var c in Temperature.GetDefaultCalibrationSettings()) { calibration[c.Key] = c.Value; } foreach (var c in Flow.GetDefaultCalibrationSettings()) { calibration[c.Key] = c.Value; } calibration[Weight.AdjustWeightFactorSetting] = Common.KegSettings.WeightCalibrationFactor.ToString(); calibration[Weight.AdjustWeightOffsetSetting] = Common.KegSettings.WeightCalibrationOffset.ToString(); if (calibration.ContainsKey(Temperature.AdjustTemperatureSetting)) { calibration[Temperature.AdjustTemperatureSetting] = new Measurement(-2.0f, Measurement.UnitsOfMeasure.Fahrenheit); } else { calibration.Add(Temperature.AdjustTemperatureSetting, new Measurement(-2.0f, Measurement.UnitsOfMeasure.Fahrenheit)); } //Flow Calibration calibration[Flow.FlowCalibrationFactorSetting] = Common.KegSettings.FlowCalibrationFactor.ToString(); calibration[Flow.FlowCalibrationOffsetSetting] = Common.KegSettings.FlowCalibrationOffset.ToString(); App._flowControl = new FlowControl(App.calibration); App._flowControl.Initialize(1000, 1000); App._flow = new Flow(App.calibration); App._flow.Initialize(1000, 1000); //Objects Initializations App._temperature = new Temperature(App.calibration); //App._temperature.TemperatureChanged += OnTemperatureChange; App._temperature.Initialize(1000, 10000); App._weight = new Weight(App.calibration); //App._weight.WeightChanged += OnWeightChange; App._weight.Initialize(); //App._weight.Initialize(1000, 50000); App._weight.Initialize(1000, 10000); KegLogger.KegLogTrace("Kegocnizer App Loaded", "AppLoad", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, null); } catch (Exception ex) { Dictionary <string, string> log = new Dictionary <string, string>(); foreach (var item in calibration) { log.Add(item.Key, item.Value.ToString()); } KegLogger.KegLogTrace(ex.Message, "App:InitializeCallibrations", SeverityLevel.Critical, log); KegLogger.KegLogException(ex, "App:InitializeCallibrations", SeverityLevel.Critical); #if !DEBUG throw; #endif } }
public MainPage() { this.InitializeComponent(); //this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled; this.DataContext = this; Debug.WriteLine("MainPage!!"); MainPageDispatcher = Window.Current.Dispatcher; timer = new DispatcherTimer(); timer.Tick += Timer_Tick; timer.Interval = TimeSpan.FromSeconds(1); refreshTimer = new DispatcherTimer(); refreshTimer.Tick += RefreshTimer_Tick; refreshTimer.Interval = TimeSpan.FromHours(2); // Refresh every 2 hrs this.startScanTitle.Text = this["Page1Initiazing"]; if (Common.KegSettings == null) { Task.Run(() => Common.GetKegSettings()).Wait(); } //Get display Orientation var orient = Common.GetCurrentDisplaySize(); Debug.WriteLine($"Display:{orient.Item1}, {orient.Item2}"); Debug.WriteLine($"Window Bounds: Width-{Window.Current.Bounds.Width},Height-{Window.Current.Bounds.Height}"); if (orient.Item2 == Windows.Graphics.Display.DisplayOrientations.Landscape || orient.Item2 == Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped) { Common.AppWindowWidth = orient.Item1.Width - 10; } else { Common.AppWindowWidth = orient.Item1.Width + 10; } /******** LOCAL TEST ********/ if (localTestOrientation) { //use one of below for local testing only //Portrait Common.AppWindowWidth = Window.Current.Bounds.Width + 20; //Landscape //Common.AppWindowWidth = Window.Current.Bounds.Width - 10; } TriggerOfVisualState.MinWindowWidth = Common.AppWindowWidth; //TriggerOfVisualStateBoth.MinWindowWidth = Common.AppWindowWidth; //Initialize Initialize(); this.Loaded += async(sender, e) => { await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () => { Window.Current.CoreWindow.KeyDown += OnKeyDown; App._temperature.TemperatureChanged += OnTemperatureChange; App._weight.WeightChanged += OnWeightChange; UpdateDateTime(); timer.Start(); refreshTimer.Start(); this.startScanTitle.Text = this["Page1Initiazing"]; Debug.WriteLine(" Loaded!"); }); try { await MainPageDispatcher.RunAsync(CoreDispatcherPriority.Low, () => { bool valid = CheckKegStatus(); if (valid) { this.startScanTitle.Text = this["Page1BodyText"]; } }); } catch (Exception ex) { this.startScanTitle.Text = ex.Message; KegLogger.KegLogException(ex, "MainPage:Loaded", SeverityLevel.Critical); } }; this.Unloaded += (sender, e) => { timer.Stop(); refreshTimer.Stop(); App._temperature.TemperatureChanged -= OnTemperatureChange; App._weight.WeightChanged -= OnWeightChange; }; KegLogger.KegLogTrace("Kegocnizer MainPage Loaded", "MainPageLoad", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, null); }
private bool CheckKegStatus() { Debug.WriteLine(" Refreshing CheckKeg Status ..."); this.WarningBorderBrush.Visibility = Visibility.Collapsed; this.warningTitle.Visibility = Visibility.Collapsed; this.PintsText.Style = App.Current.Resources["AppSubheaderTextBlockStyle"] as Style; //TODO: check all validations in Async bool valid = false; if (Common.KegSettings == null) { Task.Run(() => Common.GetKegSettings()).Wait(); } //Maintenance Mode if (Common.KegSettings.MaintenanceMode) { this.Maintenance = true; return(valid); } //Evalaute KegSettings //Core Hours: Allowed Only if outside corehours //12T14;16T18 //To decode entry to readable format StringBuilder entryToReadable = new StringBuilder(); if (Common.KegSettings.CoreHours != null) { string[] coreHours = Common.KegSettings.CoreHours.Split(Common.semiColonDelimiter, StringSplitOptions.RemoveEmptyEntries); //Int32 currentHour = DateTime.Now; //Validation if (coreHours.Length == 0) { valid = false; } foreach (var itemEntry in coreHours) { //Split into string[] entry = itemEntry.Split(Common.timeTDelimiter); DateTime startTime = DateTime.Today; //12AM DateTime endTime = DateTime.Today.AddDays(1); //11:59PM if (entry.Length > 1) { if (entry[0].Trim().Length > 0) { int[] hrmin = entry[0].Split(Common.colonDelimiter).Select(x => int.Parse(x.ToString())).ToArray(); startTime = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, hrmin[0], (hrmin.Length > 1 ? hrmin[1] : 0), 0); } if (entry[1].Trim().Length > 0) { int[] hrmin = entry[1].Split(Common.colonDelimiter).Select(x => int.Parse(x.ToString())).ToArray(); endTime = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day, hrmin[0], (hrmin.Length > 1 ? hrmin[1] : 0), 0); } entryToReadable.Append(startTime.ToString("hh:mm tt")); entryToReadable.Append(" To "); entryToReadable.Append(endTime.ToString("hh:mm tt")); entryToReadable.Append(","); //If multiple corehours are supplied, then all should be satisifed valid = !(DateTime.Now.Ticks > startTime.Ticks && DateTime.Now.Ticks < endTime.Ticks); } else { //reject valid = false; } } } if (!valid) { //debugging purpose if (!App.IgnoreCoreHours) { string coreHoursDisplay = entryToReadable.ToString(); if (coreHoursDisplay.EndsWith(",")) { coreHoursDisplay = coreHoursDisplay.Substring(0, coreHoursDisplay.Length - 1); } this.startScanTitle.Text = string.Format(this["CoreHoursException"], coreHoursDisplay); this.WarningBorderBrush.BorderBrush = App.Current.Resources["BorderBrush"] as SolidColorBrush; return(valid); } } //Validate CoreDays //ex: Mon,Tue, Wed, Thu,Fri string[] coreDays = Common.KegSettings.CoreDays.Split(Common.commaDelimiter, StringSplitOptions.RemoveEmptyEntries).Select(x => x.ToLowerInvariant().Trim()).ToArray(); string charToday = DateTime.Today.ToString("ddd").ToLowerInvariant().Trim(); if (coreDays.Contains(charToday)) { valid = true; } else { //debugging purpose if (!App.IgnoreCoreHours) { valid = false; this.startScanTitle.Text = string.Format(this["CoreDaysException"], Common.KegSettings.CoreDays); this.WarningBorderBrush.BorderBrush = App.Current.Resources["BorderBrush"] as SolidColorBrush; return(valid); //throw new Exception(string.Format(Common.GetResourceText("CoreDaysException"), Common.KegSettings.CoreDays)); } } //Avaialble Pints //TODO: Measurement wtMeasurement = App._weight.GetWeight(); if (wtMeasurement != null) { //float percentage = wtMeasurement.Amount * 10 / (Common.KegSettings.MaxKegWeight - Common.KegSettings.EmptyKegWeight); float percentage = wtMeasurement.Amount / (Common.KegSettings.MaxKegWeight - Common.KegSettings.EmptyKegWeight); Debug.WriteLine($"Percentage1: {percentage}"); //TODO : Check the calibration if (percentage > 100.00f) { PintsText.Text = $"99% full"; } else { PintsText.Text = $"{Math.Round(percentage)}% full"; } if (wtMeasurement.Amount < Common.MINIMUMLIMITTOEMPTY) { //this.startScanTitle.Text = string.Format(Common.GetResourceText("Page1KegEmpty")); this.warningTitle.Visibility = Visibility.Visible; this.warningTitle.Text = string.Format(this["Page1KegEmpty"]); this.WarningBorderBrush.BorderBrush = App.Current.Resources["BorderBrush"] as SolidColorBrush; this.PintsText.Foreground = App.Current.Resources["BorderBrush"] as SolidColorBrush; //DONT Stop user to proceed further as Weight can be not too accurate and helps user to get drink //valid = false; //return valid; } } try { Debug.WriteLine(" Refreshing LocalDB entries..."); //Clean localDB SqLiteHelper localDB = new SqLiteHelper(); //Log Metrics //localDB.LogExpiredUserConsumption(Common.USERTIMEBASELINE); localDB.LogExpiredUserConsumption(Common.KegSettings.UserConsumptionReset); //Clean entries of user consumptions older than x minutes localDB.DeleteExpiredUserConsumption(Common.KegSettings.UserConsumptionReset); } catch (Exception ex) { KegLogger.KegLogException(ex, "MainPage:CheckKegStatus:DeleteExpiredUserConsumption", SeverityLevel.Error); // new dictionary<string, string>() { // {"userbaseline", common.usertimebaseline.tostring() } //}); } if (valid) { this.startScanTitle.Text = this["Page1BodyText"]; } return(valid); }
internal async void OnFlowChange(object sender, MeasurementChangedEventArgs e) { await Page2Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { try { Debug.WriteLine($"Prior: {e.GetType().Name}: {e.Measurement}"); if (e.Measurement != null && e.Measurement.Amount > 0.0f && e.Measurement.Amount > lastMeasurement) { Debug.WriteLine($"****: {e.GetType().Name}: {e.Measurement} ****"); lastMeasurement = e.Measurement.Amount; Counter = Common.COUNTERSHORTWAIT; if (!timer.IsEnabled) { Reset(false); } else { timer.Stop(); timer.Start(); } //HidePopupCounter(); AllowedLimitFill(e.Measurement.Amount); //Check user max limit if ((totalConsumption + e.Measurement.Amount) >= Common.KegSettings.MaxUserOuncesPerHour) { //Cut-off user App._flowControl.IsActive = false; // If Limit Reached, display required text this.Page2Part1Text.Text = Common.GetResourceText("Page2LimitSorryText"); this.Page2Part2Text.Text = Common.GetResourceText("Page2LimitReachedText"); this.Page2Image.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/no-beer.png")); //TODO: //Better to show message in popup about why user need to exit //String: Page2LimitReachedText } else { if (!imageLoaded) { //Start Pouring: this.Page2Part1Text.Text = Common.GetResourceText("Page2SuccessValidationText"); this.Page2Part2Text.Text = Common.GetResourceText("Page2SuccessStart"); this.Page2Image.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/beer.gif")); imageLoaded = true; } } } } catch (Exception ex) { KegLogger.KegLogException(ex, "Page2:OnFlowChanged", SeverityLevel.Error); KegLogger.KegLogTrace(ex.Message, "Page2:OnFlowChanged", SeverityLevel.Error, new Dictionary <string, string>() { { "Measurement", e.Measurement != null ? e.Measurement.Amount.ToString(): string.Empty } }); } }); }
/// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { KegLogger.KegLogException(e.Exception, "App:NavigationFailed", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error); }