예제 #1
0
        public Int32 AddPersonConsumption(string userId, float ounces)
        {
            try
            {
                using (SqliteConnection db =
                           new SqliteConnection(SqliteConnectionString))
                {
                    db.Open();
                    string sql = "INSERT INTO Keg_Visitor (VisitorId, Ounces, VisitedDateTime) VALUES (@visitorId, @ounces, @visitedDateTime);";

                    // Commit results.
                    using (SqliteCommand command = new SqliteCommand(sql, db))
                    {
                        command.Parameters.AddWithValue("@visitorId", userId);
                        command.Parameters.AddWithValue("@ounces", ounces);
                        command.Parameters.AddWithValue("@visitedDateTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        command.Prepare();

                        return(command.ExecuteNonQuery());
                    }
                }
            }
            catch (Exception ex)
            {
                //KegLogger.KegLogException(ex, "SqLiteHelper:AddPersonConsumption", SeverityLevel.Error);

                KegLogger.KegLogTrace(ex.Message, "SqLiteHelper:AddPersonConsumption", SeverityLevel.Error,
                                      new Dictionary <string, string>()
                {
                    { "UserID", userId }, { "Ounces", ounces.ToString() }
                });
                throw;
            }
        }
예제 #2
0
        /// <summary>
        /// returns the total consumption in last 24 hours
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public Double GetPersonConsumption(string userId)
        {
            try
            {
                using (SqliteConnection db =
                           new SqliteConnection(SqliteConnectionString))
                {
                    db.Open();
                    string sql = "SELECT total(Ounces) FROM Keg_Visitor WHERE VisitorId = @visitorId;";

                    // Commit results.
                    using (SqliteCommand command = new SqliteCommand(sql, db))
                    {
                        command.Parameters.AddWithValue("@visitorId", userId);
                        var reader = command.ExecuteScalar();
                        //return 0 or number
                        return(Double.Parse(reader.ToString()));
                    }
                }
            }
            catch (Exception ex)
            {
                KegLogger.KegLogTrace(ex.Message, "SqLiteHelper:GetPersonConsumption", SeverityLevel.Error,
                                      new Dictionary <string, string>()
                {
                    { "UserID", userId }
                });
                throw;
            }
        }
예제 #3
0
        /// <summary>
        /// Delete entries related to user of their old consumption
        /// </summary>
        /// <param name="sinceHours"></param>
        public void DeleteExpiredUserConsumption(Int32 sinceMinutes)
        {
            try
            {
                using (SqliteConnection db =
                           new SqliteConnection(SqliteConnectionString))
                {
                    db.Open();
                    //select VisitedDateTime, datetime('now', 'localtime'), strftime('%s', VisitedDateTime), strftime('%s', datetime(VisitedDateTime,'1 hour')), strftime('%s', datetime('now', 'localtime')) FROM Test  WHERE strftime('%s', datetime(VisitedDateTime,'1 hour')) < strftime('%s', datetime('now', 'localtime'))
                    string sql = $"DELETE FROM Keg_Visitor WHERE strftime('%s', datetime(VisitedDateTime,'{sinceMinutes} minutes')) < strftime('%s', datetime('now', 'localtime'));";

                    // Commit results.
                    using (SqliteCommand command = new SqliteCommand(sql, db))
                    {
                        var result = command.ExecuteScalar();
                    }
                }
            }
            catch (Exception ex)
            {
                KegLogger.KegLogTrace(ex.Message, "SqLiteHelper:DeleteExpiredUserConsumption", SeverityLevel.Error,
                                      new Dictionary <string, string>()
                {
                    { "Con", SqliteConnectionString }
                });
                //throw;
            }
        }
예제 #4
0
        public void Clean()
        {
            String tableDropCommand = "DROP TABLE IF EXISTS Keg_Visitor";

            try
            {
                using (SqliteConnection db =
                           new SqliteConnection(SqliteConnectionString))
                {
                    db.Open();

                    SqliteCommand dropTable = new SqliteCommand(tableDropCommand, db);

                    dropTable.ExecuteReader();

                    InitializeSqLiteDatabase();
                }
            }
            catch (Exception ex)
            {
                KegLogger.KegLogTrace(ex.Message, "SqLiteHelper:Clean", SeverityLevel.Error,
                                      new Dictionary <string, string>()
                {
                    { "Con", SqliteConnectionString }
                });
                throw;
            }
        }
        public void OnKeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs e)
        {
            if (e.VirtualKey == Windows.System.VirtualKey.Enter)
            {
                this.userGuid = Hasher.GetSmartCardHash(sb.ToString());
                Debug.WriteLine(userGuid);
                KegLogger.KegLogTrace("User", "UserScan", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, new Dictionary <string, string>()
                {
                    { "hashcode", this.userGuid }
                });

                //resetting
                sb.Clear();
                bool status = CheckKegStatus();

                if (!status)
                {
                    //Appropriate messages are handled in above method
                    this.userGuid = string.Empty;
                    return;
                }

                Window.Current.CoreWindow.KeyDown -= OnKeyDown;
                //cardDetected = true;
                this.Frame.Navigate(typeof(Page2), $"FromMain:{userGuid}");
            }
            else
            {
                sb.Append((int)e.VirtualKey - 48);
            }
        }
