/// <summary>
        /// Delete the specified map
        /// </summary>
        /// <param name="mapHashId"></param>
        public void DeleteMap(string mapHashId)
        {
            if (string.IsNullOrWhiteSpace(mapHashId))
            {
                throw HttpResponseExceptionHelper.Create("Invalid map hash id provided", HttpStatusCode.BadRequest);
            }

            using (var db = new SystemDBContext())
            {
                var map = db.Maps.FirstOrDefault(x => x.HashId == mapHashId && x.CreatorhashId == UserToken.UserId);
                if (map == null)
                {
                    throw HttpResponseExceptionHelper.Create("No zone correspond to given hash id",
                                                             HttpStatusCode.BadRequest);
                }

                db.Maps.Remove(map);
                db.SaveChanges();

                var leaderboard = db.Leaderboards.FirstOrDefault(x => x.ZoneHashId == mapHashId);
                if (leaderboard != null)
                {
                    db.Leaderboards.Remove(leaderboard);
                    db.SaveChanges();
                }
            }
        }
Exemplo n.º 2
0
        public ActionResult ApproveOrders()
        {
            //OrdersPendingIndexView viewModel = new OrdersPendingIndexView();

            string username = User.Identity.Name;                                                            // get current logged in user

            Supervisor supervisor = db.Supervisors.SingleOrDefault(s => s.UserProfile.UserName == username); // gets supervisor from username

            // query retrieves orders which have not been checked by project supervisor
            var query = from o in db.Orders.Include("Student").Include("Student.Project").Include("Components")
                        where (o.Student.Project.Supervisor.SupervisorID == supervisor.SupervisorID && o.IsChecked == false) // display orders for students for supervisor
                        select o;

            // checks each order if they are above budget and if they are then marks the boolean as true and saves to db
            foreach (Order o in query)
            {
                if (o.OrderTotal > o.Student.Project.Budget)
                {
                    o.IsOverBudget    = true;
                    db.Entry(o).State = EntityState.Modified;
                }
            }

            db.SaveChanges();

            // view model.Ienumberalbe = query

            return(View(query));
        }
        public void DeleteUser(UserToken userToken)
        {
            using (var db = new SystemDBContext())
            {
                var user = db.Users.FirstOrDefault(x => x.HashId == userToken.UserId);
                if (user == null)
                {
                    throw HttpResponseExceptionHelper.Create("Identifiant d'usager invalide", HttpStatusCode.BadRequest);
                }

                db.Users.Remove(user);
                db.SaveChanges();
            }

            // delete all users friends
            var friendService = new FriendService(userToken);

            friendService.DeleteAllFriends();

            // delete profile
            var profileService = new ProfileService(userToken);

            profileService.DeleteMyProfile();

            // Delete daylies
            var dailyService = new DailyService(userToken);

            dailyService.DeleteAllDaily();
        }
Exemplo n.º 4
0
        public void ClearAll()
        {
            ClearDatabase();

            using (var context = new SystemDBContext())
            {
                var felixHash = GetFelixHashId();

                // Delete all Users
                foreach (var id in context.Users.Where(x => x.HashId != felixHash).Select(e => e.Id))
                {
                    var entity = new UserModel()
                    {
                        Id = id
                    };
                    context.Users.Attach(entity);
                    context.Users.Remove(entity);
                }

                // Delete all Profiles
                foreach (var id in context.Profiles.Where(x => x.UserHashId != felixHash).Select(e => e.Id))
                {
                    var entity = new ProfileModel()
                    {
                        Id = id
                    };
                    context.Profiles.Attach(entity);
                    context.Profiles.Remove(entity);
                }

                context.SaveChanges();
            }
        }
        public void AddLeaderEntry(string zoneHashId, LeaderModel leader)
        {
            if (string.IsNullOrWhiteSpace(zoneHashId))
            {
                throw HttpResponseExceptionHelper.Create("Empty map hash id specified", HttpStatusCode.BadRequest);
            }

            if (!LeaderModelHelper.IsValid(leader))
            {
                throw HttpResponseExceptionHelper.Create("Invalid leader entry specified", HttpStatusCode.BadRequest);
            }

            using (var db = new SystemDBContext())
            {
                var leaderboard = db.Leaderboards.FirstOrDefault(x => x.ZoneHashId == zoneHashId);

                if (leaderboard == null)
                {
                    throw HttpResponseExceptionHelper.Create("Invalid map hash id provided. No related map.",
                                                             HttpStatusCode.BadRequest);
                }

                leaderboard.Leaders = GetLeaderString(InsertLeader(leaderboard, leader));
                db.SaveChanges();
            }
        }
