public void CreatingCounters()
        {
            var context = new RealEstateContext();

            var counters = context.Database.GetCollection("counters");

            counters.Drop();

            var arguments = new FindAndModifyArgs
            {
                Query           = Query.EQ("_id", "apples"),
                Update          = Update.Inc("counter", 1),
                SortBy          = SortBy.Null,
                VersionReturned = FindAndModifyDocumentVersion.Modified,
                Upsert          = true
            };
            var apples = counters.FindAndModify(arguments);

            Console.WriteLine("FindAndModify Initialize: " + apples.ModifiedDocument);

            arguments.VersionReturned = FindAndModifyDocumentVersion.Original;
            apples = counters.FindAndModify(arguments);
            Console.WriteLine("FindAndModify (before): " + apples.ModifiedDocument);

            arguments.VersionReturned = FindAndModifyDocumentVersion.Modified;
            apples = counters.FindAndModify(arguments);
            Console.WriteLine("FindAndModify (after): " + apples.ModifiedDocument);
        }
예제 #2
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RealEstateContext db)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseGraphiQl();

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            db.EnsureSeedData();
        }
예제 #3
0
        public IQueryable <LoggedUserModel> GetAll(string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new RealEstateContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);

                if (user == null)
                {
                    throw new InvalidOperationException("Invalid user");
                }

                if (user.Role.UserRole == "admin")
                {
                    var models = this.GetAllUsers(context, user);

                    return(models.OrderByDescending(u => u.FullName));
                }
                else
                {
                    throw new ArgumentException("The user is not admin. Don't have permissions");
                }
            });

            return(responseMsg);
        }
예제 #4
0
        public RealEstateController()
        {
            RealEstateContext db = DBInitialization.InitializeDB();

            _realEstateService = new RealEstateService(db);
            _emailService      = new EmailService(db);
        }
예제 #5
0
        public UserModel GetById(int id, string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new RealEstateContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);

                if (user == null)
                {
                    throw new InvalidOperationException("Invalid user");
                }

                if (user.Role.UserRole == "admin")
                {
                    UserModel resultUser = this.GetUserById(context, id);

                    return(resultUser);
                }
                else
                {
                    throw new ArgumentException("The user is not admin. Don't have permissions");
                }
            });

            return(responseMsg);
        }
예제 #6
0
        private static void PropertySearch(RealEstateContext context)
        {
            Console.Write("Min price:");
            int minPrice = int.Parse(Console.ReadLine());

            Console.Write("Max price:");
            int maxPrice = int.Parse(Console.ReadLine());

            Console.Write("Min size:");
            int minSize = int.Parse(Console.ReadLine());

            Console.Write("Max size:");
            int maxSize = int.Parse(Console.ReadLine());

            IPropertiesService service = new PropertiesService(context);

            var properties = service.Search(minPrice, maxPrice, minSize, maxSize);

            int count = 0;

            foreach (var property in properties.Where(x => x.Price > 0))
            {
                Console.WriteLine($"{++count}. {property}");
            }
        }
예제 #7
0
        public HttpResponseMessage LogOutUser(string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
            {
                var context = new RealEstateContext();
                using (context)
                {
                    var user = context.Users.FirstOrDefault(
                        usr => usr.SessionKey == sessionKey);

                    if (user == null)
                    {
                        throw new InvalidOperationException("Invalid session key");
                    }

                    if (user.SessionKey != null)
                    {
                        user.SessionKey = null;
                        context.SaveChanges();
                    }
                    else
                    {
                        throw new InvalidOperationException("The user is already logged out");
                    }


                    var response =
                        this.Request.CreateResponse(HttpStatusCode.OK);
                    return(response);
                }
            });

            return(responseMsg);
        }
예제 #8
0
        public HttpResponseMessage UpdateUserById(int id, [FromBody] UserModel updatedUser, string sessionKey)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(() =>
            {
                var context = new RealEstateContext();

                var user = context.Users.FirstOrDefault(usr => usr.SessionKey == sessionKey);

                if (user == null)
                {
                    throw new InvalidOperationException("Invalid user");
                }

                if (user.Role.UserRole == "admin")
                {
                    UpdateUser(context, updatedUser, id);

                    var response =
                        this.Request.CreateResponse(HttpStatusCode.OK);
                    return(response);
                }
                else
                {
                    throw new ArgumentException("The user is not admin. Don't have permissions");
                }
            });

            return(responseMsg);
        }
