Exemple #1
0
        public ActionResult <string> Get()
        {
            MongoManager  dbManager = new MongoManager("Data_Classifier");
            List <string> list      = dbManager.LoadRecords <string>("Users");

            return(list.Count.ToString());
        }
Exemple #2
0
        public async Task AddSingleSong(string href)
        {
            try
            {
                var token       = AgonManager.GetSpotifyTokens(this);
                var currentQuiz = await MongoManager.GetQuizFromSession(token.Username);

                var newSong = await Task.Run(async() => await AgonManager.AddSongToQuiz(token, href));

                var newQuiz = JsonConvert.DeserializeObject <Quiz>(currentQuiz);
                newQuiz.Songs.Add(newSong);

                var quizToStore = JsonConvert.SerializeObject(newQuiz);

                await MongoManager.SaveQuizToSession(quizToStore, token.Username);
            }
            catch (MongoException mex)
            {
                HttpContext.Session.SetString("error", mex.Message);
                RedirectToError();
            }
            catch (Exception ex)
            {
                HttpContext.Session.SetString("error", ex.Message);
                RedirectToError();
            }
        }
Exemple #3
0
        public async Task <IActionResult> UpdateQuestions(string id)
        {
            var questionText = Request.Form["item.Text"];
            var answerText   = Request.Form["item.CorrectAnswer"];


            Quiz updatedQuiz;

            try
            {
                var jsonQuiz = await MongoManager.GetQuizFromSession(HttpContext.User.Identity.Name);

                updatedQuiz = AgonManager.UpdateQuestions(questionText, answerText, jsonQuiz, id);
                await MongoManager.ReplaceOneQuizAsync(updatedQuiz.Owner, updatedQuiz.Name, JsonConvert.SerializeObject(updatedQuiz), "Quizzes");

                var currentQuiz = JsonConvert.SerializeObject(updatedQuiz);
                await MongoManager.SaveQuizToSession(currentQuiz, HttpContext.User.Identity.Name);
            }
            catch (MongoException mex)
            {
                HttpContext.Session.SetString("error", mex.Message);
                return(RedirectToAction("Error", "Home"));
            }
            catch (Exception ex)
            {
                HttpContext.Session.SetString("error", ex.Message);
                return(RedirectToAction("Error", "Home"));
            }


            return(RedirectToAction("EditQuiz", "Quiz"));
        }
        private static ProdutoInMemory BuscarProduto(string nome)
        {
            ProdutoInMemory produtoNaMemoria = ProdutoInMemoryDao.GetByNome(nome);

            if (produtoNaMemoria == null)
            {
                IMongoCollection <Produto> collection = MongoManager.open <Produto>("Produto");
                Produto produto = collection.Find(x => x.Nome.Equals(nome)).FirstOrDefault();

                if (produto == null)
                {
                    return(null);
                }

                produtoNaMemoria = new ProdutoInMemory
                {
                    Id    = produto.Id.ToString(),
                    Nome  = produto.Nome,
                    Valor = produto.Valor
                };

                ProdutoInMemoryDao.Set(produtoNaMemoria);
            }

            return(produtoNaMemoria);
        }
Exemple #5
0
        /// <summary>
        /// Login operation
        /// Create a session for user if auth is Ok.
        /// </summary>
        /// <param name="login"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static AuthenticationResponse Login(string login, string password)
        {
            login    = login.Trim();
            password = password.Trim();
            Users user = MongoManager.FirstOrDefault <Users>(x => x.Login == login);

            if (user == null)
            {
                throw new Exception($"There is no user {login} in the Database.");
            }

            if (user.Password != password)
            {
                throw new Exception("The password is wrong.");
            }

            Sessions session = MongoManager.SingleOrDefault <Sessions>(x => x.UserId == user._id);

            if (session == null)
            {
                session = new Sessions(Crypto.GenerateUniqueKey(), user._id);

                MongoManager.AddItemInCollection(session);
            }

            log.Information($"Added session {session._id}.");

            return(new AuthenticationResponse(user, session));
        }
