Example #1
0
 public void POST([FromBody] JObject value)
 {
     using (ModelContainer _model = new ModelContainer())
     {
         Routes newGps = value.ToObject <Routes>();
         _model.Routes.Add(newGps);
         _model.SaveChanges();
     }
 }
Example #2
0
 /// <summary>
 /// Disable login for specific user by his internal unique ID.
 /// </summary>
 /// <param name="userId">User ID to disable.</param>
 public void DisableUser(Guid userId)
 {
     using (var mc = new ModelContainer())
     {
         var user = ModelHelper.GetUserById(mc, userId);
         user.IsDisabled = true;
         mc.SaveChanges();
     }
 }
 public static bool addFile(DataFile file)
 {
     using (ModelContainer context = new ModelContainer())
     {
         context.DataFiles.Add(file);
         context.SaveChanges();
         return(true);
     }
 }
Example #4
0
 /// <summary>
 /// Mark category as "deleted".
 /// </summary>
 /// <param name="categoryId">Category ID to mark as deleted.</param>
 public void DeleteCategory(int categoryId)
 {
     using (var mc = new ModelContainer(GetPersonalConnection(UserName)))
     {
         var category = ModelHelper.GetCategoryById(mc, categoryId);
         category.Deleted = DateTime.UtcNow;
         mc.SaveChanges();
     }
 }
Example #5
0
 public static bool addAttribute(Attribute attribute)
 {
     using (ModelContainer context = new ModelContainer())
     {
         context.Attributes.Add(attribute);
         context.SaveChanges();
         return(true);
     }
 }
