| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163 |
- 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 = 1;
- 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", 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];
- 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
- }
- }
- }
|