예제 #1
0
        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);
        }
예제 #2
0
        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;
            }
        }
        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);
            }
        }
예제 #4
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;
            }
        }
예제 #5
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;
            }
        }
예제 #6
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;
            }
        }
예제 #7
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;
            }
        }
예제 #8
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);
        }
예제 #9
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;
        }
예제 #10
0
        private async void UpdateUserConsumption()
        {
            this.imageLoaded = false;

            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                if (null != this.loggedInUser && deliverOunces)
                {
                    if (App._flow != null)
                    {
                        Measurement desp = App._flow.GetFlow();
                        if (desp != null)
                        {
                            dispensed.Add(desp.Amount);
                        }
                    }


                    //Disable FlowControl
                    if (App._flowControl != null)
                    {
                        App._flowControl.IsActive = false;
                        Reset(false);
                    }

                    //Resetting dispensed collection to 0
                    if (App._flow != null)
                    {
                        App._flow.ResetFlow();
                    }

                    float totalDispensed = dispensed != null ? dispensed.Sum() : 0.0f;

                    if (totalDispensed > 0.0f)
                    {
                        SqLiteHelper localDB = new SqLiteHelper();
                        //TODO: Dummy code of random value
                        //localDB.AddPersonConsumption(this.loggedInUser.HashCode, new Random().Next(1, 20));
                        localDB.AddPersonConsumption(this.loggedInUser.HashCode, totalDispensed);

                        KegLogger.KegLogEvent("Beer Delivered!", "Delivered", new Dictionary <string, string>()
                        {
                            { "UserID", this.loggedInUser.HashCode },
                            { "Quantity", totalDispensed.ToString() }
                        });
                    }
                }

                this.loggedInUser = null;
                this.Frame.Navigate(typeof(MainPage), $"FromPage2:");
            });
        }
예제 #11
0
 private static bool CheckValidUrl()
 {
     try
     {
         //TODO: Add Validation
         //Constants.COSMOSAzureFunctionsURL
         return(true);
     }
     catch (Exception ex)
     {
         KegLogger.KegLogException(ex, "GlobalSettings:GetKegSetting", SeverityLevel.Critical);
         throw ex;
     }
 }
예제 #12
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;
            }
        }
예제 #13
0
 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() }
             //});
         }
     });
 }
예제 #14
0
        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);
            }
        }
예제 #15
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);
        }
예제 #16
0
        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);
            }
        }
        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);
        }
예제 #18
0
        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;
            }
        }
예제 #19
0
        //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;
            }
        }
예제 #20
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);
 }
예제 #21
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);
        }
예제 #22
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);
        }
예제 #23
0
        //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();
        }
예제 #24
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)
 {
     KegLogger.KegLogException(e.Exception, "App:NavigationFailed", Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error);
 }