Example #6
0
        public ActionResult NovyPrispevek(Prispevek prispevek)
        {
            using (ModelContainer db = new ModelContainer())
            {
                int idUzivatel = int.Parse(Session["uzivatelID"].ToString());

                //vyhledám potřebné informace - aktuálně přihlášený uživatel a interpreta ke kterému potřebuji vložit příspěvek
                Uzivatel aktualnePrihlaseny = db.Uzivatele.Where(x => x.Id == idUzivatel).First();

                String    nazevInterpreta   = Session["interpretNazev"].ToString();
                Interpret aktualniInterpret = db.Interpreti.Where(x => x.Nazev == nazevInterpreta).First();

                //doplnim vyhledané informace
                prispevek.DatumPridani = DateTime.Now;
                prispevek.Interpret    = aktualniInterpret;
                prispevek.Autor        = aktualnePrihlaseny;
                prispevek.Schvalen     = false;

                //vyhledám uživatele který je správcem interpreta
                int      idSpravce         = db.SpravciInterpretu.Where(x => x.Interpret.Nazev == nazevInterpreta).Select(x => x.UzivatelId).First();
                Uzivatel spravceInterpreta = db.Uzivatele.Where(x => x.Id == idSpravce).First();

                prispevek.Obsah = System.Net.WebUtility.HtmlEncode(prispevek.Obsah);

                //vytvořím žádost
                Zadost novaZadost = new Zadost();
                novaZadost.Interpret   = aktualniInterpret;
                novaZadost.Prispevek   = prispevek;
                novaZadost.StavZadosti = StavZadosti.Cekajici;
                novaZadost.ZadostOd    = aktualnePrihlaseny;
                novaZadost.ZadostKomu  = spravceInterpreta;
                novaZadost.TypZadosti  = TypZadosti.ZadostPisen;



                //pokud uživatel který vkládá příspěvek je zároveň správcem daného interpreta pak se nemusí čekat na schválení žádosti a příspěvek bude přidán
                if (spravceInterpreta.Prezdivka.Equals(aktualnePrihlaseny.Prezdivka))
                {
                    novaZadost.StavZadosti = StavZadosti.Schvalena;
                    prispevek.Schvalen     = true;
                }


                //vložím nový příspěvek
                db.Prispevky.Add(prispevek);

                //vložím novou žádost
                db.Zadosti.Add(novaZadost);

                //uložím změny
                db.SaveChanges();

                //vrátit view které zobrazí odeslání žádosti o příspěvku a vysvětlení co dál
                return(View("NovyPrispevekPotvrzeni"));
            }
        }
        public ActionResult Create([Bind(Include = "Id,dtEntrada,nome,qtdContato,dtPrimeiraVisita,tempoEntrada,bandB,bandA,bandN,bandD,etapaLEAD,etapaATENDIMENTO,etapaAGENDAMENTO,etapaVISITA,etapaPROPOSTA,etapaVENDA,observacao,dtCadastro,JustContatoId,CanalAtracaoId,CanalComunicacaoId,midiaOrigem,TipoContatoId,sexo,cidade,TipoImoveisId,VisitasId,SituacaoId,EmpresaId,FilialId1,JustAvancoId")] GestaoLeads gestaoLeads)
        {
            if (ModelState.IsValid)
            {
                db.GestaoLeadsSet.Add(gestaoLeads);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.CanalAtracaoId     = new SelectList(db.CanalAtracaoSet, "Id", "nome", gestaoLeads.CanalAtracaoId);
            ViewBag.JustContatoId      = new SelectList(db.JustContatoSet, "Id", "nome", gestaoLeads.JustContatoId);
            ViewBag.CanalComunicacaoId = new SelectList(db.CanalComunicacaoSet, "Id", "nome", gestaoLeads.CanalComunicacaoId);
            ViewBag.TipoImoveisId      = new SelectList(db.TipoImoveisSet, "Id", "nome", gestaoLeads.TipoImoveisId);
            ViewBag.TipoContatoId      = new SelectList(db.TipoContatoSet, "Id", "nome", gestaoLeads.TipoContatoId);
            ViewBag.EmpresaId          = new SelectList(db.EmpresaSet, "Id", "nome", gestaoLeads.EmpresaId);
            ViewBag.FilialId1          = new SelectList(db.FilialSet, "Id", "nome", gestaoLeads.FilialId);
            ViewBag.JustAvancoId       = new SelectList(db.JustAvancoSet, "Id", "nome", gestaoLeads.JustAvancoId);
            return(View(gestaoLeads));
        }
Example #8
0
        public Product AddProduct(string name, string property, string description, decimal cost, double volume, bool isIngr, bool isMerch, byte measure,
                                  string vendorCode, double cleanLoss, double fryLoss, double otherLosses,
                                  double protains, double fats, double carbohydrates, double energyCalorie, double energyJoule,
                                  Category category, Company manufacturer)
        {
            Product p = new Product
            {
                Name               = name,
                Property           = property,
                Description        = description,
                Cost               = cost,
                FinalVolume        = volume,
                IsExist            = true,
                IsIngredient       = isIngr,
                IsMerchandise      = isMerch,
                Measure            = (Measure)measure,
                VendorCode         = vendorCode,
                LossDuringCleaning = cleanLoss,
                LossDuringFrying   = fryLoss,
                OtherLosses        = otherLosses,

                Energy =
                {
                    Protains      = protains,
                    Fats          = fats,
                    Carbohydrates = carbohydrates,
                    EnergyCalorie = energyCalorie,
                    EnergyJoule   = energyJoule,
                },

                Category     = category,
                Manufacturer = manufacturer,
            };

            cont.Product.Add(p);
            cont.SaveChanges();

            foreach (var b in cont.Branch.ToList())
            {
                new WarehouseRepository(cont).AddWarehouse(DateTime.Now, 0, b, p);
            }
            return(p);
        }
Example #9
0
        /// <summary>
        /// Добавляет пользователя в базу
        /// </summary>
        /// <param name="firstName">Фамилия</param>
        /// <param name="surName">Ммя</param>
        /// <param name="middleName">Отчество</param>
        /// <param name="login">Логин</param>
        /// <param name="password">Пароль</param>
        /// <param name="position">Номер должности</param>
        /// <returns>Добавленный пользователь</returns>
        public Person AddPerson(string firstName, string surName, string middleName,
                                string login, string password, int position, string email, string phone)
        {
            Person person = new Person
            {
                firstName  = firstName,
                surName    = surName,
                middleName = middleName,
                login      = login,
                password   = password.GetHashCode().ToString(),
                Position   = (Position)position,
                email      = email,
                phone      = phone,
            };

            cont.Person.Add(person);
            cont.SaveChanges();
            return(person);
        }
Example #10
0
        public Order AddOrder(int employee, int table, int client)
        {
            Order p = new Order
            {
                FinalPrice  = 0,
                DateOfOrder = DateTime.Now,
                IsOpen      = true,
                Employee    = (Employee)cont.Person.Single(pers => pers.Id == employee),
                Table       = cont.Table.Single(t => t.Id == table),
                Client      = (Client)cont.Person.Single(c => c.Id == client),
                //Employee = employee,
                //Table = table,
                //Client = client,
            };

            cont.Order.Add(p);
            cont.SaveChanges();
            return(p);
        }
Example #11
0
        public bool AddPhoto(string imglocation, string fullname, string date, string location, string eveniment, string person)
        {
            ModelContainer context = new ModelContainer();
            var            query   = from p5 in context.Pictures
                                     where p5.Path == imglocation
                                     select p5;
            bool ok = true;

            try
            {
                foreach (Picture p5 in query)
                {
                    ok = false;
                }
            }
            catch { }

            if (ok == false)
            {
                return(false);
            }
            else
            {
                Picture p = new Picture()
                {
                    Name = fullname,
                    Path = imglocation,
                    Date = date,
                };


                context.Pictures.Add(p);
                if (location != null || eveniment != null)
                {
                    Details p1 = new Details()
                    {
                        eveniment = location,
                        location  = eveniment,
                        Picture   = p
                    };
                    context.Details.Add(p1);
                }
                if (person != null)
                {
                    Person p2 = new Person()
                    {
                        person_name = person,
                        Picture     = p
                    };
                    context.People.Add(p2);
                    context.SaveChanges();
                }
                return(true);
            }
        }
Example #12
0
        /// <summary>
        /// Update specific transfer transaction.
        /// </summary>
        /// <remarks>
        /// Deposit or withdrawal transactions are not updatable with this method.
        /// To update deposit or withdrawal transaction use <see cref="UpdateTransaction"/> method instead.
        /// </remarks>
        /// <param name="transactionId">Transfer transaction ID.</param>
        /// <param name="user1Id">User 1 unique ID.</param>
        /// <param name="account1Id">Account 1 ID.</param>
        /// <param name="user2Id">User 2 unique ID.</param>
        /// <param name="account2Id">Account 2 ID.</param>
        /// <param name="operationDate">Operation date.</param>
        /// <param name="amount">Amount of assets.</param>
        /// <param name="comment">Comment notes.</param>
        /// <exception cref="NotSupportedException">
        /// Only <see cref="JournalType.Transfer"/> journal type supported.
        /// </exception>
        public void UpdateTransfer(
            int transactionId,
            Guid user1Id,
            int account1Id,
            Guid user2Id,
            int account2Id,
            DateTime operationDate,
            decimal amount,
            string comment)
        {
            if (user1Id == Guid.Empty)
            {
                throw new ArgumentException("User1 ID must not be empty.");
            }

            if (user2Id == Guid.Empty)
            {
                throw new ArgumentException("User2 ID must not be empty.");
            }

            // Remove leading and closing spaces
            string commentNote = comment.Trim();

            // Check comment max length
            if (commentNote.Length > 256)
            {
                throw new Exception("Comment is too long. Maximum length is 256.");
            }

            // Check amount positiveness
            if (amount < 0)
            {
                throw new Exception("Amount must not be less then 0.");
            }

            var dateTime = operationDate.ToUniversalTime();

            using (var mc = new ModelContainer())
            {
                // Todo: add user ID account ID to the GetTransacionById() method call to
                // join them with transaction ID to prevent unauthorized delete
                // Do this for all user-aware calls (i.e. Categories, Accounts etc.)
                Transaction transaction = ModelHelper.GetTransacionById(mc, transactionId);

                if (transaction.JournalType != (byte)JournalType.Transfer)
                {
                    throw new NotSupportedException(string.Format("Only {0} journal type supported.", JournalType.Transfer));
                }

                ModelHelper.DeleteTransaction(mc, transactionId, dateTime);
                ModelHelper.CreateTransfer(mc, dateTime, account1Id, account2Id, amount, commentNote);
                mc.SaveChanges();
            }
        }
Example #13
0
        /// <summary>
        /// Mark account as "deleted".
        /// </summary>
        /// <param name="accountId">Account ID to mark as deleted.</param>
        public void DeleteAccount(int accountId)
        {
            using (var mc = new ModelContainer(GetPersonalConnection(UserName)))
            {
                var account = ModelHelper.GetAccountById(mc, accountId);

                account.IsClosed      = true;
                account.ClosedChanged = DateTime.UtcNow;

                mc.SaveChanges();
            }
        }
Example #14
0
 public void Add(GraphicsCard item)
 {
     try {
         Error = null;
         using (var context = new ModelContainer()) {
             context.Components.Add(item);
             context.SaveChanges();
         }
     } catch (Exception ex) {
         Error = ex;
     }
 }
Example #15
0
 public void Add(Order item)
 {
     try {
         Error = null;
         using (var context = new ModelContainer()) {
             context.Orders.Add(item);
             context.SaveChanges();
         }
     } catch (Exception ex) {
         Error = ex;
     }
 }
        public IHttpActionResult PutReservation(int id, Reservation reservation)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != reservation.Id)
            {
                return(BadRequest());
            }

            db.Clients.Attach(reservation.Client);
            db.Rooms.Attach(reservation.Room);

            Reservation updatedReservation = db.Reservations.Find(id);

            updatedReservation.Client    = reservation.Client;
            updatedReservation.Room      = reservation.Room;
            updatedReservation.EndDate   = reservation.EndDate;
            updatedReservation.StartDate = reservation.StartDate;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ReservationExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public ActionResult AddComments(int FlightID, string Comments)
        {
            StringBuilder sbComments = new StringBuilder();
            Comments      comments   = new Comments();

            comments.FlightsId = FlightID;
            comments.content   = Comments;
            sbComments.Append(HttpUtility.HtmlEncode(comments.content));
            // Only decode bold and underline tags
            sbComments.Replace("&lt;b&gt;", "[b]");
            sbComments.Replace("&lt;/b&gt;", "[/b]");
            sbComments.Replace("&lt;u&gt;", "[u]");
            sbComments.Replace("&lt;/u&gt;", "[/u]");
            comments.content = sbComments.ToString();
            if (!ModelState.IsValid)
            {
                return(View());
            }
            db.Comments.Add(comments);
            db.SaveChanges();
            return(RedirectToAction("Details", new { id = FlightID }));
        }
 private void GuardarAvance()
 {
     using (ModelContainer conexion = new ModelContainer())
     {
         var examen = conexion.Examenes
             .Where(p => p.IdExamen == examenIdExamen).
             FirstOrDefault();
         examen.avance = contadorDeAvance;
         examen.preguntasResueltas = this.preguntasResueltas;
         examen.banderaReanudar = true;
         conexion.SaveChanges();
     }
 }
 public void DeleteEmployee(int id)
 {
     if (cont.Order.ToList().Exists(o => o.Employee.Id == id) ||
         cont.Shift.ToList().Exists(o => o.Person.Id == id))
     {
         ((Employee)cont.Person.SingleOrDefault(p => p.Id == id)).IsWorking = false;
         return;
     }
     cont.Person.Remove(cont.Person.Find(id));
     cont.SaveChanges();
 }
