Пример #1
0
        public async Task <ActionResult> NewUser()
        {
            //Added authentication check below
            bool newUser = false;

            bool.TryParse(User.FindFirst("newUser")?.Value, out newUser);//Try and find the newUser boolean claim and put into variable

            if (User.Identity.IsAuthenticated)
            {
                if (newUser)
                {
                    //Create user profile in Cosmos DB
                    Users user = new Users();
                    user.UserId       = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                    user.FirstName    = User.Identity.Name;
                    user.LastName     = User.FindFirst(ClaimTypes.Surname).Value;
                    user.ShoppingCart = new Dictionary <string, string>();
                    user.OrderHistory = new List <string>();

                    var newUserProfile = await CosmosDBClient <Users> .CreateItemAsync(user, "Users");

                    return(RedirectToAction(nameof(HomeController.Index)));
                }

                return(RedirectToAction(nameof(HomeController.Index)));
            }
            return(RedirectToAction(nameof(HomeController.Index)));
        }
Пример #2
0
 public static bool GetUser(string email, out UserModel user)
 {
     email = Utils.RemoveSpecialCharacters(email.ToLowerInvariant());
     user  = CosmosDBClient.Query <UserModel>(limitOne: true, crossPartition: true)
             .Where(u => u.Email == email).AsEnumerable().FirstOrDefault();
     return(user != null);
 }
Пример #3
0
        public async Task <ActionResult> Product(string selectedProductId)
        {
            //Fetch product data from Cosmos DB
            var ProductDetails = await CosmosDBClient <Products> .GetItemAsync(selectedProductId, "Products");

            return(View(ProductDetails));
        }
Пример #4
0
        public async Task <ActionResult> CreateOrder(List <string> OrderedProducts)
        {
            //Create a new order model object
            Orders order = new Orders();

            order.OrderedProducts = OrderedProducts;
            order.OrderUserId     = User.FindFirst(ClaimTypes.NameIdentifier).Value;
            order.OrderStatus     = "Created";

            //Create a new order in Cosmos DB
            var OrderPost = await CosmosDBClient <Orders> .CreateItemAsync(order, "Orders");

            //Place the Order on a Service Bus queue for fulfillment processing
            await ServiceBusClient.SendMessageAsync(order.ToString());

            //Add the newly generated order ID to the user's order history
            var UserProfile = await CosmosDBClient <Users> .GetItemAsync(User.FindFirst(ClaimTypes.NameIdentifier).Value, "Users");

            UserProfile.OrderHistory.Add(OrderPost.Id);

            //Clear their shopping cart
            UserProfile.ShoppingCart.Clear();

            //Update Cosmos DB with the changes
            var UpdatedUserProfile = await CosmosDBClient <Users> .UpdateItemAsync(UserProfile.UserId, UserProfile, "Users");

            return(RedirectToAction(nameof(HomeController.Index), "Home"));
        }
Пример #5
0
        // Dependency injection uses this constructor to instantiate MainDialog
        public MainDialog(ToDoLUISRecognizer luisRecognizer, ILogger <MainDialog> logger, IConfiguration configuration, CosmosDBClient cosmosDBClient)
            : base(nameof(MainDialog))
        {
            _luisRecognizer = luisRecognizer;
            Logger          = logger;
            Configuration   = configuration;
            _cosmosDBClient = cosmosDBClient;


            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new TextPrompt(UserValidationDialogID, UserValidation));
            AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));
            AddDialog(new CreateTaskDialog(_cosmosDBClient));
            AddDialog(new ViewTaskDialog(Configuration, _cosmosDBClient));
            AddDialog(new DeleteTaskDialog(_cosmosDBClient));
            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), new WaterfallStep[]
            {
                UserExistsStepAsync,
                UserIDStepAsync,
                IntroStepAsync,
                ActStepAsync,
                FinalStepAsync,
            }));

            // The initial child Dialog to run.
            InitialDialogId = nameof(WaterfallDialog);
        }