Exemplo n.º 6
0
        public HttpResponseMessage PutLocation([FromBody] JToken token) //klasa da mozes da iscitavas prosledjene primitivne tipove
        {
            HttpResponseMessage msg = new HttpResponseMessage();

            var id      = token.Value <int>("id");
            var address = token.Value <string>("address");

            try
            {
                using (SystemDBContext db = new SystemDBContext())
                {
                    Lokacija lk = db.Lokacije.FirstOrDefault(x => x.LocationId == id);

                    lk.Address.FullAddress = address;

                    db.SaveChanges();

                    msg = Request.CreateResponse(HttpStatusCode.OK, lk);
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error occured while updating");
            }

            return(msg);
        }
        public void RemoveFriend(string HashId, string Username)
        {
            if (HashId.IsNullOrWhiteSpace() || Username.IsNullOrWhiteSpace())
            {
                throw HttpResponseExceptionHelper.Create("Null friend name or id specified", HttpStatusCode.BadRequest);
            }

            if (UserToken == null)
            {
                throw HttpResponseExceptionHelper.Create("User token not specified", HttpStatusCode.BadRequest);
            }

            using (var db = new SystemDBContext())
            {
                var toremove = db.Friends.FirstOrDefault(x => x.Player1HashId == UserToken.UserId &&
                                                         x.Player1Username == UserToken.Username &&
                                                         x.Player2HashId == HashId &&
                                                         x.Player2Username == Username);
                if (toremove == null)
                {
                    toremove = db.Friends.FirstOrDefault(x => x.Player1HashId == HashId &&
                                                         x.Player1Username == Username &&
                                                         x.Player2HashId == UserToken.UserId &&
                                                         x.Player2Username == UserToken.Username);
                }
                if (toremove != null)
                {
                    db.Friends.Remove(toremove);
                    db.SaveChanges();
                }
            }
        }
Exemplo n.º 8
0
        public HttpResponseMessage PostMusterija([FromBody] Komentar kom)
        {
            HttpResponseMessage msg  = new HttpResponseMessage();
            KomentarRepository  repo = new KomentarRepository();

            try
            {
                using (var db = new SystemDBContext())
                {
                    kom.PostingTime = DateTime.Now;
                    kom.Id          = repo.GetKomentari().Count + 1;

                    db.Komentari.Add(kom);
                    db.SaveChanges();

                    msg = Request.CreateResponse(HttpStatusCode.Created, kom);
                    msg.Headers.Location = new Uri(Request.RequestUri + kom.Id.ToString());

                    return(msg);
                }
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
            }
        }
Exemplo n.º 9
0
        public HttpResponseMessage PutMusterijaKomentarisala(Musterija m) //kada komentarise, stavim da ej true
        {
            HttpResponseMessage msg = new HttpResponseMessage();

            try
            {
                using (SystemDBContext db = new SystemDBContext())
                {
                    Musterija must = db.Musterije.FirstOrDefault(x => x.Username == m.Username);

                    if (must != null)
                    {
                        must.Commented = true;
                        db.SaveChanges();

                        msg = Request.CreateResponse(HttpStatusCode.OK, must);
                    }
                    else
                    {
                        msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Customer is not registered.");
                    }
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Error - {e.Message}");
            }

            return(msg);
        }
        /// <summary>
        /// Update map information
        /// </summary>
        /// <param name="mapModel"></param>
        /// <returns></returns>
        public void UpdateMap(MapModel mapModel)
        {
            if (string.IsNullOrWhiteSpace(mapModel.HashId))
            {
                throw HttpResponseExceptionHelper.Create("No map hash id specified", HttpStatusCode.BadRequest);
            }

            using (var db = new SystemDBContext())
            {
                var map = db.Maps.FirstOrDefault(x => x.HashId == mapModel.HashId);

                if (map == null)
                {
                    throw HttpResponseExceptionHelper.Create("No map correspond to the given hashId",
                                                             HttpStatusCode.BadRequest);
                }

                // Update info
                if (!string.IsNullOrWhiteSpace(mapModel.Content))
                {
                    map.Content = mapModel.Content;
                }
                map.Level = mapModel.Level;

                map.UpdateTime = TimeHelper.CurrentCanadaTime();

                // Mark entity as modified
                db.Entry(map).State = System.Data.Entity.EntityState.Modified;
                // call SaveChanges
                db.SaveChanges();
            }
        }
        private DailyModel GetTodayDaily()
        {
            using (var db = new SystemDBContext())
            {
                var today    = DateTime.Today;
                var tomorrow = today.AddDays(1).AddHours(-1);

                var daily =
                    db.Daylies.FirstOrDefault(
                        x => x.UserHashId == UserToken.UserId && x.BeginTime >= today && x.EndTime <= tomorrow);

                if (daily == null)
                {
                    daily = new DailyModel()
                    {
                        BeginTime  = today,
                        EndTime    = tomorrow,
                        IsDone     = false,
                        UserHashId = UserToken.UserId,
                        DailyType  = DailyModelHelper.GetDailyType(today)
                    };

                    db.Daylies.Add(daily);
                    db.SaveChanges();
                }
                return(daily);
            }
        }
Exemplo n.º 12
0
        public HttpResponseMessage PostLocation([FromBody] Adresa address)
        {
            HttpResponseMessage msg  = new HttpResponseMessage();
            LokacijaRepository  repo = new LokacijaRepository();

            try
            {
                using (SystemDBContext db = new SystemDBContext())
                {
                    Lokacija lk = new Lokacija()
                    {
                        Address = new Adresa()
                        {
                            FullAddress = address.FullAddress
                        },
                        CoordinateX = 0,
                        CoordinateY = 0,
                        LocationId  = repo.GetLokacije().Count + 1
                    };

                    db.Lokacije.Add(lk);
                    db.SaveChanges();

                    msg = Request.CreateResponse(HttpStatusCode.Created, lk.LocationId); //vracam ID sacuvane lokacije
                    msg.Headers.Location = new Uri(Request.RequestUri + lk.LocationId.ToString());
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error occured while updating");
            }

            return(msg);
        }
Exemplo n.º 13
0
        public HttpResponseMessage PutIdForComm(JToken token)
        {
            HttpResponseMessage msg = new HttpResponseMessage();

            var komId = token.Value <int>("komId");
            var vozId = token.Value <int>("id");

            try
            {
                using (SystemDBContext db = new SystemDBContext())
                {
                    //Komentar k = db.Komentari.FirstOrDefault(x => x.Id == komId);
                    Voznja v = db.Voznje.FirstOrDefault(x => x.Id == vozId);

                    if (v != null)
                    {
                        v.CommentID = komId;

                        db.SaveChanges();

                        msg = Request.CreateResponse(HttpStatusCode.NoContent);
                    }
                    else
                    {
                        msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "There was internal error, drive is deleted.");
                    }
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error occured while finishing");
            }

            return(msg);
        }
Exemplo n.º 14
0
        public HttpResponseMessage PutChangeType(JToken token)
        {
            HttpResponseMessage msg = new HttpResponseMessage();

            var type     = token.Value <string>("type");
            var username = token.Value <string>("username");

            try
            {
                using (SystemDBContext db = new SystemDBContext())
                {
                    Vozac vozac = db.Vozaci.FirstOrDefault(x => x.Username == username);

                    if (vozac != null)
                    {
                        vozac.Car.Type = GetType(type);

                        db.SaveChanges();

                        msg = Request.CreateResponse(HttpStatusCode.NoContent);
                    }
                    else
                    {
                        msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "There was internal error, drive is deleted.");
                    }
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error occured while finishing");
            }

            return(msg);
        }
Exemplo n.º 15
0
        public HttpResponseMessage PutChangeFinalLocation(Vozac vozac)
        {
            HttpResponseMessage msg = new HttpResponseMessage();

            try
            {
                using (SystemDBContext db = new SystemDBContext())
                {
                    Vozac v = db.Vozaci.FirstOrDefault(x => x.Username == vozac.Username);

                    if (vozac != null)
                    {
                        v.LocationID = vozac.LocationID;

                        db.SaveChanges();

                        msg = Request.CreateResponse(HttpStatusCode.NoContent);
                    }
                    else
                    {
                        msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "There was internal error, drive is deleted.");
                    }
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error occured while finishing");
            }

            return(msg);
        }
Exemplo n.º 16
0
        private HttpResponseMessage UpdateUser(Vozac sentObj, Roles role, HttpResponseMessage msg)
        {
            using (SystemDBContext db = new SystemDBContext())
            {
                if (role == Roles.Admin)
                {
                    Admin a = db.Admini.FirstOrDefault(x => x.Username == sentObj.Username);

                    a.PhoneNumber = sentObj.PhoneNumber;
                    a.Password    = sentObj.Password;
                    a.Name        = sentObj.Name;
                    a.Lastname    = sentObj.Lastname;
                    a.Jmbg        = sentObj.Jmbg;
                    a.Gender      = sentObj.Gender;
                    a.Email       = sentObj.Email;

                    msg = Request.CreateResponse(HttpStatusCode.OK, a);
                    msg.Headers.Location = new Uri(Request.RequestUri + a.Username);
                }
                else if (role == Roles.Customer)
                {
                    Musterija m = db.Musterije.FirstOrDefault(x => x.Username == sentObj.Username);

                    m.PhoneNumber = sentObj.PhoneNumber;
                    m.Password    = sentObj.Password;
                    m.Name        = sentObj.Name;
                    m.Lastname    = sentObj.Lastname;
                    m.Jmbg        = sentObj.Jmbg;
                    m.Gender      = sentObj.Gender;
                    m.Email       = sentObj.Email;

                    msg = Request.CreateResponse(HttpStatusCode.OK, m);
                    msg.Headers.Location = new Uri(Request.RequestUri + m.Username);
                }
                else
                {
                    Vozac v = db.Vozaci.FirstOrDefault(x => x.Username == sentObj.Username);

                    v.PhoneNumber = sentObj.PhoneNumber;
                    v.Password    = sentObj.Password;
                    v.Name        = sentObj.Name;
                    v.Lastname    = sentObj.Lastname;
                    v.Jmbg        = sentObj.Jmbg;
                    v.Gender      = sentObj.Gender;
                    v.Email       = sentObj.Email;

                    v.Location = sentObj.Location;

                    msg = Request.CreateResponse(HttpStatusCode.OK, v);
                    msg.Headers.Location = new Uri(Request.RequestUri + v.Username);
                }

                db.SaveChanges();
            }

            return(msg);
        }
        public ProfileModel UpdateMyProfile(ProfileModel newProfile)
        {
            if (UserToken == null)
            {
                throw HttpResponseExceptionHelper.Create("User token not specified", HttpStatusCode.BadRequest);
            }
            using (var db = new SystemDBContext())
            {
                var profile = db.Profiles.FirstOrDefault(x => x.UserHashId == UserToken.UserId);
                if (profile == null)
                {
                    throw HttpResponseExceptionHelper.Create("No profile exist with specified user Id",
                                                             HttpStatusCode.BadRequest);
                }


                // Modify profile
                if (newProfile == null)
                {
                    throw HttpResponseExceptionHelper.Create("Invalid providen profile",
                                                             HttpStatusCode.BadRequest);
                }

                profile.IsPrivate   = newProfile.IsPrivate;
                profile.Description = newProfile.Description;
                profile.Picture     = newProfile.Picture;

                if ((int)newProfile.PrincessTitle > (int)profile.PrincessTitle)
                {
                    profile.PrincessTitle = newProfile.PrincessTitle;
                }

                if (newProfile.Experience > profile.Experience)
                {
                    profile.Experience = newProfile.Experience;
                }

                if (newProfile.Level > profile.Level)
                {
                    profile.Level = newProfile.Level;
                }

                if (!string.IsNullOrWhiteSpace(newProfile.StatsString))
                {
                    profile.StatsString = newProfile.StatsString;
                }

                if (!string.IsNullOrWhiteSpace(newProfile.AchievementsString) && !newProfile.AchievementsString.Contains("null"))
                {
                    profile.AchievementsString = newProfile.AchievementsString;
                }

                // call SaveChanges
                db.SaveChanges();
                return(profile);
            }
        }
        public ActionResult EnableAccount(int id)
        {
            UserProfile user = db.UserProfiles.Find(id); // retreives user

            user.IsChecked  = true;
            user.IsVerifyed = true;

            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified; //saves changes of new state to db
                db.SaveChanges();
            }

            return(RedirectToAction("ReactivateAccount")); // refreshes the reactivate view
        }
        public void CompleteDaily()
        {
            var daily = GetTodayDaily();

            using (var db = new SystemDBContext())
            {
                daily        = db.Daylies.Find(daily.Id);
                daily.IsDone = true;
                db.SaveChanges();
            }
        }
Exemplo n.º 20
0
        public ActionResult ViewNotNotifiedOrderedOrders(int id)
        {
            Order order = db.Orders.Find(id);

            if (order.StudentIsNotified != true)              // if the student is not notified then send an email to notify
            {
                order.StudentIsNotified = true;               // set status to true
                SendOrderReadyToCollectEmail(order.OrderID);  // send the email
                db.Entry(order).State = EntityState.Modified; // save the order object changes
                db.SaveChanges();

                return(RedirectToAction("ViewNotNotifiedOrderedOrders")); // refresh view
            }
            else
            {
                //send email method here
                SendOrderReadyToCollectEmail(order.OrderID);        // send email
                return(RedirectToAction("ViewNotCollectedOrders")); // send to orders not collected view
            }
        }
Exemplo n.º 21
0
        public void PrepareVoteResponse(string content)
        {
            NodeVoteResponse response;

            try
            {
                response = JsonConvert.DeserializeObject <NodeVoteResponse>(content);
                SendMessage(response);
            }
            catch (JsonException e)
            {
                _logger.Error(e);
                throw e;
            }

            using (var db = new SystemDBContext())
            {
                VoteStatus voteStatus = new VoteStatus
                {
                    Idvn      = response.IDVN,
                    VoteState = "Voted"
                };

                Block block = new Block
                {
                    //  BlockId = response.block.BlockId,
                    CreatedOn    = (DateTime)response.block.CreatedOn,
                    PartyId      = (int)response.block.PartyChoosed,
                    Gender       = response.block.Gender,
                    Hash         = response.block.Hash,
                    Idbd         = response.block.Idbd,
                    PreviousHash = response.block.PreviousHash,
                    RegionId     = (int)response.block.RegionChoosed,
                    YearBirth    = 1999// (int)response.block.YearBirth
                };
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        db.Add(voteStatus);
                        db.Add(block);
                        db.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();
                        _logger.Error(e);
                        Console.WriteLine(e);
                    }
                }
            }
        }
