Beispiel #1
0
 public ActionResult StudentCreate([Bind(Include = "Firstname,Lastname")] Student newStudent, int Courseid)
 {
     if (ModelState.IsValid)
     {
         using (var context = new context())
         {
             context.Students.Add(newStudent);            //save name of student and get a Studentid in return from database
             int numberOfChanges = context.SaveChanges(); //get hold of how many objects that was saved.
             if (numberOfChanges >= 1)                    //if more than one is returned the save was a success and fetch then relevant data from database
             {
                 newStudent.StudentCourses     = context.Courses.SqlQuery("SELECT * FROM Courses WHERE CourseId=@id", new SqlParameter("@id", Courseid)).ToList();
                 newStudent.StudentAssignments = context.Assignments.SqlQuery("SELECT * FROM Assignments WHERE CourseId=@id AND IsTemplateAssignment='True'", new SqlParameter("@id", Courseid)).ToList();
                 int numberOfAssignments = newStudent.StudentAssignments.Count(); //get hold of how many assignments the course have
                 for (int i = 0; i < numberOfAssignments; i++)                    //for each assignment create another and copy over the relevant info from the assingment template
                 {
                     Assignment newAssignment = new Assignment();
                     newAssignment.AssignmentName       = newStudent.StudentAssignments[i].AssignmentName;
                     newAssignment.CourseId             = newStudent.StudentAssignments[i].CourseId;
                     newAssignment.Description          = newStudent.StudentAssignments[i].Description;
                     newAssignment.IsCompletedByStudent = false;
                     newAssignment.IsTemplateAssignment = false;
                     newAssignment.StudentId            = newStudent.StudentId;
                     newStudent.StudentAssignments.Add(newAssignment); //add the new assignment to the list of assignments
                 }
                 for (int i = 0; i < numberOfAssignments; i++)         //Remove the template assignments
                 {
                     if (newStudent.StudentAssignments[i].AssignmentId != 0)
                     {
                         newStudent.StudentAssignments.Remove(newStudent.StudentAssignments[i]);
                         i--;
                     }
                 }
             }
             context.SaveChanges();
         }
         return(RedirectToAction("Students", "Home"));
     }
     return(RedirectToAction("Students", "Home"));
 }
Beispiel #2
0
 // DELETE Product
 public JsonResult DeleteProduct(int id)
 {
     try
     {
         var product = _context.Products.Where(c => c.Id == id).SingleOrDefault();
         if (product != null)
         {
             _context.Products.Remove(product);
             _context.SaveChanges();
         }
     }
     catch (Exception e)
     {
         Console.Write(e.Data + "Exception Occured");
         return(new JsonResult {
             Data = "Deletion Falied", JsonRequestBehavior = JsonRequestBehavior.AllowGet
         });
     }
     return(new JsonResult {
         Data = "Success", JsonRequestBehavior = JsonRequestBehavior.AllowGet
     });
 }
Beispiel #3
0
 public ActionResult CourseCreate([Bind(Include = "CourseName,Description")] Course newCourse)
 {
     if (ModelState.IsValid)
     {
         using (var context = new context())
         {
             newCourse.TeacherId = 1;
             context.Courses.Add(newCourse);
             int numberOfSavedObjects = context.SaveChanges();
         }
     }
     return(RedirectToAction("Courses", "Home"));
 }
Beispiel #4
0
        public ActionResult edituser(Guid id, bool enabled)
        {
            var user = db.user.Find(id);

            user.enabled = enabled;
            db.SaveChanges();
            return(RedirectToAction("user"));
        }
        public usersController(context context)
        {
            _context = context;

            if (_context.users.Count() == 0)
            {
                // Create a new user if collection is empty,
                // which means you can't delete all users.
                _context.users.Add(new user {
                    UserName = "******", Name = "jesus", LastName = "enrique", Age = 27
                });
                _context.SaveChanges();
            }
        }
Beispiel #6
0
        public hardwareController(context context)
        {
            _context = context;

            if (_context.hardware.Count() == 0)
            {
                // Create a new user if collection is empty,
                // which means you can't delete all users.
                _context.hardware.Add(new hardware {
                    HardwareName = "prueba2"
                });
                _context.SaveChanges();
            }
        }