Пример #6
0
        /// <summary>
        /// Queries CosmosDB for each of the token types
        /// sorts results based on location (if provided) and date
        /// </summary>
        public static IEnumerable <NoteModel> QueryNotes(string userId, string queryContents, string city, Point userLocation = null)
        {
            List <string> uniqueTokens = IndexerBase.GetDistinctTokens(queryContents).ToList();

            if (uniqueTokens.Count == 0)
            {
                return(new List <NoteModel>());
            }
            IQueryable <NoteModel> notes = CosmosDBClient.Query <NoteModel>().Where(n => n.UserId == userId);

            foreach (string token in uniqueTokens)
            {
                if (string.IsNullOrWhiteSpace(token))
                {
                    continue;
                }
                // Check each Indexer for membership
                if (new HashTagIndexer().IsMember(token))
                {
                    new HashTagIndexer().FilterNoteKeys(ref notes, token);
                    TransactionModel.AddTransaction(userId, TransactionModel.TransactionType.Search, token, city, userLocation);
                    continue; // index membership is disjoint
                }
                // Check each Indexer for membership
                if (new LocationIndexer().IsMember(token))
                {
                    new LocationIndexer().FilterNoteKeys(ref notes, token);
                    continue; // index membership is disjoint
                }
                else if (new DateIndexer().IsMember(token))
                {
                    new DateIndexer().FilterNoteKeys(ref notes, token);
                    continue; // index membership is disjoint
                }
                else if (new DateRangeIndexer().IsMember(token))
                {
                    // Date range is an exception where it's not stored as an actual index
                    // but instead a range of indices
                    new DateRangeIndexer().FilterNoteKeys(ref notes, token);
                    continue; // index membership is disjoint
                }
                else
                {
                    // Allow user to forget to add '#' when querying hashtags
                    //new HashTagIndexer().FilterNoteKeys(ref notes, "#" + token);

                    // Word is always the default token
                    new WordIndexer().FilterNoteKeys(ref notes, token);
                }
            }
            return(notes);
            //// Build the query based on the tokens
            //if (userLocation != null)
            //{

            //    return notes.OrderByDescending(n => n.Location.Distance(userLocation))
            //                .ThenBy(n => n.LastUpdatedTime);
            //}
            //return notes.OrderByDescending(n => n.LastUpdatedTime);
        }
Пример #7
0
        public static IEnumerable <string> GetRecentLocations(string userId)
        {
            // TODO: Include frequency into sorting
            IQueryable <TransactionModel> transactions = CosmosDBClient.Query <TransactionModel>().Where(t => t.UserId == userId).Where(t => t.City != string.Empty).Where(t => t.City != null);
            IEnumerable <string>          tags         = transactions.OrderBy(t => t.TransactionTime).Select(t => t.City).AsEnumerable().Distinct();

            return(tags);
        }
Пример #8
0
        public async Task <ActionResult> Category(string category)
        {
            ViewData["Category"] = category;

            //Fetch items from the specific category
            var CategoryProducts = await CosmosDBClient <Products> .GetItemsAsync("Products", p => p.ProductCategory == category);

            return(View(CategoryProducts));
        }
Пример #9
0
        public async Task <ActionResult> Tag(string tag)
        {
            ViewData["Tag"] = tag;

            //Fetch items containing a specific tag
            var TagProducts = await CosmosDBClient <Products> .GetItemsAsync("Products", p => p.ProductTags.Contains(tag));

            return(View(TagProducts));
        }
Пример #10
0
        public static NoteModel AddNote(string content, string city, float latitude, float longitude, string email, string userId)
        {
            NoteModel note = new NoteModel(content, city, latitude, longitude, email, userId);

            if (CosmosDBClient.Insert(note))
            {
                return(note);
            }
            return(null);
        }