Exemplo n.º 22
0
        public void ClearDatabase()
        {
            using (var context = new SystemDBContext())
            {
                var felixHash = GetFelixHashId();
                // Delete all Maps
                foreach (var id in context.Maps.Where(x => x.CreatorhashId != felixHash).Select(e => e.Id))
                {
                    var entity = new MapModel()
                    {
                        Id = id
                    };
                    context.Maps.Attach(entity);
                    context.Maps.Remove(entity);
                }


                // Delete all Dailies
                foreach (var id in context.Daylies.Where(x => x.UserHashId != felixHash).Select(e => e.Id))
                {
                    var entity = new DailyModel()
                    {
                        Id = id
                    };
                    context.Daylies.Attach(entity);
                    context.Daylies.Remove(entity);
                }

                // Delete all Leaderboards
                foreach (var id in context.Leaderboards.Select(e => e.Id))
                {
                    var entity = new LeaderboardModel()
                    {
                        Id = id
                    };
                    context.Leaderboards.Attach(entity);
                    context.Leaderboards.Remove(entity);
                }

                // Delete all Friends
                foreach (var id in context.Friends.Select(e => e.Id))
                {
                    var entity = new FriendModel()
                    {
                        Id = id
                    };
                    context.Friends.Attach(entity);
                    context.Friends.Remove(entity);
                }

                context.SaveChanges();
            }
        }
        /// <summary>
        /// Create a new map in database and return it's hashid
        /// </summary>
        /// <param name="mapModel"></param>
        /// <returns></returns>
        public string CreateNewMap(MapModel mapModel)
        {
            if (!IsValid(mapModel))
            {
                throw HttpResponseExceptionHelper.Create("Invalid map model information", HttpStatusCode.BadRequest);
            }

            using (var db = new SystemDBContext())
            {
                // set hash
                mapModel.CreatorhashId = UserToken.UserId;
                mapModel.HashId        = GetMapHash(mapModel);

                if (db.Maps.FirstOrDefault(x => x.HashId == mapModel.HashId) != null)
                {
                    throw HttpResponseExceptionHelper.Create(
                              "Map already exist with name : " + mapModel.Name + "  From user : " + UserToken.Username,
                              HttpStatusCode.BadRequest);
                }

                mapModel.CreationDate = TimeHelper.CurrentCanadaTimeString();
                mapModel.UpdateTime   = TimeHelper.CurrentCanadaTime();

                // save database
                db.Maps.Add(mapModel);
                db.SaveChanges();

                // create leaderboard for map
                var leaderboard = new LeaderboardModel()
                {
                    ZoneHashId = mapModel.HashId,
                    Leaders    = LeaderboardModelHelper.GetLeaderString(new List <LeaderModel>())
                };

                db.Leaderboards.Add(leaderboard);
                db.SaveChanges();

                return(mapModel.HashId);
            }
        }
        public void DeleteAllDaily()
        {
            using (var db = new SystemDBContext())
            {
                var dailies = db.Daylies.Where(x => x.UserHashId == UserToken.UserId).ToList();

                foreach (var daily in dailies)
                {
                    db.Daylies.Remove(daily);
                }
                db.SaveChanges();
            }
        }