Beispiel #7
0
        public ActionResult EditCar(int ID, Car car)
        {
            context data = new context();

            Car tempCar = data.Cars.FirstOrDefault(ca => ca.ID == ID);

            tempCar.Title       = car.Title;
            tempCar.Brand       = car.Brand;
            tempCar.PriceForDay = car.PriceForDay;

            data.SaveChanges();

            return(RedirectToAction("ShowCarsCards"));
        }
Beispiel #8
0
        public ActionResult ReserveCar(int id, ClientReserveCarViewModel ViewModel)
        {
            ViewModel.CarID = id;

            context data = new context();

            data.Cars.FirstOrDefault(ca => ca.ID == ViewModel.CarID).RentDate = DateTime.Today;

            data.Cars.FirstOrDefault(ca => ca.ID == ViewModel.CarID).period = ViewModel.Period;

            data.Cars.FirstOrDefault(ca => ca.ID == ViewModel.CarID).CarIsReserved(ViewModel.NationalId, ViewModel.Period);

            if (data.Clients.FirstOrDefault(cli => cli.ssn == ViewModel.NationalId) != null)
            {
                data.Clients.FirstOrDefault(cli => cli.NationalId == ViewModel.NationalId).RentedCarsHistory.Add(data.Cars.FirstOrDefault(ca => ca.ID == ViewModel.CarID));
            }
            else
            {
                Client client = new Client {
                    ssn        = ViewModel.NationalId,
                    NationalId = ViewModel.NationalId,
                    City       = ViewModel.City,
                    Country    = ViewModel.Country,
                    Street     = ViewModel.Street,
                    FirstName  = ViewModel.FirstName,
                    LastName   = ViewModel.LastName,
                    Phone      = ViewModel.Phone
                };

                if (client.RentedCarsHistory == null)
                {
                    client.RentedCarsHistory = new List <Car>();
                }

                client.RentedCarsHistory.Add(data.Cars.FirstOrDefault(ca => ca.ID == ViewModel.CarID));

                data.Clients.Add(client);
            }
            data.SaveChanges();

            if (ModelState.IsValid)
            {
                return(RedirectToAction("ShowCarsCards"));
            }
            else
            {
                return(RedirectToAction("AddCar"));
            }
        }
Beispiel #9
0
        // PUT: odata/WebApi(5)
        public IHttpActionResult Put([FromODataUri] int key, Delta <Cliente> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Cliente cliente = db.Cliente.Find(key);

            if (cliente == null)
            {
                return(NotFound());
            }

            patch.Put(cliente);

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

            return(Updated(cliente));
        }
 public ActionResult AssignmentCreate([Bind(Include = "AssignmentName, Description")] Assignment newAssignmet, int Courseid)
 {
     newAssignmet.CourseId = Courseid;
     //newAssignmet.StudentId = 999999;
     newAssignmet.IsTemplateAssignment = true;
     newAssignmet.IsCompletedByStudent = false;
     if (ModelState.IsValid)
     {
         using (var context = new context())
         {
             context.Assignments.Add(newAssignmet);
             context.SaveChanges();
         }
         return(RedirectToAction("Assignments", "Home"));
     }
     return(RedirectToAction("Assignments", "Home"));
 }
 public ActionResult Create(RegisterViewModel model)
 {
     try
     {
         using (context ctx = new context())
         {
             ctx.users.Add(model);
             ctx.SaveChanges();
             ViewBag.status = "Success!!!";
         }
         return(View());
     }
     catch (Exception ex)
     {
         ViewBag.status = "Error: " + ex.Message + ", " + ex.InnerException;
         return(View());
     }
 }
Beispiel #12
0
        public ActionResult Index()
        {
            MachineEvent _event = new MachineEvent();

            _event.assetID = "94200";
            _event.state   = "RUNNING";
            _event.ticks   = DateTime.Now.Ticks.ToString();


            context db = new context();

            db.machineEvents.Add(_event);
            db.SaveChanges();



            return(Json(_event, JsonRequestBehavior.AllowGet));
        }