예제 #9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, RealEstateContext context)
        {
            context.Database.MigrateAsync();
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseAuthentication();
            //app.UseStaticFiles(new StaticFileOptions()
            //{
            //    FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"node_modules")),
            //    RequestPath = new PathString("/node_modules")
            //});
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Default}/{action=CaptureInfo}/{id?}");
            });
        }
 public UsersController(IRealEstateRepo userRepo, IMapper mapper,
                        RealEstateContext context)
 {
     this.userRepo = userRepo;
     this._mapper  = mapper;
     this._context = context;
 }
예제 #11
0
        private static void HandlePropertyChangeNotificationMessage(PropertyChangeNotificationMessage propertyChangeNotificationMessage)
        {
            IRealEstateContext context = new RealEstateContext(ConfigurationManager.ConnectionStrings["RealEstateConnection"].ToString());
            IRealEstatePropertyInterestRepository realEstatePropertyInterestRepository = new RealEstatePropertyInterestRepository(context);
            IRealEstateNotificationRepository     realEstateNotificationRepository     = new RealEstateNotificationRepository(context);
            var propertyInterests = realEstatePropertyInterestRepository.GetRealEstatePropertyInterests(propertyChangeNotificationMessage.PropertyId);

            foreach (var propertyInterest in propertyInterests)
            {
                //Create Notification
                var notification = new RealEstateNotification
                {
                    Message    = "Property Modification. Please check",
                    PropertyId = propertyChangeNotificationMessage.PropertyId,
                    UserId     = propertyInterest.UserId
                };
                realEstateNotificationRepository.CreateRealEstateNotification(notification);

                //Send Email Notification
                MailHelper mailHelper = new MailHelper();
                mailHelper.Recipient = propertyInterest.User.UserName;
                mailHelper.Subject   = "Property Change Notification";
                mailHelper.Sender    = ConfigurationManager.AppSettings["EmailFromAddress"];
                mailHelper.Body      = $"Property - {propertyInterest.Property.PropertyName} is modified. Please check the app for details";
                mailHelper.Send();
            }
        }
        public void UsingSetToModifyADocument()
        {
            var documents = new RealEstateContext().Database.GetCollection <BsonDocument>("documents");

            var person = new BsonDocument {
                { "name", "bob" }
            };

            documents.Insert(person);

            Console.WriteLine("\nBefore:");
            Console.WriteLine(documents.FindOneById(person["_id"]));

            var query  = Query.EQ("_id", person["_id"]);
            var update = Update.Set("age", 54);

            documents.Update(query, update);

            Console.WriteLine("\nQuery Document:");
            Console.WriteLine(query);
            Console.WriteLine("\nUpdate Document:");
            Console.WriteLine(update.ToJson());

            Console.WriteLine("\nAfter:");
            Console.WriteLine(documents.FindOneById(person["_id"]));
        }
        public AppViewModel()
        {
            _context = new RealEstateContext();

            if (!_context.Database.Exists())
            {
                _context.RunSeeds();
            }

            AppartmentsVM = new AppartmentsViewModel(_context);
            ClientsVM     = new ClientsViewModel(_context);
            DealsVM       = new DealsViewModel(_context);
            UsersVM       = new UsersViewModel(_context);
            StatsVM       = new StatsViewModel(_context);

            AuthModal = new AuthModal();

            ChangeViewCommand   = new RelayCommand <object>(ChangeView);
            GetDealsCommand     = new RelayCommand <object>(GetDeals);
            AuthenticateCommand = new RelayCommand <object>(Authenticate);
            LogoutCommand       = new RelayCommand <object>(Logout);

            IsReloadOn    = true;
            SwitchCommand = new RelayCommand <object>(_ => IsReloadOn = !IsReloadOn);
        }
        public void UpdatingMultipleDocuments()
        {
            var documents = new RealEstateContext().Database.GetCollection <BsonDocument>("documents");

            documents.Drop();

            documents.Insert(new BsonDocument {
                { "name", "bob" }
            });
            documents.Insert(new BsonDocument {
                { "name", "jane" }
            });
            documents.Insert(new BsonDocument {
                { "name", "anne" }
            });

            Console.WriteLine("\nBefore:");
            documents.FindAll().ToList().ForEach(Console.WriteLine);

            var query  = Query.NE("name", "anne");
            var update = Update.Set("age", 54);

            documents.Update(query, update, UpdateFlags.Multi);

            Console.WriteLine("\nQuery Document:");
            Console.WriteLine(query);
            Console.WriteLine("\nUpdate Document:");
            Console.WriteLine(update.ToJson());

            Console.WriteLine("\nAfter:");
            documents.FindAll().ToList().ForEach(Console.WriteLine);
        }
        public static ApplicationUserManager Create(
            IdentityFactoryOptions <ApplicationUserManager> options,
            IOwinContext context)
        {
            RealEstateContext      db      = context.Get <RealEstateContext>();
            ApplicationUserManager manager = new ApplicationUserManager(new UserStore <ApplicationUser>(db));

            return(manager);
        }
