コード例 #1
0
        private StableAPIResponse HandleDELETE <E>(APIGatewayProxyRequest request, StableContext ctx) where E : class
        {
            try {
                string adminCode = Environment.GetEnvironmentVariable("admin_code");
                if (adminCode == null || adminCode == "")
                {
                    throw new InvalidOperationException("admin_code not set on server");
                }

                if (!request.Headers.ContainsKey("admin_code"))
                {
                    throw new ArgumentException("admin_code is missing");
                }

                if (request.Headers["admin_code"] != adminCode)
                {
                    throw new UnauthorizedAccessException("Invalid admin_code");
                }

                E obj = JsonConvert.DeserializeObject <E>(request.Body);

                /*
                 * Gotta wrap DB ops in a transaction
                 * otherwise, if they die in a try catch
                 * it could leave an uncommitted tx on the db
                 * causing problems with future requests
                 * using(var tx = ctx.Database.BeginTransaction()) {
                 *
                 * }
                 */
                using (var tx = ctx.Database.BeginTransaction()) {
                    try {
                        //Logger.LogLine(obj.GetType().ToString());
                        ctx.Remove(obj);
                        //ctx.Attach(obj);
                        //ctx.Remove(obj);
                        //ctx.dates.Remove(ctx.dates.Single(thus => thus.date == date));
                        int status = ctx.SaveChanges();
                        tx.Commit();
                        return(new StableAPIResponse()
                        {
                            Body = JsonConvert.SerializeObject((status == 1)),
                            StatusCode = HttpStatusCode.OK
                        });
                    } catch (Exception e) {
                        tx.Rollback();
                        Logger.LogLine(e.ToString());
                        return(new StableAPIResponse()
                        {
                            Body = JsonConvert.SerializeObject(new Result(e)),
                            StatusCode = HttpStatusCode.InternalServerError
                        });
                    }
                }
            } catch (Exception e) {
                Logger.LogLine(e.ToString());
                return(StableAPIResponse.BadRequest(e));
            }
        }
コード例 #2
0
        private StableAPIResponse HandlePUT <E>(APIGatewayProxyRequest request, StableContext ctx, Func <E, IDbContextTransaction, StableAPIResponse> func) where E : class
        {
            try {
                string adminCode = Environment.GetEnvironmentVariable("admin_code");
                if (adminCode == null || adminCode == "")
                {
                    throw new InvalidOperationException("admin_code not set on server");
                }

                if (!request.Headers.ContainsKey("admin_code"))
                {
                    throw new ArgumentException("admin_code is missing");
                }

                if (request.Headers["admin_code"] != adminCode)
                {
                    throw new UnauthorizedAccessException("Invalid admin_code");
                }

                E obj = JsonConvert.DeserializeObject <E>(request.Body);

                using (var tx = ctx.Database.BeginTransaction()) {
                    try {
                        return(func(obj, tx));

                        var existing = ctx.Attach(obj);
                        ctx.Entry(existing).State = EntityState.Modified;
                        int status = ctx.SaveChanges();
                        tx.Commit();
                        return(new StableAPIResponse()
                        {
                            Body = JsonConvert.SerializeObject((status == 1)),
                            StatusCode = HttpStatusCode.OK
                        });
                    } catch (Exception e) {
                        tx.Rollback();
                        Logger.LogLine(e.ToString());
                        return(new StableAPIResponse()
                        {
                            Body = JsonConvert.SerializeObject(new Result(e)),
                            StatusCode = HttpStatusCode.InternalServerError
                        });
                    }
                }
            } catch (Exception e) {
                Logger.LogLine(e.ToString());
                return(StableAPIResponse.BadRequest(e));
            }
        }
コード例 #3
0
        public static RegistrationRequest FromPresentation(StableContext ctx, uint p_id, uint v_id, string v_key)
        {
            var p   = ctx.presentations.AsNoTracking().First(thus => thus.presentation_id == p_id);
            var p_s = ctx.schedule.AsNoTracking().First(thus => thus.presentation_id == p.presentation_id);

            return(new RegistrationRequest()
            {
                date = p_s.date,
                block_id = p_s.block_id,
                presentation_id = p_id,
                viewer_id = v_id,
                viewer_key = v_key,
                location_id = p_s.location_id
            });
        }
