public override BarcodeGroup GenerateFastTrackBarcode(FastTrackOptions options)
        {
            var result = base.GenerateFastTrackBarcode(options);

            new BarcodeCreation
            {
                RecordID = Guid.NewGuid(),
                BarcodeRecordID = options.SavedRecordId,
                Name = options.PassengerName,
                Airline = options.Airline.FormattedAirline(),
                AirlineGuid = options.AirlineGuid,
                DepartureAirport = options.DepartureAirport,
                DepartureAirportGuid = options.DepartureAirportGuid,
                DestinationAirport = options.DestinationAirport,
                DestinationAirportGuid = options.DestinationAirportGuid,
                UserType = MapUserType(options.UserType),
                TicketType = options.TicketType,
                StartDate = DateTime.Parse(options.StartDate),
                EndDate = DateTime.Parse(options.EndDate),
                EmailAddress = options.Email,
                CreatedDateTime = DateTime.Now
            }.Save();

            return result;
        }
        public MemoryStream GenerateFile(FastTrackOptions options)
        {
            var result = _barcodeGenerator.GenerateFastTrackBarcode(options);

            var stream = new MemoryStream();
            result.image.Save(stream, ImageFormat.Bmp);
            stream.Position = 0;

            return stream;
        }
 public BarcodeGroup GenerateFastTrackBarcode(FastTrackOptions options)
 {
     Random rndNumber = new Random();
     //	Generate random name
     //var png = new PersonNameGenerator();
     string name;
     if (rndNumber.Next(0, 2) == 0)
     {
         name = "Mrs Test Name";// + png.GenerateRandomFemaleFirstName() + " " + png.GenerateRandomLastName();
     }
     else
     {
         name = "Mr Test Name";// + png.GenerateRandomMaleFirstName() + " " + png.GenerateRandomLastName();
     }
     //	random flight number
     var ag = AccessGateFlightInfo.ToList(DateTime.Today.AddDays(-7), DateTime.Today);
     Console.WriteLine(ag.Count);
     if (ag.Count == 0)
     {
         Console.WriteLine("No Flights");
         return new BarcodeGroup();
     }
     var randomFlight = ag[rndNumber.Next(0, ag.Count - 1)];
     var flightNo = randomFlight.FlightNo;
     if (flightNo.Length < 5)
     {
         flightNo = flightNo.PadRight(5, ' ');
     }
     //	random seat
     var seat = "";
     var rndSeatLetter = rndNumber.Next(65, 73);
     var seatLetter = (char)rndSeatLetter;
     var rndSeatNumber = rndNumber.Next(1, 11);
     seat = string.Format("{0}{1}", rndSeatNumber, seatLetter).PadLeft(4, '0');
     //	random cisn
     var rndCisn = rndNumber.Next(0, 150);
     var cisn = rndCisn.ToString().PadLeft(5, '0');
     //	return barcode
     BarcodeOptions testParams = new BarcodeOptions()
     {
         Name = name,
         FlightNo = flightNo,
         Seat = seat,
         CISN = cisn,
         StartDate = DateTime.Today.AddDays(-7).ToString("yyyyMMdd"),
         EndDate = DateTime.Today.ToString("yyyyMMdd"),
         AP = "test"
     };
     var bw = new BarcodeWriter
     {
         Format = BarcodeFormat.PDF_417,
         Options = { Margin = 2 }
     };
     return Generate(bw, testParams);
 }
        public MemoryStream GenerateFile(FastTrackOptions options)
        {
            var barcodeList = new List<BarcodeGroup>();

            for (var i = 0; i < options.Quantity; i++)
            {
                barcodeList.Add(_barcodeGenerator.GenerateFastTrackBarcode(options));
            }
            
            return _pdfBarcodesGenerator.GeneratePdf(new MemoryStream(), barcodeList, options.Quantity);
        }
        public bool EmailBarcodeFile(FastTrackOptions options, IBarcodeFileGenerator barcodeFileGenerator)
        {
            try
            {
                if (options == null || barcodeFileGenerator == null || string.IsNullOrWhiteSpace(options.Email))
                    return false;

                EmailOptions emailOptions = new EmailOptions()
                {
                    To = new List<string>(),
                    From = "*****@*****.**",
                    Subject = "GeneratedBarcode" + DateTime.Now.ToString("dd MMM yyyy HH mm") + ".pdf",
                    AttachmentStreams = new List<AttachmentStream>()
                };

                StringBuilder emailBody = new StringBuilder();

                emailBody.Append(string.Format("Generated {0} barcode {1} for {2}.\n", options.Quantity,
                    (options.Quantity > 1 ? "s " : " "), options.Name));

                emailBody.Append(string.Format("Departure Airport: {0}\n", options.DepartureAirport));
                emailBody.Append(string.Format("Destination Airport: {0}\n", options.DestinationAirport));
                emailBody.Append(string.Format("User Type: {0}\n", options.UserType));
                emailBody.Append(string.Format("Ticket Type: {0}\n", options.TicketType));
                emailBody.Append(string.Format("From {0} to {1}", options.StartDate, options.EndDate));

                emailOptions.Body = emailBody.ToString();
                emailOptions.To.Add(options.Email);

                emailOptions.AttachmentStreams.Add(new AttachmentStream()
                {
                    FileStream = new MemoryStream(barcodeFileGenerator.GenerateFile(options).ToArray()),
                    FileName = emailOptions.Subject
                });

                _emailer.Send(emailOptions);

                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
        public override BarcodeGroup GenerateFastTrackBarcode(FastTrackOptions options)
        {
            var result = base.GenerateFastTrackBarcode(options);

            options.SavedRecordId = Guid.NewGuid();

            new FastTrackBarcode
            {
                RecordID = options.SavedRecordId,
                BarcodeHash = SEMS.BusinessObjects.Hashing.MurMur3.ToInt(result.barcode),
                Barcode = result.barcode,
                PassengerName = options.PassengerName,
                PNRCode = options.Pnr,
                FromAirport = options.DepartureAirport,
                CarrierDesignator = "---",
                FlightNumber = "-",
                CheckInSequenceNumber = result.serial.ToString(),
                Deleted = false,
                CreatedOn = DateTime.Now,
                UpdatedOn = DateTime.Now
            }.Save();

            return result;
        }
        public CommonModule(IPdfTemplateHelper pdfTemplateHelper, IEmailer emailer,
            IPdfBarcodesGenerator pdfBarcodesGenerator) : base("/api")
		{
		    _pdfTemplateHelper = pdfTemplateHelper;
            _emailer = emailer;
            _pdfBarcodesGenerator = pdfBarcodesGenerator;
            //	BARCODE FUNCTIONS
			//	Returns a list of airports
			Get["/getAirports"] = _ =>
			{
				var airportList = CustomerSite.ToList().Where(x => x.IsAirport).ToList().OrderBy(x => x.Name);
				return Response.AsJson(airportList.ToList());
			};
			//	Returns a list of airports that have been formatted for a select input
			Get["/getAirportList"] = _ =>
			{
				var airports = CustomerSite.ToList().Where(x => x.IsAirport).ToList();
				List<SelectList> airportList = new List<SelectList>();

				foreach(var airport in airports)
				{
					airportList.Add(new SelectList(){
						id = airport.RecordID,
						text = airport.Name.Trim()
					});
				}

				return Response.AsJson(airportList.OrderBy(x => x.text).ToList());
			};
            
            //	Returns all available pdf templates
		    Get["/getPdfTemplates"] = _ => Response.AsJson(_pdfTemplateHelper.GetTemplates());

            //	Returna a list of Airlines
            Get["/getAirlines"] = _ =>
			{
				var airlineList = AirlineDBO.ToList().OrderBy(x => x.Name);
				return Response.AsJson(airlineList.ToList());
			};
			//	Returns a list of Airlines that have been formatted for a select input
			Get["/getAirlineList"] = _ =>
			{
				var airlines = AirlineDBO.ToList();
				List<SelectList> airlineList = new List<SelectList>();

				foreach(var airline in airlines)
				{
					airlineList.Add(new SelectList()
					{
						id = airline.RecordID,
						text = airline.Name.Trim()
					});
				}

				return Response.AsJson(airlineList.OrderBy(x => x.text).ToList());
			};
            //  Returns a list of barcodes
            Post["/getBarcodes/{type}"] = _ =>
            {
				BarcodeWhere where = this.Bind<BarcodeWhere>();
				DateTime start = new DateTime();
				DateTime end = new DateTime();
				bool validStart = DateTime.TryParse(where.StartDate, out start);
				bool validEnd = DateTime.TryParse(where.EndDate, out end);
				//	If no dates were provided, this gets all.
				if(!validStart && !validEnd)
				{
					var barcodeList = BarcodeCreation.ToListDTO();
					return Response.AsJson(barcodeList.OrderByDescending(x => x.CreatedDateTime).ToList());
				}
				//	If one of the dates isn't valid, this returns.
				else if(!validStart || !validEnd)
				{
					return HttpStatusCode.BadRequest;
				}
				//	Otherwise this returns the filtered results
				else
				{
					var barcodeList = BarcodeCreation.ToListDTO(start, end);
					return Response.AsJson(barcodeList.OrderByDescending(x => x.CreatedDateTime).ToList());
				}
            };
			//	Returns all the details of a barcode - BarcodeCreation, FastTrackBarcode, FastTrackBarcode.Actions
			Get["/getBarcode/{type}/{recordID}"] = _ =>
			{
				Guid recordID;
				bool validGuid = Guid.TryParse(_.recordID, out recordID);
				//	If an invalid Guid was provided, return bad request
				if (!validGuid)
				{
					return HttpStatusCode.BadRequest;
				}
				var barcode = BarcodeCreation.Load(recordID);
				return Response.AsJson(barcode);
			};
			//	Returns a list of barcode actions
			Get["/getBarcodeActions/{type}/{recordID}"] = _ =>
			{
				Guid recordGUID;
				bool validGuid = Guid.TryParse(_.recordID, out recordGUID);
				if (!validGuid)
				{
					return HttpStatusCode.BadRequest;
				}
				var fastTrackActions = FastTrackBarcode.Actions(recordGUID);
				return Response.AsJson(fastTrackActions);
			};
			//	For creating a barcode
			Post["/createBarcode/{type}/{format}"] = _ =>
			{
				string type = _.type;
				string format = _.format;
				//	If departure airport, copy to guid field and then replace with iata
			    IBarcodeGenerator barcodeGenerator = null;
			    FastTrackOptions barcodeOptions = new FastTrackOptions
			    {
			        Quantity = 1
			    };

                Guid temp = new Guid();
                //	Generate barcode
                switch (type)
				{
					case "fasttrack":
				        barcodeGenerator =
				            new AddbarcodeCreationRecordToDb(new SaveFastTrackBarcodeRecordToDb(new BarcodeGenerator()));

                        barcodeOptions = this.Bind<FastTrackOptions>();

                        //	If airline, copy to guid field and then replace with iata, unless it is ---
                        if (!string.IsNullOrWhiteSpace(barcodeOptions.Airline) && barcodeOptions.Airline.Trim() != "---")
						{
							if(Guid.TryParse(barcodeOptions.Airline, out temp))
							{
								Airline airline = Airline.Load(temp);
								//	If no airline was found, empty airline fields
								if(airline == null)
								{
									barcodeOptions.Airline = "---";
									barcodeOptions.AirlineGuid = null;
								}
								//	Otherwise update fields
								else
								{
									barcodeOptions.Airline = airline.AirlineIATA;
									barcodeOptions.AirlineGuid = temp;
								}
							}
						}
						//	If departure airport, copy to guid field and then replace with iata
						if (!string.IsNullOrWhiteSpace(barcodeOptions.DepartureAirport))
						{
							if(Guid.TryParse(barcodeOptions.DepartureAirport, out temp))
							{
								CustomerSite site = CustomerSite.Load(temp);
								//	If no airport was found, that means it doesn't exist, so empties departure fields
								if(site == null)
								{
									barcodeOptions.DepartureAirport = null;
									barcodeOptions.DepartureAirportGuid = null;
								}
								//	Otherwise update fields
								else
								{
									barcodeOptions.DepartureAirportGuid = temp;
									barcodeOptions.DepartureAirport = site.AirportIATADesignation;
								}
							}
						}
						//	If destination airport, copy to guid field and then replace with iata
						if (!string.IsNullOrWhiteSpace(barcodeOptions.DestinationAirport))
						{
							if (Guid.TryParse(barcodeOptions.DestinationAirport, out temp))
							{
								//	If the same as departure, just copy name
								if(barcodeOptions.DepartureAirport == barcodeOptions.DestinationAirport)
								{
									barcodeOptions.DestinationAirport = barcodeOptions.DepartureAirport;
									barcodeOptions.DestinationAirportGuid = barcodeOptions.DepartureAirportGuid;
								}
								//	Otherwise load airport details
								else
								{
									CustomerSite site = CustomerSite.Load(temp);
									//	If no airport was found, that means it doesn't exist, so empties departure fields
									if (site == null)
									{
										barcodeOptions.DestinationAirport = null;
										barcodeOptions.DestinationAirportGuid = null;
									}
									//	Otherwise update fields
									else
									{
										barcodeOptions.DestinationAirportGuid = temp;
										barcodeOptions.DestinationAirport = site.AirportIATADesignation;
									}
								}
							}
						}
						break;
					case "test":
                        barcodeGenerator = new TestBarcodeGenerator();
						break;
					default:
						return HttpStatusCode.BadRequest;
				}
				switch (format)
				{
					case "image":
						List<string> returnText = new List<string>();
                        IBarcodeFileGenerator imageGenerator = new BarcodeImageFileGenerator(barcodeGenerator);

                        for (var i = 0; i < barcodeOptions.Quantity; i++)
				        {
				            returnText.Add(Convert.ToBase64String(imageGenerator.GenerateFile(barcodeOptions).ToArray()));
				        }

						return Response.AsJson(returnText);
					//break;
					case "email":
				        var result = new EmailFastTrackBarcodes(_emailer).EmailBarcodeFile(barcodeOptions,
				            new BarcodePdfFileGenerator(barcodeGenerator, _pdfBarcodesGenerator));

				        return result ? HttpStatusCode.Accepted : HttpStatusCode.BadRequest;
					case "pdf":
				        var stream =
				            new BarcodePdfFileGenerator(barcodeGenerator, _pdfBarcodesGenerator).GenerateFile(barcodeOptions);
                        var streamClone = new MemoryStream(stream.ToArray());
                        Response response = new Response();
				        response.Headers.Add("Content-Disposition",
				            "attachment; filename=GeneratedBarcode" + DateTime.Now.ToString("dd MMM yyyy HH mm") + ".pdf");

						response.Headers.Add("responseType", "arraybuffer");
						response.Contents = responseStream =>
						{
                            streamClone.CopyTo(responseStream);
						};
						return response;
				}
				//	Return BadRequest if not returned already
				return HttpStatusCode.BadRequest;
			};
			//	Exports all the barcodes
			Post["/exportBarcodes/{type}"] = _ =>
			{
				List<string> barcodeGuids = this.BindTo(new List<string>());
				//	If no guids were posted, export all
				if (barcodeGuids.Count() == 0)
				{
					return CSVExporter.ExportBarcodes();
				}
				//	Otherwise export select few
				else
				{
					return CSVExporter.ExportBarcodes(barcodeGuids);
				}
			};
			//	logs the user in using sems data object
			Post["/login/{type}"] = _ =>
			{
				//bind to object model
				var loginParams = this.Bind<Login>();
				//decrypt username
				loginParams.Username = Decrypt.DecryptString(loginParams.Username, _.type + "key");
				//pass sems data obejct user method the username
				var user = User.LoadUser(loginParams.Username);
				//if no user, return 401
				if (user == null)
				{
					Console.WriteLine("No User");
					return HttpStatusCode.Unauthorized;
				}
				//decrypt password
				loginParams.Password = Decrypt.DecryptString(loginParams.Password, _.type + "key");
				//if incorrect password, return 401
				if (user.Password != loginParams.Password)
				{
					Console.WriteLine("Wrong Password");
					return HttpStatusCode.Unauthorized;
				}
				var token = user.RecordID;
				//login but dont redirect, this is handled front end by angular
				return this.LoginWithoutRedirect(token);
			};
			//	logs the user in using sems data object
			Post["/login"] = _ =>
            {
                //bind to object model
                var loginParams = this.Bind<Login>();
				//pass sems data obejct user method the username
				var user = MachSecure.SEMS.DataObjects.User.LoadUser(loginParams.Username);
                //if no user, return 401
                if (user == null)
				{
					Console.WriteLine("Wrong Username");
					return HttpStatusCode.Unauthorized;
				}
                //if incorrect password, return 401
                if (user.Password != loginParams.Password)
				{
					Console.WriteLine("Wrong Password");
					return HttpStatusCode.Unauthorized;
				}
				var token = user.RecordID;
                //login but dont redirect, this is handled front end by angular
                return this.LoginWithoutRedirect(token);
            };
			//	log the user out and redirect to home
            Get["/logout"] = _ => this.LogoutAndRedirect("../#/");
			//	Gets the current logged in user
            Get["/user"] = _ =>
            {
                var user = Context.CurrentUser;
                return Response.AsJson(user);
            };
			//	Tests connection
            Get["/test"] = _ =>
            {
                List<string> s = new List<string>();
				//SMTP.SendEmail("*****@*****.**", "Test Email", "This is a test e-mail");

				for (int i = 0; i < 1000000; i++)
                {
                    s.Add("test");
                }

                return Response.AsJson(s);
            };
		//	/BARCODE ACTIONS
		//	ROSTER IMPORT FUNCTIONS
			//	Returns contents of a csv file
			Post["/readCSV"] = _ =>
			{
				ReadCsvOptions options = this.Bind<ReadCsvOptions>();
				ReturnResult result = new ReturnResult();
				var files = Request.Files;
				//	If no file, return
				if(files.Count() == 0)
				{
					result.Success = false;
					result.Error = "No file found";
					result.ErrorDescription = "No CSV file was uploaded";
					result.Result = null;
					return Response.AsJson(result);
				}
				List<CsvObject> csvs = new List<CsvObject>();
				foreach (var file in files)
				{
					string extension = Path.GetExtension(file.Name);
					//	If not a csv file, return
					if(extension != ".csv")
					{
						result.Success = false;
						result.Error = "Invalid file";
						result.ErrorDescription = file.Name + " is not a csv file";
						result.Result = null;
						return Response.AsJson(result);
					}
					StreamReader csvReader = new StreamReader(file.Value);
					CsvObject csv = new CsvObject();
					List<string[]> rows = new List<string[]>();
					int index = 0;
					bool escape = false;
					while (!csvReader.EndOfStream && escape != true)
					{
						string line = csvReader.ReadLine();
						string[] values = line.Split(',');
						//	If headers, place into headers string[]
						if (index == 0)
						{
							csv.Headers = values;
						}
						else
						{
							rows.Add(values);
						}
						index++;
						//	If there is a limit, and this exceeds it, this sets escape to true
						if (options.Limit != null && options.Limit > 0 && index > options.Limit)
						{
							escape = true;
						}
					}
					csv.Rows = rows;
					csvs.Add(csv);
				}
				//	To get this far, it was successful, so it returns so
				result.Success = true;
				result.Error = null;
				result.ErrorDescription = null;
				result.Result = csvs;
				return Response.AsJson(result);
			};
		//	/ROSTER IMPORT FUNCTIONS
		}
        public BarcodeGroup GenerateFastTrackBarcode(FastTrackOptions options)
        {
            Random rndNumber = new Random();
            BarcodeWriter barcodeWriter = new BarcodeWriter
            {
                Format = BarcodeFormat.PDF_417,
                Options = { Margin = 2 }
            };
            //	Get airline string
            string airline = options.Airline.FormattedAirline();

            //	Generate cisn from random number
            int randomCISN = rndNumber.Next(0, 150);
            string CISN = randomCISN.ToString().PadLeft(5, '0');

            options.PassengerName = options.Name.Length > 20
                ? options.Name.Substring(0, 20)
                : options.Name.PadRight(20, ' ');

            //	Generate pnr from dates
            DateTime startDateTime = Convert.ToDateTime(options.StartDate);
            DateTime endDateTime = Convert.ToDateTime(options.EndDate);
            string jDate = (startDateTime.DayOfYear + 14).ToString().PadLeft(3, '0');

            var securityValue = options.PassengerName.ToArray().Sum(c => (int) c) +
                                options.DepartureAirport.ToArray().Sum(c => (int) c) + CISN.ToArray().Sum(c => (int) c);

            string r = (rndNumber).Next(100, 700).ToString();
            int securityFactor = Convert.ToInt32(r, 16);
            securityValue += securityFactor;
            options.Pnr = string.Format("{0}{1}", securityFactor.ToString("X3"), securityValue.ToString("X4"));
            //	Generate barcode
            string barcode = "";
            switch (options.TicketType)
            {
                case 2:
                    //	M1{Name}E{ PNR }{Departure}{Destination}{Airline}0000-000Y001A{CISN}023FASTTRACK[{Start}To{End}][ADFE]
                    barcode = string.Format("M1{0}E{1}{2}{3}{4}0000-000Y001A{5}023FASTTRACK[{6}To{7}][ADFE]",
                        options.PassengerName, options.Pnr, options.DepartureAirport, options.DestinationAirport,
                        airline, CISN, startDateTime.ToString("yyyyMMdd"), endDateTime.ToString("yyyyMMdd"));
                    break;
                case 3:
                    //	M1{Name}E{ PNR }{Departure}{Destination}{Airline}0000-000Y001A{CISN}023FASTTRACK[{Start}To{End}][ADFE]
                    barcode = string.Format("M1{0}E{1}{2}{3}{4}0000-000Y001A{5}023FASTTRACK[{6}To{7}][ADFE]",
                        options.PassengerName, options.Pnr, options.DepartureAirport, options.DestinationAirport,
                        airline, CISN, startDateTime.ToString("yyyyMMdd"), endDateTime.ToString("yyyyMMdd"));
                    break;
                default:
                    //	M1{Name}EAE1D4BC{Departure}{Destination}{Airline}0000-000Y001A{CISN}01DFASTTRACK[{Start}To{End}]
                    barcode = string.Format("M1{0}E{1}{2}{3}{4}0000-000Y001A{5}01DFASTTRACK[{6}To{7}]",
                        options.PassengerName, options.Pnr, options.DepartureAirport, options.DestinationAirport,
                        airline, CISN, startDateTime.ToString("yyyyMMdd"), endDateTime.ToString("yyyyMMdd"));
                    break;
            }
            //	Generate barcode
            return new BarcodeGroup
            {
                barcode = barcode,
                image = barcodeWriter.Write(barcode),
                serial = Convert.ToInt32(CISN)
            };
        }
 public virtual BarcodeGroup GenerateFastTrackBarcode(FastTrackOptions options)
 {
     return _barcodeGenerator.GenerateFastTrackBarcode(options);
 }