Exemple #6
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="env"></param>
        public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            string aggregationPipelinesPath = Path.Combine(dataPath, "AggregationPipelines");
            string configFilePath           = Path.Combine(dataPath, "MongoDB", "MongoConfig.xml");
            string credentialFilePath       = Path.Combine(dataPath, "MongoDB", "MongoCredentials.xml");

            MongoManager.Configure(aggregationPipelinesPath, configFilePath, credentialFilePath);

            log.Information($"{BaseSettings.ApiName} started. Version = [{BaseSettings.ApiVersion}].");

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                log.Information("Development Env enabled.");
            }
            else
            {
                log.Information("Production Env enabled.");
            }


            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger(c => c.RouteTemplate = $"/{BaseSettings.SwaggerBaseUrl}/swagger/{{documentName}}/swagger.json");
            //app.UseSwagger();
            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c => {
                c.SwaggerEndpoint("swagger/v1/swagger.json", $"{BaseSettings.ApiName} {BaseSettings.ApiVersion}");
                c.RoutePrefix = BaseSettings.SwaggerBaseUrl;
            });

            app.UseRouting();
            app.UseCors(builder => builder.WithOrigins(Configuration.GetSection("AppConfiguration:corsOrigins").Get <string[]>()).AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            app.UseAuthorization();
        }
Exemple #7
0
        public static string GetChartData(string data)
        {
            try
            {
                PositionDateRangeItem pdItem = new PositionDateRangeItem();
                pdItem = JsonConvert.DeserializeObject <PositionDateRangeItem>(data);
                List <QueryResultItem> chartData = new List <QueryResultItem>();

                MongoManager          mongoManager = new MongoManager();
                List <CollectionItem> positions    = new List <CollectionItem>();

                if (string.IsNullOrEmpty(pdItem.Positions))
                {
                    positions = mongoManager.GetAllCollectionsOfType(Constants.Database.CollectionType.Humiture);
                }
                else
                {
                    string[] pos = pdItem.Positions.Split(',');

                    foreach (string s in pos)
                    {
                        positions.Add(new CollectionItem(s, CollectionType.Humiture));
                    }
                }

                chartData = mongoManager.SelectFromCollections(positions, FilterBuilder.Humiture.BuildFilter(pdItem.FromDate, pdItem.ToDate));
                return(JsonConvert.SerializeObject(chartData));
            }
            catch (Exception ex)
            {
                LoggingManager.LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, ex);
            }
            return("");
        }
Exemple #8
0
        /// <summary>
        /// Create or update the recipe.
        /// </summary>
        public void Save()
        {
            bool isNew = _id == ObjectId.Empty;

            MongoManager.Save(this);

            log.Information($"{(isNew ? "Added" : "Updated")} recipe {_id}.");
        }
Exemple #9
0
        static MongoCollections()
        {
            var db    = MongoManager.getDB();
            var store = db.GetCollection <StoreMgDTO>(MongoKeyConst.CollectionName);
            var geoindexMapLocation = IndexKeys <StoreMgDTO> .GeoSpatial(c => c.Location);

            store.EnsureIndex(geoindexMapLocation, IndexOptions.SetGeoSpatialRange(0, 300));
        }
Exemple #10
0
        public string Post(UserModel user)
        {
            MongoManager dbManager = new MongoManager("Data_Classifier");

            dbManager.InsertRecord <UserModel>("Users", user);
            //var identity = HttpContext.User.Identity as ClaimsIdentity;
            //IList<Claim> claim = identity.Claims.ToList();
            //var userName = claim[0].Value;
            return("Succes!");
        }
Exemple #11
0
        public static async Task <UserVM> GetUserVMAsync(string username, bool loggedIn)
        {
            List <Quiz> quizzes = new List <Quiz>();

            quizzes = JsonConvert.DeserializeObject <List <Quiz> >(await MongoManager.GetAllQuizzesAsync(username));

            var userVM = new UserVM(username, quizzes, loggedIn);

            return(userVM);
        }
