| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.IO;
- using System.Net;
- using System.Management;
- using Newtonsoft.Json;
- using Newtonsoft.Json.Serialization;
- using Microsoft.Win32;
- using System.Security.Cryptography;
- using System.Data.SQLite;
- using System.Windows.Forms;
- using System.Globalization;
- using System.Threading;
- using System.Data.Common;
- namespace BulkPrinting
- {
- public class Utility
- {
- public static string GetHDDSerial()
- {
- ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
- string result;
- ManagementObjectCollection.ManagementObjectEnumerator enumerator = null;
- try
- {
- enumerator = managementObjectSearcher.Get().GetEnumerator();
- while (enumerator.MoveNext())
- {
- string text = ((ManagementObject)enumerator.Current)["SerialNumber"].ToString();
- text = text.Replace(" ", "").Replace(".", "");
- if (text != "")
- {
- result = text;
- return result.Length > 15 ? result.Substring(result.Length - 15, 15) : result;
- }
- }
- }
- finally
- {
- if (enumerator != null)
- {
- ((IDisposable)enumerator).Dispose();
- }
- }
- result = "SERIAL ERROR";
- return result.Length > 15 ? result.Substring(result.Length - 15, 15) : result;
- }
- public static bool Login(LoginData UserLoginData, bool Offline, bool RememberMe) {
- string MaxDBPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Configuration.MaxDataPathName);
- string PostData = JsonConvert.SerializeObject(UserLoginData);
- byte[] data = Encoding.ASCII.GetBytes(PostData);
- HttpWebRequest request = WebRequest.Create("https://" + Configuration.ServerDN + ":" + Configuration.ServerPort + "/api/login") as HttpWebRequest;
- request.ServerCertificateValidationCallback = delegate { return true; };
- request.Method = "POST";
- request.ContentType = "application/json";
- request.ContentLength = data.Length;
- request.Accept = "application/json";
- try
- {
- using (var stream = request.GetRequestStream())
- {
- stream.Write(data, 0, data.Length);
- }
- string responseString;
- using (var response = (HttpWebResponse)request.GetResponse())
- {
- responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
- }
- Globals.SessionData = JsonConvert.DeserializeObject<OKResponse>(responseString);
- if (RememberMe == true)
- {
- SaveSetting("Username", UserLoginData.Username);
- SaveSetting("UserID", UserLoginData.UserId.ToString());
- }
- else {
- SaveSetting("Username", "");
- SaveSetting("UserID", "");
- }
- SaveSetting("VendorID", UserLoginData.VendorId.ToString());
- Globals.SessionEncryptedDatabasePassword = Globals.SessionData.Credentials.Payload.EncryptedDatabasePassword;
- Globals.SessionSalt = Globals.SessionData.Credentials.Salt;
- Globals.SessionIterations = Globals.SessionData.Credentials.Iterations;
- return true;
- }
- catch (WebException) {
- return false;
- }
- }
- public static bool RESTRequest<R>(ref R Result, string RESTPath)
- {
- return RESTRequest<bool?, R>(null, ref Result, RESTPath);
- }
- public static bool RESTRequest<T, R>(T POSTData, ref R Result, string RESTPath) {
- string MaxDBPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Configuration.MaxDataPathName);
- HttpWebRequest request = WebRequest.Create("https://" + Configuration.ServerDN + ":" + Configuration.ServerPort + RESTPath) as HttpWebRequest;
- request.ServerCertificateValidationCallback = delegate { return true; };
- request.Headers.Add("Authorization", "Bearer " + Globals.SessionData.AccessToken);
- request.ContentType = "application/json";
- request.Accept = "application/json";
- try
- {
- if (POSTData != null)
- {
- string PostData = JsonConvert.SerializeObject(POSTData);
- byte[] data = Encoding.ASCII.GetBytes(PostData);
- request.ContentLength = data.Length;
- request.Method = "POST";
- using (var stream = request.GetRequestStream())
- {
- stream.Write(data, 0, data.Length);
- }
- }
- else {
- request.Method = "GET";
- }
- string responseString;
- using (var response = (HttpWebResponse)request.GetResponse())
- {
- responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
- }
- Result = JsonConvert.DeserializeObject<R>(responseString);
- return true;
- }
- catch (WebException)
- {
- return false;
- }
- }
- /*
- private static bool RegSave(string Key, string Value)
- {
- bool Result;
- try
- {
- RegistryKey MaxRegistry = Registry.CurrentUser.OpenSubKey("Software\\M@X\\BulkPrint");
- Registry.SetValue(MaxRegistry.Name, Key, Value);
- Registry.CurrentUser.Close();
- Result = true;
- }
- catch (Exception)
- {
- Result = false;
- }
- return Result;
- }
- public static string RegFetch(string Key)
- {
- string Result;
- try
- {
- RegistryKey MaxRegistry = Registry.CurrentUser.OpenSubKey("Software\\M@X\\BulkPrint");
- Result = Registry.GetValue(MaxRegistry.Name, Key, "").ToString();
- Registry.CurrentUser.Close();
- }
- catch (Exception)
- {
- Result = "";
- }
- return Result;
- }
- */
- private static bool SaveSetting(string Key, string Value)
- {
- SavedSettings StoredValues = LoadSavedSettings();
- switch (Key)
- {
- case "Username":
- StoredValues.Username = Value;
- break;
- case "UserID":
- if (Value == "")
- StoredValues.UserId = 0;
- else
- StoredValues.UserId = int.Parse(Value);
- break;
- case "VendorID":
- if (Value == "")
- StoredValues.VendorId = 0;
- else
- StoredValues.VendorId = int.Parse(Value);
- break;
- default:
- return false;
- }
- string MaxAppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Configuration.MaxDataPathName);
- string MaxSettingsFilePath = Path.Combine(MaxAppDataPath, "maxsettings.dat");
- File.WriteAllText(MaxSettingsFilePath, JsonConvert.SerializeObject(StoredValues));
- return true;
- }
- public static string LoadSetting(string Key)
- {
- SavedSettings StoredValues = LoadSavedSettings();
- string ReturnVal = "";
- switch (Key)
- {
- case "Username":
- ReturnVal = StoredValues.Username;
- break;
- case "UserID":
- ReturnVal = StoredValues.UserId.ToString();
- break;
- case "VendorID":
- ReturnVal = StoredValues.VendorId.ToString();
- break;
- default:
- return "";
- }
- if (ReturnVal == "0")
- return "";
- return ReturnVal;
- }
- private static SavedSettings LoadSavedSettings() {
- string MaxAppDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Configuration.MaxDataPathName);
- string MaxSettingsFilePath = Path.Combine(MaxAppDataPath, "maxsettings.dat");
- SavedSettings StoredValues = new SavedSettings();
- if (!Directory.Exists(MaxAppDataPath))
- {
- Directory.CreateDirectory(MaxAppDataPath);
- }
- if (File.Exists(MaxSettingsFilePath)) {
- StoredValues = JsonConvert.DeserializeObject<SavedSettings>(File.ReadAllText(MaxSettingsFilePath));
- }
- else {
- File.WriteAllText(MaxSettingsFilePath, JsonConvert.SerializeObject(StoredValues));
- }
- return StoredValues;
- }
-
- public static byte[] Transform(ICryptoTransform transform, byte[] input)
- {
- using (var memoryStream = new MemoryStream())
- using (var cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write))
- {
- cryptoStream.Write(input, 0, input.Length);
- cryptoStream.FlushFinalBlock();
- return memoryStream.ToArray();
- }
- }
- public static byte[] AesDecryptBytes(byte[] cipherText, byte[] key)
- {
- using (var aes = Aes.Create())
- using (var decryptor = aes.CreateDecryptor(key, new byte[16]))
- {
- return Transform(decryptor, cipherText);
- }
- }
- public static string AesDecryptString(byte[] cipherText, byte[] key)
- {
- return Encoding.ASCII.GetString(AesDecryptBytes(cipherText, key));
- }
- public static string TripleDESDecrypt(string cipherText, TripleDES des)
- {
- using (var decryptor = des.CreateDecryptor(des.Key, des.IV))
- {
- return Encoding.UTF8.GetString(Transform(decryptor, Convert.FromBase64String(cipherText)));
- }
- }
- public static string TripleDESDecrypt(string cipherText, byte[] key)
- {
- using (var des = TripleDES.Create())
- {
- des.Key = key;
- des.IV = new byte[8];
- return TripleDESDecrypt(cipherText, des);
- }
- }
- public static Batch GetBatch(int BatchId) {
- Batch RequestedBatch = new Batch();
- bool OrderResult = Utility.RESTRequest<Batch>(ref RequestedBatch, String.Format("/api/batches/{0}", BatchId));
- return RequestedBatch;
- }
- public static string GetNextInternalReference()
- {
- InternalReferenceResponse InternalReferenceRequest = new InternalReferenceResponse();
- bool OrderResult = Utility.RESTRequest<InternalReferenceResponse>(ref InternalReferenceRequest, "/api/vendors/nextinternalref");
- return InternalReferenceRequest.InternalReference;
- }
- public static void DownloadBatch(Batch BatchItem)
- {
- if (BatchItem == null) {
- return;
- }
- Batch BatchRefresh = GetBatch(BatchItem.Id);
- string Sql = "DELETE FROM Batch WHERE Id=@id";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@id", BatchItem.Id));
- Command.ExecuteNonQuery();
- Sql = "INSERT INTO Batch (Id,OrderDate,OrderGuid,OrderReference,NetworkId,NetworkName,ProductId,ProductDescription ,VoucherType,FaceValue,DiscountPercentage,RequestedQuantity,DeliveredQuantity,Cost,ReadyForDownload,InternalReference)" +
- "VALUES (@a,@b,@c,@d,@e,@f,@g,@h,@i,@j,@k,@l,@m,@n,@o,@p)";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@a", BatchRefresh.Id));
- Command.Parameters.Add(new SQLiteParameter("@b", BatchRefresh.OrderDate));
- Command.Parameters.Add(new SQLiteParameter("@c", BatchRefresh.OrderGuid));
- Command.Parameters.Add(new SQLiteParameter("@d", BatchRefresh.OrderReference));
- Command.Parameters.Add(new SQLiteParameter("@e", BatchRefresh.NetworkId));
- Command.Parameters.Add(new SQLiteParameter("@f", BatchRefresh.NetworkName));
- Command.Parameters.Add(new SQLiteParameter("@g", BatchRefresh.ProductId));
- Command.Parameters.Add(new SQLiteParameter("@h", BatchRefresh.ProductDescription));
- Command.Parameters.Add(new SQLiteParameter("@i", BatchRefresh.VoucherType));
- Command.Parameters.Add(new SQLiteParameter("@j", BatchRefresh.FaceValue));
- Command.Parameters.Add(new SQLiteParameter("@k", BatchRefresh.DiscountPercentage));
- Command.Parameters.Add(new SQLiteParameter("@l", BatchRefresh.RequestedQuantity));
- Command.Parameters.Add(new SQLiteParameter("@m", BatchRefresh.DeliveredQuantity));
- Command.Parameters.Add(new SQLiteParameter("@n", BatchRefresh.Cost));
- Command.Parameters.Add(new SQLiteParameter("@o", BatchRefresh.ReadyForDownload));
- Command.Parameters.Add(new SQLiteParameter("@p", BatchRefresh.InternalReference));
- Command.ExecuteNonQuery();
- if (BatchRefresh.ReadyForDownload == true)
- {
- DownloadVouchers(BatchItem);
- }
- }
- public static void DownloadVouchers(Batch BatchItem, int PageNumber = 1) {
- string Sql;
- SQLiteCommand Command;
- Page<Voucher> VoucherBatch = new Page<Voucher>();
- bool BatchResult = Utility.RESTRequest<Page<Voucher>>(ref VoucherBatch, String.Format("/api/batches/{0}/vouchers/?page={1}&pageSize=1000", BatchItem.Id,PageNumber));
- if (PageNumber == 1) //Execute on first pass only
- {
- Sql = "DELETE FROM Voucher WHERE BatchId=@id";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@id", BatchItem.Id));
- Command.ExecuteNonQuery();
- }
- using (var Trans = Globals.DBConnection.BeginTransaction())
- {
- foreach (var VoucherItem in VoucherBatch.Items)
- {
- Sql = "INSERT INTO Voucher (Id,SequenceNumber,ExpiryDate,Serial,EncryptedPIN,BatchId)" +
- "VALUES (@id,@sequence_number,@expiry_date,@serial,@encrypted_pin,@batch_id)";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@id", VoucherItem.Id));
- Command.Parameters.Add(new SQLiteParameter("@sequence_number", VoucherItem.SequenceNumber));
- Command.Parameters.Add(new SQLiteParameter("@expiry_date", VoucherItem.ExpiryDate.Date));
- Command.Parameters.Add(new SQLiteParameter("@serial", VoucherItem.Serial));
- Command.Parameters.Add(new SQLiteParameter("@encrypted_pin", VoucherItem.EncryptedPIN));
- Command.Parameters.Add(new SQLiteParameter("@batch_id", BatchItem.Id));
- Command.ExecuteNonQuery();
- }
- Trans.Commit();
- }
- if (VoucherBatch.PageNumber < VoucherBatch.NumPages) {
- DownloadVouchers(BatchItem, PageNumber + 1);
- }
- }
- public static void SyncAllBatches(int PageNumber = 1)
- {
- string Sql;
- Page<Batch> BatchList = new Page<Batch>();
- bool BatchResult = Utility.RESTRequest<Page<Batch>>(ref BatchList, String.Format("/api/batches/?page={0}", PageNumber));
- foreach (var BatchItem in BatchList.Items)
- {
- Sql = "SELECT COUNT(*) FROM Voucher WHERE BatchId=@id";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@id", BatchItem.Id));
- int Count = Convert.ToInt32(Command.ExecuteScalar());
- if (BatchItem.ReadyForDownload==false || Count == 0 || Count < BatchItem.RequestedQuantity)
- {
- DownloadBatch(BatchItem);
- }
- }
- if (BatchList.PageNumber < BatchList.NumPages) {
- SyncAllBatches(PageNumber + 1);
- }
- }
- public static void PrintVouchers(int BatchId, int StartSeqNo, int EndSeqNo)
- {
- int VoucherCount = 0;
- int RowCount = 0;
- int PageCount = (int) Math.Ceiling(((decimal)StartSeqNo)/20);
- int TotalCount = 0;
- string SerialNumberTrimmed;
- bool IsReprint;
- var PrinterInitString = new StringBuilder();
- PrinterInitString.Append(Printer.INITIALISE_PRINTER).Append(Printer.EMPHASISE_ON).Append(Printer.UNIDIRECTIONAL_OFF).Append(Printer.CHARPITCHELITE);
- int initJobID = Globals.MaxPrinter.Open("Printer_Init");
- if (initJobID == 0) return;
- Globals.MaxPrinter.Print(PrinterInitString.ToString());
- Globals.MaxPrinter.Close();
- List<EventLog> LogEvents = new List<EventLog>();
- IList<PrintVoucher> VoucherRow = new List<PrintVoucher>();
- SQLiteCommand Command = new SQLiteCommand("SELECT DISTINCT v.Id,v.SequenceNumber,v.Serial,v.EncryptedPIN,v.BatchId,b.ProductDescription,l.VoucherId From Voucher v LEFT JOIN Batch b on v.BatchId = b.Id LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype WHERE v.BatchId=@batch_id AND v.SequenceNumber BETWEEN @seqstartno AND @seqendno ORDER BY v.SequenceNumber", Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@batch_id", BatchId));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher));
- Command.Parameters.Add(new SQLiteParameter("@seqstartno", StartSeqNo));
- Command.Parameters.Add(new SQLiteParameter("@seqendno", EndSeqNo));
- using (SQLiteDataReader read = Command.ExecuteReader())
- {
- while (read.Read())
- {
- VoucherCount++;
- PrintVoucher IndividualVoucher = new PrintVoucher();
- IndividualVoucher.SequenceNumber = (int)read["SequenceNumber"];
- IndividualVoucher.BatchId = (int)read["BatchId"];
- IndividualVoucher.Serial = (string)read["Serial"];
- IndividualVoucher.VoucherId = (int)read["Id"];
- IndividualVoucher.Description = (string)read["ProductDescription"];
- IsReprint = !read.IsDBNull(6);
- if (IsReprint)
- {
- IndividualVoucher.Description = "*" + IndividualVoucher.Description;
- }
- IndividualVoucher.DecryptedPIN = Utility.TripleDESDecrypt((string)read["EncryptedPIN"], Globals.SessionVoucherKey);
- VoucherRow.Add(IndividualVoucher);
- if (VoucherCount >= 5 || TotalCount == (EndSeqNo - StartSeqNo))
- {
- RowCount++;
- string PrintRow = "\r\n\n\n ";
- for (int Column = 0; Column < VoucherRow.Count(); Column++)
- {
- IndividualVoucher = VoucherRow[Column];
- PrintRow += (Column == 2 ? " " : "") + (" " + IndividualVoucher.DecryptedPIN).PadRight(30, ' ');
- }
- PrintRow = PrintRow.TrimEnd() + "\r\n\n ";
- for (int Column = 0; Column < VoucherRow.Count(); Column++)
- {
- IndividualVoucher = VoucherRow[Column];
- SerialNumberTrimmed = IndividualVoucher.Serial;
- if (SerialNumberTrimmed.Length > 24)
- {
- SerialNumberTrimmed = SerialNumberTrimmed.Substring(0, 24);
- }
- PrintRow += (Column == 2 ? " " : "") + SerialNumberTrimmed.PadRight(30, ' ');
- }
- PrintRow = PrintRow.TrimEnd() + "\r\n ";
- for (int Column = 0; Column < VoucherRow.Count(); Column++)
- {
- IndividualVoucher = VoucherRow[Column];
- int CurrentPage = (int)Math.Ceiling(((decimal)IndividualVoucher.SequenceNumber) / 20);
- PrintRow += (Column == 2 ? " " : "") + String.Format("{0}/{1}/{2}", IndividualVoucher.BatchId, IndividualVoucher.SequenceNumber, PageCount).PadRight(30, ' ');
- }
- PrintRow = PrintRow.TrimEnd() + "\r\n ";
- for (int Column = 0; Column < VoucherRow.Count(); Column++)
- {
- IndividualVoucher = VoucherRow[Column];
- PrintRow += (Column == 2 ? " " : "") + IndividualVoucher.Description.PadRight(30, ' ');
- }
- PrintRow = PrintRow.TrimEnd() + "\r\n\n\n\n\n\n\n\n\n\n\n";
- int JobID = Globals.MaxPrinter.Open("Vouchers");
- if (JobID == 0) return;
- Globals.MaxPrinter.Print(PrintRow);
- Globals.MaxPrinter.Close();
- foreach (PrintVoucher PrintedVoucher in VoucherRow)
- {
- var ExportEvent = new EventLog();
- ExportEvent.EventType = VendorEvent.VendorEventType.PrintVoucher;
- ExportEvent.VoucherId = PrintedVoucher.VoucherId;
- ExportEvent.Retry = IsReprint;
- LogEvents.Add(ExportEvent);
- }
- VoucherRow = new List<PrintVoucher>();
- VoucherCount = 0;
- if (RowCount >= 4)
- {
- //Globals.MaxPrinter.NewPage();
- PageCount++;
- RowCount = 0;
- //Globals.MaxPrinter.GetJobInfo(JobID);
- }
- }
- TotalCount++;
- }
- }
- Utility.LogBulkEvents(LogEvents);
- }
- public enum UserPermissions {
- CanPrintOnline,
- CanReprintOnline,
- CanPrintOffline,
- CanReprintOffline,
- BulkExport,
- BulkOrder,
- BulkViewPins,
- BulkReExport
- }
- public static bool CheckUserAccess(UserPermissions Permission) {
- if (Globals.SessionData.Credentials.Payload.User.Level == (int)UserLevel.Administrator) {
- return true;
- }
- switch (Permission) {
- case UserPermissions.CanPrintOnline:
- return Globals.SessionData.Credentials.Payload.User.CanPrintOnline;
- case UserPermissions.CanReprintOnline:
- return Globals.SessionData.Credentials.Payload.User.CanReprintOnline;
- case UserPermissions.CanPrintOffline:
- return Globals.SessionData.Credentials.Payload.User.CanPrintOffline;
- case UserPermissions.CanReprintOffline:
- return Globals.SessionData.Credentials.Payload.User.CanReprintOffline;
- case UserPermissions.BulkViewPins:
- return Globals.SessionData.Credentials.Payload.User.BulkViewPins;
- case UserPermissions.BulkOrder:
- return Globals.SessionData.Credentials.Payload.User.BulkOrder;
- case UserPermissions.BulkExport:
- return Globals.SessionData.Credentials.Payload.User.BulkExport;
- case UserPermissions.BulkReExport:
- return Globals.SessionData.Credentials.Payload.User.BulkReExport;
- default:
- return false;
- }
- }
- public static void Logout() {
- if (Globals.SessionData != null)
- {
- string Sql = "DELETE FROM SessionData"; //Destroy stored session data
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.ExecuteNonQuery();
- string SessionDataJson = JsonConvert.SerializeObject(Globals.SessionData);
- Sql = "INSERT INTO SessionData (Key,Value) VALUES (@key,@value)";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@key", "SessionDataJson"));
- Command.Parameters.Add(new SQLiteParameter("@value", SessionDataJson));
- Command.ExecuteNonQuery();
- Utility.LogEvent(VendorEvent.VendorEventType.Logout);
- while (Globals.LogSyncRunning || Globals.LogSyncThread.IsAlive)
- {
- Globals.LogSyncThread.Join();
- }
- Globals.DBConnection.Close();
- Globals.SessionData = null;
- Globals.SessionDatabasePassword = null;
- Globals.SessionVoucherKey = null;
- Globals.SessionMode = SessionModes.Invalid;
- Globals.ProductCatalogue = null;
- Globals.MaxPrinter.Close();
- UserLoginForm LoginForm = (UserLoginForm)Application.OpenForms["UserLoginForm"];
- LoginForm.Show();
- }
- }
- public static int GetLastSyncedLogID() {
- VendorEventsMetaData MetaData = new VendorEventsMetaData();
- bool MetaDataResult = Utility.RESTRequest<VendorEventsMetaData>(ref MetaData, "/api/vendorevents/meta");
- if (MetaData.LastVendorEventRemoteId == null) {
- return 0;
- }
- return (int)MetaData.LastVendorEventRemoteId;
- }
- public static bool SyncLogs()
- {
- Globals.LogSyncRunning = true;
- bool ReSyncLogs = true;
- while (ReSyncLogs)
- {
- ReSyncLogs = false;
- int LastSyncedLogID = GetLastSyncedLogID();
- string Sql = "SELECT MAX(Id) FROM Logs";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- var result = Command.ExecuteScalar()?.ToString() ?? "0";
- if (string.IsNullOrWhiteSpace(result)) result = "0";
- int LastRecordedLogId = int.Parse(result.ToString());
- if (LastRecordedLogId > LastSyncedLogID)
- { //If local logs are newer than server logs
- List<RemoteVendorEvent> EventList = new List<RemoteVendorEvent>();
- RemoteVendorEvent NextEvent;
- RemoteVendorEventResponse LastVendorEventIdSynced;
- int Counter = 0;
- Command = new SQLiteCommand("Select Id,UserId,VoucherId,EventDate,EventType From Logs WHERE Id > @id", Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@id", LastSyncedLogID));
- using (SQLiteDataReader read = Command.ExecuteReader())
- {
- while (read.Read())
- {
- Counter += 1;
- NextEvent = new RemoteVendorEvent();
- NextEvent.Id = read.GetInt32(0);
- NextEvent.UserId = read.GetInt32(1);
- if (read.IsDBNull(2) == true)
- {
- NextEvent.VoucherId = null;
- }
- else
- {
- NextEvent.VoucherId = read.GetInt32(2);
- }
- NextEvent.EventDate = (DateTime)read.GetDateTime(3);
- NextEvent.EventType = (VendorEvent.VendorEventType)Enum.Parse(typeof(VendorEvent.VendorEventType), read.GetValue(4).ToString());
- NextEvent.VendorId = Globals.SessionData.Credentials.Payload.Vendor.id;
- EventList.Add(NextEvent);
- if (Counter == 1000)
- { //Send logs in pages of 1000
- LastVendorEventIdSynced = new RemoteVendorEventResponse();
- bool EventPostResult = Utility.RESTRequest<List<RemoteVendorEvent>, RemoteVendorEventResponse>(EventList, ref LastVendorEventIdSynced, "/api/vendorevents/");
- Counter = 0;
- EventList = new List<RemoteVendorEvent>();
- }
- }
- if (Counter > 0)
- { //Left over logs not synced in a 100 item page
- LastVendorEventIdSynced = new RemoteVendorEventResponse();
- bool EventPostResult = Utility.RESTRequest<List<RemoteVendorEvent>, RemoteVendorEventResponse>(EventList, ref LastVendorEventIdSynced, "/api/vendorevents/");
- }
- }
- }
- else if (LastSyncedLogID > LastRecordedLogId)
- { //Server logs are newer than local logs, indicating loss of local database - resync entire table
- Sql = "DELETE FROM Logs";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.ExecuteNonQuery();
- Page<VendorEvent> EventPage;
- int TotalPages = 1;
- for (int PageNumber = 1; PageNumber <= TotalPages; PageNumber++)
- {
- EventPage = new Page<VendorEvent>();
- bool EventGetResult = Utility.RESTRequest<Page<VendorEvent>>(ref EventPage, String.Format("/api/vendorevents/?page={0}&pagesize=1000", PageNumber));
- if (TotalPages == 1)
- { //Number of pages is sent with first page, so update on the fly
- TotalPages = EventPage.NumPages;
- }
- using (var Trans = Globals.DBConnection.BeginTransaction())
- {
- foreach (VendorEvent Event in EventPage.Items)
- {
- if (Event.RemoteId != null) //Only interested in downloading locally generated logs
- {
- Sql = "INSERT INTO Logs (Id, UserId, VoucherId, EventDate, EventType, Retry) VALUES (@id, @userid, @voucherid, @eventdate, @eventtype, @retry)";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@id", Event.RemoteId));
- Command.Parameters.Add(new SQLiteParameter("@userid", Event.UserId));
- Command.Parameters.Add(new SQLiteParameter("@voucherid", Event.VoucherId));
- Command.Parameters.Add(new SQLiteParameter("@eventdate", Event.EventDate.UtcDateTime));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", Event.EventType));
- Command.Parameters.Add(new SQLiteParameter("@retry", Event.Retry));
- Command.ExecuteNonQuery();
- }
- }
- Trans.Commit();
- }
- }
- }
- if (Globals.LogSyncWaiting)
- {
- Globals.LogSyncWaiting = false;
- ReSyncLogs = true;
- }
- }
- Globals.LogSyncRunning = false;
- return true;
- }
- public static void LogBulkEvents(List<EventLog> EventLogs)
- {
- string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
- using (var Trans = Globals.DBConnection.BeginTransaction())
- {
- foreach (var EventLog in EventLogs)
- {
- using (SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection))
- {
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- Command.Parameters.Add(new SQLiteParameter("@voucherid", EventLog.VoucherId));
- Command.Parameters.Add(new SQLiteParameter("@eventdate", DateTime.UtcNow));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", EventLog.EventType));
- Command.Parameters.Add(new SQLiteParameter("@retry", EventLog.Retry));
- Command.ExecuteNonQuery();
- }
- }
- Trans.Commit();
- }
- //string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
- //SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- if (Globals.SessionMode == SessionModes.Online)
- {
- //if (Globals.LogSyncTask != null && Globals.LogSyncTask.Status == TaskStatus.Running)
- if (Globals.LogSyncRunning)
- {
- Globals.LogSyncWaiting = true;
- return;
- }
- Globals.LogSyncThread = new Thread(() => SyncLogs());
- Globals.LogSyncThread.Start();
- //var Result = await Task.Run(() => SyncLogs()).ConfigureAwait(false);
- }
- }
- public static void LogEvent(VendorEvent.VendorEventType EventType, int? VoucherId = null, bool Retry = false)
- {
- string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
- using (SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection))
- {
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- Command.Parameters.Add(new SQLiteParameter("@voucherid", VoucherId));
- Command.Parameters.Add(new SQLiteParameter("@eventdate", DateTime.UtcNow));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", EventType));
- Command.Parameters.Add(new SQLiteParameter("@retry", Retry));
- Command.ExecuteNonQuery();
- }
- //string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
- //SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- if (Globals.SessionMode == SessionModes.Online)
- {
- //if (Globals.LogSyncTask != null && Globals.LogSyncTask.Status == TaskStatus.Running)
- if (Globals.LogSyncRunning)
- {
- Globals.LogSyncWaiting = true;
- return;
- }
- Globals.LogSyncThread = new Thread(() => SyncLogs());
- Globals.LogSyncThread.Start();
- //var Result = await Task.Run(() => SyncLogs()).ConfigureAwait(false);
- }
- }
- private static void SaveCurrentUserUsage() {
- string Sql = "DELETE FROM AccessControlTracking WHERE UserID = @userid";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- Command.ExecuteNonQuery();
- Sql = "INSERT INTO AccessControlTracking (UserID, Date, Permission, CurrentUsage) Values" +
- "(@userid, datetime('now'), 'OfflinePrint', @offlineprintvalue)," +
- "(@userid, datetime('now'), 'OfflineReprint', @offlinereprintvalue)," +
- "(@userid, datetime('now'), 'OnlinePrint', @onlineprintvalue)," +
- "(@userid, datetime('now'), 'OnlineReprint', @onlinereprintvalue)," +
- "(@userid, datetime('now'), 'BulkOrder', @bulkorder)," +
- "(@userid, datetime('now'), 'BulkExport', @bulkexport)";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- Command.Parameters.Add(new SQLiteParameter("@offlineprintvalue", Globals.UserCurrentUsage.OfflinePrintValue));
- Command.Parameters.Add(new SQLiteParameter("@offlinereprintvalue", Globals.UserCurrentUsage.OfflineReprintValue));
- Command.Parameters.Add(new SQLiteParameter("@onlineprintvalue", Globals.UserCurrentUsage.OnlinePrintValue));
- Command.Parameters.Add(new SQLiteParameter("@onlinereprintvalue", Globals.UserCurrentUsage.OnlineReprintValue));
- Command.Parameters.Add(new SQLiteParameter("@bulkorder", Globals.UserCurrentUsage.BulkOrderValue));
- Command.Parameters.Add(new SQLiteParameter("@bulkexport", Globals.UserCurrentUsage.BulkExportValue));
- Command.ExecuteNonQuery();
- }
- public static void AddUserUsage(UserLimits.UserLimitTypes UserLimitType, decimal Value) {
- DateTime ServerDate = Globals.SessionData.Credentials.Payload.Date;
- DateTime Today = DateTime.Now;
- if (ServerDate.Date != Today.Date) //prevent system time tampering
- {
- MessageBox.Show("Date mismatch detected. Logging out.", "Server Date Mismatch", MessageBoxButtons.OK, MessageBoxIcon.Error);
- Logout();
- return;
- }
- switch (UserLimitType) {
- case UserLimits.UserLimitTypes.OfflinePrint:
- Globals.UserCurrentUsage.OfflinePrintValue += Value;
- break;
- case UserLimits.UserLimitTypes.OfflineReprint:
- Globals.UserCurrentUsage.OfflineReprintValue += Value;
- break;
- case UserLimits.UserLimitTypes.OnlinePrint:
- Globals.UserCurrentUsage.OnlinePrintValue += Value;
- break;
- case UserLimits.UserLimitTypes.OnlineReprint:
- Globals.UserCurrentUsage.OnlineReprintValue += Value;
- break;
- case UserLimits.UserLimitTypes.BulkExport:
- Globals.UserCurrentUsage.BulkExportValue += Value;
- break;
- case UserLimits.UserLimitTypes.BulkOrder:
- Globals.UserCurrentUsage.BulkOrderValue += Value;
- break;
- }
- //Immediately write to db to avoid cheating
- SaveCurrentUserUsage();
- }
- public static Boolean IsValueWithinRemainingUserLimit(UserLimits.UserLimitTypes UserLimitType, decimal Value) {
- decimal RemainingUserLimit = CheckRemainingUserLimit(UserLimitType);
- if (RemainingUserLimit == -1 || RemainingUserLimit >= Value) {
- return true;
- }
- return false;
- }
- public static decimal CheckRemainingUserLimit(UserLimits.UserLimitTypes UserLimitType) {
- if (Globals.SessionData.Credentials.Payload.User.Level == (int)UserLevel.Administrator)
- {
- return -1; //Signifies unlimited
- }
- switch (UserLimitType)
- {
- case UserLimits.UserLimitTypes.OfflinePrint:
- if (Globals.SessionData.Credentials.Payload.User.CanPrintOffline)
- {
- if (Globals.SessionData.Credentials.Payload.User.OfflinePrintValue > 0) //Unlimited from server is signified by 0, but remaining limit at 0 means limit reached, so change unlimited to -1 for internal use
- {
- return Globals.SessionData.Credentials.Payload.User.OfflinePrintValue - Globals.UserCurrentUsage.OfflinePrintValue;
- }
- else
- {
- return -1; //Signifies unlimited
- }
- }
- else
- {
- return 0;
- }
- case UserLimits.UserLimitTypes.OfflineReprint:
- if (Globals.SessionData.Credentials.Payload.User.CanReprintOffline)
- {
- if (Globals.SessionData.Credentials.Payload.User.OfflineReprintValue > 0) //Unlimited from server is signified by 0, but remaining limit at 0 means limit reached, so change unlimited to -1 for internal use
- {
- return Globals.SessionData.Credentials.Payload.User.OfflineReprintValue - Globals.UserCurrentUsage.OfflineReprintValue;
- }
- else
- {
- return -1; //Signifies unlimited
- }
- }
- else
- {
- return 0;
- }
- case UserLimits.UserLimitTypes.OnlinePrint:
- if (Globals.SessionData.Credentials.Payload.User.CanPrintOnline)
- {
- if (Globals.SessionData.Credentials.Payload.User.OnlinePrintValue > 0) //Unlimited from server is signified by 0, but remaining limit at 0 means limit reached, so change unlimited to -1 for internal use
- {
- return Globals.SessionData.Credentials.Payload.User.OnlinePrintValue - Globals.UserCurrentUsage.OnlinePrintValue;
- }
- else
- {
- return -1; //Signifies unlimited
- }
- }
- else
- {
- return 0;
- }
- case UserLimits.UserLimitTypes.OnlineReprint:
- if (Globals.SessionData.Credentials.Payload.User.CanReprintOnline)
- {
- if (Globals.SessionData.Credentials.Payload.User.OnlineReprintValue > 0) //Unlimited from server is signified by 0, but remaining limit at 0 means limit reached, so change unlimited to -1 for internal use
- {
- return Globals.SessionData.Credentials.Payload.User.OnlineReprintValue - Globals.UserCurrentUsage.OnlineReprintValue;
- }
- else
- {
- return -1; //Signifies unlimited
- }
- }
- else
- {
- return 0;
- }
- case UserLimits.UserLimitTypes.BulkExport:
- if (Globals.SessionData.Credentials.Payload.User.BulkExport)
- {
- if (Globals.SessionData.Credentials.Payload.User.BulkExportMaxValue > 0) //Unlimited from server is signified by 0, but remaining limit at 0 means limit reached, so change unlimited to -1 for internal use
- {
- return Globals.SessionData.Credentials.Payload.User.BulkExportMaxValue - Globals.UserCurrentUsage.BulkExportValue;
- }
- else
- {
- return -1; //Signifies unlimited
- }
- }
- else
- {
- return 0;
- }
- case UserLimits.UserLimitTypes.BulkOrder:
- if (Globals.SessionData.Credentials.Payload.User.BulkOrder)
- {
- if (Globals.SessionData.Credentials.Payload.User.BulkOrderMaxValue > 0) //Unlimited from server is signified by 0, but remaining limit at 0 means limit reached, so change unlimited to -1 for internal use
- {
- return Globals.SessionData.Credentials.Payload.User.BulkOrderMaxValue - Globals.UserCurrentUsage.BulkOrderValue;
- }
- else
- {
- return -1; //Signifies unlimited
- }
- }
- else
- {
- return 0;
- }
- }
- return 0;
- }
- private static int GetVoucherPrintCountFromLogs(int VoucherId)
- {
- string Sql = "SELECT COUNT(*) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@voucherid", VoucherId));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher));
- return int.Parse(Command.ExecuteScalar().ToString());
- }
- private static DateTime GetVoucherFirstPrintDateFromLogs(int VoucherId)
- {
- string Sql = "SELECT MIN(EventDate) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@voucherid", VoucherId));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher));
- return (DateTime)Command.ExecuteScalar();
- }
- private static decimal GetVoucherFaceValue(int VoucherId)
- {
- string Sql = "SELECT b.FaceValue FROM Voucher v LEFT JOIN Batch b on v.BatchId = b.Id WHERE v.Id=@voucherid";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@voucherid", VoucherId));
- return (decimal)Command.ExecuteScalar();
- }
- private static UserLimits CalculateUsageFromLogs() {
- UserLimits CalculateUsage = new UserLimits();
- CalculateUsage.OfflinePrintValue = 0;
- CalculateUsage.OfflineReprintValue = 0;
- CalculateUsage.OnlinePrintValue = 0;
- CalculateUsage.OnlineReprintValue = 0;
- var CurrentDate = DateTime.Today.Date;
- CultureInfo IVC = CultureInfo.InvariantCulture;
- string Sql = "SELECT VoucherId FROM Logs WHERE UserId=@userid AND EventDate BETWEEN @eventdatea AND @eventdateb AND EventType=@eventtype";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- Command.Parameters.Add(new SQLiteParameter("@eventdatea", CurrentDate.ToString("yyyy-MM-dd 00:00:00", IVC)));
- Command.Parameters.Add(new SQLiteParameter("@eventdateb", CurrentDate.ToString("yyyy-MM-dd 23:59:59", IVC)));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher));
- int VoucherId;
- decimal VoucherFaceValue;
- using (SQLiteDataReader read = Command.ExecuteReader())
- {
- while (read.Read())
- {
- VoucherId = read.GetInt32(0);
- VoucherFaceValue = GetVoucherFaceValue(VoucherId);
- //Don't distinguish between online and offline usage for log recalculations
- CalculateUsage.OfflinePrintValue += VoucherFaceValue;
- CalculateUsage.OnlinePrintValue += VoucherFaceValue;
- if (GetVoucherPrintCountFromLogs(VoucherId) > 1) { //For reprinted vouchers just assume all prints were reprints - log recalculations should be stricter to prevent cheating
- CalculateUsage.OfflineReprintValue += VoucherFaceValue;
- CalculateUsage.OnlineReprintValue += VoucherFaceValue;
- }
- }
- }
- return CalculateUsage;
- }
- public static void InitialiseUserLimits()
- {
- Globals.UserCurrentUsage = new UserLimits();
- UserLimits CurrentUserLimits = new UserLimits();
- string Sql = "SELECT COUNT(*) FROM AccessControlTracking WHERE UserID = @userid";
- SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- int Result = int.Parse(Command.ExecuteScalar().ToString());
- Sql = "SELECT Date FROM AccessControlTracking WHERE UserID = @userid";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- object ResultDate = Command.ExecuteScalar();
- bool DatePassed = false;
- if (ResultDate != null) {
- DateTime DateResult = DateTime.Parse(Command.ExecuteScalar().ToString());
- if (DateResult.Date < Globals.SessionData.Credentials.Payload.Date.Date) {
- DatePassed = true;
- }
- }
- if (DatePassed)
- { //Fresh day since last db write or data missing - fetch usage from logs incase of tampering
- Globals.UserCurrentUsage = CalculateUsageFromLogs();
- SaveCurrentUserUsage(); //Immediately write calculated usage to DB
- }
- else
- {
- if (Result == 6)
- {
- Sql = "SELECT UserID, Permission, CurrentUsage FROM AccessControlTracking WHERE UserID = @userid";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- using (SQLiteDataReader read = Command.ExecuteReader())
- {
- while (read.Read())
- {
- switch (read["Permission"])
- {
- case "OfflinePrint":
- Globals.UserCurrentUsage.OfflinePrintValue = (decimal)read["CurrentUsage"];
- break;
- case "OfflineReprint":
- Globals.UserCurrentUsage.OfflineReprintValue = (decimal)read["CurrentUsage"];
- break;
- case "OnlinePrint":
- Globals.UserCurrentUsage.OnlinePrintValue = (decimal)read["CurrentUsage"];
- break;
- case "OnlineReprint":
- Globals.UserCurrentUsage.OnlineReprintValue = (decimal)read["CurrentUsage"];
- break;
- case "BulkOrder":
- Globals.UserCurrentUsage.BulkOrderValue = (decimal)read["CurrentUsage"];
- break;
- case "BulkExport":
- Globals.UserCurrentUsage.BulkExportValue = (decimal)read["CurrentUsage"];
- break;
- }
- }
- }
- }
- else
- {
- Globals.UserCurrentUsage = CalculateUsageFromLogs();
- SaveCurrentUserUsage(); //Immediately write calculated usage to DB
- }
- }
- }
- public static int GetNumberOfUnprintedVouchersInRange(int StartSeqNo, int EndSeqNo, int BatchId) {
- int UnprintedVouchers = 0;
- int VoucherId;
- string Sql;
- SQLiteCommand Command;
- for (int SeqNo = StartSeqNo; SeqNo <= EndSeqNo; SeqNo++)
- {
- Sql = "SELECT Id FROM Voucher WHERE SequenceNumber=@sequencenumber AND BatchId=@batchid";
- Command = new SQLiteCommand(Sql, Globals.DBConnection);
- Command.Parameters.Add(new SQLiteParameter("@sequencenumber", SeqNo));
- Command.Parameters.Add(new SQLiteParameter("@batchid", BatchId));
- VoucherId = int.Parse(Command.ExecuteScalar().ToString());
- int NumPrintedVouchers = GetVoucherPrintCountFromLogs(VoucherId);
- if (NumPrintedVouchers == 0) {
- UnprintedVouchers++;
- }
- }
- return UnprintedVouchers;
- }
- public class BulkLogger : IDisposable
- {
- SQLiteTransaction transaction;
- SQLiteCommand logCommand;
- public BulkLogger()
- {
- transaction = Globals.DBConnection.BeginTransaction();
- string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
- logCommand = new SQLiteCommand(Sql, Globals.DBConnection);
- logCommand.Transaction = transaction;
- }
- public void LogEvent(VendorEvent.VendorEventType EventType, int? VoucherId = null, bool Retry = false)
- {
- var Command = logCommand;
- if (Command.Parameters.Count == 0)
- {
- Command.Parameters.Add(new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
- Command.Parameters.Add(new SQLiteParameter("@voucherid", VoucherId));
- Command.Parameters.Add(new SQLiteParameter("@eventdate", DateTime.UtcNow));
- Command.Parameters.Add(new SQLiteParameter("@eventtype", EventType));
- Command.Parameters.Add(new SQLiteParameter("@retry", Retry));
- }
- else
- {
- Command.Parameters[1].Value = VoucherId;
- Command.Parameters[2].Value = DateTime.UtcNow;
- Command.Parameters[3].Value = EventType;
- Command.Parameters[4].Value = Retry;
- }
- Command.ExecuteNonQuery();
- }
- private void SyncLogs()
- {
- //string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
- //SQLiteCommand Command = new SQLiteCommand(Sql, Globals.DBConnection);
- if (Globals.SessionMode == SessionModes.Online)
- {
- //if (Globals.LogSyncTask != null && Globals.LogSyncTask.Status == TaskStatus.Running)
- if (Globals.LogSyncRunning)
- {
- Globals.LogSyncWaiting = true;
- return;
- }
- Globals.LogSyncThread = new Thread(() => SyncLogs());
- Globals.LogSyncThread.Start();
- //var Result = await Task.Run(() => SyncLogs()).ConfigureAwait(false);
- }
- }
- #region IDisposable Support
- private bool disposedValue = false; // To detect redundant calls
- protected virtual void Dispose(bool disposing)
- {
- if (!disposedValue)
- {
- if (disposing)
- {
- transaction.Commit();
- logCommand.Dispose();
- SyncLogs();
- }
- // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
- // TODO: set large fields to null.
- disposedValue = true;
- }
- }
- // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
- // ~BulkLogger() {
- // // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
- // Dispose(false);
- // }
- // This code added to correctly implement the disposable pattern.
- public void Dispose()
- {
- // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
- Dispose(true);
- // TODO: uncomment the following line if the finalizer is overridden above.
- // GC.SuppressFinalize(this);
- }
- #endregion
- }
- }
- }
|