// GET: /Play/Details/5
        public ActionResult Details(int? id) 
        {
            using (var context = new AF_Context())
            {
                var play = (from p in context.Plays select p).FirstOrDefault(p => p.PlayId == id);
                if (play == null)
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                var data = new PlayCastDTO(play);

                data.Helpers = (from pjob in context.RelationsPersonPlayJob select pjob)
                    .Where(pjob => pjob.PlayId == data.PlayId)
                    .Include(pjob => pjob.Person)
                    .Include(pjob => pjob.Job)
                    .OrderBy(pjob => pjob.JobId)
                    .ToList()
                    .Select(PersonFunctionDTO.FromJobEntity);

                data.Cast = (from prole in context.RelationsPersonPlayRole select prole)
                    .Where(prole => prole.PlayId == data.PlayId)
                    .Include(prole => prole.Person)
                    .OrderBy(prole => prole.RelationPersonPlayRoleId)
                    .ToList()
                    .Select(PersonFunctionDTO.FromRoleEntity);

                return View(data);
            }
        }
        /* Award AddAward(int playId, int festivalId, int categoryId, int userId);

         List<AwardMixedDTO> SearchAwards(AwardsSearchingCriteria criteria, int pageNr, int pageAmount)

         public ListResponse<ModuleDto> GetModules(SingleRequest request)
         {
             //Warning: unbound list read from db, do not do this at home!
             return ListResponse.Create(request,
                 InTransaction(tc => tc.Entities.ModuleInstances.Include(mi => mi.ModuleDef).ToList()
                                                         .Select(_moduleAssembler.ToSimpleDto).ToList()));
         }
         */

        //public string GetData(int value)
        //{
        //    return string.Format("You entered: {0}", value);
        //}

        //public CompositeType GetDataUsingDataContract(CompositeType composite)
        //{
        //    if (composite == null)
        //    {
        //        throw new ArgumentNullException("composite");
        //    }
        //    if (composite.BoolValue)
        //    {
        //        composite.StringValue += "Suffix";
        //    }
        //    return composite;
        //}

        #region Awards
        public SingleItemResponse<AwardDataDTO> AddAward(AwardDataDTO newAward)
        {
            var newAwardFull = new Award()
            {
                CategoryId = newAward.CategoryId,
                PlayId = newAward.PlayId,
                EditedBy = GetUserId(),
                EditDate = DateTime.Now
            };

            using (var context = new AF_Context())
            {
                try
                {
                    context.Awards.Add(newAwardFull);
                    context.SaveChanges();
                    int id = newAwardFull.AwardId;
                    return GetAward(id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
 public async Task<ActionResult> Index()
 {
     using (var context = new AF_Context())
     {
         var festivals = (from ft in context.Festivals select ft.FestivalId).ToArrayAsync();
         return View(await festivals);
     }
 }
 // AF_Context context = new AF_Context();
  
  #region Award
  public async Task AddAward(Award newAward)
  {
      using (var context = new AF_Context())
      {
          try
          {
              context.Awards.Add(newAward);
              int recordsAffected = await context.SaveChangesAsync();
          }
          catch (Exception ex)
          {
              throw ex;
          }
      }
  }
 public async Task<Award> GetAward(int id)
 {
     using (var context = new AF_Context())
     {
         try
         {
             //Category cat = await Task.Run<Category>(() => context.Categories.First(c => c.CategoryId == id));
             Award awa = context.Awards.First(a => a.CategoryId == id);
             awa.Editor = context.Users.First(u => u.UserId == awa.EditedBy);
             return (awa);
         }
         catch (Exception ex)
         {
             throw ex;
         }
         return null;
     }
 }
 public async Task UpdateAward(Award updateData)
 {
     using (var context = new AF_Context())
     {
         try
         {
             /*Award awa = await (from a in context.Awards
                                      where a.AwardId == updateData.AwardId
                                      select a).ToListAsync();*/
             Award awa = context.Awards.First(a => a.AwardId == updateData.AwardId);
             context.Entry(awa).CurrentValues.SetValues(updateData);
             await context.SaveChangesAsync();
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
 public async Task RemoveAward(int id)
 {
     using (var context = new AF_Context())
     {
         try
         {
             /*List<Award> awa = await (from a in context.Awards
                 where a.AwardId == id
                 select a).ToListAsync();*/
             Award awa = context.Awards.First(a => a.AwardId == id);
             context.Awards.Remove(awa);
             await context.SaveChangesAsync();
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
 public override void Validate(string userName, string password)
 {
     using (var context = new AF_Context())
     {
         const string pepper = "50.L1`(f761OJdG6fc835M(5(+Ju2!P6,4330_N*/%xz<j7(N15KC'8l997'0c0CEg";
         ICryptoService cryptoService = new PBKDF2();
         try
         {
             User u = context.Users.FirstOrDefault(c => c.Login == userName);
             if (u == null)
                 throw new SecurityTokenException("Wrong Username or Password");
             bool verified = cryptoService.Compare(cryptoService.Compute(cryptoService.Compute(password, u.Salt), pepper), u.Password);
             if (!verified)
                 throw new SecurityTokenException("Wrong Username or Password");
         }
         catch (Exception ex)
         {
             throw;
         }
     }
 }
        static void Main(string[] args)
        {

            string pass = "";
            int id=0;
            ICryptoService cryptoService = new PBKDF2();
            const string pepper = "50.L1`(f761OJdG6fc835M(5(+Ju2!P6,4330_N*/%xz<j7(N15KC'8l997'0c0CEg";

            Console.WriteLine("Select user by id:");
            if (int.TryParse(Console.ReadLine(),out id))
            {
                using (var context = new AF_Context())
                {
                    try
                    {
                        User user = context.Users.First(u => u.UserId == id);
                        if (user != null)
                        {
                            while (string.IsNullOrEmpty(pass))
                            {
                                Console.WriteLine("Input Password:");
                                pass = Console.ReadLine();
                            }
                            user.Salt = cryptoService.GenerateSalt();
                            user.Password = cryptoService.Compute(cryptoService.Compute(pass, user.Salt), pepper);

                        }
                        context.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }



        }
 // GET: /Festival/Details/5
 public ActionResult Details(int? id)
 {
     using (var context = new AF_Context())
     {
         if (id == null)
         {
             return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
         }
         var skip = 0;//pageAmount * (pageNr - 1);
         int pageAmount = 100;
         var query = (from p in context.Plays select p).Where(p => p.FestivalId == id);
         if (query == null)
         {
             return HttpNotFound();
         }
         List<PlayDataDTO> tmp = new List<PlayDataDTO>();
         foreach (Play pla in (query.OrderBy(p => p.FestivalId)
             .ThenBy(p => p.Day)
             .ThenBy(p => p.Order)
             .Skip(skip)
             .Take(pageAmount)))
         {
             var newPlayDto = new PlayDataDTO()
             {
                 PlayId = pla.PlayId,
                 Title = pla.Title,
                 Author = pla.Author,
                 FestivalId = pla.FestivalId,
                 Day = pla.Day,
                 Order = pla.Order,
                 PlayedBy = pla.PlayedBy,
                 Motto = pla.Motto
             };
             tmp.Add(newPlayDto);
         }
         return View(tmp);
     }
 }
 // GET: /Play/
 public ActionResult Index()
 {
     using (var context = new AF_Context())
     {
         //var plays = context.Plays;//.Include(p => p.Editor).Include(p => p.Festival);
         //return View(plays.ToList());
         var skip = 0;//pageAmount * (pageNr - 1);
         int pageAmount = 100;
         var query = (from p in context.Plays select p);
         if (query == null)
         {
             return HttpNotFound();
         }
         List<PlayDataDTO> tmp = new List<PlayDataDTO>();
         foreach (Play pla in (query.OrderBy(p => p.FestivalId)
             .ThenBy(p => p.Day)
             .ThenBy(p => p.Order)
             .Skip(skip)
             .Take(pageAmount)))
         {
             var newPlayDto = new PlayDataDTO()
             {
                 PlayId = pla.PlayId,
                 Title = pla.Title,
                 Author = pla.Author,
                 FestivalId = pla.FestivalId,
                 Day = pla.Day,
                 Order = pla.Order,
                 PlayedBy = pla.PlayedBy,
                 Motto = pla.Motto
             };
             tmp.Add(newPlayDto);
         }
         return View(tmp);
     }
 } 
 // GET: /Festival/
 public ActionResult Index()
 {
     //var festivals = db.Festivals.Include(f => f.Editor);
     //return View(festivals.ToList());
     using (var context = new AF_Context())
     {
         var skip = 0;//pageAmount * (pageNr - 1);
         int pageAmount = 100;
         List<FestivalDTO> tmp = new List<FestivalDTO>();
         foreach (Festival fe in (from f in context.Festivals//.Include(u => u.Editor)
                                  select f).OrderBy(f => f.Year).Skip(skip).Take(pageAmount))
         {
             var newFestivalDto = new FestivalDTO()
             {
                 FestivalId = fe.FestivalId,
                 Year = fe.Year,
                 BeginningDate = fe.BeginningDate,
                 EndDate = fe.EndDate
             };
             tmp.Add(newFestivalDto);
         }
         return View(tmp);
     }
 }
 public ListResponse<JobDTO> GetAllJobs()
 {
     using (var context = new AF_Context())
     {
         try
         {
             List<JobDTO> tmp = new List<JobDTO>();
             foreach (Job jo in from j in context.Jobs select j)
             {
                 var newJobDto = new JobDTO()
                 {
                     JobId = jo.JobId,
                     JobTitle = jo.JobTitle
                 };
                 tmp.Add(newJobDto);
             }
             return (new ListResponse<JobDTO>(tmp));
         }
         catch (Exception ex)
         {
             throw;
         }
         return null;
     }
 }
 private int GetUserId()
 {
     string login = ServiceSecurityContext.Current.PrimaryIdentity.Name;
     using (var context = new AF_Context())
     {
         try
         {
             User us = context.Users.First(u => u.Login == login);
             return (us.UserId);
         }
         catch (Exception ex)
         {
             throw;
         }
     }
 }
 public ActionResult Edit(int? id)
 {
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     using (var context = new AF_Context())
     {
         Festival fes = context.Festivals.Find(id);
         if (fes == null)
         {
             return HttpNotFound();
         }
         var newFestivalDto = new FestivalDTO()
         {
             FestivalId = fes.FestivalId,
             Year = fes.Year,
             BeginningDate = fes.BeginningDate,
             EndDate = fes.EndDate,
         };
         //ViewBag.EditedBy = new SelectList(db.Users, "UserId", "Login", play.EditedBy);
         //ViewBag.FestivalId = new SelectList(db.Festivals, "FestivalId", "FestivalId", play.FestivalId);
         return View(newFestivalDto);
     }
 }
        public SingleItemResponse<PlayDataDTO> GetPlay(int id)
        {
            using (var context = new AF_Context())
            {
                try
                {
                    Play pla = context.Plays.First(p => p.PlayId == id);

                    var newPlayDto = new PlayDataDTO()
                    {
                        PlayId = pla.PlayId,
                        Title = pla.Title,
                        Author = pla.Author,
                        FestivalId = pla.FestivalId,
                        Day = pla.Day,
                        Order = pla.Order,
                        PlayedBy = pla.PlayedBy,
                        Motto = pla.Motto
                    };
                    return (new SingleItemResponse<PlayDataDTO>(newPlayDto));
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
 public ListResponse<UserDTO> GetAllUsers()
 {
     using (var context = new AF_Context())
     {
         try
         {
             List<UserDTO> tmp = new List<UserDTO>();
             foreach (User a in (from u in context.Users select u))
             {
                 var newUserDto = new UserDTO()
                 {
                     UserId = a.UserId,
                     Login = a.Login,
                     FirstName = a.FirstName,
                     LastName = a.LastName,
                     Email = a.Email
                 };
                 tmp.Add(newUserDto);
             }
             return (new ListResponse<UserDTO>(tmp));
         }
         catch (Exception ex)
         {
             throw;
         }
     }
 }
        public SingleItemResponse<AwardDataDTO> UpdateAward(AwardDataDTO updateData)
        {
            var updateDataFull = new Award()
            {
                AwardId = updateData.AwardId,
                CategoryId = updateData.CategoryId,
                PlayId = updateData.PlayId,
                EditedBy = GetUserId(),
                EditDate = DateTime.Now
            };

            using (var context = new AF_Context())
            {
                try
                {
                    Award awa = context.Awards.First(a => a.AwardId == updateData.AwardId);
                    context.Entry(awa).CurrentValues.SetValues(updateDataFull);
                    context.SaveChanges();
                    int id = updateData.AwardId;
                    return GetAward(id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<JobDTO> UpdateJob(JobDTO updateData)
        {
            var updateDataFull = new Job()
            {
                JobId = updateData.JobId,
                JobTitle = updateData.JobTitle,
                EditedBy = GetUserId(),
                EditDate = DateTime.Now
            };

            using (var context = new AF_Context())
            {
                try
                {
                    Job jo = context.Jobs.First(j => j.JobId == updateData.JobId);
                    context.Entry(jo).CurrentValues.SetValues(updateDataFull);
                    context.SaveChanges();
                    int id = updateData.JobId;
                    return GetJob(id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<PositionDTO> UpdatePosition(PositionDTO updateData)
        {
            var updateDataFull = new Position()
            {
                PositionId = updateData.PositionId,
                PositionTitle = updateData.PositionTitle,
                Section = updateData.Section,
                Order = updateData.Order,
                EditedBy = GetUserId(),
                EditDate = DateTime.Now
            };

            using (var context = new AF_Context())
            {
                try
                {
                    Position pos = context.Positions.First(p => p.PositionId == updateData.PositionId);
                    context.Entry(pos).CurrentValues.SetValues(updateDataFull);
                    context.SaveChanges();
                    int id = updateData.PositionId;
                    return GetPosition(id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<PositionDTO> GetPosition(int id)
        {
            using (var context = new AF_Context())
            {
                try
                {
                    Position pos = context.Positions.First(p => p.PositionId == id);
                    //awa.Editor = context.Users.First(u => u.UserId == awa.EditedBy);

                    var newPositionDto = new PositionDTO()
                    {
                        PositionId = pos.PositionId,
                        PositionTitle = pos.PositionTitle,
                        Section = pos.Section,
                        Order = pos.Order
                    };
                    return (new SingleItemResponse<PositionDTO>(newPositionDto));
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<PlayDataDTO> AddPlay(PlayDataDTO newPlay)
        {
            var newPlayFull = new Play()
            {
                Title = newPlay.Title,
                Author = newPlay.Author,
                FestivalId = newPlay.FestivalId,
                Day = newPlay.Day,
                Order = newPlay.Order,
                PlayedBy = newPlay.PlayedBy,
                Motto = newPlay.Motto,
                EditedBy = GetUserId(),
                EditDate = DateTime.Now
            };

            using (var context = new AF_Context())
            {
                try
                {
                    context.Plays.Add(newPlayFull);
                    context.SaveChanges();
                    int id = newPlayFull.PlayId;
                    return GetPlay(id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<PlayTitleDTO> GetPlayTitle(int id)
        {
            using (var context = new AF_Context())
            {
                try
                {
                    Play pla = context.Plays.First(p => p.PlayId == id);

                    var newPlayDto = new PlayTitleDTO()
                    {
                        PlayId = pla.PlayId,
                        Title = pla.Title,
                    };
                    return (new SingleItemResponse<PlayTitleDTO>(newPlayDto));
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        } 
        public ListResponse<PlayTitleDTO> SearchPlaysTitles(PlaysSearchingCriteria criteria, int pageNr, int pageAmount)
        {
            using (var context = new AF_Context())
            {
                try
                {
                    var skip = pageAmount * (pageNr - 1);
                    var query = (from p in context.Plays select p);
                    if (criteria.FestivalIdFilter != null)
                        query = query.Where(p => p.FestivalId == criteria.FestivalIdFilter);
                    if (!String.IsNullOrEmpty(criteria.Author))
                        query = query.Where(p => p.Author.Contains(criteria.Author));
                    if (!String.IsNullOrEmpty(criteria.Title))
                        query = query.Where(p => p.Title.Contains(criteria.Title));
                    if (!String.IsNullOrEmpty(criteria.Motto))
                        query = query.Where(p => p.Motto.Contains(criteria.Motto));

                    List<PlayTitleDTO> tmp = new List<PlayTitleDTO>();
                    foreach (Play pla in (query.OrderBy(p => p.FestivalId)
                        .ThenBy(p => p.Day)
                        .ThenBy(p => p.Order)
                        .Skip(skip)
                        .Take(pageAmount)))
                    {
                        var newPlayDto = new PlayTitleDTO()
                        {
                            PlayId = pla.PlayId,
                            Title = pla.Title,
                        };
                        tmp.Add(newPlayDto);
                    }
                    return (new ListResponse<PlayTitleDTO>(tmp));
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
 public ActionResult Create([Bind(Include = "FestivalId,Year,BeginningDate,EndDate")] FestivalDTO updateData)
 {
     if (ModelState.IsValid)
     {
         var updateDataFull = new Festival()
         {
             //FestivalId = updateData.FestivalId,
             Year = updateData.Year,
             BeginningDate = updateData.BeginningDate,
             EndDate = updateData.EndDate,
             EditedBy = 1,//GetUserId(),
             EditDate = DateTime.Now
         };
         using (var context = new AF_Context())
         {
             context.Festivals.Add(updateDataFull);
             context.SaveChanges();
             return RedirectToAction("Index");
         }
     }
     //ViewBag.EditedBy = new SelectList(db.Users, "UserId", "Login", play.EditedBy);
     //ViewBag.FestivalId = new SelectList(db.Festivals, "FestivalId", "FestivalId", play.FestivalId);
     return View(updateData);
 }
 public ListResponse<PositionDTO> GetAllPositions()
 {
     using (var context = new AF_Context())
     {
         try
         {
             List<PositionDTO> tmp = new List<PositionDTO>();
             foreach (Position pos in context.Positions.OrderBy(s => s.Section).ThenBy(o => o.Order))
             {
                 var newPositionDto = new PositionDTO()
                 {
                     PositionId = pos.PositionId,
                     PositionTitle = pos.PositionTitle,
                     Section = pos.Section,
                     Order = pos.Order
                 };
                 tmp.Add(newPositionDto);
             }
             return (new ListResponse<PositionDTO>(tmp));
         }
         catch (Exception ex)
         {
             throw;
         }
     }
 }
        public SingleItemResponse<JobDTO> GetJob(int id)
        {
            using (var context = new AF_Context())
            {
                try
                {
                    Job jo = context.Jobs.First(j => j.JobId == id);

                    var newJobDto = new JobDTO()
                    {
                        JobId = jo.JobId,
                        JobTitle = jo.JobTitle
                    };
                    return (new SingleItemResponse<JobDTO>(newJobDto));
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<UserDTO> GetUser(int id)
        {
            using (var context = new AF_Context())
            {
                try
                {
                    User us = context.Users.First(u => u.UserId == id);

                    var newUserDto = new UserDTO()
                    {
                        UserId = us.UserId,
                        Login = us.Login,
                        FirstName = us.FirstName,
                        LastName = us.LastName,
                        Email = us.Email
                    };
                    return (new SingleItemResponse<UserDTO>(newUserDto));
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<PositionDTO> AddPosition(PositionDTO newPosition)
        {
            var newPositionFull = new Position()
            {
                PositionTitle = newPosition.PositionTitle,
                Section = newPosition.Section,
                Order = newPosition.Order,
                EditedBy = GetUserId(),
                EditDate = DateTime.Now
            };

            using (var context = new AF_Context())
            {
                try
                {
                    context.Positions.Add(newPositionFull);
                    context.SaveChanges();
                    int id = newPositionFull.PositionId;
                    return GetPosition(id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }
        public SingleItemResponse<PlayDataDTO> UpdatePlay(PlayDataDTO updateData)
        {
            var updateDataFull = new Play()
            {
                PlayId = updateData.PlayId,
                Title = updateData.Title,
                Author = updateData.Author,
                FestivalId = updateData.FestivalId,
                Day = updateData.Day,
                Order = updateData.Order,
                PlayedBy = updateData.PlayedBy,
                Motto = updateData.Motto,
                EditedBy = GetUserId(),
                EditDate = DateTime.Now
            };

            using (var context = new AF_Context())
            {
                try
                {
                    Play pla = context.Plays.First(p => p.PlayId == updateData.PlayId);
                    context.Entry(pla).CurrentValues.SetValues(updateDataFull);
                    context.SaveChanges();
                    int id = updateData.PlayId;
                    return GetPlay(id);
                }
                catch (Exception ex)
                {
                    throw;
                }
            }
        }