Example #20
0
        /// <summary>Añade un usuario a la base de datos.</summary>
        /// <param name="jugador">El jugador.</param>
        /// <returns>El resultado de la operacion</returns>
        /// <exception cref="EntityException">En caso de que ocurra un error en la base de datos</exception>

        public DBOperationResult.AddResult AddUser(IRegisterService.Jugador jugador)
        {
            DBOperationResult.AddResult result;
            try
            {
                CheckObjectJugador(jugador);
            }
            catch (FormatException)
            {
                result = DBOperationResult.AddResult.NullObject;
                return(result);
            }

            DataAccess.ModelContainer container = new ModelContainer();
            ICollection <Jugador>     usuarios  = new List <Jugador>
            {
                new Jugador {
                    Nombre         = jugador.Nombre,
                    Correo         = jugador.Correo,
                    Elo            = "",
                    PuntuaciónAlta = 0,
                    Ranking        = new Ranking
                    {
                        Posicion = 0
                    },
                    Usuario = new Usuario {
                        Username     = jugador.Username,
                        Password     = jugador.Password,
                        Confirmación = "False",
                        Código       = int.Parse(jugador.Código)
                    }
                },
            };

            foreach (var usuario in usuarios)
            {
                container.JugadorSet.Add(usuario);
            }
            try
            {
                container.SaveChanges();
                result = DBOperationResult.AddResult.Success;
            }
            catch (EntityException)
            {
                result = DBOperationResult.AddResult.SQLError;
            }


            return(result);
        }