예제 #16
0
 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
 public void Configure(IApplicationBuilder app, IWebHostEnvironment env, RealEstateContext db)
 {
     if (env.IsDevelopment())
     {
         app.UseDeveloperExceptionPage();
     }
     app.UseMvc();
     db.EnsureSeedData();
 }
예제 #17
0
   public REDataController(
      FantasyZoneContext FantasyZoneContext,
           QOTDContext QOTDContext,
          RealEstateContext RealEstateContext 
           ){
            _context = FantasyZoneContext;
            _qotdContext=  QOTDContext;
        _realEstateContext=RealEstateContext;

            }
        public async Task <RealEstateNotification> CreateRealEstateNotification(RealEstateNotification realEstateNotification)
        {
            realEstateNotification.CreatedDate = DateTime.Now;
            realEstateNotification.IsActive    = true;
            realEstateNotification.IsRead      = false;
            RealEstateContext.RealEstateNotification.Add(realEstateNotification);
            await RealEstateContext.SaveChangesAsync();

            return(realEstateNotification);
        }
        public ClientsViewModel(RealEstateContext context)
        {
            _context = context;

            Load();

            ShowCommand   = new RelayCommand <ClientModel>(ShowClient);
            SaveCommand   = new RelayCommand <int>(SaveClient);
            CancelCommand = new RelayCommand <int>(CancelClientChanges);
            DropCommand   = new RelayCommand <object>(DropClient);
        }
        public UsersViewModel(RealEstateContext context)
        {
            _context = context;

            Load();

            ShowCommand   = new RelayCommand <UserModel>(ShowUser);
            SaveCommand   = new RelayCommand <int>(SaveUser);
            CancelCommand = new RelayCommand <int>(CancelUserChanges);
            DropCommand   = new RelayCommand <object>(DropUser);
        }
예제 #21
0
        public HttpResponseMessage PostRegisterUser(UserModel model)
        {
            var responseMsg = this.PerformOperationAndHandleExceptions(
                () =>
            {
                var context = new RealEstateContext();
                using (context)
                {
                    this.ValidateUsername(model.Username);
                    this.ValidateNickname(model.FullName);
                    this.ValidateAuthCode(model.AuthCode);
                    var usernameToLower = model.Username.ToLower();
                    var nicknameToLower = model.FullName.ToLower();
                    var user            = context.Users.FirstOrDefault(
                        usr => usr.Username == usernameToLower ||
                        usr.FullName.ToLower() == nicknameToLower);

                    if (user != null)
                    {
                        throw new InvalidOperationException("Users exists");
                    }

                    user = new User()
                    {
                        Username = usernameToLower,
                        FullName = model.FullName,
                        AuthCode = model.AuthCode,
                        Role     = new Role {
                            UserRole = model.Role
                        }
                    };

                    context.Users.Add(user);
                    context.SaveChanges();

                    user.SessionKey = this.GenerateSessionKey(user.Id);
                    context.SaveChanges();

                    var loggedModel = new LoggedUserModel()
                    {
                        FullName   = user.FullName,
                        SessionKey = user.SessionKey
                    };

                    var response =
                        this.Request.CreateResponse(HttpStatusCode.Created,
                                                    loggedModel);
                    return(response);
                }
            });

            return(responseMsg);
        }
