Esempio n. 1
0
        public async Task ReceiveApplications()
        {
            var json = "";

            Console.WriteLine("Hub");
            using (var dbCon = PostgresConn.GetConn())
            {
                var command = dbCon.CreateCommand();
                command.CommandType = CommandType.Text;
                command.CommandText = @"SELECT * FROM ""public"".""restaurants"" WHERE published=false";
                var reader = command.ExecuteReader();
                if (!reader.HasRows)
                {
                    await this.Clients.All.SendAsync("ReceiveApplications", "");
                }
                var restaurants = new List <(string, Guid)>();
                while (reader.Read())
                {
                    var name = reader.GetString("name");
                    var id   = reader.GetGuid("id");
                    restaurants.Add((name, id));
                }
                json = JsonConvert.SerializeObject(restaurants);
                Console.WriteLine(json);
                await this.Clients.All.SendAsync("ReceiveApplications", json);
            }
        }
        public async void GetAllRestaurants()
        {
            try
            {
                using (var dbCon = PostgresConn.GetConn())
                {
                    var restaurants        = new RestaurantRepository().GetAllRestaurants(dbCon);
                    var serializerSettings = new JsonSerializerSettings();
                    serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    var json = JsonConvert.SerializeObject(restaurants, serializerSettings);

                    if (!Response.HasStarted)
                    {
                        Response.StatusCode = 200;
                    }

                    if (json.Contains("[null]"))
                    {
                        await Response.Body.WriteAsync(new byte[] { });
                    }
                    else
                    {
                        await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(json));
                    }
                }
            }
            catch (Exception e)
            {
                if (!Response.HasStarted)
                {
                    Response.StatusCode = 400;
                }
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));
            }
        }
Esempio n. 3
0
        public async void CreateOrder(object data)
        {
            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            Order order;
            var   dict         = JObject.Parse(data.ToString());
            var   userId       = int.Parse(dict["userId"].ToString());
            var   restaurantId = dict["restaurantId"].ToString();
            var   timeToGet    = dict["timeToGet"].ToString();
            var   tableId      = dict["tableId"].ToString();
            var   dishesIds    = dict["dishesIds"].ToString().Trim('[').Trim(']').Split(", ");

            try
            {
                order = new Order(userId, restaurantId, tableId, timeToGet, dishesIds);
                Console.WriteLine(order);
                using (var dbCon = PostgresConn.GetConn())
                {
                    if (dbCon == null)
                    {
                        Console.WriteLine("null");
                    }
                    new OrderRepository().Insert(dbCon, order);
                    Console.WriteLine("insert");
                    Response.StatusCode = 201;
                }

                Console.WriteLine("insert");
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync(e.Message);
            }
        }
Esempio n. 4
0
        public void Insert(NpgsqlConnection dbCon, IDbEntity entity)
        {
            var order   = entity as Order;
            var command = dbCon.CreateCommand();

            command.CommandType = CommandType.Text;
            command.CommandText =
                $"INSERT INTO public.orders (id, \"userId\", \"restaurantId\", \"tableId\", \"creationDateTime\", \"timeToGet\", \"isCompleted\") " +
                $"VALUES" +
                $" ('{order.Id}',{order.UserId}, '{order.RestaurantId}', '{order.TableId}', {order.CreationDateTime}, '{order.TimeToGet}', {order.IsCompleted} )";
            command.ExecuteNonQuery();
            foreach (var dishesId in order.DishesIds)
            {
                using (var con = PostgresConn.GetConn())
                {
                    command             = con.CreateCommand();
                    command.CommandType = CommandType.Text;
                    command.CommandText =
                        $"INSERT INTO public.orderswithdishes (\"orderId\", \"dishId\") " +
                        $"VALUES" +
                        $" ('{order.Id}', '{dishesId}' )";
                    command.ExecuteNonQuery();
                }
            }
        }