コード例 #4
0
 public StockController(StableContext context)
 {
     _context = context;
 }
コード例 #5
0
 public PlanningController(StableContext context)
 {
     _context = context;
 }
コード例 #6
0
 public AuthController(StableContext context)
 {
     _context = context;
 }
コード例 #7
0
        static void PlaceViewers(bool saveToDB)
        {
            var conStr = new MySqlConnectionStringBuilder();

            using (StreamReader file = File.OpenText("config.json")) {
                using (JsonTextReader r = new JsonTextReader(file)) {
                    JObject conf = (JObject)JToken.ReadFrom(r);
                    conStr.Server   = (string)conf["server"];
                    conStr.Port     = uint.Parse((string)conf["port"]);
                    conStr.UserID   = (string)conf["user"];
                    conStr.Password = (string)conf["password"];
                    conStr.Database = (string)conf["database"];
                    conStr.SslMode  = MySqlSslMode.Required;
                }
            }

            bool clean = true;

            clean = false;

            using (StableContext ctx = StableContextFactory.Build(conStr.ToString())) {
                //3 2 4 1
                var viewers = ctx.Viewers;
                Console.WriteLine($"Fetched {viewers.Count} viewers");

                var schedule = ctx.Schedule;
                schedule = schedule.Where(thus => thus.presentation_id != PrepPresentationId).ToList();                 //ignore prep

                var dates = ctx.Dates;
                Console.WriteLine($"Fetched {dates.Count} dates");


                var newRegistrations = new List <Registration>();

                var currentRegistrations = ctx.Registrations;

                var capacityCheck = new Dictionary <Schedule, int>();
                foreach (Schedule s in schedule)
                {
                    capacityCheck.Add(s, currentRegistrations.Count(thus => thus.presentation_id == s.presentation_id));
                }

                Console.WriteLine($"Fetched {schedule.Count} schedules");

                var blocks = ctx.Blocks;
                Console.WriteLine($"Fetched {blocks.Count} blocks");

                // var preferences = ctx.preferences.ToList();
                // Console.WriteLine($"Fetched {preferences.Count} preferences");

                var presentations = ctx.Presentations.Where(thus => thus.Key < 142);

                // int expected_count = blocks.Count;
                const int retry_count = 5;

                var coreqs = ctx.CoRequisiteMembersList;



                DateTime start = DateTime.Now;

                //foreach schedule (date, block)
                //get viewers that aren't signed up for this block
                //loop over those viewrs, each time place them in the least filled presentation

                foreach (var date in dates)
                {
                    foreach (var block in blocks)
                    {
                        Schedule s = new Schedule()
                        {
                            date     = date.date,
                            block_id = block.Key
                        };

                        if (date.date == 20190503 && block.Key > 2)
                        {
                            continue;
                        }

                        List <uint> unregistered = GetUnRegistered(date, block.Value, viewers, currentRegistrations, newRegistrations);

                        unregistered.Randomize();

                        int x = 0;
                        foreach (var viewer in unregistered)
                        {
                            var pres = capacityCheck.Where(thus => thus.Key.date == date.date && thus.Key.block_id == block.Key).OrderBy(thus => thus.Value);

                            bool added = false;
                            foreach (var p in pres)
                            {
                                int current_size = capacityCheck[p.Key];

                                int cap = p.Key.location_id == LocationId_MPR ? 38 : 32;

                                if (current_size >= cap)
                                {
                                    continue;
                                }


                                //attempt to add to

                                CoRequisiteMember co = null;
                                if ((co = coreqs.FirstOrDefault(thus => thus.p_id == p.Key.presentation_id)) != null)
                                {
                                    var otherPresentation = coreqs.First(thus => thus.group_id == co.group_id && thus.p_id != co.p_id);
                                    var otherSchedule     = schedule.First(thus => thus.presentation_id == otherPresentation.p_id);

                                    if (currentRegistrations.Concat(newRegistrations).Any(thus => thus.date == otherSchedule.date && thus.block_id == otherSchedule.block_id && thus.viewer_id == viewer))
                                    {
                                        continue;
                                        //Already registered in coreq's timeslot
                                    }
                                    else
                                    {
                                        newRegistrations.Add(new Registration()
                                        {
                                            date            = date.date,
                                            block_id        = block.Key,
                                            presentation_id = p.Key.presentation_id,
                                            viewer_id       = viewer
                                        });

                                        capacityCheck[p.Key]++;

                                        newRegistrations.Add(new Registration()
                                        {
                                            date            = otherSchedule.date,
                                            block_id        = otherSchedule.block_id,
                                            presentation_id = otherSchedule.presentation_id,
                                            viewer_id       = viewer
                                        });

                                        capacityCheck[otherSchedule]++;
                                    }



                                    added = true;
                                    break;
                                }

                                newRegistrations.Add(new Registration()
                                {
                                    date            = date.date,
                                    block_id        = block.Key,
                                    presentation_id = p.Key.presentation_id,
                                    viewer_id       = viewer
                                });

                                capacityCheck[p.Key]++;
                                added = true;
                                break;
                            }

                            if (!added)
                            {
                                Console.WriteLine($"Force Adding {s}");
                                //force add
                                var fPres = capacityCheck.Where(thus => thus.Key.date == date.date && thus.Key.block_id == block.Key).OrderBy(thus => thus.Value);
                                foreach (var p in fPres)
                                {
                                    CoRequisiteMember co = null;
                                    if ((co = coreqs.FirstOrDefault(thus => thus.p_id == p.Key.presentation_id)) != null)
                                    {
                                        var otherPresentation = coreqs.First(thus => thus.group_id == co.group_id && thus.p_id != co.p_id);
                                        var otherSchedule     = schedule.First(thus => thus.presentation_id == otherPresentation.p_id);

                                        if (currentRegistrations.Concat(newRegistrations).Any(thus => thus.date == otherSchedule.date && thus.block_id == otherSchedule.block_id && thus.viewer_id == viewer))
                                        {
                                            continue;
                                            //Already registered in coreq's timeslot
                                        }
                                        else
                                        {
                                            newRegistrations.Add(new Registration()
                                            {
                                                date            = date.date,
                                                block_id        = block.Key,
                                                presentation_id = p.Key.presentation_id,
                                                viewer_id       = viewer
                                            });

                                            capacityCheck[p.Key]++;

                                            newRegistrations.Add(new Registration()
                                            {
                                                date            = otherSchedule.date,
                                                block_id        = otherSchedule.block_id,
                                                presentation_id = otherSchedule.presentation_id,
                                                viewer_id       = viewer
                                            });

                                            capacityCheck[otherSchedule]++;
                                        }



                                        added = true;
                                        break;
                                    }

                                    newRegistrations.Add(new Registration()
                                    {
                                        date            = date.date,
                                        block_id        = block.Key,
                                        presentation_id = p.Key.presentation_id,
                                        viewer_id       = viewer
                                    });

                                    capacityCheck[p.Key]++;

                                    break;
                                }
                            }
                            x++;
                        }
                        x = 0;
                    }
                }

                //sanity check
                foreach (var v in viewers.Values)
                {
                    int vC = currentRegistrations.Concat(newRegistrations).Count(thus => thus.viewer_id == v.viewer_id);
                    if (vC != 8)
                    {
                        Console.WriteLine($"Error, {v.viewer_id} {vC}");
                    }
                }

                DateTime end = DateTime.Now;
                Console.WriteLine($"Took {(end - start).TotalMilliseconds} ms to sort");
                if (saveToDB)
                {
                    start = DateTime.Now;

                    if (clean && false)
                    {
                        using (var tx = ctx.Database.BeginTransaction()) {
                            try {
                                ctx.Database.ExecuteSqlCommand("DELETE FROM `registrations`;");
                                tx.Commit();
                            } catch (Exception e) {
                                tx.Rollback();
                                Console.WriteLine(e);
                            }
                        }
                    }

                    using (var tx = ctx.Database.BeginTransaction()) {
                        try {
                            ctx.registrations.AddRange(newRegistrations);
                            ctx.SaveChanges();
                            tx.Commit();
                        } catch (Exception e) {
                            tx.Rollback();
                            Console.WriteLine(e);
                        }
                    }

                    end = DateTime.Now;
                    Console.WriteLine($"Took {(end - start).TotalMilliseconds} ms to add to db!");
                }

                foreach (var e in capacityCheck)
                {
                    Console.WriteLine(e.Key.block_id + " " + e.Key.presentation_id + " " + e.Value);
                }
                if (!saveToDB)
                {
                    Console.WriteLine("Did not save to DB!");
                }

                Console.WriteLine($"{newRegistrations.Count} entries to add to DB!");
            }
            Console.WriteLine("Clean: " + clean.ToString());
        }