Exemplo n.º 25
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            //ukoliko menjamo tabelu nakon sto je napravljena, mora da se dropuje i kreira nova
            Database.SetInitializer(new SystemSeeder());

            //programsko ucitavanje admina
            string[] info = new string[10];
            string   path = AppDomain.CurrentDomain.BaseDirectory + "Admini.txt";

            using (StreamReader sr = File.OpenText(path))
            {
                string s = String.Empty;
                while ((s = sr.ReadLine()) != null)
                {
                    info = s.Split(';');
                    try //samo jendom ce dodati admine, sledeci put nece, zbog jedinstvenosti kljuca
                    {
                        using (SystemDBContext db = new SystemDBContext())
                        {
                            Admin a = new Admin()
                            {
                                Username    = info[0],
                                Password    = info[1],
                                Name        = info[2],
                                Lastname    = info[3],
                                Gender      = (Genders)Enum.Parse(typeof(Genders), info[4]),
                                Jmbg        = info[5],
                                PhoneNumber = info[6],
                                Email       = info[7],
                                Role        = (Roles)Enum.Parse(typeof(Roles), info[8]),
                                DriveStatus = (DrivingStatus)Enum.Parse(typeof(DrivingStatus), info[9]),
                            };

                            db.Admini.Add(a);
                            db.SaveChanges();
                        }
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine($"Error - {e.Message}");
                    }
                }
            }
        }
