Esempio n. 1
0
        public async Task <IActionResult> DetailsPost(int id)
        {
            if (ModelState.IsValid)
            {
            }

            // Security Claims
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            // Claims Identity
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            // add the current User as the Creator of the Rating
            UserServicesRatingViewModel.CurrentUserId = claim.Value;

            // Check the State Model Binding
            if (ModelState.IsValid)
            {
                var userServiceFromDb = await _colibriDbContext.UserServicesRatings
                                        .Where(p => p.UserServiceId == id)
                                        .FirstOrDefaultAsync();

                _colibriDbContext.UserServicesRatings.Add(userServiceFromDb);

                await _colibriDbContext.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(View(UserServicesRatingViewModel));
            }
        }
Esempio n. 2
0
        public async Task <IActionResult> RateUser(string id)
        {
            if (id == "")
            {
                return(NotFound());
            }

            // get the individual User
            ApplicationUserViewModel.ApplicationUser = await _colibriDbContext.ApplicationUsers
                                                       .Where(p => p.Id.ToLower().Contains(id.ToLower()))
                                                       .FirstOrDefaultAsync();

            // save the Changes in DB
            await _colibriDbContext.SaveChangesAsync();

            // i18n
            ViewData["RateQuestion"]   = _localizer["RateQuestionText"];
            ViewData["Save"]           = _localizer["SaveText"];
            ViewData["BackToList"]     = _localizer["BackToListText"];
            ViewData["ProductRating"]  = _localizer["ProductRatingText"];
            ViewData["RateProduct"]    = _localizer["RateProductText"];
            ViewData["ShowAllRatings"] = _localizer["ShowAllRatingsText"];

            return(View(ApplicationUserViewModel));
        }
Esempio n. 3
0
        public async Task <IActionResult> Details(int id)
        {
            // get the individual Product
            var product = await _colibriDbContext.Products
                          .Include(p => p.CategoryGroups)
                          .Include(p => p.CategoryTypes)
                          //.Include(p => p.SpecialTags)
                          .Where(p => p.Id == id)
                          .FirstOrDefaultAsync();

            // count the Number of Clicks on the Product
            product.NumberOfClicks += 1;

            // save the Changes in DB
            await _colibriDbContext.SaveChangesAsync();

            // i18n
            ViewData["ProductDetails"] = _localizer["ProductDetailsText"];
            ViewData["Name"]           = _localizer["NameText"];
            ViewData["Price"]          = _localizer["PriceText"];
            ViewData["CategoryGroup"]  = _localizer["CategoryGroupText"];
            ViewData["CategoryType"]   = _localizer["CategoryTypeText"];
            ViewData["SpecialTag"]     = _localizer["SpecialTagText"];
            ViewData["RemoveFromBag"]  = _localizer["RemoveFromBagText"];
            ViewData["Order"]          = _localizer["OrderText"];
            ViewData["Description"]    = _localizer["DescriptionText"];
            ViewData["BackToList"]     = _localizer["BackToListText"];

            return(View(product));
        }
Esempio n. 4
0
        // POST
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                // Security Claims
                System.Security.Claims.ClaimsPrincipal currentUser = this.User;

                // Claims Identity
                var claimsIdentity = (ClaimsIdentity)this.User.Identity;
                var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

                UserSubscribeNotificationsViewModel.ApplicationUserCategoryTypesSubscriber.ApplicationUserId =
                    claim.Value;

                // create a DB Entry
                var result = await _colibriDbContext.ApplicationUserCategoryTypesSubscribers
                             .AddAsync(UserSubscribeNotificationsViewModel
                                       .ApplicationUserCategoryTypesSubscriber);

                if (result != null)
                {
                    await _colibriDbContext.SaveChangesAsync();

                    _logger.LogInformation("User chose the Notification Category Type.");
                }
                return(RedirectToAction("Index", "", new { area = "" }));
            }
            return(Page());
        }