Example #21
0
 public IHttpActionResult PostEditAppoint([FromUri] int id)
 {
     using (var db = new ModelContainer())
     {
         var existingApp = db.Appointments.SingleOrDefault(a => a.Id_Appointment == id);
         if (null != existingApp)
         {
             db.Entry(existingApp).State = EntityState.Deleted;
             db.SaveChanges();
             return(Ok(existingApp.Id_Appointment + " Deleted successfully"));
         }
         return(Ok("Could not DELETE appointment! - Please call clinic"));//fail
     }
 }
        public ActionResult Create([Bind(Include = "Id,BookingsId")] Files files, HttpPostedFileBase file)
        {
            if (ModelState.IsValid)
            {
                if (file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path     = Path.Combine(Server.MapPath("~/fileUploads"), fileName);
                    files.path = path;
                    files.name = fileName;
                    file.SaveAs(path);
                    db.Files.Add(files);
                    db.SaveChanges();
                    ViewBag.Message = "Upload Successful";
                }


                return(RedirectToAction("Index"));
            }

            ViewBag.BookingsId = new SelectList(db.Bookings, "Id", "name", files.BookingsId);
            return(View(files));
        }
Example #23
0
        /// <summary>
        /// Update account details to new values.
        /// </summary>
        /// <param name="accountId">Account ID.</param>
        /// <param name="name">Account new name.</param>
        public void UpdateAccount(int accountId, string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Account name must not be empty.");
            }

            using (var mc = new ModelContainer(GetPersonalConnection(UserName)))
            {
                var account = ModelHelper.GetAccountById(mc, accountId);
                account.Name = name;
                mc.SaveChanges();
            }
        }