Exemplo n.º 26
0
        public HttpResponseMessage PostMusterija([FromBody] JToken token)
        {
            HttpResponseMessage msg;
            VoznjaRepository    repo = new VoznjaRepository();

            var start     = token.Value <int>("start");
            var driver    = token.Value <string>("user");
            var type      = token.Value <string>("type");
            var admin     = token.Value <string>("admin");
            var adminSts  = token.Value <int>("adminStatus");
            var driverSts = token.Value <int>("driverStatus");

            TypeOfCar typeC = GetTypeInEnum(type);

            try
            {
                using (var db = new SystemDBContext())
                {
                    Voznja v = new Voznja()
                    {
                        StartPointID      = start,
                        DriverID          = driver,
                        TypeOfCar         = typeC,
                        Id                = repo.GetVoznje().Count + 1,
                        Status            = GetStatus(adminSts),
                        TimeOfReservation = DateTime.Now,
                        AdminID           = admin
                    };

                    Vozac voz = db.Vozaci.FirstOrDefault(x => x.Username == driver);
                    voz.DriveStatus = GetStatus(driverSts);
                    Admin a = db.Admini.FirstOrDefault(x => x.Username == admin);
                    a.DriveStatus = GetStatus(adminSts);

                    db.Voznje.Add(v);
                    db.SaveChanges();

                    msg = Request.CreateResponse(HttpStatusCode.Created, v);
                    msg.Headers.Location = new Uri(Request.RequestUri + v.Id.ToString());

                    return(msg);
                }
            }
            catch (Exception e)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e));
            }
        }
        private UserModel CreateUser(UserModel user)
        {
            //Check if user is valid
            if (string.IsNullOrWhiteSpace(user.Username) && string.IsNullOrWhiteSpace(user.FacebookId))
            {
                throw HttpResponseExceptionHelper.Create("Informations invalides", HttpStatusCode.BadRequest);
            }

            using (var db = new SystemDBContext())
            {
                // save database
                var newUser = db.Users.Add(user);
                db.SaveChanges();
                return(newUser);
            }
        }
