using NAudio.Wave;
using NFCSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace MagusEvents
{
///
/// Interaction logic for Scanmeal.xaml
///
public partial class Scanmeal : Page
{
DispatcherTimer Timer = new DispatcherTimer();
public Frame main;
public Frame Header;
Database DATA = new Database();
//bool nfcBusy = false;
private int nfcBusy = 0;
Events Eventsprofile = new Events();
bool busy_scanning = false;
int AID;
System.Threading.Thread playSoundThread;
private string currentDirectory;
public Scanmeal()
{
InitializeComponent();
AID = DATA.GetAccreditationID();
string path = @"c:\temp_acc\";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Scanning.Focus();
InitializeComponent();
Timer = new DispatcherTimer();
Timer.Interval = TimeSpan.FromSeconds(10);
Timer.Tick += new EventHandler(reset);
currentDirectory = System.IO.Directory.GetCurrentDirectory();
/*if (!NFCHandler.IsInitialized)
{
NFCHandler.Init();
//startpulling();
}
else
{
startpulling();
}*/
if (AID > 0)
{
Eventsprofile = DATA.GetEvent(AID.ToString());
//GET MEALS DETAILS
int CurrentDay = Eventsprofile.DayNumber;
int NumberMeals = Eventsprofile.MealsPerDay;
int CurrentMeals = Eventsprofile.SessionNumer;
MealsTitle.Text = "MEALS (Day " + CurrentDay + ")";
ZonesWrapa.Children.Clear();
StackPanel meal_season = new StackPanel();
meal_season.HorizontalAlignment = HorizontalAlignment.Left;
meal_season.Orientation = Orientation.Horizontal;
int n = 1;
while (n <= NumberMeals)
{
Border B = new Border();
B.Height = 120;
B.Width = 120;
if (n == CurrentMeals)
{
B.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFF"));
}
else
{
B.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6193AF"));
}
B.Margin = new Thickness(0, 15, 15, 0);
Label L = new Label();
L.Content = n.ToString();
L.FontSize = 50;
if (n == CurrentMeals)
{
L.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#000"));
}
else
{
L.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ccc"));
}
L.Padding = new Thickness(45, 20, 45, 20);
B.Child = L;
meal_season.Children.Add(B);
n++;
}
ZonesWrapa.Children.Add(meal_season);
}
}
//------------------------------NFC SCANNOR--------------------------------------
int BUSY = 0;
private void startpulling()
{
if (!NFCHandler.IsInitialized) return;
if (NFCHandler.Readers.Count() > 0)
{
NFCHandler.Readers[0].TagFound += Snapscan;
NFCHandler.Readers[0].StartPolling();
}
}
private void Snapscan(NFCTag Tag)
{
if (Tag != null)
{
BUSY = 1;
string code = "";
if (nfcBusy == 0)
{
code = Tag.UID.ToString();
if (code.Length == 11)
{
this.Dispatcher.Invoke(() =>
{
busy_scanning = true;
nfcBusy = 1;
Timer.Stop();
UserProfile(code, 1);
});
}
}
}
}
/* private void theForm_TagFound(NFCTag Tag)
{
try
{
nfcBusy = true;
if (Tag != null)
{
//tATR.Text = Tag.ATR;
//tUID.Text = Tag.UID;
//tType.Text = Tag.GetType().Name;
//SendKeys(Key.Enter);
//MessageBox.Show(Tag.UID.ToString());
string nfccode = Tag.UID.ToString();
this.Dispatcher.Invoke(() =>
{
if (nfccode != "" && nfccode.Length==11)
{
//CHandler.Readers[0].StopPolling();
//CHandler.Release();
MessageBox.Show(nfcBusy.ToString());
Person ProfleDb = new Person();
Person Profile = ProfleDb.GetByNFC(nfccode, AID);
if (Profile.AASID > 0)
{
Timer.Stop();
Profile Page = new Profile();
main.Content = Page;
Page.main = main;
Page.barcode = Barcode;
Page.UserProfile();
}
else
{
//MessageBox.Show("Profile Not found");
}
}
else
{
//MessageBox.Show("Code is:"+ nfccode);
}
});
}
}
catch (Exception E)
{
MessageBox.Show(E.ToString());
}
}*/
//------------------------------END NFC SCANNOR--------------------------------------
private void reset(object sender, EventArgs e)
{
if (busy_scanning == false)
{
Console.WriteLine("REST:");
if (Timer.IsEnabled)
{
Timer.Stop();
}
Scanmeal Page = new Scanmeal();
main.Content = Page;
Page.main = main;
}
}
private void GoToSettings(object sender, MouseButtonEventArgs e)
{
Timer.Stop();
Setup Page = new Setup();
main.Content = Page;
Page.main = main;
Page.Header = Header;
Page.OPT = 1;
}
private string Barcode = string.Empty; //TO DO use a StringBuilder instead
Stopwatch sw = new Stopwatch();
DispatcherTimer ST = new DispatcherTimer();
private void ScanninAcc(object sender, KeyEventArgs e)
{
try
{
if (Timer.IsEnabled)
{
Timer.Stop();
}
Barcode = Scanning.Text;
if (e.Key == Key.Tab || e.Key == Key.Return)
{
var pliter = Barcode.Split('|');
if (pliter[0] == "UNDO")
{
Meals M = new Meals();
string sql = "DELETE FROM Food WHERE AASID = '" + pliter[1] + "' AND Day = '" + pliter[3] + "' AND Season = '" + pliter[5] + "'; ";
Console.WriteLine("DELETE " + sql);
bool delete = M.delete(sql);
if (delete == true)
{
Scanmeal Page = new Scanmeal();
main.Content = Page;
Page.main = main;
Page.Header = Header;
}
}
else
{
ST = new DispatcherTimer();
ST.Tick += new EventHandler(Scaning);
ST.Start();
Scanning.Text = "";
}
}
}
catch { }
}
private void Scaning(object sender, EventArgs e)
{
try
{
if (busy_scanning == false)
{
Timer.Stop();
busy_scanning = true;
ST.Stop();
Scanning.Focus();
/*Profile Page = new Profile();
main.Content = Page;
Page.main = main;
Page.barcode = Barcode;
Page.UserProfile();*/
UserProfile(Barcode);
Barcode = "";
busy_scanning = false;
}
else
{
Barcode = "";
}
}
catch { }
}
public void UserProfile(string Bar_code, int nfc = 0)
{
if (AID > 0)
{
try
{
Console.WriteLine("Barcode " + Bar_code);
Person ProfleDb = new Person();
Person Profile;
if (nfc == 1)
{
Profile = ProfleDb.GetByNFC(Bar_code, AID);
ViewProfile(Profile);
}
else
{
Profile = ProfleDb.GetRow(Bar_code, AID);
ViewProfile(Profile);
}
//SAVE DATA
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
busy_scanning = false;
nfcBusy = 0;
}
}
private void ViewProfile(Person Profile)
{
string IMAGE = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBw8ODg4PDhEQDQ4PDw0QDQ8ODQ8PDQ0PFREWFhYRExMYHSggGBolGxUTITEhJSkrLi4uFx8zODMsNygtLisBCgoKDg0NFQ8PFSsZFRkrLTcrKy0rKys3Ny0tNzcrKzctLSsrKysrKysrKysrKysrKysrKysrKysrKysrKysrK//AABEIAOEA4QMBIgACEQEDEQH/xAAaAAEAAwEBAQAAAAAAAAAAAAAAAwQFAQIH/8QAMRABAAECBAQFAgUFAQAAAAAAAAECEQMEITESMlFxQWGBkbEiwUJScqHRgpLh8PEF/8QAFgEBAQEAAAAAAAAAAAAAAAAAAAEC/8QAFhEBAQEAAAAAAAAAAAAAAAAAAAER/9oADAMBAAIRAxEAPwD7UAqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAhzGZpo0nWqdqY3UsTHxKt54Y6U6e8pq40aq4jeYjvMI5zWH+aP3lm8EdL99XqIjomri/Gcw/zR7T/D3Tj0TtVT7s0mmOhpjWGTTM08szT2nT2WsLOTGlf90feF1MXAjW0xrEioAAAAAAAAAAAAAAAAAAIM1j8Eaa1Tyx907Lrr46pqnx0p8oS1Y8RG8zrM7z1ehxloAAAB0cAT5bG4Jt+Gd/LzX2UvZPEvTad6fhZWbE4DSAAAAAAAAAAAAAAAAK+erthzEb1Wp91Fb/8AQ2o7zP7KrNajgCKAAAAAAJ8pVauPPRA94fNT3j5IjTAbZAAAAAAAAAAAAAAAAVM/+DvV8Qqref2p7z8KjNajgCKAAAAAAPeHzU94+XhJhc1PeAaQDbAAAAAAAAAAAAAAAACrn+Wn9X2lTXM/y0/q+0qbNagAigAAAAACTB5qe8I0mDzU94EaQDbIAAAAAAAAAAAAAAACvno+iJ6VRP2UmljUcVNUdY07sxmtQARQAAAAABLlovXT3RLWSp1mekERcAbZAAAAAAAAAAAAAAAAGfmaOGqek6x2aCvnKL038afhKsUQGWgAAAAABpZajhpjrOsqWXo4qo6by0VjNAGkAAAAAAAAAAAAAAAACYAGZi0cNUx7dnhfzeFxReN4+OiixWo4AKAAOiXLYXFV5Rv/AAIs5TDtTed5+E4NsgAAAAAAAAAAAAAAAAI8bHpo5pt5bz7AkFCvO1TyRaOtW/pCCviq5qpq8r6eyauNCvNYdO9UX6RrKliV01TemJiPOLPEUxG0WdTVxwBFAAFvBzOHTFtaeszGk+qo6I06MSmrlmJ7TD1ZkTTH/N0tGPXTtPFHSrX911MaQrYedpnmiaJ96fdYib6xq0joAAAAAAAAAAPNdcUxeqYiPMHpHjY1NEfVNukeM+iri52Z0w4tH5p39IVuHW86zPjOspq4mxM3XVy/RT1/FP8ACGKIjXees6y6Mq6OAoAAAAAAAA64AO4dU08s28vCfRwEXMLORtX9M9fw/wCFqGU9YWJVRyzp+WdpXTGmIMLNU1aT9NXSdp7SnaZAAAAHKqoiLzNojxl4x8aKIvPpHjLOxK6q5vX6UxtCWrIsY2dmdMOP6qvtCrVF5vVM1T5+Ho9OM2qACgAAAAAAAAAAAAAAAAAEveHjV07TeOlWvtPg8ANDBzNNWnLV0nx7T4pmTKzl81MWiqbx4T08pWVnF0OKOse40jKqrmueKfHljpA4MNgAAAAAAAAAAAAAAAAAAAAAAAAAFv8AbgABcuAFy4AXLgBcuAFy4AXLgBcuAFy4AXLgBcuAFy4AXLgBcuAFy4AXAX4dBQAQAAAAAAAAAAAAAAAAAAAAAAAAAAf/2Q==";
this.Dispatcher.Invoke(() =>
{
if (!Timer.IsEnabled)
{
Timer.Start();
}
int Active = 0;
if (Profile.AAID > 0)
{
foundData.Visibility = Visibility.Visible;
NotfoundData.Visibility = Visibility.Hidden;
try
{
string path = @"c:\temp_acc\" + Profile.AAID + ".txt";
if (File.Exists(path))
{
string img = System.IO.File.ReadAllText(path);
string[] imgPlit = img.Split(',');
ProfileImage.Source = Base64StringToBitmap(imgPlit[1]); ;
}
else
{
ProfileImage.Source = Base64StringToBitmap(IMAGE);
}
}
catch { }
FullName.Text = Profile.FirstName + " " + Profile.Surname;
CompanyName.Text = Profile.organisation;
CategoryName.Text = Profile.Category;
Role_Name.Text = Profile.Role;
if (Profile.RoleColor != "")
{
Role_Name_color.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString(Profile.RoleColor));
}
else
{
Role_Name_color.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00981E"));
}
int AllAccess = 0;
string ZONES = Profile.aZones;
string newstr = ZONES.Replace("\"", "");
string newstr1 = newstr.Replace("[", "");
string newstr2 = newstr1.Replace("]", "");
bool FULLACCESS = newstr2.Contains("312");
string TIME_Split = DateTime.Now.ToString("HHmm");
int TIME_int = Convert.ToInt32(TIME_Split);
Zones ActivezonesDb = new Zones();
List ActiveZones = new List();
int CountLocked = DATA.GetLockedCount(AID.ToString());
if (CountLocked > 0)
{
ActiveZones = ActivezonesDb.GetActiveByArrayLocked(newstr2, AID.ToString());
}
else
{
ActiveZones = ActivezonesDb.GetActiveByArray(newstr2, AID.ToString());
}
if (FULLACCESS == true)
{
AllAccess = 1;
ActiveZones = ActivezonesDb.GetActiveByArray(newstr2, AID.ToString());
}
List ActiveZonesNew = new List();
foreach (Zones row in ActiveZones)
{
Console.WriteLine("Zone Number:" + row.Number);
string FromTime = row.FromTime;
string ToTime = row.ToTime;
string FromTime_Spling = FromTime.Replace(":", "");
string ToTime_Spling = ToTime.Replace(":", "");
int FromTime_int = Convert.ToInt32(FromTime_Spling);
int ToTime_int = Convert.ToInt32(ToTime_Spling);
if (FromTime_int == 0 && ToTime_int == 0)
{
ActiveZonesNew.Add(row);
}
else
{
if (TIME_int >= FromTime_int && TIME_int <= ToTime_int)
{
ActiveZonesNew.Add(row);
}
}
}
string base64 = "";
foreach (Zones row in ActiveZonesNew)
{
Active = 1;
if (row.ZTID == 24)
{
AllAccess = 1;
base64 = row.Icon;
}
}
if (AllAccess == 1)
{
Active = 1;
AllAccessWrapa.Visibility = Visibility.Visible;
}
else
{
}
//check if he has all access
}
else
{
foundData.Visibility = Visibility.Hidden;
NotfoundData.Visibility = Visibility.Visible;
FullName.Text = "Invalid";
CompanyName.Text = "N/A";
CategoryName.Text = "N/A";
Role_Name.Text = "N/A";
ProfileImage.Source = Base64StringToBitmap(IMAGE);
}
if (Active == 1)
{
UnDoMealWarpa.Visibility = Visibility.Visible;
// Meals
Meals meal = new Meals();
Meals meal_profile = meal.GetRow(Profile.AASID, Eventsprofile.DayNumber, Eventsprofile.SessionNumer);
//MessageBox.Show("DATA "+ meal_profile.AASID);
/*
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode("UNDO|" + Profile.AASID + "|day|" + Eventsprofile.DayNumber + "|season|" + Eventsprofile.SessionNumer, QRCodeGenerator.ECCLevel.Q);
Base64QRCode qrCode = new Base64QRCode(qrCodeData);
string qrCodeImageAsBase64 = qrCode.GetGraphic(20);
QR_Remove.Source = Base64StringToBitmap(qrCodeImageAsBase64);
*/
string file = @"c:\temp_acc\meal.txt";
if (!File.Exists(file))
{
File.CreateText(file);
}
string report = System.IO.File.ReadAllText(file);
string date = DateTime.Now.ToString("yyyy-MM-dd");
string TIME_Split = DateTime.Now.ToString("HHmm");
string newReport = report + Profile.AASID + "|" + date + "|" + TIME_Split + "|" + Profile.FirstName + " " + Profile.Surname + "|1|0|" + Eventsprofile.DayNumber + "|" + Eventsprofile.SessionNumer + ";";
System.IO.File.WriteAllText(file, newReport);
if (meal_profile.AASID > 0)
{
NotAllowed();
//GET MEALS DETAILS
int CurrentDay = Eventsprofile.DayNumber;
int NumberMeals = Eventsprofile.MealsPerDay;
int CurrentMeals = Eventsprofile.SessionNumer;
MealsTitle.Text = "MEALS (Day " + CurrentDay + ")";
ZonesWrapa.Children.Clear();
StackPanel meal_season = new StackPanel();
meal_season.HorizontalAlignment = HorizontalAlignment.Left;
meal_season.Orientation = Orientation.Horizontal;
int n = 1;
while (n <= NumberMeals)
{
Border B = new Border();
B.Height = 120;
B.Width = 120;
if (n == CurrentMeals)
{
B.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00981E"));
}
else
{
B.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#6193AF"));
}
//
B.Margin = new Thickness(0, 15, 15, 0);
Label L = new Label();
L.Content = n.ToString();
L.FontSize = 50;
if (n == CurrentMeals)
{
L.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#000"));
}
else
{
L.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ccc"));
}
L.Padding = new Thickness(45, 20, 45, 20);
B.Child = L;
meal_season.Children.Add(B);
n++;
}
ZonesWrapa.Children.Add(meal_season);
//Save_Report("Checkin_Meals.json", Profile);
}
else
{
Allowed();
//save data
string sql = "insert into Food (AASID,Day,Season) values ('" + Profile.AASID + "','" + Eventsprofile.DayNumber + "','" + Eventsprofile.SessionNumer + "')";
meal.save_to_db(sql);
file = @"c:\temp_acc\meal.txt";
report = System.IO.File.ReadAllText(file);
date = DateTime.Now.ToString("yyyy-MM-dd");
TIME_Split = DateTime.Now.ToString("HHmm");
newReport = report + Profile.AASID + "|" + date + "|" + TIME_Split + "|" + Profile.FirstName + " " + Profile.Surname + "|0|1|" + Eventsprofile.DayNumber + "|" + Eventsprofile.SessionNumer + ";";
System.IO.File.WriteAllText(file, newReport);
//Save_Report("Checkin_Meals.json", Profile);
//MessageBox.Show("Allowed");
}
}
else
{
UnDoMealWarpa.Visibility = Visibility.Hidden;
NotAllowed();
}
});
}
private void NotAllowed()
{
try
{
/*
this.Dispatcher.Invoke(() =>
{
playSound_No();
});*/
ScanningWrapa.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#BF360C"));
ScanningText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffffff"));
ScanningText.Text = "DENIED";
//Scanning.Text = string.Empty;
//Scanning.Focus();
}
catch { }
}
private void playSound_OK()
{
try
{
if (File.Exists(currentDirectory + "\\ok.wav"))
{
var Mplayer = new System.Media.SoundPlayer();
Mplayer.SoundLocation = currentDirectory + "\\ok.wav";
Mplayer.PlaySync();
}
}
catch { }
}
private void playSound_No()
{
try
{
if (File.Exists(currentDirectory + "\\Bazz.wav"))
{
var Mplayer = new System.Media.SoundPlayer();
Mplayer.SoundLocation = currentDirectory + "\\Bazz.wav";
Mplayer.PlaySync();
}
}
catch { }
}
private void Allowed()
{
try
{
/*
this.Dispatcher.Invoke(() =>
{
playSound_OK();
});*/
ScanningWrapa.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#00981E"));
ScanningText.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ffffff"));
ScanningText.Text = "GRANTED";
//Scanning.Text = string.Empty;
//Scanning.Focus();
}
catch { }
}
private void Save_Report(string filename, Person Profile)
{
try
{
string time = DateTime.Now.ToString("HH:mm");
string date = DateTime.Now.ToString("yyyy-MM-dd");
Checkin data = new Checkin();
data.AASID = Profile.AASID;
data.Name = Profile.FirstName + " " + Profile.Surname;
data.Time = date + " " + date;
data.Allowed = 1;
data.NotAllowed = 0;
var fullPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
var Path = System.IO.Path.Combine(fullPath, filename);
string Pagedata = System.IO.File.ReadAllText(Path);
var JsonObjects = Newtonsoft.Json.JsonConvert.DeserializeObject(Pagedata);
List newData = new List();
if (JsonObjects.Count() > 0)
{
foreach (Checkin row in JsonObjects)
{
newData.Add(row);
}
}
newData.Add(data);
string json = Newtonsoft.Json.JsonConvert.ToString(newData);
System.IO.File.WriteAllText(Path, json);
}
catch (Exception Error)
{
Console.WriteLine(Error);
}
}
public static BitmapImage Base64StringToBitmap(string base64String)
{
var imgBytes = Convert.FromBase64String(base64String);
BitmapImage bitmapImage = new BitmapImage();
MemoryStream ms = new MemoryStream(imgBytes);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.EndInit();
return bitmapImage;
}
}
}