Example #24
0
        public static Tag updateTag(Tag newTag)
        {
            using (ModelContainer context = new ModelContainer())
            {
                Tag oldTag = context.Tags.Find(newTag.Id);
                if (oldTag == null)
                {
                    return(null);
                }

                oldTag.Name = newTag.Name;
                context.SaveChanges();
                return(oldTag);
            }
        }
Example #25
0
        /// <summary>
        /// Delete specific transaction.
        /// </summary>
        /// <param name="userId">The user unique ID.</param>
        /// <param name="accountId">The account ID.</param>
        /// <param name="transactionId">Transaction ID.</param>
        /// <param name="operationDate">Operation date.</param>
        public void DeleteTransaction(Guid userId, int accountId, int transactionId, DateTime operationDate)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentException("User ID must not be empty.");
            }

            var dateTime = operationDate.ToUniversalTime();

            using (var mc = new ModelContainer())
            {
                ModelHelper.DeleteTransaction(mc, transactionId, dateTime);
                mc.SaveChanges();
            }
        }
Example #26
0
        public ActionResult Like(int Id)
        {
            string Username = Session["Username"].ToString();
            Like   _like    = db.Likes.Where(m => m.UserUsername == Username && m.ProductId == Id).FirstOrDefault();

            if (_like != null)
            {
                db.Likes.Remove(_like);
                db.SaveChanges();
            }
            ((IObjectContextAdapter)db).ObjectContext.Detach(_like);

            Like like = new Like();

            like.ProductId    = Id;
            like.UserUsername = Username;
            db.Likes.Add(like);
            db.SaveChanges();
            ((IObjectContextAdapter)db).ObjectContext.Detach(like);

            Product product = db.Products.Find(Id);
            int     Likes   = product.Count_Like;

            Likes++;
            product.Count_Like = Likes;
            if (ModelState.IsValid)
            {
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
            }
            if (Request.IsAjaxRequest())
            {
                return(PartialView());
            }
            return(View());
        }