예제 #22
0
        private IQueryable <LoggedUserModel> GetAllUsers(RealEstateContext context, User user)
        {
            var users = from u in context.Users
                        select new LoggedUserModel
            {
                FullName   = u.FullName,
                SessionKey = u.SessionKey
            };

            // users = users.Where(u => u.FullName != user.FullName);
            return(users);
        }
예제 #23
0
        private static void DistrictWithAvgPricePerSquareMeter(RealEstateContext context)
        {
            Console.WriteLine("District with average price per m²");

            IDistrictService service = new DistrictService(context);

            var districts = service.DistrictWithAveragePricePerSquareMeter();

            foreach (var district in districts.OrderByDescending(x => x.AveragePricePerSquareMeter))
            {
                Console.WriteLine(district);
            }
        }
예제 #24
0
        private static void DistrictInfo(RealEstateContext context)
        {
            IDistrictService service = new DistrictService(context);

            var districts = service.DistrictsInfo();

            int count = 0;

            foreach (var district in districts.OrderByDescending(x => x.AveragePrice))
            {
                Console.WriteLine($"{++count}. {district}");
            }
        }
예제 #25
0
        // GET api/values
        public IEnumerable <string> Get()
        {
            var context = new RealEstateContext();
            var user    = new User();

            user.Nickname = "Kostaa";
            user.Username = "******";
            user.AuthCode = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            context.Users.Add(user);
            context.SaveChanges();

            return(new string[] { "value1", "value2" });
        }
예제 #26
0
        public void Inject()
        {
            var query = Query <Rental> .LTE(r => r.Price, 500);

            var queryable = new RealEstateContext()
                            .Rentals.AsQueryable()
                            .Where(r => query.Inject());

            var translated = MongoQueryTranslator.Translate(queryable)
                             as SelectQuery;

            Console.WriteLine(translated.BuildQuery());
        }
예제 #27
0
        private Role UpdateOrEdinRole(RealEstateContext context, string role)
        {
            Role roleDb      = new Role();
            var  doRoleExist = context.Roles.FirstOrDefault(r => r.UserRole == role);

            if (doRoleExist == null)
            {
                roleDb.UserRole = role;
                context.Roles.Add(roleDb);
                context.SaveChanges();
                return(roleDb);
            }
            return(doRoleExist);
        }
예제 #28
0
        private static void FilterByTag(RealEstateContext context)
        {
            Console.WriteLine("Enter tags:");
            string tags = Console.ReadLine();

            IPropertiesService service = new PropertiesService(context);

            var properties = service.TagFilter(tags);

            foreach (var property in properties)
            {
                Console.WriteLine(property);
            }
        }
예제 #29
0
        private UserModel GetUserById(RealEstateContext context, int id)
        {
            var       userDb       = context.Users.First(u => u.Id == id);
            UserModel userToReturn = new UserModel()
            {
                Username = userDb.Username,
                FullName = userDb.FullName,
                Role     = userDb.Role != null?userDb.Role.UserRole:"No role",
                AuthCode = userDb.AuthCode
            };


            return(userToReturn);
        }
예제 #30
0
        public AppartmentsViewModel(RealEstateContext context)
        {
            _context = context;
            Load();

            //General Commands
            ShowCommand   = new RelayCommand <AppartmentModel>(ShowAppartment);
            SaveCommand   = new RelayCommand <int>(SaveAppartment);
            CancelCommand = new RelayCommand <int>(CancelAppartmentChanges);
            DropCommand   = new RelayCommand <object>(DropAppartment);
            //Search Commands
            SearchCommand = new RelayCommand <object>(SearchAppartment);
            FilterCommand = new RelayCommand <bool?>(FilterAppartment);
            ReloadCommand = new RelayCommand <object>(ReloadAppartment);
        }
 public RealEstateRepository(RealEstateContext context, ILogger<RealEstateRepository> logger)
 {
     _context = context;
     _logger = logger;
 }
 public RealEstateContextSeedData(RealEstateContext context, UserManager<RealEstateUser> userManager)
 {
     _context = context;
     _userManager = userManager;
 }