예제 #25
0
        private async void StartAction(string userId)
        {
            StandardPopup.IsOpen = false;
            lastMeasurement      = 0.0f;

            string beepFileName = "beep-06.wav";

            //Start Validation
            if (Common.KegSettings == null)
            {
                await Common.GetKegSettings();
            }

            //User Validation
            await Page2Dispatcher.RunAsync(CoreDispatcherPriority.Low, async() =>
            {
                if (Window.Current.Bounds.Width >= Common.AppWindowWidth)
                {
                    this.Page2LimitText1.Text = $"{Common.KegSettings.MaxUserOuncesPerHour.ToString()} Oz.(Max)";
                    this.Page2LimitText3.Text = "0 Oz.(Min)";
                }
                else
                {
                    this.Page2LimitText3.Text = $"{Common.KegSettings.MaxUserOuncesPerHour.ToString()} Oz.(Max)";
                    this.Page2LimitText1.Text = "0 Oz.(Min)";
                }


                User user         = await User.GetUserByHashcode(userId);
                this.loggedInUser = user;

                Dictionary <string, string> props = new Dictionary <string, string>
                {
                    { "UserID", user != null ? user.HashCode : string.Empty }
                };

                KegLogger.KegLogEvent("User Badge Scan", "BadgeScan", props);

                if (null != this.loggedInUser && this.loggedInUser.Type == "KegUser")
                {
                    //Check Database
                    SqLiteHelper localDB = new SqLiteHelper();

                    //Check if 25 people limit reached
                    //Check Event serve Count
                    Int32 visited = localDB.GetVisitedPersonsCount(Common.KegSettings.MaxEventDurationMinutes);

                    if (visited >= Common.KegSettings.MaxPersonsPerEvent)
                    {
                        this.Page2Part1Text.Text = Common.GetResourceText("Page2ServeLimitText");

                        List <string> visitors = localDB.GetVisitedPersons(Common.KegSettings.MaxEventDurationMinutes).ToList();
                        if (visitors.Any(v => v.Equals(this.loggedInUser.HashCode, StringComparison.InvariantCultureIgnoreCase)))
                        {
                            //Found in list and this particular user is allowed
                        }
                        else
                        {
                            //Not found, no new users accepted
                            this.Page2Part1Text.Text = Common.GetResourceText("Page2ServeLimitText");
                            this.Page2Image.Source   = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/no-beer.png"));

                            beepFileName = "fail-buzzer-04.wav";

                            Counter = Common.COUNTERSHORTWAIT;
                            timer.Start();

                            //Raise event on max count reached
                            KegLogger.KegLogEvent("Max Visitors reached!", "MaxVisitors", null);

                            return;
                        }
                    }

                    //Check total consumption
                    totalConsumption = localDB.GetPersonConsumption(userId);
                    if (totalConsumption >= Common.KegSettings.MaxUserOuncesPerHour)
                    {
                        // 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"));

                        beepFileName = "fail-buzzer-04.wav";

                        //TODO:
                        //Start a timer to return to main screen
                        Counter = Common.COUNTERSHORTWAIT;
                        timer.Start();
                    }
                    else
                    {
                        //Success:
                        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/checkmark.png"));

                        this.GridConsumption.Visibility  = Visibility.Visible;
                        this.Page2OuncesPanel.Visibility = Visibility.Visible;

                        this.Page2LimitText2.Text = $"{totalConsumption.ToString()} Oz";

                        AllowedLimitFill();

                        deliverOunces = true;
                        dispensed     = new List <float>();


                        //Initialize
                        if (App._flowControl != null)
                        {
                            //App._flowControl = new FlowControl(App.calibration);
                            App._flowControl.FlowControlChanged += OnFlowControlChanged;
                            // App._flowControl.Initialize(1000, 1000);

                            App._flowControl.IsActive = true;
                            Reset(true);
                        }

                        if (App._flow != null)
                        {
                            //App._flow = new Flow(App.calibration);
                            App._flow.FlowChanged += OnFlowChange;
                            //App._flow.Initialize();
                            //App._flow.Initialize(1000, 1000);

                            App._flow.ResetFlow();
                        }

                        //Initialize Flow measure
                        dispensed = new List <float>();

                        Counter = Common.COUNTERWAIT;
                        timer.Start();
                    }
                }
                else
                {
                    ////Access Denied:
                    this.Page2Part1Text.Text = Common.GetResourceText("Page2SorryText");
                    this.Page2Part2Text.Text = Common.GetResourceText("Page2ContactText");
                    this.Page2Image.Source   = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appx:///Assets/no-beer.png"));

                    beepFileName = "fail-buzzer-04.wav";
                    //TODO:
                    //Start a timer to return to main screen
                    Counter = Common.COUNTERSHORTWAIT;
                    timer.Start();

                    //denied users
                    KegLogger.KegLogEvent("User Denied!", "UserDenied", new Dictionary <string, string>()
                    {
                        { "UserID", userId }
                    });
                }

                PlayBeep(beepFileName);
            });
        }
예제 #26
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 }
                    });
                }
            });
        }
예제 #27
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
            }
        }
        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);
        }
        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);
        }