Example #27
0
        static public void SendMessage(string FromUsername, string ToUsername, string Message)
        {
            InMail inmail = new InMail();

            inmail.IsRead       = false;
            inmail.Date         = About_Controller.CurrentDate;
            inmail.FromUsername = FromUsername;
            inmail.ToUsername   = ToUsername;
            inmail.Value        = Message;
            ModelContainer db = new ModelContainer();

            db.InMails.Add(inmail);
            db.SaveChanges();
            FromUsername = ToUsername = Message = null;
        }
Example #28
0
 public ActionResult Compose(InMail inmail)
 {
     inmail.IsRead       = false;
     inmail.Date         = About_Controller.CurrentDate;
     inmail.FromUsername = Session["Username"].ToString();
     if (inmail.ToUsername != inmail.FromUsername)
     {
         if (ModelState.IsValid)
         {
             db.InMails.Add(inmail);
             db.SaveChanges();
             return(Redirect("~/MessageCenter/Index"));
         }
     }
     else
     {
         ViewBag.Message = "خطا! ارسال با خطا رو به رو شد. لطفا در وارد کردن اطلاعات دقت نمائید.";
     }
     if (Request.IsAjaxRequest())
     {
         return(PartialView(inmail));
     }
     return(View(inmail));
 }
Example #29
0
        /// <summary>
        /// Update category details to new values.
        /// </summary>
        /// <param name="categoryId">Category ID.</param>
        /// <param name="name">Category new name.</param>
        /// <param name="categoryType">Category new type.</param>
        public void UpdateCategory(int categoryId, string name, CategoryType categoryType)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("Category name must not be empty.");
            }

            using (var mc = new ModelContainer(GetPersonalConnection(UserName)))
            {
                var category = ModelHelper.GetCategoryById(mc, categoryId);
                category.Name         = name;
                category.CategoryType = (byte)categoryType;
                mc.SaveChanges();
            }
        }