Esempio n. 5
0
        public async Task <IActionResult> CreatePOST()
        {
            // i18n
            ViewData["ArchiveEntries"]      = _localizer["ArchiveEntriesText"];
            ViewData["Back"]                = _localizer["BackText"];
            ViewData["CategoryGroup"]       = _localizer["CategoryGroupText"];
            ViewData["CategoryType"]        = _localizer["CategoryTypeText"];
            ViewData["CreatedOn"]           = _localizer["CreatedOnText"];
            ViewData["CreateEntry"]         = _localizer["CreateEntryText"];
            ViewData["Create"]              = _localizer["CreateText"];
            ViewData["EditEntry"]           = _localizer["EditEntryText"];
            ViewData["IsOffer"]             = _localizer["IsOfferText"];
            ViewData["NewEntry"]            = _localizer["NewEntryText"];
            ViewData["Title"]               = _localizer["TitleText"];
            ViewData["TypeOfCategoryGroup"] = _localizer["TypeOfCategoryGroupText"];
            ViewData["Update"]              = _localizer["UpdateText"];
            ViewData["DeleteEntry"]         = _localizer["DeleteEntryText"];
            ViewData["Delete"]              = _localizer["DeleteText"];

            // Convert
            ArchiveViewModel.ArchiveEntry.CategoryTypeId = Convert.ToInt32(Request.Form["CategoryTypeId"].ToString());

            // If ModelState is not valid, return View
            if (!ModelState.IsValid)
            {
                return(View(ArchiveViewModel));
            }

            // Strings für TypeOfCategoryGroup schreiben
            if (ArchiveViewModel.ArchiveEntry.TypeOfCategoryGroup.Equals("0"))
            {
                ArchiveViewModel.ArchiveEntry.TypeOfCategoryGroup = "Product";
            }
            else
            {
                ArchiveViewModel.ArchiveEntry.TypeOfCategoryGroup = "Service";
            }

            // add timestamp to "CreatedOn"
            ArchiveViewModel.ArchiveEntry.CreatedOn = System.DateTime.Now;

            // save changes to DB
            _colibriDbContext.ArchiveEntry.Add(ArchiveViewModel.ArchiveEntry);
            await _colibriDbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 6
0
        public async Task <IActionResult> Create(SpecialTags specialTags)
        {
            // Check the State Model Binding
            if (ModelState.IsValid)
            {
                _colibriDbContext.Add(specialTags);
                await _colibriDbContext.SaveChangesAsync();

                // avoid Refreshing the POST Operation -> Redirect
                //return View("Details", newCategory);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                // one can simply return to the Form View again for Correction
                return(View(specialTags));
            }
        }
Esempio n. 7
0
        public async Task <IActionResult> Edit(string id, ApplicationUser applicationUser)
        {
            if (id != applicationUser.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                ApplicationUser userFromDb = await _colibriDbContext.ApplicationUsers
                                             .Where(u => u.Id == id)
                                             .FirstOrDefaultAsync();

                // Properties or the User
                userFromDb.FirstName      = applicationUser.FirstName;
                userFromDb.LastName       = applicationUser.LastName;
                userFromDb.Email          = applicationUser.Email;
                userFromDb.PhoneNumber    = applicationUser.PhoneNumber;
                userFromDb.Street         = applicationUser.Street;
                userFromDb.CareOf         = applicationUser.CareOf;
                userFromDb.City           = applicationUser.City;
                userFromDb.Zip            = applicationUser.Zip;
                userFromDb.Country        = applicationUser.Country;
                userFromDb.Modified       = DateTime.Now;
                userFromDb.LockoutEnabled = applicationUser.LockoutEnabled;

                // handle the Lockout by the Admin manually
                if (!applicationUser.LockoutEnabled)
                {
                    userFromDb.LockoutEnd = null;
                }
                else
                {
                    userFromDb.LockoutEnd = DateTimeOffset.MaxValue;
                }

                // save Changes
                await _colibriDbContext.SaveChangesAsync();

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

            return(View(applicationUser));
        }
Esempio n. 8
0
        public async Task <IActionResult> Create(CategoryGroups categoryGroups)
        {
            // Check the State Model Binding
            if (ModelState.IsValid)
            {
                // Strings für TypeOfCategoryGroup schreiben
                if (categoryGroups.TypeOfCategoryGroup.Equals("0"))
                {
                    categoryGroups.TypeOfCategoryGroup = "Product";
                }
                else
                {
                    categoryGroups.TypeOfCategoryGroup = "Service";
                }

                _colibriDbContext.Add(categoryGroups);
                await _colibriDbContext.SaveChangesAsync();

                // Publish the Created Category
                using (var bus = RabbitHutch.CreateBus("host=localhost"))
                {
                    //bus.Publish(categoryGroups, "create_category_groups");
                    //await bus.PublishAsync("create_category_groups").ContinueWith(task =>
                    // {
                    //     if (task.IsCompleted && !task.IsFaulted)
                    //     {
                    //         Console.WriteLine("Task Completed");
                    //         Console.ReadLine();
                    //     }
                    // });
                    await bus.SendAsync("create_category_groups", categoryGroups);
                }


                // avoid Refreshing the POST Operation -> Redirect
                return(RedirectToAction(nameof(Index)));
                //return RedirectToAction("Index", "CategoryGroups", new { area = "Admin" });
            }
            else
            {
                // one can simply return to the Form View again for Correction
                return(View(categoryGroups));
            }
        }
Esempio n. 9
0
        public async Task <IActionResult> Index()
        {
            //Notifications message = new Notifications();

            using (var bus = RabbitHutch.CreateBus("host=localhost"))
            {
                bus.SubscribeAsync <CategoryGroups>("create_category_groups",
                                                    groups => Task.Factory.StartNew(() =>
                {
                    var message = "Added Category Group: " + groups.Name;
                    SubscriberViewModel.Notifications.Message          = message;
                    SubscriberViewModel.Notifications.NotificationType = "CategoryGroup";
                }));


                bus.Subscribe <CategoryTypes>("create_category_types",
                                              categoryTypes => Task.Factory.StartNew(() =>
                {
                    var message = "Added Category Type: " + categoryTypes.Name;
                    SubscriberViewModel.Notifications.Message          = message;
                    SubscriberViewModel.Notifications.NotificationType = "CategoryType";
                }));

                //bus.Subscribe<Products>("create_product_by_admin",
                //    categoryTypes => Task.Factory.StartNew(() =>
                //    {
                //        var message = "Added Product by Admin: " + typeof(Products);
                //        SubscriberViewModel.Notifications.Message = message;
                //        SubscriberViewModel.Notifications.NotificationType = "ProductsByAdmin";
                //    }));
            }

            // persist
            if (SubscriberViewModel.Notifications.Message != null)
            {
                await _colibriDbContext.AddAsync(SubscriberViewModel.Notifications);

                await _colibriDbContext.SaveChangesAsync();
            }

            return(View(SubscriberViewModel));
        }
Esempio n. 10
0
        public async Task <IActionResult> DeleteConfirmed(int id)
        {
            // get an Appointment from the DB
            var appointment = await _colibriDbContext.Appointments.FindAsync(id);

            _colibriDbContext.Appointments.Remove(appointment);

            await _colibriDbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 11
0
        public async Task <IActionResult> DeletePOST()
        {
            // Suchanfragen von DB löschen
            var entries = _colibriDbContext.SearchEntry.ToList();

            foreach (var x in entries)
            {
                _colibriDbContext.Remove(x);
            }
            await _colibriDbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 12
0
        public async Task <IActionResult> createPost()
        {
            //// Security Claims
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            //// Claims Identity
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            // Check the State Model Binding
            if (ModelState.IsValid)
            {
                // add a UserService first to retrieve it, so one can add User Service to it
                _colibriDbContext.Add(UserServicesAddToEntityViewModel.UserServices);
                await _colibriDbContext.SaveChangesAsync();

                // Image being saved
                // use the Hosting Environment
                string webRootPath = _hostingEnvironment.WebRootPath;

                // retrieve all Files (typed by the User in the View )
                var files = HttpContext.Request.Form.Files;

                // to update the User Service from the DB: retrieve the Db Files
                // new Properties will be added to the specific User Service -> Id needed!
                var userServicesFromDb = _colibriDbContext.UserServices.Find(UserServicesAddToEntityViewModel.UserServices.Id);

                // Image File has been uploaded from the View
                if (files.Count != 0)
                {
                    // Image has been uploaded
                    // the exact Location of the ImageFolderProduct for the Service
                    var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderService);

                    // find the Extension of the File
                    var extension = Path.GetExtension(files[0].FileName);

                    // use the FileStreamObject -> copy the File from the Uploaded to the Server
                    // create the File on the Server
                    using (var filestream = new FileStream(Path.Combine(uploads, UserServicesAddToEntityViewModel.UserServices.Id + extension), FileMode.Create))
                    {
                        files[0].CopyTo(filestream);
                    }

                    // ProductsImage = exact Path of the Image on the Server + ImageName + Extension
                    userServicesFromDb.Image = @"\" + StaticDetails.ImageFolderService + @"\" + UserServicesAddToEntityViewModel.UserServices.Id + extension;
                }
                // Image File has not been uploaded -> use a default one
                else
                {
                    // a DUMMY Image if the User does not have uploaded any File (default Image)
                    var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderService + @"\" + StaticDetails.DefaultServiceImage);

                    // copy the Image from the Server and rename it as the ProductImage ID
                    System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.ImageFolderService + @"\" + UserServicesAddToEntityViewModel.UserServices.Id + ".jpg");

                    // update the ProductFromDb.Image with the actual FileName
                    userServicesFromDb.Image = @"\" + StaticDetails.ImageFolderService + @"\" + UserServicesAddToEntityViewModel.UserServices.Id + ".jpg";
                }

                // add the current User as the Creator of the Advertisement
                userServicesFromDb.ApplicationUserId = claim.Value;

                // add the CreatedOn Property to the Model
                userServicesFromDb.CreatedOn = DateTime.Now;

                // save the Changes asynchronously
                // update the Image Part inside of the DB
                await _colibriDbContext.SaveChangesAsync();

                // Publish the Created Advertisement's Product
                using (var bus = RabbitHutch.CreateBus("host=localhost"))
                {
                    Console.WriteLine("Publishing an User Service Message.");
                    Console.WriteLine();

                    //bus.Publish<AdvertisementViewModel>(AdvertisementViewModel, "my_subscription_id");
                    //bus.Publish(productsFromDb, "my_subscription_id");

                    await bus.SendAsync("create_user_service", userServicesFromDb);
                }

                // TODO
                // Convert to JSON
                //var parsedJson = new JavaScriptSerializer().Serialize(ProductsViewModel);
                var result = Json(UserServicesAddToEntityViewModel);

                // avoid Refreshing the POST Operation -> Redirect
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                // one can simply return to the Form View again for Correction
                return(View(UserServicesAddToEntityViewModel));
            }
        }
Esempio n. 13
0
        public async Task <IActionResult> CreatePost()
        {
            // Check the State Model Binding
            if (ModelState.IsValid)
            {
                //add a Product first to retrieve it, so one can add Properties to it
                _colibriDbContext.Add(ProductsViewModel.Products);
                await _colibriDbContext.SaveChangesAsync();

                // TODO save in the Search Entity
                //_colibriDbContext.Add(ProductsViewModel.CategoryTypes);
                //await _colibriDbContext.SaveChangesAsync();


                // Image being saved
                // use the Hosting Environment
                string webRootPath = _hostingEnvironment.WebRootPath;

                // retrieve all Files (typed by the User in the View )
                var files = HttpContext.Request.Form.Files;

                // to update the Products from the DB: retrieve the Db Files
                // new Properties will be added to the specific Product -> Id needed!
                var productsFromDb = _colibriDbContext.Products.Find(ProductsViewModel.Products.Id);

                // Image File has been uploaded from the View
                if (files.Count != 0)
                {
                    // Image has been uploaded
                    // the exact Location of the ImageFolderProduct
                    var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderProduct);

                    // find the Extension of the File
                    var extension = Path.GetExtension(files[0].FileName);

                    // use the FileStreamObject -> copy the File from the Uploaded to the Server
                    // create the File on the Server
                    using (var filestream = new FileStream(Path.Combine(uploads, ProductsViewModel.Products.Id + extension), FileMode.Create))
                    {
                        files[0].CopyTo(filestream);
                    }

                    // ProductsImage = exact Path of the Image on the Server + ImageName + Extension
                    productsFromDb.Image = @"\" + StaticDetails.ImageFolderProduct + @"\" + ProductsViewModel.Products.Id + extension;
                }
                // Image File has not been uploaded -> use a default one
                else
                {
                    // a DUMMY Image if the User does not have uploaded any File (default Image)
                    var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderProduct + @"\" + StaticDetails.DefaultProductImage);

                    // copy the Image from the Server and rename it as the ProductImage ID
                    System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.ImageFolderProduct + @"\" + ProductsViewModel.Products.Id + ".jpg");

                    // update the ProductFromDb.Image with the actual FileName
                    productsFromDb.Image = @"\" + StaticDetails.ImageFolderProduct + @"\" + ProductsViewModel.Products.Id + ".jpg";
                }

                // add the CreatedOn Property to the Model
                productsFromDb.CreatedOn = DateTime.Now;

                // save the Changes asynchronously
                // update the Image Part inside of the DB
                await _colibriDbContext.SaveChangesAsync();

                // Publish the Created Product
                //using (var bus = RabbitHutch.CreateBus("host=localhost"))
                //{
                //    //bus.Publish(categoryGroups, "create_category_groups");
                //    await bus.PublishAsync("create_product_by_admin").ContinueWith(task =>
                //    {
                //        if (task.IsCompleted && !task.IsFaulted)
                //        {
                //            Console.WriteLine("Task Completed");
                //            Console.ReadLine();
                //        }
                //    });
                //}

                using (var bus = RabbitHutch.CreateBus("host=localhost"))
                {
                    await bus.SendAsync("create_product_by_admin", productsFromDb);
                }


                // avoid Refreshing the POST Operation -> Redirect
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                // one can simply return to the Form View again for Correction
                return(View(ProductsViewModel));
            }
        }
Esempio n. 14
0
        // GET : Action for SearchOffer
        public async Task <IActionResult> SearchOffer(HomeIndexViewModel model)
        {
            // i18n
            ViewData["SearchOffers"]  = _localizer["SearchOffersText"];
            ViewData["SearchString"]  = _localizer["SearchStringText"];
            ViewData["Details"]       = _localizer["DetailsText"];
            ViewData["Sorry1"]        = _localizer["Sorry1Text"];
            ViewData["Sorry2"]        = _localizer["Sorry2Text"];
            ViewData["Title"]         = _localizer["TitleText"];
            ViewData["CategoryGroup"] = _localizer["CategoryGroupText"];
            ViewData["CategoryType"]  = _localizer["CategoryTypeText"];
            ViewData["CreatedOn"]     = _localizer["CreatedOnText"];
            ViewData["Products"]      = _localizer["ProductsText"];
            ViewData["Service"]       = _localizer["ServiceText"];

            SearchViewModel.SearchAdvertisement = model.SearchAdvertisement;

            // Prüfen, ob es ein aktuelles PRODUKTE-Angebot in der Datenbank gibt
            SearchViewModel.ProductsList = await _colibriDbContext.Products.Where(m => m.Name.Contains(SearchViewModel.SearchAdvertisement)).Where(m => m.isOffer == true).ToListAsync();

            SearchViewModel.ProductsCounter = SearchViewModel.ProductsList.Count();

            // Prüfen, ob es ein aktuelles DIENSTLEISTUNGS-Angebot in der Datenbank gibt
            SearchViewModel.UserServicesList = await _colibriDbContext.UserServices.Where(m => m.Name.Contains(SearchViewModel.SearchAdvertisement)).Where(m => m.isOffer == true).ToListAsync();

            SearchViewModel.UserServicesCounter = SearchViewModel.UserServicesList.Count();

            // Gesamte Anzahl Resultate
            SearchViewModel.ResultsCounter = SearchViewModel.ProductsCounter + SearchViewModel.UserServicesCounter;

            // Falls kein aktuelles Angebot in der Datenbank gefunden wird, wird im Archiv gesucht, ob in der Vergangenheit ein passendes Angebot erfasst wurde
            if (SearchViewModel.ResultsCounter < 1)
            {
                // Ergebnisse werden absteigend sortiert und die Top 3 Werte werden zurückgegeben
                SearchViewModel.ArchiveEntryList = await _colibriDbContext.ArchiveEntry.Where(m => m.Name.Contains(SearchViewModel.SearchAdvertisement)).Where(m => m.isOffer == true).Include(m => m.CategoryGroups).Include(m => m.CategoryTypes).OrderByDescending(p => p.CreatedOn).Take(3).ToListAsync();

                SearchViewModel.ResultsCounterArchive = SearchViewModel.ArchiveEntryList.Count();
            }

            // Einträge für SUCHANFRAGEN in Tabelle SearchEntry schreiben
            if (SearchViewModel.SearchAdvertisement != null)
            {
                if (SearchViewModel.SearchAdvertisement.Length > 2)
                {
                    var userSearch = new SearchEntry();

                    userSearch.SearchDate  = System.DateTime.Now;
                    userSearch.SearchText  = SearchViewModel.SearchAdvertisement;
                    userSearch.Counter     = 1;
                    userSearch.SearchOffer = true;

                    // Falls Resultat vorhanden
                    if (SearchViewModel.ResultsCounter > 0)
                    {
                        userSearch.FullSuccess = true;
                        userSearch.PartSuccess = false;
                        userSearch.NoSuccess   = false;
                    }

                    // Falls Resultat in Archive gefunden wird
                    else
                    {
                        if (SearchViewModel.ResultsCounterArchive > 0)
                        {
                            userSearch.FullSuccess = false;
                            userSearch.PartSuccess = true;
                            userSearch.NoSuccess   = false;
                        }
                        // Falls kein Resultat gefunden wird
                        else
                        {
                            userSearch.FullSuccess = false;
                            userSearch.PartSuccess = false;
                            userSearch.NoSuccess   = true;
                        }
                    }

                    // Add userSearch to DB and save changes
                    _colibriDbContext.SearchEntry.Add(userSearch);
                    await _colibriDbContext.SaveChangesAsync();
                }
            }
            return(View(SearchViewModel));
        }
Esempio n. 15
0
        public async Task <IActionResult> CreateProductPOST()
        {
            // Security Claims
            System.Security.Claims.ClaimsPrincipal currentUser = this.User;

            // Claims Identity
            var claimsIdentity = (ClaimsIdentity)this.User.Identity;
            var claim          = claimsIdentity.FindFirst(ClaimTypes.NameIdentifier);

            // Convert
            AdvertisementViewModel.Product.CategoryTypeId = Convert.ToInt32(Request.Form["CategoryTypeId"].ToString());

            // If ModelState is not valid, return View
            if (!ModelState.IsValid)
            {
                return(View(AdvertisementViewModel));
            }

            // add the current User as the Creator of the Advertisement
            AdvertisementViewModel.Product.ApplicationUserId   = claim.Value;
            AdvertisementViewModel.Product.ApplicationUserName = claimsIdentity.Name;

            //// combine the Advertisement Offer's Date and Time for the DueDateFrom Property
            //AdvertisementViewModel.Product.DueDateFrom = AdvertisementViewModel.Product.DueDateFrom
            //    .AddHours(AdvertisementViewModel.Product.DueTimeFrom.Hour)
            //    .AddMinutes(AdvertisementViewModel.Product.DueTimeFrom.Minute);

            //// combine the Advertisement Offer's Date and Time for the DueDateTo Property
            //AdvertisementViewModel.Product.DueDateTo = AdvertisementViewModel.Product.DueDateTo
            //    .AddHours(AdvertisementViewModel.Product.DueTimeTo.Hour)
            //    .AddMinutes(AdvertisementViewModel.Product.DueTimeTo.Minute);

            // add timestamp to "CreatedOn"
            AdvertisementViewModel.Product.CreatedOn = System.DateTime.Now;

            // set "available" to TRUE
            AdvertisementViewModel.Product.Available = true;

            // set "isOffer" to FALSE
            AdvertisementViewModel.Product.isOffer = false;

            // If ModelState is valid, save changes to DB
            _colibriDbContext.Products.Add(AdvertisementViewModel.Product);
            await _colibriDbContext.SaveChangesAsync();

            // Save Image
            // use the Hosting Environment
            string webRootPath = _hostingEnvironment.WebRootPath;

            // retrieve all Files (typed by the User in the View )
            var files = HttpContext.Request.Form.Files;

            // to update the Products from the DB: retrieve the Db Files
            // new Properties will be added to the specific Product -> Id needed!
            var productsFromDb = _colibriDbContext.Products.Find(AdvertisementViewModel.Product.Id);

            // Image File has been uploaded from the View
            //if (files != null)
            if (files.Count() > 0)
            {
                if (files[0].Length > 0)
                {
                    // the exact Location of the ImageFolderProduct
                    //var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderProduct);
                    var uploads = Path.Combine(webRootPath, "img/ProductImage");

                    // find the Extension of the File
                    //var extension = Path.GetExtension(files[0].FileName);
                    var extension = files[0].FileName.Substring(files[0].FileName.LastIndexOf("."), files[0].FileName.Length - files[0].FileName.LastIndexOf("."));

                    // use the FileStreamObject -> copy the File from the Uploaded to the Server
                    // create the File on the Server
                    using (var filestream = new FileStream(Path.Combine(uploads, AdvertisementViewModel.Product.Id + extension), FileMode.Create))
                    {
                        files[0].CopyTo(filestream);
                    }

                    // ProductsImage = exact Path of the Image on the Server + ImageName + Extension
                    //productsFromDb.Image = @"\" + StaticDetails.ImageFolderProduct + @"\" + AdvertisementViewModel.Product.Id + extension;
                    productsFromDb.Image = @"\img\ProductImage\" + AdvertisementViewModel.Product.Id + extension;
                }
            }
            else
            {
                // a DUMMY Image if the User does not have uploaded any File (default Image)
                //var uploads = Path.Combine(webRootPath, StaticDetails.ImageFolderProduct + @"\" + StaticDetails.DefaultProductImage);
                var uploads = Path.Combine(webRootPath, @"img\ProductImage\" + StaticDetails.DefaultProductImage);

                // copy the Image from the Server and rename it as the ProductImage ID
                //System.IO.File.Copy(uploads, webRootPath + @"\" + StaticDetails.ImageFolderProduct + @"\" + AdvertisementViewModel.Product.Id + ".jpg");
                System.IO.File.Copy(uploads, webRootPath + @"\img\ProductImage\" + AdvertisementViewModel.Product.Id + ".jpg");

                // update the ProductFromDb.Image with the actual FileName
                productsFromDb.Image = @"\img\ProductImage\" + AdvertisementViewModel.Product.Id + ".jpg";
            }

            await _colibriDbContext.SaveChangesAsync();

            // Publish the Created Advertisement's Product
            using (var bus = RabbitHutch.CreateBus("host=localhost"))
            {
                Console.WriteLine("Publishing an Advertisement Message.");
                Console.WriteLine();

                //bus.Publish<AdvertisementViewModel>(AdvertisementViewModel, "my_subscription_id");
                //bus.Publish(productsFromDb, "my_subscription_id");

                await bus.SendAsync("create_advertisement", productsFromDb);
            }

            // Eintrag für ArchiveEntry erstellen
            ArchiveEntry archiveEntry = new ArchiveEntry()
            {
                Name                = AdvertisementViewModel.Product.Name,
                Description         = AdvertisementViewModel.Product.Description,
                isOffer             = false,
                CategoryTypeId      = AdvertisementViewModel.Product.CategoryTypeId,
                CategoryGroupId     = AdvertisementViewModel.Product.CategoryGroupId,
                TypeOfCategoryGroup = "Product",
                CreatedOn           = System.DateTime.Now
            };

            // Eintrag in ArchiveEntry-DB schreiben
            _colibriDbContext.ArchiveEntry.Add(archiveEntry);
            await _colibriDbContext.SaveChangesAsync();

            // Zurück zu Index-View
            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 16
0
        public async Task <IActionResult> Create(CategoryTypesAndCategoryGroupsViewModel model)
        {
            // i18n
            ViewData["CreateCategoryType"] = _localizer["CreateCategoryTypeText"];
            ViewData["Create"]             = _localizer["CreateText"];
            ViewData["BackToList"]         = _localizer["BackToListText"];
            ViewData["Name"] = _localizer["NameText"];

            // Check the State Model Binding
            if (ModelState.IsValid)
            {
                // check if CategoryTypes exists or not & check if Combination of CategoryTypes and CategoryGroup exists
                var doesCategoryTypesExist = _colibriDbContext.CategoryTypes.Where(s => s.Name == model.CategoryTypes.Name).Count();
                var doesCategoryTypesAndCategoryGroupsExist = _colibriDbContext.CategoryTypes.Where(s => s.Name == model.CategoryTypes.Name && s.CategoryGroupId == model.CategoryTypes.CategoryGroupId).Count();

                if (doesCategoryTypesExist > 0 && model.isNew)
                {
                    // error
                    StatusMessage = "Error : CategoryTypes Name already exists";
                }
                else
                {
                    if (doesCategoryTypesExist == 0 && !model.isNew)
                    {
                        // error
                        StatusMessage = "Error : CategoryTypes does not exist";
                    }
                    else
                    {
                        if (doesCategoryTypesAndCategoryGroupsExist > 0)
                        {
                            // error
                            StatusMessage = "Error : CategoryTypes and CategoryGroups combination already exists";
                        }
                        else
                        {
                            if (model.CategoryTypes.PLZ == null)
                            {
                                model.CategoryTypes.isGlobal = true;
                            }

                            // Wenn keine Fehler, kombinierten Name ergänzen
                            // Product / UserService
                            model.CategoryTypes.CategoryGroups = await _colibriDbContext.CategoryGroups.Where(m => m.Id == model.CategoryTypes.CategoryGroupId).FirstOrDefaultAsync();

                            if (model.CategoryTypes.CategoryGroups.TypeOfCategoryGroup.Equals("Product"))
                            {
                                model.CategoryTypes.NameCombined = "Product - " + model.CategoryTypes.CategoryGroups.Name + " - " + model.CategoryTypes.Name;
                            }
                            else
                            {
                                model.CategoryTypes.NameCombined = "Service - " + model.CategoryTypes.CategoryGroups.Name + " - " + model.CategoryTypes.Name;
                            }

                            // Eintrag in DB schreiben
                            _colibriDbContext.Add(model.CategoryTypes);
                            await _colibriDbContext.SaveChangesAsync();


                            // Publish the Created Category Type
                            using (var bus = RabbitHutch.CreateBus("host=localhost"))
                            {
                                //bus.Publish(categoryTypes, "create_category_types");
                                await bus.SendAsync("create_category_types", model.CategoryTypes);
                            }

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

            // If ModelState is not valid
            CategoryTypesAndCategoryGroupsViewModel modelVM = new CategoryTypesAndCategoryGroupsViewModel()
            {
                CategoryGroupsList = _colibriDbContext.CategoryGroups.ToList(),
                CategoryTypes      = model.CategoryTypes,
                CategoryTypesList  = _colibriDbContext.CategoryTypes.OrderBy(p => p.Name).Select(p => p.Name).ToList(),
                StatusMessage      = StatusMessage
            };

            return(View(modelVM));
        }