Exemple #12
0
        public async Task <IActionResult> PlayQuiz(string pin, string validusername)
        {
            QuizPlayerVM quizPlayerVM;
            bool         pinExists;

            try
            {
                pinExists = await MongoManager.CheckIfPinExistsAsync(pin, "runningQuizzes");
            }
            catch (MongoException mex)
            {
                HttpContext.Session.SetString("error", mex.Message);
                return(RedirectToAction("Error", "Home"));
            }
            catch (Exception ex)
            {
                HttpContext.Session.SetString("error", ex.Message);
                return(RedirectToAction("Error", "Home"));
            }

            if (pinExists)
            {
                try
                {
                    quizPlayerVM = await AgonManager.CreateQuizPlayerVM(pin, validusername);
                }
                catch (MongoException mex)
                {
                    HttpContext.Session.SetString("error", mex.Message);
                    return(RedirectToAction("Error", "Home"));
                }
                catch (Exception ex)
                {
                    HttpContext.Session.SetString("error", ex.Message);
                    return(RedirectToAction("Error", "Home"));
                }

                string cacheKey = pin;
                var    players  = _memoryCache.Get <List <string> >(cacheKey);

                if (players == null)
                {
                    players = new List <string>();
                }

                players.Add(validusername);
                _memoryCache.Set <List <string> >(cacheKey, players);

                return(View(quizPlayerVM));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
Exemple #13
0
        public static async Task <AnswerKeyVM> GetAnswerKeyVMAsync(string quizID)
        {
            AnswerKeyVM daBoss = new AnswerKeyVM();

            daBoss.RunningQuizID = quizID;

            var runningQuizJson = await MongoManager.GetOneQuizAsync(quizID, "runningQuizzes");

            var runningQuiz = JsonConvert.DeserializeObject <RunningQuiz>(runningQuizJson);

            var submittedAnswersJson = await MongoManager.GetAllAnswerFormsAsync(quizID, "answers");

            var submittedAnswers = JsonConvert.DeserializeObject <List <AnswerForm> >(submittedAnswersJson);

            // Stoppa in allt på rätt sätt i rätt AKVM

            var answerkeySongs = new List <AnswerKeySongVM>();

            int counter = 0;

            for (int i = 0; i < runningQuiz.Songs.Count; i++)
            {
                var questions = new List <AnswerKeyQuestionVM>();
                for (int j = 0; j < runningQuiz.Songs[i].Questions.Count; j++)
                {
                    var    answers = new List <AnswerKeySubmittedAnswerVM>();
                    string answer  = "";

                    for (int k = 0; k < submittedAnswers.Count; k++)
                    {
                        answer = submittedAnswers[k].Answers[counter];
                        answers.Add(new AnswerKeySubmittedAnswerVM {
                            Answer = answer, SubmitterName = submittedAnswers[k].SubmitterName, IsCorrect = (answer.ToLower() == (runningQuiz.Songs[i].Questions[j].CorrectAnswer).ToLower())
                        });
                    }
                    var correctAnswer = runningQuiz.Songs[i].Questions[j].CorrectAnswer;
                    var text          = runningQuiz.Songs[i].Questions[j].Text;
                    questions.Add(new AnswerKeyQuestionVM {
                        CorrectAnswer = correctAnswer, Text = text, SubmittedAnswers = new List <AnswerKeySubmittedAnswerVM>()
                    });
                    questions[j].SubmittedAnswers.AddRange(answers);
                    counter++;
                }
                var artist = runningQuiz.Songs[i].Artist;
                var title  = runningQuiz.Songs[i].Title;
                answerkeySongs.Add(new AnswerKeySongVM {
                    Artist = artist, Title = title, Questions = new List <AnswerKeyQuestionVM>()
                });
                answerkeySongs[i].Questions.AddRange(questions);
            }

            daBoss.Songs.AddRange(answerkeySongs);
            return(daBoss);
        }
Exemple #14
0
        public Startup(IHostingEnvironment env)
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath);

            builder.AddEnvironmentVariables();

            Configuration = builder.Build();
            MongoManager.SetupMongoClient(Configuration["MongoConnection"]);
            SpotifyManager.SetVariables(Configuration["SpotifyClientId"], Configuration["SpotifyClientSecret"]);
        }
Exemple #15
0
        /////////////////////////////////////////////
        /// <summary>
        /// データベース登録スレッド
        /// </summary>
        public async void StartMongoDBThread(IConfiguration config)
        {
            priceQueue = new BlockingCollection <Price>(MaxPriceQueueSize);

            var server   = config["MongoDB:Server"];
            var database = config["MongoDB:Database"];
            var user     = config["MongoDB:User"];
            var password = config["MongoDB:Password"];
            var port     = config.GetValue <int>("MongoDB:Port");

            if (string.IsNullOrEmpty(server))
            {
                Log("[MongoDB] no server settings.");
                RunFlag = false;
                return;
            }
            /////////////////////////////////////////////
            //      別スレッドで処理
            await Task.Run(() =>
            {
                try
                {
                    mongoManager = new MongoManager(server, database, user, password, port);
                }
                catch (Exception e)
                {
                    Log($"Database Connection Error:" + e.Message);
                    RunFlag = false;
                }

                while (RunFlag)
                {
                    if (!priceQueue.TryTake(out var price, Timeout.Infinite))
                    {
                        continue;
                    }
                    if (price == null)
                    {
                        continue;
                    }
                    try
                    {
                        price.Id = ObjectId.GenerateNewId().ToString();
                        mongoManager.Insert(price, price.Pair);
                    }
                    catch (Exception e)
                    {
                        Log($"[MongoDB] {e.Message}");
                    }
                }
                RunFlag = false;
            });
        }