Example #30
0
        public async Task <bool> SetCarType(ModelContainer db, TelegramChat chat, AlertType alertType, CarType carType)
        {
            var telegramChatSetting = await db.TelegramChatSettings
                                      .FirstOrDefaultAsync(x => x.TelegramChatId == chat.Id && x.Type == alertType)
                                      .ConfigureAwait(false);

            if (telegramChatSetting == null)
            {
                return(false);
            }

            telegramChatSetting.CarType = carType;
            db.SaveChanges();
            return(true);
        }
        public Res Bind(Test t, Group g, ModelContainer data)
        {
            bool Success = true;
            try
            {
                g.Tests.Add(t);
                data.Tests.First(tt => tt.TestId == t.TestId).Groups.Add(g);
                data.SaveChanges();

            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, null);
        }
        public Res ChangeTextQuastion(Func<Quastion, bool> p, string text, ModelContainer data)
        {
            bool Success = true;
            IEnumerable<Quastion> quastions = null;
            try
            {
                quastions = data.Quastions.Select(row => row).Where(p);
                foreach(Quastion q in quastions)
                    q.Text = text;
                data.SaveChanges();
            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, quastions);
        }
 public Res ChangeVariant(Func<Variant, bool> p, string Text, bool isValid, ModelContainer data)
 {
     bool Success = true;
     IEnumerable<Variant> variants = null;
     try
     {
         variants = data.Variants.Select(row => row).Where(p);
         foreach (Variant v in variants)
         {
             v.IsValid = isValid;
             v.Text = Text;
         }
         data.SaveChanges();
     }
     catch (Exception e)
     {
         Success = false;
     }
     return new Res(Success, variants);
 }
 public Res DeleteVariant(Func<Variant, bool> p, ModelContainer data)
 {
     bool Success = true;
     IEnumerable<Variant> variants = null;
     try
     {
         variants = data.Variants.Select(row => row).Where(p);
         foreach (Variant v in variants)
         {
             data.Variants.Remove(v);
         }
         data.SaveChanges();
     }
     catch (Exception e)
     {
         Success = false;
     }
     return new Res(Success, variants);
 }
        public Res Check(Test t, ModelContainer data, aspnet_Users user)
        {
            int c = 0;
            bool Success = true;
            try
            {
                Test test = (ReadTests(x => x.TestId == t.TestId, data).Value as IEnumerable<Test>).First();
                //сравнение вопросов у тестов
                for(int i = 0; i < test.Quastions.ToList().Count; i++)
                {
                    int b = 1;
                    for(int j = 0; j < test.Quastions.ToList()[i].Variants.Count; j++)
                    {
                        if (test.Quastions.ToList()[i].Variants.ToList()[j].IsValid != t.Quastions.ToList()[i].Variants.ToList()[j].IsValid)
                        {
                            b = 0;
                        }
                    }
                    c += b;

                }

                //сохранение результатов, только если не уже не был пройден этот тест
                if (data.Results.FirstOrDefault(x => x.aspnet_Users.UserId == user.UserId && x.TestId == t.TestId) != null)
                    return new Res(Success, data.Results.FirstOrDefault(x => x.aspnet_Users.UserId == user.UserId && x.TestId == t.TestId).Result1);
                Result r = data.Results.Create();
                r.TestId = t.TestId;
                r.Test = test;
                r.Result1 = c;
                r.aspnet_Users = user;
                r.aspnet_Users_UserId = user.UserId;
                data.Results.Add(r);
                data.SaveChanges();
            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, c);
        }
        public Res DeleteTests(Func<Test, bool> p, ModelContainer data)
        {
            bool Success = true;
            IEnumerable<Test> tests = null;
            try
            {
                tests = data.Tests.Select(row => row).Where(p);
                foreach (Test t in tests.ToList())
                {
                    data.Tests.Remove(t);

                }
                data.SaveChanges();
            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, tests);
        }
 public Res DeleteQuastions(Func<Quastion, bool> p, ModelContainer data)
 {
     bool Success = true;
     IEnumerable<Quastion> quastions = null;
     try
     {
         quastions = data.Quastions.Select(row => row).Where(p);
         foreach (Quastion q in quastions)
             data.Quastions.Remove(q);
         data.SaveChanges();
     }
     catch (Exception e)
     {
         Success = false;
     }
     return new Res(Success, quastions);
 }
 public Res CreateVariant(Quastion q, string Text, bool isValid, ModelContainer data)
 {
     bool Success = true;
     IEnumerable<Quastion> quastions = null;
     try
     {
         Quastion quastion = data.Quastions.First(x => x.QuastionId == q.QuastionId);
         Variant v = data.Variants.Create();
         v.VariantId = Guid.NewGuid();
         v.IsValid = isValid;
         v.Text = Text;
         v.Quastion = q;
         data.Variants.Add(v);
         data.SaveChanges();
     }
     catch (Exception e)
     {
         Success = false;
     }
     return new Res(Success, quastions);
 }
        public Res CreateQuastion(Test test, string text, ModelContainer data)
        {
            bool Success = true;
            IEnumerable<Quastion> quastions = null;
            try
            {
                Quastion q = data.Quastions.Create();
                q.QuastionId = Guid.NewGuid();
                q.Text = text;
                q.Test = data.Tests.First(x => x.TestId == test.TestId);
                data.Quastions.Add(q);
                data.SaveChanges();
            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, quastions);
        }
        public Res CreateTests(string TestName, Discipline discipline, ModelContainer data)
        {
            bool Success = true;
            IEnumerable<Test> tests = null;
            try
            {
                Test test = data.Tests.Create();
                test.TestId = Guid.NewGuid();
                test.Name = TestName;
                test.Discipline = discipline;
                data.Tests.Add(test);
                data.SaveChanges();
            }
            catch (Exception e)
            {
                Success = false;
            }

            return new Res(Success, tests);
        }