コード例 #8
0
 public EventController(StableContext context)
 {
     _context = context;
 }
コード例 #9
0
		static void PlaceViewers(bool saveToDB) {
			var conStr = new MySqlConnectionStringBuilder();
			using(StreamReader file = File.OpenText("config.json")) {
				using(JsonTextReader r = new JsonTextReader(file)) {
					JObject conf = (JObject)JToken.ReadFrom(r);
					conStr.Server = (string)conf["server"];
					conStr.Port = uint.Parse((string)conf["port"]);
					conStr.UserID = (string)conf["user"];
					conStr.Password = (string)conf["password"];
					conStr.Database = (string)conf["database"];
					conStr.SslMode = MySqlSslMode.Required;
				}
			}

			bool clean = true;

			using(StableContext ctx = StableContextFactory.Build(conStr.ToString())) {
				//3 2 4 1
				var viewers = ctx.Viewers;
				Console.WriteLine($"Fetched {viewers.Count} viewers");

				var schedule = ctx.Schedule;

				var capacityCheck = new Dictionary<Schedule, uint>();
				foreach(Schedule s in schedule) {
					capacityCheck.Add(s, 0);
				}
				Console.WriteLine($"Fetched {schedule.Count} schedules");

				var blocks = ctx.Blocks;
				Console.WriteLine($"Fetched {blocks.Count} blocks");

				var preferences = ctx.preferences.ToList();
				Console.WriteLine($"Fetched {preferences.Count} preferences");

				var presentations = ctx.Presentations;

				Console.WriteLine($"Fetched {presentations.Count} presentations");

				int expected_count = blocks.Count;
				const int retry_count = 5;

				uint f_count = 0;
				var toAddToDB = new List<Registration>();
				{
					string s;
					char c;
					do {
						Console.Write("Prioritize by grade? (y/n): ");
						s = Console.ReadLine().ToUpper();
						if(s.Length > 0) {
							c = s[0];
							if(c == 'Y' || c == 'N') {
								prioritizeByGrade = c == 'Y';
								break;
							}
						} else {
							c = ' ';
						}
					} while(true);
				}

				uint[] grade_pri = new uint[] { 0 };
				if(prioritizeByGrade) {
					grade_pri = new uint[] { 3, 2, 4, 1 };
				}
				
				uint max_viewers = 26;

				do {
					try {
						Console.Write($"max_viewers [{max_viewers}]: ");
						string s = Console.ReadLine();
						if(s.Length == 0)
							break;
						
						max_viewers = uint.Parse(s);
						break;
					} catch {
						Console.WriteLine("Invalid input!");
					}
				} while(true);


				var registrationsToAdd = new List<Registration>();

				DateTime start = DateTime.Now;

				foreach(Block b in blocks.Values) {
					var temp_s = new Schedule() { date = date };
					temp_s.block_id = b.block_id;

					foreach(uint g in grade_pri) {
						var viewers_to_proc = new List<uint>();


						if(prioritizeByGrade)
							viewers_to_proc.AddRange(from thus in viewers where thus.Value.grade_id == g select thus.Value.viewer_id);
						else
							viewers_to_proc.AddRange(from thus in viewers select thus.Value.viewer_id);

						viewers_to_proc.Randomize();

						foreach(uint v in viewers_to_proc) {
							//var currentSelectedPresentations = new List<uint>();
							var v_pref = (from thus in preferences where thus.viewer_id == v orderby thus.order select thus.presentation_id).ToList();

							var currentRegistrations = (from thus in registrationsToAdd where thus.viewer_id == v select thus.presentation_id).ToList();

							bool randomize = v_pref.Count < presentations.Count;
							if(randomize) {
								Dictionary<uint, int> currentPCount = new Dictionary<uint, int>();
								foreach(var p_id in presentations.Keys) {
									currentPCount.Add(
										p_id,
										registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == p_id)
									);
								}
								var popOrder = currentPCount.OrderBy(thus => thus.Value);
								v_pref = popOrder.Select(thus => thus.Key).ToList();
								//v_pref = (from thus in presentations select thus.Value.presentation_id).ToList();
							}

							

							//if(currentRegistrations.Count == 1)
								//Console.WriteLine();

							v_pref = v_pref.Where(thus => !currentRegistrations.Contains(thus)).ToList();

							var v_pref_queue = new Queue<uint>(v_pref);

							uint presentation_to_add;

							//Add capacity check
							int presentationViewerCount = 0;
							do {
								if(v_pref_queue.Count == 0) {
									f_count++;
									foreach(uint p_idd in presentations.Select(thus => thus.Value.presentation_id)) {
										var c2 = registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == p_idd);

										//Console.WriteLine($"{p_idd}: {c2}");
									}

									v_pref = v_pref.Where(thus => !currentRegistrations.Contains(thus)).ToList();
									v_pref_queue = new Queue<uint>(v_pref);

									presentation_to_add = v_pref_queue.Dequeue();

									break;
								}
								presentation_to_add = v_pref_queue.Dequeue();
								
								presentationViewerCount = registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == presentation_to_add);

								//if(presentationViewerCount >= max_viewers)
									//Console.WriteLine();

							} while(presentationViewerCount >= max_viewers);

							registrationsToAdd.Add(new Registration() {
								date = temp_s.date,
								block_id = temp_s.block_id,
								presentation_id = presentation_to_add,
								viewer_id = v
							});

						}
					}
				
					foreach(uint p_idd in presentations.Select(thus => thus.Value.presentation_id)) {
						var c2 = registrationsToAdd.Count(thus => thus.date == temp_s.date && thus.block_id == temp_s.block_id && thus.presentation_id == p_idd);

						Console.WriteLine($"{temp_s.block_id} {p_idd}: {c2}");
					}

				}

				clean = registrationsToAdd.Count == viewers.Count * blocks.Count;

				toAddToDB = registrationsToAdd;
				/*
				foreach(uint g in grade_pri) {
					// if(g != 3)
					// 	continue;
					var viewers_to_proc = new List<uint>();

					if(prioritizeByGrade)
						viewers_to_proc.AddRange(from thus in viewers where thus.Value.grade_id == g select thus.Value.viewer_id);
					else
						viewers_to_proc.AddRange(from thus in viewers select thus.Value.viewer_id);

					viewers_to_proc.Randomize();

					foreach(uint v in viewers_to_proc) {
						var registrationEntries = new List<Tuple<uint, uint>>();
						var currentSelectedPresentations = new List<uint>();
						var v_pref = (from thus in preferences where thus.viewer_id == v orderby thus.order select thus.presentation_id).ToList();
						
						bool randomize = v_pref.Count < presentations.Count;
						
						
						var temp_s = new Schedule(){ date = date };
						var blocks_r = blocks.Values.ToList();

						int error_count = 0;
						do {

							blocks_r.Randomize();
							foreach(Block b in blocks_r) {
								temp_s.block_id = b.block_id;

								if(randomize) {
									var r_p = from thus in capacityCheck orderby thus.Value select thus.Key.presentation_id;

									foreach(uint p in r_p) {
										if(currentSelectedPresentations.Contains(p))
											continue;
										temp_s.presentation_id = p;
										if(!capacityCheck.ContainsKey(temp_s))
											continue;
										if(capacityCheck[temp_s] >= max_viewers)
											continue;
										capacityCheck[temp_s]++;
										registrationEntries.Add(new Tuple<uint, uint>(b.block_id, p));
										currentSelectedPresentations.Add(p);
										break;
									}
									continue;
								}

								foreach(uint p in v_pref) {
									if(currentSelectedPresentations.Contains(p))
										continue;
									temp_s.presentation_id = p;
									if(!capacityCheck.ContainsKey(temp_s))
										continue;
									if(capacityCheck[temp_s] >= max_viewers)
										continue;
									capacityCheck[temp_s]++;
									registrationEntries.Add(new Tuple<uint, uint>(b.block_id, p));
									currentSelectedPresentations.Add(p);
									break;
								}

							}
							if(currentSelectedPresentations.Count != expected_count) {
								//Console.WriteLine("ERROR " + string.Join(", ", bleh_v));

								//undo
								foreach(var toRemove in registrationEntries) {
									temp_s.block_id = toRemove.Item1;
									temp_s.presentation_id = toRemove.Item2;
									capacityCheck[temp_s]--;
								}
								registrationEntries.Clear();
								currentSelectedPresentations.Clear();
								error_count++;
								if(error_count > retry_count) {
									clean = false;
									break;
								}

							} else {
								foreach(var toAdd in registrationEntries) {
									toAddToDB.Add(new Registration() {
										date = temp_s.date,
										block_id = toAdd.Item1,
										presentation_id = toAdd.Item2,
										viewer_id = v
									});
								}
							}
						} while(currentSelectedPresentations.Count != expected_count);
						
						//var rng = randomize ? "RNG" : "";
						//Console.WriteLine($"Student: {v} {rng} {string.Join(", ", bleh)}");
					}

					
				}
				*/

				DateTime end = DateTime.Now;
				Console.WriteLine($"Took {(end - start).TotalMilliseconds} ms to sort");
				Console.WriteLine($"F Count: {f_count}");
				if(saveToDB) {
					start = DateTime.Now;

					if(clean) {
						using(var tx = ctx.Database.BeginTransaction()) {
							try {
								ctx.Database.ExecuteSqlCommand("DELETE FROM `registrations`;");
								tx.Commit();
							} catch(Exception e) {
								tx.Rollback();
								Console.WriteLine(e);
							}
						}
						using(var tx = ctx.Database.BeginTransaction()) {
							try {
								ctx.registrations.AddRange(toAddToDB);
								ctx.SaveChanges();
								tx.Commit();
							} catch(Exception e) {
								tx.Rollback();
								Console.WriteLine(e);
							}
						}
					}

					end = DateTime.Now;
					Console.WriteLine($"Took {(end - start).TotalMilliseconds} ms to add to db!");
				}

				foreach(var e in capacityCheck) {
					Console.WriteLine(e.Key.block_id + " " + e.Key.presentation_id + " " + e.Value);
				}
				if(!saveToDB)
					Console.WriteLine("Did not save to DB!");
				
				Console.WriteLine($"{toAddToDB.Count} entries to add to DB!");
			}
			Console.WriteLine("Clean: " + clean.ToString());
		}