Exemple #16
0
        /// <summary>
        /// We remove the deleted ingredient id from the recipes.
        /// </summary>
        /// <param name="ingredient"></param>
        void HandleDeletedIngredient(Ingredients ingredient)
        {
            List <Recipes> recipes = MongoManager.Where <Recipes>(x => x.Ingredients.Any(x => x._id == ingredient._id));

            foreach (var recipe in recipes)
            {
                recipe.Ingredients.RemoveAll(x => x._id == ingredient._id);
                recipe.Save();
            }

            MongoManager.DeleteItems <IngredientPrices>(x => x.IngredientId == ingredient._id);
        }
Exemple #17
0
        /// <summary>
        /// Main constructor.
        /// </summary>
        /// <param name="ingredient"></param>
        public Ingredients(Ingredients ingredient)
        {
            if (MongoManager.ItemExists <Ingredients>(x => x.Name == ingredient.Name))
            {
                throw new Exception($"There is already an ingredient [{ingredient.Name}] - {ingredient.PriceUnit} - [{string.Join(", ", ingredient.Categories)}].");
            }

            BaseQuantity = ingredient.BaseQuantity;
            Name         = ingredient.Name;
            PriceUnit    = ingredient.PriceUnit;
            Categories   = ingredient.Categories;
        }
Exemple #18
0
        /// <summary>
        /// Create or update the ingredient.
        /// </summary>
        public void Save()
        {
            bool isNew = _id == ObjectId.Empty;

            if (!isNew && !MongoManager.ItemExists <Users>(x => x.Login == Login))
            {
                throw new Exception($"There is no user [{Login}].");
            }

            MongoManager.Save(this);

            log.Information($"{(isNew ? "Added" : "Updated")} user [{Login}] - {_id}.");
        }
Exemple #19
0
        /// <summary>
        /// We remove the deleted recipe id from the recipe.
        /// </summary>
        /// <param name="recipe"></param>
        void HandleDeletedRecipe(Recipes recipe)
        {
            List <Weeks> weeks = MongoManager.Where <Weeks>(x => x.Days.Any(y => y.Meals.Any(z => z._id == recipe._id)));

            foreach (var week in weeks)
            {
                foreach (var day in week.Days)
                {
                    day.Meals.RemoveAll(x => x._id == recipe._id);
                }

                week.Save(week.UserId);
            }
        }
Exemple #20
0
        public static async Task RemoveSongFromQuiz(SpotifyTokens token, int indexToRemove)
        {
            string currentQuizJson;
            Quiz   currentQuiz;

            currentQuizJson = await MongoManager.GetQuizFromSession(token.Username);

            currentQuiz = JsonConvert.DeserializeObject <Quiz>(currentQuizJson);

            currentQuiz.Songs.RemoveAt(indexToRemove);

            currentQuizJson = JsonConvert.SerializeObject(currentQuiz);
            await MongoManager.SaveQuizToSession(currentQuizJson, token.Username);
        }
Exemple #21
0
        /// <summary>
        /// Retrieve the current week.
        /// </summary>
        /// <param name="userId">Id of the user.</param>
        /// <returns></returns>
        public static Weeks GetWeek(ObjectId userId)
        {
            Weeks week = MongoManager.GetAggregate <Weeks>(weeksIndex, x => x.UserId == userId).FirstOrDefault();

            if (week == null)
            {
                week      = new Weeks();
                week.Days = new List <Day>();
                return(week);
            }

            week.Days = week.Days.OrderBy(x => x.Position).ToList();
            return(week);
        }
Exemple #22
0
        /// <summary>
        /// Main constructor.
        /// </summary>
        /// <param name="recipe"></param>
        public Recipes(Recipes recipe)
        {
            if (MongoManager.ItemExists <Recipes>(x => x.Name == recipe.Name))
            {
                throw new Exception($"There is already a recipe [{recipe.Name}].");
            }

            TimesCooked = recipe.TimesCooked;
            Type        = recipe.Type;
            UserId      = recipe.UserId;
            LastCooked  = recipe.LastCooked;
            Name        = recipe.Name;
            BestSeasons = recipe.BestSeasons;
            Ingredients = recipe.Ingredients;
        }