Exemplo n.º 28
0
        private void DeleteEntityMusterija(Musterija mus, Musterija m)
        {
            using (SystemDBContext db = new SystemDBContext())
            {
                mus      = db.Musterije.FirstOrDefault(x => x.Username == m.Username);
                mus.Role = m.Role;
                System.Random ran = new System.Random();

                Vozac v = new Vozac()
                {
                    Username    = mus.Username,
                    Email       = mus.Email,
                    Gender      = mus.Gender,
                    Jmbg        = mus.Jmbg,
                    Lastname    = mus.Lastname,
                    Name        = mus.Name,
                    Password    = mus.Password,
                    PhoneNumber = mus.PhoneNumber,
                    Role        = mus.Role,
                    Car         = new Automobil()
                    {
                        Driver       = mus.Username,
                        Registration = $"NS{ran.Next(1000, 9999)}{PasswordGenerator.Generate(length: 2, allowed: Sets.Upper)}",
                        UniqueID     = System.Web.Security.Membership.GeneratePassword(6, 2),
                        Type         = GetRandomCar(),
                        YearOfCar    = GetRandomTime(ran)
                    },
                    LocationID = db.Vozaci.Count() + 1,
                    Location   = null
                };

                Lokacija Location = new Lokacija()
                {
                    CoordinateX = 0.0,
                    CoordinateY = 0.0,
                    Address     = new Adresa("Partizanska", 19, "Novi Sad", 21000, 838531),
                    LocationId  = v.LocationID
                };

                db.Vozaci.Add(v);
                db.Musterije.Remove(mus);
                db.Lokacije.Add(Location);

                db.SaveChanges();
            }
        }