예제 #6
0
        private static async void SaveKegConfigAsync(KegConfig config)
        {
            var           client  = new System.Net.Http.HttpClient();
            string        url     = $"https://kegocnizerdemofunctions.azurewebsites.net/api/kegconfig";
            var           data    = JsonConvert.SerializeObject(config);
            StringContent content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");

            KegLogger.KegLogTrace($"Save Keg Config MaxEventDuration : {config.MaxEventDurationMinutes} MaxUserOuncesPerHour: {config.MaxUserOuncesPerHour} CoreHours: {config.CoreHours}",
                                  "App6:SaveSettings", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, null);
            var result = await client.PostAsync(url, content);
        }
예제 #7
0
        /// <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;
        }
예제 #8
0
        public void LogExpiredUserConsumption(Int32 sinceMinutes)
        {
            Dictionary <string, double> persons = new Dictionary <string, double>();

            try
            {
                using (SqliteConnection db =
                           new SqliteConnection(SqliteConnectionString))
                {
                    db.Open();
                    //select VisitedDateTime, datetime('now', 'localtime'), strftime('%s', VisitedDateTime), strftime('%s', datetime(VisitedDateTime,'1 hour')), strftime('%s', datetime('now', 'localtime')) FROM Test  WHERE strftime('%s', datetime(VisitedDateTime,'1 hour')) < strftime('%s', datetime('now', 'localtime'))
                    //string sql = $"SELECT VisitorId, SUM(Ounces) FROM Keg_Visitor WHERE strftime('%s', datetime(VisitedDateTime,'{sinceHours} hour')) < strftime('%s', datetime('now', 'localtime')) Group By VisitorId Having Sum(Ounces)> 0.0;";
                    string sql = $"SELECT VisitorId, SUM(Ounces) FROM Keg_Visitor WHERE strftime('%s', datetime(VisitedDateTime,'{sinceMinutes} minutes')) < strftime('%s', datetime('now', 'localtime')) Group By VisitorId Having Sum(Ounces)> 0.0;";

                    // Commit results.
                    using (SqliteCommand command = new SqliteCommand(sql, db))
                    {
                        var reader = command.ExecuteReader();
                        while (reader.HasRows && reader.Read())
                        {
                            if (!reader.IsDBNull(0))
                            {
                                persons.Add(
                                    reader[0].ToString(), reader.IsDBNull(1) ? 0.0 : double.Parse(reader[1].ToString()));

                                //Log Metrics
                                MetricTelemetry metricTelemetry = new MetricTelemetry();
                                metricTelemetry.Name = reader[0].ToString();
                                metricTelemetry.Sum  = reader.IsDBNull(1) ? 0.0 : double.Parse(reader[1].ToString());
                                metricTelemetry.Context.Operation.Name = "EventComplete";

                                KegLogger.KegLogMetrics("Event Complete or timeout", "EventComplete", metricTelemetry);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                KegLogger.KegLogTrace(ex.Message, "SqLiteHelper:DeleteExpiredUserConsumption", SeverityLevel.Error,
                                      new Dictionary <string, string>()
                {
                    { "Con", SqliteConnectionString }
                });
                //throw;
            }
        }
예제 #9
0
        public Page2()
        {
            this.InitializeComponent();


            Page2Dispatcher = Window.Current.Dispatcher;

            //remove
            var orient = Common.GetCurrentDisplaySize();

            Debug.WriteLine($"Page2 Display:{orient.Item1}, {orient.Item2}");
            Debug.WriteLine($"Window Bounds: Width-{Window.Current.Bounds.Width},Height-{Window.Current.Bounds.Height}");

            TriggerOfVisualState.MinWindowWidth = Common.AppWindowWidth;

            deliverOunces    = false;
            totalConsumption = 0.0f;

            this.Page2ScreenTimeout.Text = Common.GetResourceText("Page2ScreenTimeout");
            //Get the User Limits+

            timer          = new DispatcherTimer();
            timer.Tick    += Timer_Tick;
            timer.Interval = TimeSpan.FromSeconds(15);//Initial wait

            countdown          = new DispatcherTimer();
            countdown.Tick    += Countdown_Tick;
            countdown.Interval = TimeSpan.FromSeconds(1);

            this.Loaded += async(sender, e) =>
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () =>
                {
                    //timer.Start();
                    InitializeLayout();
                });
            };

            Unloaded          += Page2_Unloaded;
            this.KegTitle.Text = Common.GetResourceText("KegTitle");

            KegLogger.KegLogTrace("Kegocnizer Page2 Loaded", "Page2Load", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, null);
        }
        private void Initialize()
        {
            if (Common.KegSettings == null)
            {
                this.startScanTitle.Text = this["GenericErrorPage"];
                return;
            }

            this.Maintenance = false;

            this.TemperatureText.Text = "--";
            this.PintsText.Text       = "--";

            this.WarningBorderBrush.BorderBrush = App.Current.Resources["ApplicationPageBackgroundThemeBrush"] as SolidColorBrush;

            //SQLite Initalization
            SqLiteHelper.InitializeSqLiteDatabase();

            //Verify
            KegLogger.KegLogTrace("Initialization complete.", "Initialize", SeverityLevel.Information, null);
        }
예제 #11
0
 public void OnKeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs e)
 {
     if (e.VirtualKey == Windows.System.VirtualKey.Enter)
     {
         Dictionary <string, string> user = new Dictionary <string, string>();
         user.Add($"User id: {sb.ToString()} ", $"Hash: {Hasher.GetSmartCardHash(sb.ToString())} ");
         if (sb.Length != 0)
         {
             User u = new User();
             {
                 u.HashCode   = Hasher.GetSmartCardHash(sb.ToString());
                 u.IsApprover = false;
             }
             KegLogger.KegLogTrace($"Adding user User id: { sb.ToString()} Hash: { Hasher.GetSmartCardHash(sb.ToString())}", "App3:OnKeyDown", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, null);
             User.AddUserAsync(u);
             Window.Current.CoreWindow.KeyDown -= OnKeyDown;
             this.Frame.Navigate(typeof(Admin_App4));
         }
         sb.Clear();
         return;
     }
     sb.Append((int)e.VirtualKey - 48);
 }
예제 #12
0
        public async void OnKeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs e)
        {
            if (e.VirtualKey == Windows.System.VirtualKey.Enter)
            {
                var k = await User.GetUserByHashcode(Hasher.GetSmartCardHash(sb.ToString()));

                Dictionary <string, string> admin = new Dictionary <string, string>();
                admin.Add($"Admin id: {sb.ToString()} ", $"Hash: {Hasher.GetSmartCardHash(sb.ToString())} ");
                if (k != null && k.IsApprover)
                {
                    KegLogger.KegLogTrace("Admin Login successful", "App1:OnKeyDown", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, admin);
                    Window.Current.CoreWindow.KeyDown -= OnKeyDown;
                    this.Frame.Navigate(typeof(Admin_App2));
                }
                else
                {
                    KegLogger.KegLogTrace("Admin Login unsuccessful", "App1:OnKeyDown", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, admin);
                }
                sb.Clear();
                return;
            }
            sb.Append((int)e.VirtualKey - 48);
        }
예제 #13
0
        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                rootFrame.NavigationFailed += OnNavigationFailed;

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                rootFrame.Navigate(typeof(Admin_App1), e.Arguments);
            }
            // Ensure the current window is active
            Window.Current.Activate();
            EasClientDeviceInformation deviceInfo;
            string _productName = null;

            deviceInfo   = new EasClientDeviceInformation();
            _productName = deviceInfo.SystemProductName;
            KegLogger.KegLogTrace("Admin App Loaded", "App:Initialize", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Information, null);
        }
예제 #14
0
        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);
        }
예제 #16
0
        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 }
                    });
                }
            });
        }