Пример #11
0
        public static IEnumerable <string> GetTagsByLocation(string userId, Point userLocation, TransactionType type)
        {
            var transactions          = CosmosDBClient.Query <TransactionModel>().Where(t => t.UserId == userId && t.Type == type).Select(t => new { transaction = t, distance = ((int)t.Location.Distance(userLocation)) / 10 });
            IEnumerable <string> tags = transactions.AsEnumerable().GroupBy(t => t.transaction.Tag)
                                        .Select(g => new { g.Key, spaceSort = g.Min(t => t.distance), countSort = g.Count() })
                                        .OrderBy(g => g.spaceSort)
                                        .ThenBy(g => g.countSort)
                                        .Select(t => t.Key);

            return(tags);
        }
 private static async Task CreateSessionDocument(string databaseName, string collectionName, Session session)
 {
     try
     {
         await CosmosDBClient.GetCustomClient().CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName), session);
     }
     catch (DocumentClientException de)
     {
         throw de;
     }
 }
Пример #13
0
        /// <summary>
        /// Returns the last updated time, null if there has never been an update
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static DateTime?GetLastUpdate(string userId)
        {
            LastUpdateModel lastUpdate = CosmosDBClient.Query <LastUpdateModel>()
                                         .Where(lu => lu.UserId == userId).Where(lu => lu.Id == GetId(userId)).AsEnumerable().FirstOrDefault();

            if (lastUpdate == default(LastUpdateModel))
            {
                return(null);
            }
            return(lastUpdate.LastUpdateTime);
        }
Пример #14
0
        public async Task <ActionResult> AddToCart(string ItemName, string ItemId, string ItemCategory)
        {
            //Get the user's current data (containing their shopping cart)
            Users UserData = await CosmosDBClient <Users> .GetItemAsync(User.FindFirst(ClaimTypes.NameIdentifier).Value, "Users");

            //Add the new item to the Shopping Cart dictionary
            UserData.ShoppingCart.Add(ItemName, ItemId);

            //Return the updated data to CosmosDB
            var ShoppingCartUpdate = await CosmosDBClient <Users> .UpdateItemAsync(User.FindFirst(ClaimTypes.NameIdentifier).Value, UserData, "Users");

            return(RedirectToAction(nameof(ShopController.Category), "Shop", new { category = ItemCategory }));
        }
Пример #15
0
        public ViewTaskDialog(IConfiguration configuration, CosmosDBClient cosmosDBClient) : base(nameof(ViewTaskDialog))
        {
            Configuration   = configuration;
            _cosmosDBClient = cosmosDBClient;

            var waterfallSteps = new WaterfallStep[]
            {
                ShowTasksStepAsync,
            };

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));

            InitialDialogId = nameof(WaterfallDialog);
        }
Пример #16
0
        private static List <Session> ExecuteSimpleQuery(string databaseName, string collectionName, string status)
        {
            // Set some common query options.
            FeedOptions queryOptions = new FeedOptions {
                MaxItemCount = -1, EnableCrossPartitionQuery = true
            };

            // Find the Sesison by its sessionid.
            IQueryable <Session> sessionQuery = CosmosDBClient.GetCustomClient().CreateDocumentQuery <Session>(
                UriFactory.CreateDocumentCollectionUri(databaseName, collectionName),
                "SELECT * FROM c WHERE c.status = '" + status + "' ORDER BY c._ts DESC",
                queryOptions);

            Console.WriteLine("Running LINQ query...");
            return(sessionQuery.ToList());
        }
Пример #17
0
        public DeleteTaskDialog(CosmosDBClient cosmosDBClient) : base(nameof(DeleteTaskDialog))
        {
            _cosmosDBClient = cosmosDBClient;

            var waterfallSteps = new WaterfallStep[]
            {
                ShowTasksStepAsync,
                DeleteTasksStepAsync,
                DeleteMoreTasksStepAsync,
            };

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));

            InitialDialogId = nameof(WaterfallDialog);
        }