Exemple #23
0
        public virtual void Initialize()
        {
            if (!IsMongoNeeded)
            {
                return;
            }

            string aggregationPipelinesPath = Path.Combine(dataPath, "AggregationPipelines");
            string configFilePath           = Path.Combine(dataPath, "MongoDB", "MongoConfig.xml");
            string credentialFilePath       = Path.Combine(dataPath, "MongoDB", "MongoCredentials.xml");

            if (MongoManager.aggregationPipelinesLoader.Aggregates == null || MongoManager.aggregationPipelinesLoader.Aggregates.Count == 0)
            {
                MongoManager.Configure(aggregationPipelinesPath, configFilePath, credentialFilePath);
            }
        }
Exemple #24
0
        /// <summary>
        /// Check session and returns some related objects.
        /// </summary>
        /// <param name="sessionKey"></param>
        /// <returns></returns>
        public static AuthenticationResponse AuthenticateSession(string sessionKey)
        {
            // Get session
            Sessions session = MongoManager.FirstOrDefault <Sessions>(s => s.Key == sessionKey);

            if (session == null)
            {
                // BAD auth
                log.Error("Auth FAILED, fail to get the fetched database row.");
                return(BaseResponse <AuthenticationResponse> .BadAuth());
            }

            // OK, session existing
            log.Information($"Auth OK, for userId = [{session.UserId}].");

            return(new AuthenticationResponse(MongoManager.First <Users>(x => x._id == session.UserId), session));
        }
Exemple #25
0
        /// <summary>
        /// Create or update the list of week ingredients.
        /// </summary>
        /// <param name="userId"></param>
        public void Save(ObjectId userId)
        {
            bool isNew = _id == ObjectId.Empty;

            if (!isNew && UserId != userId)
            {
                throw new Exception("This is not your list of week ingredients.");
            }
            else
            {
                UserId = userId;
            }

            MongoManager.Save(this);

            log.Information($"{(isNew ? "Added" : "Updated")} list of week ingredients {_id}.");
        }
Exemple #26
0
        public static async Task SaveAnswerAsync(StringValues answers, string _id, string submitterName)
        {
            var answerForm = new AnswerForm();

            foreach (var answer in answers)
            {
                answerForm.Answers.Add(answer);
            }
            answerForm.RunningQuizId = _id;
            answerForm.SubmitterName = submitterName;
            answerForm.Timestamp     = DateTime.Now.ToString();

            // Add cache-counter.

            var jsonAnswer = JsonConvert.SerializeObject(answerForm);
            await MongoManager.SaveDocumentAsync("answers", jsonAnswer);
        }
Exemple #27
0
 public async Task DropPin(string id)
 {
     try
     {
         await MongoManager.RemovePinFromQuiz(id, "runningQuizzes");
     }
     catch (MongoException mex)
     {
         HttpContext.Session.SetString("error", mex.Message);
         RedirectToError();
     }
     catch (Exception ex)
     {
         HttpContext.Session.SetString("error", ex.Message);
         RedirectToError();
     }
 }
Exemple #28
0
 public async Task RemoveQuiz(string id)
 {
     try
     {
         await MongoManager.DeleteDocument(id, "Quizzes");
     }
     catch (MongoException mex)
     {
         HttpContext.Session.SetString("error", mex.Message);
         RedirectToError();
     }
     catch (Exception ex)
     {
         HttpContext.Session.SetString("error", ex.Message);
         RedirectToError();
     }
 }
Exemple #29
0
        public async Task <IActionResult> EditQuiz() // 2016-11-25 21:31 - Här kan man ta in _id och få det från Home/ViewPlaylists, om man vill och behöver
        {
            var currentQuiz = await MongoManager.GetQuizFromSession(HttpContext.User.Identity.Name);

            if (currentQuiz != null && currentQuiz != "")
            {
                var quizToEdit = JsonConvert.DeserializeObject <Quiz>(currentQuiz);

                await SaveQuiz();

                return(View(quizToEdit));
            }
            else
            {
                return(RedirectToAction("UserLoggedIn", "Home"));
            }
        }
Exemple #30
0
        /// <summary>
        /// Save WebSocket user connections on hubs.
        /// </summary>
        public static void SaveUserConnectionIds()
        {
            Configurations configurations = MongoManager.First <Configurations>();
            SignalRServers server         = configurations.SignalRServers;
            SignalRHub     hub            = configurations.SignalRServers.Hubs.First(x => x.Type == SignalRHubTypes.Events);

            hub.ConnectedClients = UserConnectionIds.Sum(x => x.Value.Count);

            configurations.SignalRServers.Hubs[configurations.SignalRServers.Hubs.IndexOf(hub)] = hub;

            UpdateDefinition <Configurations> update = Builders <Configurations> .Update.Set(x => x.SignalRServers, server);

            MongoManager.UpdateItems(new List <ObjectId>()
            {
                configurations._id
            }, update);
        }