コード例 #10
0
 public PersonController(StableContext context)
 {
     _context = context;
 }
コード例 #11
0
 public MembershipController(StableContext context)
 {
     _context = context;
 }
コード例 #12
0
 public HorseController(StableContext context)
 {
     _context = context;
 }
コード例 #13
0
        public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)
        {
            Logger = context.Logger;
            object resultObject = new object();
            int    resultCode   = 405;

            var noSignups = new APIGatewayProxyResponse()
            {
                Body    = "{}",
                Headers = new Dictionary <string, string>()
                {
                    { "access-control-allow-origin", Environment.GetEnvironmentVariable("SITE_DOMAIN") }
                },
                StatusCode = 418
            };
            bool enabled = bool.Parse(Environment.GetEnvironmentVariable("enabled"));

            bool freeforall = false;


            if (apigProxyEvent.Path.Contains("/api") && apigProxyEvent.Path.Length > 4)
            {
                apigProxyEvent.Path = apigProxyEvent.Path.Substring(4, apigProxyEvent.Path.Length - 4);
            }

            //Pre check the request path to save time

            switch (apigProxyEvent.Path.ToLower())
            {
            case "/":
                return(new StableAPIResponse {
                    Body = "What are you doing here?",
                    StatusCode = HttpStatusCode.OK
                });

            case "/status":
                if (apigProxyEvent.HttpMethod == "GET")
                {
                    return(new StableAPIResponse {
                        Body = JsonConvert.SerializeObject(enabled),
                        StatusCode = HttpStatusCode.OK
                    });
                }
                return(new StableAPIResponse {
                    Body = "{}",
                    StatusCode = HttpStatusCode.NotFound
                });

            case "/games":
            case "/games/":
            case "/participants":
            case "/participants/":
            case "/schedule":
            case "/schedule/":
            case "/scores":
            case "/scores/":
            case "/score_type":
            case "/score_type/":
            case "/print":
            case "/print/":
                break;


            default:
                return(new StableAPIResponse {
                    Body = "{}",
                    StatusCode = HttpStatusCode.NotFound
                });
            }

            StableAPIResponse response = new StableAPIResponse {
                Body       = "{}",
                StatusCode = HttpStatusCode.NotFound
            };

            string conStr = new MySqlConnectionStringBuilder()
            {
                Server   = Environment.GetEnvironmentVariable("DB_ADDRESS"),
                Port     = uint.Parse(Environment.GetEnvironmentVariable("DB_PORT")),
                UserID   = Environment.GetEnvironmentVariable("DB_USER"),
                Password = Environment.GetEnvironmentVariable("DB_PASSWORD"),
                Database = Environment.GetEnvironmentVariable("DB_NAME"),
                SslMode  = MySqlSslMode.Required
            }.ToString();

            using (StableContext ctx = StableContextFactory.Build(conStr)) {
                switch (apigProxyEvent.HttpMethod)
                {
                case "GET":
                    #region GETs
                    switch (apigProxyEvent.Path.ToLower())
                    {
                    case "/":
                        resultObject = "What are you doing here?";
                        resultCode   = 200;
                        break;

                    case "/games":
                    case "/games/":
                        response = new StableAPIResponse()
                        {
                            Body       = JsonConvert.SerializeObject(ctx.Games),
                            StatusCode = HttpStatusCode.OK
                        };
                        break;

                    case "/participants":
                    case "/participants/":
                        response = new StableAPIResponse()
                        {
                            Body       = JsonConvert.SerializeObject(ctx.Participants),
                            StatusCode = HttpStatusCode.OK
                        };
                        break;

                    case "/schedule":
                    case "/schedule/":
                        response = new StableAPIResponse()
                        {
                            Body       = JsonConvert.SerializeObject(ctx.Schedule),
                            StatusCode = HttpStatusCode.OK
                        };
                        break;

                    case "/scores":
                    case "/scores/":
                        response = new StableAPIResponse()
                        {
                            Body       = JsonConvert.SerializeObject(ctx.Scores),
                            StatusCode = HttpStatusCode.OK
                        };
                        break;

                    case "/score_type":
                    case "/score_type/":
                        response = new StableAPIResponse()
                        {
                            Body       = JsonConvert.SerializeObject(ctx.ScoreType),
                            StatusCode = HttpStatusCode.OK
                        };
                        break;

                    case "/print":
                    case "/print/":
                        //response = HandlePrint(apigProxyEvent, ctx);
                        break;

                    default:
                        break;
                    }
                    #endregion
                    break;

                case "POST":
                    #region POSTs
                    switch (apigProxyEvent.Path.ToLower())
                    {
                    case "/games":
                    case "/games/":
                        response = HandlePOST <Game>(apigProxyEvent, ctx);
                        break;

                    case "/participants":
                    case "/participants/":
                        response = HandlePOST <Participant>(apigProxyEvent, ctx);
                        break;

                    case "/schedule":
                    case "/schedule/":
                        response = HandlePOST <Schedule>(apigProxyEvent, ctx);
                        break;

                    case "/scores":
                    case "/scores/":
                        response = HandlePOST <Score>(apigProxyEvent, ctx);
                        break;

                    case "/score_type":
                    case "/score_type/":
                        response = HandlePOST <ScoreType>(apigProxyEvent, ctx);
                        break;
                    }
                    #endregion
                    break;

                case "PUT":
                    #region PUTs
                    switch (apigProxyEvent.Path.ToLower())
                    {
                    case "/games":
                    case "/games/":
                        response = HandlePUT <Game>(apigProxyEvent, ctx, (o, tx) => {
                            var g = ctx.games.FirstOrDefault(thus => thus.id == o.id);
                            ctx.Entry(g).CurrentValues.SetValues(o);

                            //var existing = ctx.Attach(o);
                            //ctx.Entry(existing).State = EntityState.Modified;
                            int status = ctx.SaveChanges();
                            tx.Commit();
                            return(new StableAPIResponse()
                            {
                                Body = JsonConvert.SerializeObject((status == 1)),
                                StatusCode = HttpStatusCode.OK
                            });
                        });
                        break;

                    case "/participants":
                    case "/participants/":
                        response = HandlePUT <Participant>(apigProxyEvent, ctx, (o, tx) => {
                            var g = ctx.participants.FirstOrDefault(thus => thus.id == o.id);
                            ctx.Entry(g).CurrentValues.SetValues(o);
                            //var existing = ctx.Attach(o);
                            //ctx.Entry(existing).State = EntityState.Modified;
                            int status = ctx.SaveChanges();
                            tx.Commit();
                            return(new StableAPIResponse()
                            {
                                Body = JsonConvert.SerializeObject((status == 1)),
                                StatusCode = HttpStatusCode.OK
                            });
                        });
                        break;

                    case "/schedule":
                    case "/schedule/":
                        //response = HandlePUT<Schedule>(apigProxyEvent, ctx, (o, tx) => {
                        //	var g = ctx.schedule.FirstOrDefault(thus => thus.g_id == o.g_id &&);
                        //	ctx.Entry(g).CurrentValues.SetValues(o);
                        //	//var existing = ctx.Attach(o);
                        //	//ctx.Entry(existing).State = EntityState.Modified;
                        //	int status = ctx.SaveChanges();
                        //	tx.Commit();
                        //	return new StableAPIResponse() {
                        //		Body = JsonConvert.SerializeObject((status == 1)),
                        //		StatusCode = HttpStatusCode.OK
                        //	};
                        //});
                        break;

                    case "/scores":
                    case "/scores/":
                        response = HandlePUT <Score>(apigProxyEvent, ctx, (o, tx) => {
                            var g = ctx.scores.FirstOrDefault(thus => thus.g_id == o.g_id && thus.p_id == o.p_id);
                            ctx.Entry(g).CurrentValues.SetValues(o);
                            //var existing = ctx.Attach(o);
                            //ctx.Entry(existing).State = EntityState.Modified;
                            int status = ctx.SaveChanges();
                            tx.Commit();
                            return(new StableAPIResponse()
                            {
                                Body = JsonConvert.SerializeObject((status == 1)),
                                StatusCode = HttpStatusCode.OK
                            });
                        });
                        break;

                    case "/score_type":
                    case "/score_type/":
                        response = HandlePUT <ScoreType>(apigProxyEvent, ctx, (o, tx) => {
                            var g = ctx.score_type.FirstOrDefault(thus => thus.id == o.id);
                            ctx.Entry(g).CurrentValues.SetValues(o);
                            //var existing = ctx.Attach(o);
                            //ctx.Entry(existing).State = EntityState.Modified;
                            int status = ctx.SaveChanges();
                            tx.Commit();
                            return(new StableAPIResponse()
                            {
                                Body = JsonConvert.SerializeObject((status == 1)),
                                StatusCode = HttpStatusCode.OK
                            });
                        });
                        break;
                    }
                    break;

                    #endregion
                case "DELETE":
                    #region DELETEs
                    switch (apigProxyEvent.Path.ToLower())
                    {
                    case "/games":
                    case "/games/":
                        response = HandleDELETE <Game>(apigProxyEvent, ctx);
                        break;

                    case "/participants":
                    case "/participants/":
                        response = HandleDELETE <Participant>(apigProxyEvent, ctx);
                        break;

                    case "/schedule":
                    case "/schedule/":
                        response = HandleDELETE <Schedule>(apigProxyEvent, ctx);
                        break;

                    case "/scores":
                    case "/scores/":
                        response = HandleDELETE <Score>(apigProxyEvent, ctx);
                        break;

                    case "/score_type":
                    case "/score_type/":
                        response = HandleDELETE <ScoreType>(apigProxyEvent, ctx);
                        break;

                    default:
                        break;
                    }
                    #endregion
                    break;

                default:
                    break;
                }
            }
            //Logger.LogLine($"RESPONSE CODE: {((HttpStatusCode)response.StatusCode).ToString()}{Environment.NewLine}{response.Body}");

            return(response);
        }
コード例 #14
0
 public StableService(StableContext stableContext)
 {
     this.stableContext = stableContext;
 }
コード例 #15
0
 public BoxController(StableContext context)
 {
     _context = context;
 }