Пример #18
0
        /// <summary>
        /// Deletes the note and cleans up the transactions
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="noteId"></param>
        public static bool DeleteNote(string userId, string noteId)
        {
            IEnumerable <TransactionModel> transactions = TransactionModel.GetTagsByNoteId(userId, noteId);
            //Task<bool>[] deleteRequests = new Task<bool>[transactions.Count() + 1];
            //int writeIndex = 0;
            bool success = true;

            foreach (TransactionModel tranny in transactions)
            {
                success &= CosmosDBClient.Delete(tranny.Id, userId);
            }
            success &= CosmosDBClient.Delete(noteId, userId);
            return(success);
            // Wait for all to complete and combine results
            //bool[] results = Task.WhenAll(deleteRequests.ToArray()).Result;
            //return results.Aggregate((workingBool, currBool) => workingBool && currBool);
        }
Пример #19
0
        public CreateTaskDialog(CosmosDBClient cosmosDBClient) : base(nameof(CreateTaskDialog))
        {
            _cosmosDBClient = cosmosDBClient;
            var waterfallSteps = new WaterfallStep[]
            {
                TasksStepAsync,
                ActStepAsync,
                MoreTasksStepAsync,
                SummaryStepAsync
            };

            AddDialog(new WaterfallDialog(nameof(WaterfallDialog), waterfallSteps));
            AddDialog(new TextPrompt(nameof(TextPrompt)));
            AddDialog(new ConfirmPrompt(nameof(ConfirmPrompt)));
            AddDialog(new CreateMoreTaskDialog());

            InitialDialogId = nameof(WaterfallDialog);
        }
Пример #20
0
        /// <summary>
        /// Updates the note and cleans up removed tags
        /// </summary>
        public static NoteModel UpdateNote(string userId, string noteId, string noteContents, string city, float latitude, float longitude, bool completed)
        {
            NoteModel note = CosmosDBClient.Query <NoteModel>()
                             .Where(n => n.UserId == userId).Where(n => n.Id == noteId).AsEnumerable().FirstOrDefault();

            if (note == default(NoteModel))
            {
                return(null);
            }
            IEnumerable <string> removedTags;
            IEnumerable <string> newTags;

            note.SetNoteContents(noteContents, out removedTags, out newTags);
            // cleanup any removed tags (vast majority of the time user will not remove tags)
            foreach (string tag in removedTags)
            {
                TransactionModel.RemoveTransaction(userId, noteId, tag);
            }
            foreach (string tag in newTags)
            {
                TransactionModel.AddTransaction(userId, TransactionModel.TransactionType.Add, tag, city, latitude, longitude, noteId);
            }
            note.LastUpdatedTime = DateTime.UtcNow;
            if (note.City == null)
            {
                note.City = new HashSet <string>();
            }
            if (!string.IsNullOrEmpty(city))
            {
                note.City.Add(city);
            }
            note.Completed = completed;
            if (!CosmosDBClient.Update(note))
            {
                return(null);
            }
            return(note);
        }
Пример #21
0
        public static IEnumerable <TransactionModel> GetTagsByNoteId(string userId, string noteId)
        {
            IQueryable <TransactionModel> transactions = CosmosDBClient.Query <TransactionModel>().Where(t => t.UserId == userId && t.NoteId == noteId);

            return(transactions.AsEnumerable());
        }
Пример #22
0
        public static bool AddTransaction(string userId, TransactionType type, string tag, string city, Point location, string noteId = "")
        {
            TransactionModel transaction = new TransactionModel(userId, type, tag, city, location, noteId);

            return(CosmosDBClient.Insert(transaction));
        }
Пример #23
0
 public static bool RemoveTransaction(string userId, string noteId, string tag)
 {
     return(CosmosDBClient.Delete(GetId(tag, noteId), userId));
 }
Пример #24
0
 public static bool UpdateUser(UserModel user)
 {
     return(CosmosDBClient.Update(user));
 }
Пример #25
0
 public bool Save()
 {
     return(CosmosDBClient.Insert(this));
 }
Пример #26
0
        public static void SetLastUpdate(string userId)
        {
            LastUpdateModel lastUpdate = new LastUpdateModel(userId);

            CosmosDBClient.InsertOrReplace(lastUpdate);
        }