Esempio n. 5
0
        public async void GetDishById(int dishId)
        {
            try
            {
                using (var dbCon = PostgresConn.GetConn())
                {
                    var dishAsDBEntity = new DishRepository().GetById(dbCon, dishId);
                    var serializerSettings = new JsonSerializerSettings();
                    serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    var json = JsonConvert.SerializeObject(dishAsDBEntity, serializerSettings);
                    Response.StatusCode = 200;

                    if (!(dishAsDBEntity == null || json.Contains("[null]")))
                        await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(json));

                    var dish = dishAsDBEntity as Dish;
                    var filePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\")) + $"Images\\DISH{dish.RestaurantId + dish.Name}.jpg";
                    await Response.SendFileAsync(filePath);
                }

            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));
            }
        }
        public async void GetRestaurantById(Guid restaurantId)
        {
            try
            {
                using (var dbCon = PostgresConn.GetConn())
                {
                    var restaurantAsDBEntity = new RestaurantRepository().GetById(dbCon, restaurantId);
                    var serializerSettings   = new JsonSerializerSettings();
                    serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    var json = JsonConvert.SerializeObject(restaurantAsDBEntity, serializerSettings);
                    if (!Response.HasStarted)
                    {
                        Response.StatusCode = 200;
                    }

                    if (json.Contains("[null]"))
                    {
                        await Response.Body.WriteAsync(new byte[] { });
                    }
                    else
                    {
                        await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(json));
                    }

                    var restaurant = restaurantAsDBEntity as Restaurant;
                    var filePath   = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\")) + $"Images\\MAP{restaurant.Id}.jpg";
                    await Response.SendFileAsync(filePath);
                }
            }
            catch (Exception e)
            {
                //if (!Response.HasStarted) Response.StatusCode = 400; //кидало ошибку, поэтому закомментил
                //await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));
            }
        }
        public async void GetBooking(Guid restaurantId)
        {
            try
            {
                var filePath =
                    Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\")) + $"Images\\{restaurantId}.svg";
                await Response.SendFileAsync(filePath);

                using (var dbCon = PostgresConn.GetConn())
                {
                    var tables     = new TableRepository().GetByRestaurantId(dbCon, restaurantId);
                    var tablesInfo = new List <(string id, string name, bool isFree)>();
                    foreach (var table in tables)
                    {
                        tablesInfo.Add((table.TableId, table.Name, table.IsFree));
                    }
                    var json = JsonConvert.SerializeObject(tablesInfo);
                    Console.WriteLine(json);
                    await Response.WriteAsync(json);
                }
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));
            }
        }
Esempio n. 8
0
        public static void Create(string operacao)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("Insert into log_ocorrencias (operacao) values ('" + operacao + "')");

            PostgresConn.ExecutarComando(sql.ToString());
        }
        public static DataTable GetAll()
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("select * from clientes ");

            return(PostgresConn.getDataTable(sql.ToString()));
        }
        public async void RegisterPhys(object data)
        {
            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            User user;
            var  dict     = JObject.Parse(data.ToString());
            var  email    = dict["email"].ToString();
            var  password = dict["password"].ToString();
            var  phone    = dict["phone"].ToString();
            var  username = dict["username"].ToString();
            var  role     = "none";

            try
            {
                user = new User(email, password, username, phone, role);
                using (var dbCon = PostgresConn.GetConn())
                {
                    new UserRepository().Insert(dbCon, user);
                    Response.StatusCode = 201;
                }

                Console.WriteLine("insert");

                using (var dbCon = PostgresConn.GetConn())
                {
                    user = UserRepository.IsAuth(email, password, dbCon);
                }

                Console.WriteLine("get");
                var now    = DateTime.UtcNow;
                var claims = new List <Claim>();
                claims.Add(new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email));

                claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role));
                var jwt = new JwtSecurityToken(
                    issuer: AuthOptions.ISSUER,
                    audience: AuthOptions.AUDIENCE,
                    notBefore: now,
                    claims: claims,
                    expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
                    signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
                var encodedJwt         = new JwtSecurityTokenHandler().WriteToken(jwt);
                var serializerSettings = new JsonSerializerSettings();
                serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                var json = JsonConvert.SerializeObject(user, serializerSettings);
                Console.WriteLine(json);
                Response.Cookies.Append("token", encodedJwt);
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(json));
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync(e.Message);
            }
        }
        public static void Create(Cliente cliente)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("Insert into clientes (nome, idade) values ('");
            sql.Append(cliente.Nome + "'," + cliente.Idade + ")");
            PostgresConn.ExecutarComando(sql.ToString());

            //insere o log
            LogClienteRepositorio.Create("Inseriu o cliente " + cliente.Nome);
        }