Beispiel #13
0
        public ActionResult reservePackage(int id, ClientReservePackageViewModel model)
        {
            model.PackageId = id;
            context data = new context();

            Client client = new Client {
                ssn       = model.NationalId,
                City      = model.City,
                Country   = model.Country,
                Street    = model.Street,
                FirstName = model.FirstName,
                LastName  = model.LastName,
                Phone     = model.Phone
            };

            if (client.RentedPackagesHistory == null)
            {
                client.RentedPackagesHistory = new List <Package>();
            }

            client.RentedPackagesHistory.Add(data.Packages.FirstOrDefault(pack => pack.ID == model.PackageId));
            data.Clients.Add(client);

            data.SaveChanges();

            context data1 = new context();
            Package p     = data1.Packages.FirstOrDefault(ca => ca.ID == model.PackageId);

            for (int i = 0; i < 3; i++)
            {
                p.Cars[i].period   = model.Period;
                p.Cars[i].RentDate = DateTime.Today;
                p.Cars[i].ClientsList.Add(data1.Clients.FirstOrDefault(cl => cl.NationalId == model.NationalId));
            }

            p.PackageIsReserved(model.NationalId, model.Period);

            p.Period = model.Period;

            data1.SaveChanges();

            return(RedirectToAction("ShowPackageCards"));
        }