Exemplo n.º 29
0
        public HttpResponseMessage PutFinalDest(JToken token)
        {
            HttpResponseMessage msg = new HttpResponseMessage();

            var id         = token.Value <int>("Id");
            var payment    = token.Value <double>("Payment");
            var finalPoint = token.Value <int>("FinalPointID");

            try
            {
                using (SystemDBContext db = new SystemDBContext())
                {
                    Voznja    v     = db.Voznje.FirstOrDefault(x => x.Id == id);
                    Vozac     vozac = db.Vozaci.FirstOrDefault(x => x.Username == v.DriverID);
                    Musterija must  = db.Musterije.FirstOrDefault(x => x.Username == v.UserCallerID);

                    if (v != null)
                    {
                        v.Payment      = payment;
                        v.FinalPointID = finalPoint;
                        v.Status       = DrivingStatus.Successful;

                        vozac.DriveStatus = DrivingStatus.Successful;

                        if (must != null)
                        {
                            must.DriveStatus = DrivingStatus.Successful;
                        }

                        db.SaveChanges();

                        msg = Request.CreateResponse(HttpStatusCode.NoContent);
                    }
                    else
                    {
                        msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "There was internal error, drive is deleted.");
                    }
                }
            }
            catch (Exception e)
            {
                msg = Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Error occured while finishing");
            }

            return(msg);
        }
        public ActionResult Index()
        {
            string username = User.Identity.Name; // get current logged in user

            Student    student    = db.Students.SingleOrDefault(s => s.UserProfile.UserName == username);
            Supervisor supervisor = db.Supervisors.Include("UserProfile").FirstOrDefault(s => s.UserProfile.UserName == username);  // check logged in username vs name on table
            Technician technician = db.Technicians.Include("UserProfile").SingleOrDefault(s => s.UserProfile.UserName == username); // check logged in username vs name on table

            if (student != null)
            {
                return(RedirectToRoute("Student"));
            }

            else if (technician != null)
            {
                return(RedirectToRoute("Technician"));
            }

            else if (supervisor != null)
            {
                // get update project details with the right supervisor details
                foreach (Project project in db.Projects.Include("Supervisor").Include("Supervisor.UserProfile"))
                {
                    // modify fields
                    if (project.Supervisor.UserProfile.Email == supervisor.UserProfile.Email && project.Supervisor.FirstName == null)
                    {
                        Supervisor  oldSupervisor            = project.Supervisor;
                        UserProfile oldSupervisorUserProfile = project.Supervisor.UserProfile;
                        project.Supervisor                       = supervisor;           // update the project supervisor details
                        db.Entry(oldSupervisor).State            = EntityState.Deleted;  // delete old supervisor details
                        db.Entry(oldSupervisorUserProfile).State = EntityState.Deleted;  // delete old supervisor user profile//
                        db.Entry(project).State                  = EntityState.Modified; // update project details
                    }
                }
                db.SaveChanges();
                return(RedirectToRoute("Supervisor"));
            }

            else if (User.IsInRole("Admin"))
            {
                return(RedirectToRoute("Admin"));
            }

            return(View());
        }