Esempio n. 12
0
        public async void AuthJur(object data)
        {
            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            var dict     = JObject.Parse(data.ToString());
            var email    = dict["email"].ToString();
            var password = dict["password"].ToString();

            try
            {
                using (var dbCon = PostgresConn.GetConn())
                {
                    var user = UserRepository.IsAuth(email, password, dbCon);
                    if (user == null)
                    {
                        Response.StatusCode = 400;
                        await Response.WriteAsync("Incorrect login or password");
                    }
                    else
                    {
                        Console.WriteLine((user.Role));
                        if (user.Role != "owner" && user.Role != "admin")
                        {
                            Response.StatusCode = 403;
                            await Response.WriteAsync("You can't see this page");

                            return;
                        }
                        var now    = DateTime.UtcNow;
                        var claims = new List <Claim>();
                        claims.Add(new Claim(ClaimsIdentity.DefaultNameClaimType, user.Email));
                        claims.Add(new Claim(ClaimsIdentity.DefaultRoleClaimType, user.Role));
                        var jwt = new JwtSecurityToken(
                            issuer: AuthOptions.ISSUER,
                            audience: AuthOptions.AUDIENCE,
                            notBefore: now,
                            claims: claims,
                            expires: now.Add(TimeSpan.FromMinutes(AuthOptions.LIFETIME)),
                            signingCredentials: new SigningCredentials(AuthOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
                        var encodedJwt         = new JwtSecurityTokenHandler().WriteToken(jwt);
                        var serializerSettings = new JsonSerializerSettings();
                        serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                        var json = JsonConvert.SerializeObject(user, serializerSettings);
                        Response.Cookies.Append("token", encodedJwt);
                        await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(json));
                    }
                }
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync(e.Message);
            }
        }
        public static void Delete(int Id)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("delete from clientes ");

            sql.Append(" where id = " + Id);

            PostgresConn.ExecutarComando(sql.ToString());

            //insere o log
            LogClienteRepositorio.Create("delete do id " + Id);
        }
        public static void Update(Cliente cliente)
        {
            StringBuilder sql = new StringBuilder();

            sql.Append("update clientes set nome = '" + cliente.Nome + "',");
            sql.Append("idade = " + cliente.Idade);
            sql.Append(" where id = " + cliente.Id);

            PostgresConn.ExecutarComando(sql.ToString());

            //insere o log
            LogClienteRepositorio.Create("Atualizou o cliente " + cliente.Nome);
        }