Beispiel #14
0
        public ActionResult AddGroup(FormCollection Form)
        {
            string id, Groupname, Groupintro, Groupnotice;

            Groupname   = Request.Form["GroupName"].ToString();
            Groupintro  = Request.Form["GroupIntro"].ToString();
            Groupnotice = Request.Form["GroupNotice"].ToString();
            id          = Request.Form["uid"].ToString();
            //添加群表
            UserGroups ug = new UserGroups();

            ug.UG_CreateTime = DateTime.Now;
            ug.UG_Icon       = "~/Images/head.jpg";
            ug.UG_Introd     = Groupintro;
            ug.UG_kName      = Groupname;
            ug.UG_NOtice     = Groupnotice;
            ug.UG_AdminID    = (db.UserLogins.Where(a => a.id.ToString().Trim() == id.ToString().Trim()).FirstOrDefault() as UserLogin).id.ToString();
            db.UserGroups.Add(ug);
            db.SaveChanges();
            Thread.Sleep(1000);
            int groupid = Convert.ToInt32(db.UserGroups.Where(a => a.UG_AdminID == ug.UG_AdminID).OrderByDescending(a => a.UG_id).FirstOrDefault().UG_id);

            UserGroupToUSer use = new UserGroupToUSer();

            use.banned        = 0;
            use.status        = "admin";
            use.UG_CreateTime = DateTime.Now;
            use.UG_GroupID    = groupid;
            use.UG_GroupNick  = "群主";
            use.UG_UserID     = Convert.ToInt32(ug.UG_AdminID);
            db.UserGroupToUsers.Add(use);
            var me = (HttpContext.Session[HttpContext.Session.SessionID] as UserLogin).id;

            if (db.SaveChanges() > 0)
            {
                return(RedirectToAction("AddUserToG/" + groupid, "Chat"));
            }
            else

            {
                return(JavaScript("alert('群建立失败!')"));
            }
        }//创建群
        }//添加用户到群视图

        public string AddGroupUsers(int[] ids)//添加群用户
        {
            List <UserInfo>        us = new List <UserInfo>();
            List <UserGroupToUSer> ut = new List <UserGroupToUSer>();
            var id = Convert.ToInt32(Request.Params["id"].ToString().Trim());

            foreach (var item in ids)
            {
                UserInfo ls = db.UserInfos.Where(a => a.userid == item).FirstOrDefault();
                if (ls != null)
                {
                    us.Add(ls);
                }
                else
                {
                }
            }

            foreach (var item in us)
            {
                UserGroupToUSer iu = new UserGroupToUSer();
                iu.UG_CreateTime = DateTime.Now;
                iu.UG_GroupID    = id;
                iu.UG_GroupNick  = "";
                iu.UG_id         = 1;
                iu.UG_UserID     = item.userid;
                iu.status        = "normal";
                iu.banned        = 0;
                ut.Add(iu);
            }
            db.UserGroupToUsers.AddRange(ut);
            if (db.SaveChanges() > 0)
            {
                return("用户添加成功!");
            }
            else
            {
                return("用户添加失败!");
            }
        }
        public void DeleteUserExecute()
        {
            try
            {
                if (Employe != null)
                {
                    using (context context = new context())
                    {
                        //taking registration number from selected user
                        string IdNumber = Employe.IdNumber;
                        //inserting message box that will be shown when delete button is pressed
                        MessageBoxResult messageBoxResult = MessageBox.Show("Are you sure that you want to delete employe?", "Delete Confirmation", MessageBoxButton.YesNo);
                        if (messageBoxResult == MessageBoxResult.Yes)
                        {
                            //finding user and card that needs to be deleted, finding them with registration number
                            tblEmploye employeToDelete = (from r in context.tblEmployes where r.IdNumber == IdNumber select r).First();
                            //removing from database=> both user and his ID card
                            context.tblEmployes.Remove(employeToDelete);

                            // saving changes in database
                            context.SaveChanges();
                            // writing action into file
                            //Write.Writer.WriteDelete(userToDelete);
                            //// refreshing => getting new state from database
                            ListEmploye = GetAllEmployes();
                        }
                        // in case "No" is clicked in line 77
                        else
                        {
                            MessageBox.Show("Deleting proccess is stoped");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        public List <tblLOCATION> GetLocations()
        {
            string        path      = @"../../Locations.txt";
            StreamReader  sr        = new StreamReader(path);
            string        line      = "";
            List <string> locations = new List <string>();

            while ((line = sr.ReadLine()) != null)
            {
                locations.Add(line);
            }
            sr.Close();

            List <tblLOCATION> locationList = new List <tblLOCATION>();
            context            context      = new context();

            for (int i = 0; i < locations.Count; i++)
            {
                tblLOCATION   oneLocation = new tblLOCATION();
                List <string> adressList  = new List <string>();
                adressList         = locations[i].Split(',').ToList();
                oneLocation.Adress = adressList[0];
                oneLocation.Place  = adressList[1];
                oneLocation.States = adressList[2];
                locationList.Add(oneLocation);
            }
            if (context.tblLOCATIONS.Count() == 0)
            {
                for (int i = 0; i < locationList.Count; i++)
                {
                    context.tblLOCATIONS.Add(locationList[i]);
                }
            }
            context.SaveChanges();
            return(locationList);
        }
Beispiel #18
0
        //public ActionResult TeacherHideCourses(int id)
        //{
        //    return PartialView("_TeacherList", )
        //}

        public ActionResult TeacherDelete(int id)
        {
            List <Teacher> presentTeachers = new List <Teacher>();

            using (var context = new context())
            {
                foreach (var item in context.Teachers)
                {
                    presentTeachers.Add(context.Teachers.Find(item.TeacherId));
                }
                for (int i = 0; i <= presentTeachers.Count(); i++)
                {
                    if (presentTeachers[i].TeacherId == id)
                    {
                        context.Teachers.Remove(presentTeachers[i]);
                        context.SaveChanges();
                        presentTeachers = null;
                        return(PartialView("_DeletedObject"));
                    }
                }
            }
            presentTeachers = null;
            return(PartialView("_DeletedObject"));
        }
Beispiel #19
0
 public ActionResult yeniMail(iletisim p)
 {
     c.iletisims.Add(p);
     c.SaveChanges();
     return(RedirectToAction("Index"));
 }
Beispiel #20
0
        public AccountControl() : base("/Account")
        {
            Get["/", runAsync : true] = async(param, token) =>
            {
                await Task.Delay(0);

                return(this.Response.AsJson(new
                {
                    status = true,
                    message = "Account",
                }));
            };

            Get["/getBalance/{id}", runAsync : true] = async(param, token) =>
            {
                await Task.Delay(0);

                //init
                bool   status  = false;
                string message = string.Empty;
                object obj     = null;

                //process
                string userID = param.id;
                if (string.IsNullOrEmpty(userID))
                {
                    status  = false;
                    message = "id*";
                }
                else
                {
                    status = true;
                    context        db     = new context();
                    AccountService accser = new AccountService();
                    obj = accser.getBalance(db, userID);
                }

                return(this.Response.AsJson(new
                {
                    status = status,
                    message = message,
                    content = obj,
                }));
            };
            Get["/getTranfer/{accountNo}/{accountNoTranfer}/{money}", runAsync : true] = async(param, token) =>
            {
                await Task.Delay(0);

                //init
                bool   status  = false;
                string message = string.Empty;
                object obj     = null;

                string AccountNo        = param.accountNo;
                string AccountNoTranfer = param.accountNoTranfer;
                string MoneyTmp         = param.money;
                double Money            = -1;

                //process
                if (string.IsNullOrEmpty(AccountNo) || string.IsNullOrEmpty(AccountNoTranfer) || string.IsNullOrEmpty(MoneyTmp))
                {
                    status  = false;
                    message = "accountNo || accountNoTranfer || money*";
                }
                else
                {
                    status = true;
                    context db = new context();

                    Money = Convert.ToDouble(MoneyTmp);
                    AccountService accser = new AccountService();
                    obj = accser.getTranfer(db, AccountNo, AccountNoTranfer, Money);
                    db.SaveChanges();
                }

                return(this.Response.AsJson(new
                {
                    status = status,
                    message = message,
                    content = obj,
                }));
            };
        }
 public void Delete(Category p)
 {
     _object.Remove(p);
     c.SaveChanges();
 }
Beispiel #22
0
 public ActionResult yorumYap(blog b)
 {
     c.blogs.Add(b);
     c.SaveChanges();
     return(RedirectToAction("Index"));
 }
Beispiel #23
0
 public ActionResult yeniBlog(blog p)
 {
     c.blogs.Add(p);
     c.SaveChanges();
     return(RedirectToAction("Index"));
 }
Beispiel #24
0
 public IActionResult YeniDepartman(departmanlar d)
 {
     c.departmanlars.Add(d);
     c.SaveChanges();
     return(RedirectToAction("Index"));
 }
 public ActionResult Register(Register reg)
 {
     homeContext.Registers.Add(reg);
     homeContext.SaveChanges();
     return(RedirectToAction("Login"));
 }
 public void Delete(T p)
 {
     _object.Remove(p);
     c.SaveChanges();
 }
Beispiel #27
0
        public IHttpActionResult PostNewPost(dynamic blogPost)
        {
            // deserializing json object into a view model
            blogPostVM model = JsonConvert.DeserializeObject <blogPostVM>(blogPost.blogPost.ToString());

            //function in "blogPostVM" class that checks if everthing is ok
            if (model.CheckRequired())
            {
                return(BadRequest("Invalid data"));
            }
            //helperClass is a static class that contains functions that will manuiplate with data and return things we need
            string newSlug = helperClasses.createSlug(model.title);

            if (ctx.blogPost.Where(x => x.slug == newSlug).SingleOrDefault() != null)
            {
                return(BadRequest("Post already exists"));
            }

            //creating a new list of tags
            List <Tags> tagList = new List <Tags>();

            //adding tags to "Tags" table (if they don't already exist)
            foreach (string s in blogPost.blogPost.tagList)
            {
                Tags tagFromDb = ctx.tag.Where(x => x.tagName == s).SingleOrDefault();
                if (tagFromDb == null)
                {
                    Tags tag = new Tags();
                    tag.slug      = helperClasses.createSlug(s);
                    tag.tagName   = s;
                    tag.createdAt = DateTime.Now;
                    tag.updatedAt = DateTime.Now;
                    ctx.tag.Add(tag);
                    ctx.SaveChanges();
                    tagList.Add(tag);
                }
                else
                {
                    tagList.Add(tagFromDb);
                }
            }
            //creating new post
            BlogPost newPost = new BlogPost();

            newPost.slug        = helperClasses.createSlug(model.title);
            newPost.title       = model.title;
            newPost.description = model.description;
            newPost.body        = model.body;
            newPost.createdAt   = DateTime.Now;
            newPost.updatedAt   = DateTime.Now;
            ctx.blogPost.Add(newPost);

            ctx.SaveChanges();

            //joining tags to post in "BlogPostTags" table (many to many relationship with composite primary key)
            foreach (Tags tag in tagList)
            {
                BlogPostTags blogPostTag = new BlogPostTags();
                blogPostTag.PostId    = newPost.Id;
                blogPostTag.TagId     = tag.Id;
                blogPostTag.createdAt = DateTime.Now;
                blogPostTag.updatedAt = DateTime.Now;
                ctx.blogPostTag.Add(blogPostTag);
            }
            ctx.SaveChanges();

            return(Ok(viewPosts(newPost.slug)));
        }
        private void SaveExecute()
        {
            try
            {
                tblEmploye newEmploye = new tblEmploye();
                newEmploye.UserName    = Employe.UserName;
                newEmploye.Surname     = Employe.Surname;
                newEmploye.IdNumber    = Employe.IdNumber;
                newEmploye.Number      = Employe.Number;
                newEmploye.JMBG        = Employe.JMBG;
                newEmploye.DateOfBirth = CalculateBirth(Employe.JMBG);
                //for sector
                string    newSector       = Sector.SectorName;
                tblSector newSectorObject = new tblSector();
                newSectorObject.SectorName = newSector;
                List <tblSector> sectorList  = context.tblSectors.ToList();
                List <string>    sectorNames = new List <string>();
                for (int i = 0; i < sectorList.Count; i++)
                {
                    sectorNames.Add(sectorList[i].SectorName);
                }
                if (sectorNames.Contains(newSectorObject.SectorName))
                {
                    tblSector sectorToFind = new tblSector();
                    sectorToFind        = (from r in context.tblSectors where r.SectorName == newSectorObject.SectorName select r).First();
                    newEmploye.SectorID = sectorToFind.SectorID;
                    context.SaveChanges();
                }
                else
                {
                    context.tblSectors.Add(newSectorObject);
                    context.SaveChanges();
                    newEmploye.SectorID = newSectorObject.SectorID;
                    context.SaveChanges();
                }

                newEmploye.GenderID = Gender.GenderID;
                string adress = Location.Adress;
                if (Location.Adress == "Adresa1")
                {
                    Location.LocationID = 1;
                }
                if (Location.Adress == "Adresa2")
                {
                    Location.LocationID = 1;
                }
                if (Location.Adress == "Adresa3")
                {
                    Location.LocationID = 3;
                }
                if (Location.Adress == "Adresa4")
                {
                    Location.LocationID = 4;
                }
                if (Location.Adress == "Adresa5")
                {
                    Location.LocationID = 5;
                }

                newEmploye.LocationID = Location.LocationID;
                context.tblEmployes.Add(newEmploye);
                context.SaveChanges();
                addEmploye.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error occured. Make sure that you have provided valid JMBG. Please fix the problems and try again." + ex.ToString());
            }
        }
Beispiel #29
0
        public ActionResult Saleedt1(Sales se)
        {
            var a = (from abc in con.Sale where abc.id.Equals(se.id) select abc).FirstOrDefault();

            a.Name       = se.Name;
            a.Price      = se.Price;
            a.Quantity   = se.Quantity;
            a.CustomerId = se.CustomerId;
            a.Category   = se.Category;
            Saleedt(a);
            con.SaveChanges();
            return(RedirectToAction("Salelist", controllerName: "Admin"));
        }
        public HttpResponseMessage saveDraft([FromBody] List <NewDraft> components)
        {
            try
            {
                if (HttpContext.Current.Request.Cookies["sid"] == null)
                {
                    throw new UnauthorizedAccessException("You have to have be logged in to perform this action."); //TODO: strpati ovo u tijelo responsea
                }
                UserInfo userInfo = _authProvider.getAuth(HttpContext.Current.Request.Cookies["sid"].Value);
                int      id       = userInfo.UserId;

                foreach (var value in components)
                {
                    // insert new draft with this type
                    if (value.id == null)
                    {
                        CV_FRAGMENT_TYPE ft = context.CV_FRAGMENT_TYPE.Where(f => f.FRAGMENT_TYPE == value.title).FirstOrDefault();

                        COMPONENTDRAFT cd = new COMPONENTDRAFT();
                        cd.ADDITIONALINFO = value.additionalInfo;
                        cd.USER_ID        = id;
                        cd.APPROVED       = "w";
                        cd.TYPE_ID        = ft.ID;
                        XmlDocument doc = JsonConvert.DeserializeXmlNode(value.data, "root");
                        cd.DATA = doc.OuterXml;

                        /*
                         * CV_XML_FRAGMENT component = new CV_XML_FRAGMENT();
                         * component.FRAGMENT_TYPE = ft.ID;
                         * component.USER_ID = id;
                         * component.XML_DATA = "<empty></empty>";
                         *
                         * context.CV_XML_FRAGMENT.Add(component);
                         * context.SaveChanges();
                         *
                         * cd.COMPONENTID = component.ID;
                         */
                        context.COMPONENTDRAFTs.Add(cd);
                    }
                    // update
                    else
                    {
                        COMPONENTDRAFT draft = context.COMPONENTDRAFTs.FirstOrDefault(c => c.ID == value.id);
                        if (draft == null)
                        {
                            throw new Exception("Draft with specified id does not exist.");
                        }

                        XmlDocument doc = JsonConvert.DeserializeXmlNode(value.data, "root");

                        if (draft.DATA == doc.OuterXml)
                        {
                            continue;
                        }

                        if (value.additionalInfo != "")
                        {
                            draft.ADDITIONALINFO = value.additionalInfo;
                        }

                        draft.APPROVED = "w";

                        draft.DATA = doc.OuterXml;
                    }
                }

                context.SaveChanges();
            }
            catch (UnauthorizedAccessException e)
            {
                return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }
            catch (Exception e)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }

            return(new HttpResponseMessage(HttpStatusCode.Created));
        }