Esempio n. 15
0
        public async void ConfirmApplication(Guid id)
        {
            try
            {
                Restaurant restaurant = null;
                using (var dbCon = PostgresConn.GetConn())
                {
                    restaurant = new RestaurantRepository().GetById(dbCon, id) as Restaurant;
                    if (restaurant.Published)
                    {
                        throw new Exception("Restaurant has already published");
                    }
                    restaurant.Published = true;
                }

                using (var dbCon = PostgresConn.GetConn())
                {
                    new RestaurantRepository().Update(dbCon, restaurant);
                }

                var queryParams = Request.QueryString.Value.Trim('?').Split('&');
                foreach (var param in queryParams)
                {
                    var parts = param.Split('=');
                    var table = new Table(id, true, parts[1], parts[0]);
                    using (var dbCon = PostgresConn.GetConn())
                    {
                        new TableRepository().Insert(dbCon, table);
                    }
                }
                var files = Request.Form.Files;
                foreach (var formFile in files)
                {
                    if (formFile.Length > 0)
                    {
                        var filePath =
                            Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\")) + $"Images\\{id}.svg";
                        using (var stream = System.IO.File.Create(filePath))
                        {
                            await formFile.CopyToAsync(stream);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));
            }
        }
Esempio n. 16
0
        public async void AddDish()
        {
            Request.Form.TryGetValue("name", out var nameField);
            Request.Form.TryGetValue("ingredients", out var ingredientsField);
            Request.Form.TryGetValue("price", out var priceField);
            Request.Form.TryGetValue("weightInGrams", out var weightInGramsField);
            Request.Form.TryGetValue("restaurantId", out var restaurantIdField);

            var name = nameField.ToString();
            var ingredients = ingredientsField.ToString();
            var price = decimal.Parse(priceField.ToString());
            var weightInGrams = decimal.Parse(weightInGramsField.ToString());
            var restaurantId = restaurantIdField.ToString();

            var image = Request.Form.Files.GetFile("image");

            //byte[] fileBytes; преобразование картинки в массив байтов
            //using (var memoryStream = new MemoryStream())
            //{
            //    await image.CopyToAsync(memoryStream);
            //    fileBytes = memoryStream.ToArray();
                
            //}

            try
            {
                var dish = new Dish(name, ingredients, price, weightInGrams, Guid.Parse(restaurantId.ToString()));
                using (var dbCon = PostgresConn.GetConn())
                {
                    new DishRepository().Insert(dbCon, dish);
                }

                var filePath = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\..\\")) + $"Images\\DISH{restaurantId + name}.jpg";
                using (var stream = System.IO.File.Create(filePath)) // СОХРАНЕНИЕ КАРТИНКИ В ФАЙЛАХ
                {
                    await image.CopyToAsync(stream);
                }

                //Response.StatusCode = 201;
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.WriteAsync(e.Message);
            }
        }
Esempio n. 17
0
        public void Insert(NpgsqlConnection dbCon, IDbEntity entity)
        {
            var user = entity as User;

            using (var con = PostgresConn.GetConn())
            {
                if (UserWithLoginExists(con, user.Email))
                {
                    throw new Exception("User exists");
                }
            }
            var command = dbCon.CreateCommand();

            command.CommandType = CommandType.Text;
            command.CommandText =
                $"INSERT INTO \"public\".\"users\"(username, role, phone, password, email) VALUES ('{user.Username}', '{user.Role}', '{user.Phone}', '{user.Password}', '{user.Email}')";
            command.ExecuteNonQuery();
        }
Esempio n. 18
0
        public async void AuthPhys(int userId)
        {
            try
            {
                using (var dbCon = PostgresConn.GetConn())
                {
                    var restaurants = new RestaurantRepository().GetByOwnerId(dbCon, userId);
                    var json        = JsonConvert.SerializeObject(restaurants);
                    await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(json));

                    Response.StatusCode = 200;
                }
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));
            }
        }
        public async void Delete(Guid id)
        {
            try
            {
                using (var dbCon = PostgresConn.GetConn())
                {
                    new RestaurantRepository().Delete(dbCon, id);
                }
            }
            catch (Exception e)
            {
                if (!Response.HasStarted)
                {
                    Response.StatusCode = 400;
                }
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));

                throw;
            }
        }
        public async void AddRestaurant(object data)
        {
            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            var dict = JObject.Parse(data.ToString());

            var businessId  = int.Parse(dict["businessId"].ToString());
            var name        = dict["name"].ToString();
            var description = dict["description"].ToString();
            var city        = dict["city"].ToString();
            var address     = dict["address"].ToString();
            var phoneNumber = dict["phone"].ToString();
            var workingTime = dict["workingTime"].ToString();
            var ownerId     = int.Parse(dict["userId"].ToString());
            var email       = dict["email"].ToString();

            try
            {
                var restaurant = new Restaurant(businessId, name, city, address, description, ownerId, phoneNumber, workingTime, false, email);
                using (var dbCon = PostgresConn.GetConn())
                {
                    new RestaurantRepository().Insert(dbCon, restaurant);
                }

                if (!Response.HasStarted)
                {
                    Response.StatusCode = 201;
                }
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(restaurant.Id.ToString()));
            }
            catch (Exception e)
            {
                if (!Response.HasStarted)
                {
                    Response.StatusCode = 400;
                }
                await Response.WriteAsync(e.Message);
            }
        }
Esempio n. 21
0
        public async void GetApplication(Guid id)
        {
            try
            {
                using (var dbCon = PostgresConn.GetConn())
                {
                    var restaurant         = new RestaurantRepository().GetById(dbCon, id);
                    var serializerSettings = new JsonSerializerSettings();
                    serializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    var json = JsonConvert.SerializeObject(restaurant, serializerSettings);
                    Response.StatusCode = 200;

                    if (!(restaurant == null || json.Contains("[null]")))
                    {
                        await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(json));
                    }
                }
            }
            catch (Exception e)
            {
                Response.StatusCode = 400;
                await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(e.Message));
            }
        }