Esempio n. 1
0
        public async Task <ActionResult> Add(FormCollection collection)
        {
            string movieTitle = collection?.GetValue(nameof(AppDAL.pocos.Movies.Title))?.AttemptedValue;

            if (string.IsNullOrWhiteSpace(movieTitle))
            {
                throw new HttpException(400, "Title cannot be empty");
            }

            using (var dbc = new AppDAL.AppDataDbContext())
            {
                dbc.Movies.Add(new AppDAL.pocos.Movies()
                {
                    Title       = movieTitle,
                    Description = collection.GetValue(nameof(AppDAL.pocos.Movies.Description)).AttemptedValue,
                    UserId      = User.Identity.GetUserId()
                });

                try
                {
                    await dbc.SaveChangesAsync();
                }
                catch (Exception ex)
                {
                    throw new HttpException(500, $"Could not save data. {ex.Message}");
                }
            }

            return(View());
        }
        public ActionResult ActualizarPreguntas(FormCollection Formulario)
        {
            CatUsuarios Usuario = (CatUsuarios)Session["Usuario"];

            if (Usuario == null || Usuario.U_IdTipoUsuario != 2)
            {
                TempData["notice"] = "La sesión ha expirado.";
                return(RedirectToAction("Logout", "Home"));
            }


            try
            {
                int IdProyecto = Convert.ToInt32(Formulario.GetValue("IdProyecto"));
                if (IdProyecto > 0)
                {
                    foreach (var item in Formulario)
                    {
                        string[] Cadena = (item.ToString()).Split('_');

                        if (Cadena[0] == "Pregunta")
                        {
                            int  value     = Convert.ToInt32(Formulario[item.ToString()]);
                            bool respuesta = Convert.ToBoolean(value);
                            LogicaProyecto.L_ActualizarProyectoPregunta(IdProyecto, Convert.ToInt32(Cadena[1]), respuesta);
                        }
                    }
                    Session["TipoAlerta"] = "Correcto";
                    TempData["notice"]    = "Las respuestas han sido actualizadas.";
                    return(RedirectToAction("Index"));
                }
                else
                {
                    Session["TipoAlerta"] = "Error";
                    TempData["notice"]    = "No se ha podido identificar el proyecto en el que se cambiarán las respuestas.";
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                Session["TipoAlerta"] = "Error";
                MetodoGeneral.RegistroDeError(ex.Message, "Proyectos: Actualizar Proyecto Preguntas");
                TempData["notice"] = "No se ha podido comprobar que las respuestas se hayan actualizado con éxito.";
                return(RedirectToAction("Index"));
            }
        }
Esempio n. 3
0
 /// <summary>
 /// 从前端请求获取Where字符串
 /// </summary>
 /// <param name="collect"></param>
 /// <returns></returns>
 public static string GetWhere(FormCollection collect)
 {
     string where = "1=1";
     foreach (var key in collect.AllKeys)
     {
         if (key.Equals("X-Requested-With"))
         {
             continue;
         }
         string value = collect.GetValue(key).AttemptedValue;
         if (value.IsNotEmpty())
         {
             where += string.Format(" and {0} like '%{1}%'", key, value.Trim());
         }
     }
     return(where);
 }
        public string updatepackage(FormCollection colection, int groupID)
        {
            var cbids = colection["cbSelect"].Split(',');

            colection.GetValue("cbSelect");
            List <string> lstpackageids = new List <string>();

            foreach (var id in cbids)
            {
                if (id != "false")
                {
                    lstpackageids.Add(id);
                }
            }
            _itemcontainerPartialSrv.updatepackage(lstpackageids, groupID);
            return("Updated Successfully");
        }
Esempio n. 5
0
        /// <summary>
        /// Ensures the recycle bin is appended when required (i.e. user has access to the root and it's not in dialog mode)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        /// <remarks>
        /// This method is overwritten strictly to render the recycle bin, it should serve no other purpose
        /// </remarks>
        protected sealed override ActionResult <TreeNodeCollection> GetTreeNodes(string id, FormCollection queryStrings)
        {
            //check if we're rendering the root
            if (id == Constants.System.RootString && UserStartNodes.Contains(Constants.System.Root))
            {
                var altStartId = string.Empty;

                if (queryStrings.HasKey(TreeQueryStringParameters.StartNodeId))
                {
                    altStartId = queryStrings.GetValue <string>(TreeQueryStringParameters.StartNodeId);
                }

                //check if a request has been made to render from a specific start node
                if (string.IsNullOrEmpty(altStartId) == false && altStartId != "undefined" && altStartId != Constants.System.RootString)
                {
                    id = altStartId;
                }

                var nodesResult = GetTreeNodesInternal(id, queryStrings);
                if (!(nodesResult.Result is null))
                {
                    return(nodesResult.Result);
                }

                var nodes = nodesResult.Value;

                //only render the recycle bin if we are not in dialog and the start id is still the root
                //we need to check for the "application" key in the queryString because its value is required here,
                //and for some reason when there are no dashboards, this parameter is missing
                if (IsDialog(queryStrings) == false && id == Constants.System.RootString && queryStrings.HasKey("application"))
                {
                    nodes?.Add(CreateTreeNode(
                                   RecycleBinId.ToInvariantString(),
                                   id,
                                   queryStrings,
                                   LocalizedTextService.Localize("general", "recycleBin"),
                                   "icon-trash",
                                   RecycleBinSmells,
                                   queryStrings.GetRequiredValue <string>("application") + TreeAlias.EnsureStartsWith('/') + "/recyclebin"));
                }

                return(nodes ?? new TreeNodeCollection());
            }

            return(GetTreeNodesInternal(id, queryStrings));
        }
Esempio n. 6
0
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here
                IStorageService storageService = new AzureStorageService();
                string          accessToken    = storageService.GetAccessToken();
                string          form           = collection.GetValue("upn").AttemptedValue;


                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 7
0
        public void GetValue_KeyExists_ReturnsResult()
        {
            // Arrange
            FormCollection formCollection = new FormCollection()
            {
                { "foo", "1" }, { "foo", "2" }
            };

            // Act
            ValueProviderResult vpResult = formCollection.GetValue("foo");

            // Assert
            Assert.NotNull(vpResult);
            Assert.Equal(new[] { "1", "2" }, (string[])vpResult.RawValue);
            Assert.Equal("1,2", vpResult.AttemptedValue);
            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);
        }
Esempio n. 8
0
        /// <summary>
        /// Return the editor URL for the currrent node depending on the data found in the query strings
        /// </summary>
        /// <param name="id"></param>
        /// <param name="queryStrings"></param>
        /// <returns></returns>
        /// <remarks>
        /// This checks if the tree there is a OnNodeClick handler assigned, if so, it assigns it,
        /// otherwise it checks if the tree is in DialogMode, if it is then it returns an empty handler, otherwise
        /// it sets the Url to the editor's url.
        /// </remarks>
        public string GetEditorUrl(HiveId id, FormCollection queryStrings)
        {
            Mandate.ParameterNotEmpty(id, "id");
            Mandate.ParameterNotNull(queryStrings, "queryStrings");
            Mandate.That <NullReferenceException>(Url != null);

            var isDialog = queryStrings.GetValue <bool>(TreeQueryStringParameters.DialogMode);

            return(queryStrings.HasKey(TreeQueryStringParameters.OnNodeClick)    //has a node click handler?
                       ? queryStrings.Get(TreeQueryStringParameters.OnNodeClick) //return node click handler
                       : isDialog                                                //is in dialog mode without a click handler ?
                             ? "#"                                               //return empty string, otherwise, return an editor URL:
                             : Url.GetEditorUrl(
                       id,
                       EditorControllerId,
                       BackOfficeRequestContext.RegisteredComponents,
                       BackOfficeRequestContext.Application.Settings));
        }
Esempio n. 9
0
        private JsonResult SaveSubscriptionsByUser(FormCollection model)
        {
            int    scheduledId  = Convert.ToInt32(model.GetValue("ScheduledId").AttemptedValue);
            string description  = model.GetValue("Description").AttemptedValue;
            string email        = model.GetValue("Email").AttemptedValue;
            string emailComment = model.GetValue("EmailComment").AttemptedValue;
            int    userid       = model.GetValue("userId").AttemptedValue == string.Empty ? 0 : Convert.ToInt32(model.GetValue("userId").AttemptedValue);
            string subId        = model.GetValue("subId").AttemptedValue;
            int    reportId     = Convert.ToInt32(model.GetValue("ReportId").AttemptedValue);

            try
            {
                if (userid > 0)
                {
                    if (subId == "")
                    {
                        FullAddModel(email, description, emailComment, scheduledId, userid, reportId, model);
                    }
                    else
                    {
                        FullAddModel(email, description, emailComment, scheduledId, userid, reportId, model, Convert.ToInt32(subId));
                    }
                }
                else
                {
                    int partnerId = Convert.ToInt32(Session["partnerId"]);
                    IEnumerable <User> listuser = _repoUser.GetAllUsers(partnerId);
                    foreach (var item in listuser)
                    {
                        if (subId == "")
                        {
                            FullAddModel(email, description, emailComment, scheduledId, item.Id, reportId, model);
                        }
                        else
                        {
                            FullAddModel(email, description, emailComment, scheduledId, item.Id, reportId, model, Convert.ToInt32(subId));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                return(Json(new { success = false, errors = e.Message }, JsonRequestBehavior.AllowGet));
            }

            return(Json(new { success = true }, JsonRequestBehavior.AllowGet));
        }
Esempio n. 10
0
        public ActionResult Edit(int Id, FormCollection collection)
        {
            try
            {
                CategoryModel category = new CategoryModel()
                {
                    id = Id, parentCategoryId = int.Parse(collection.GetValue("parentCategoryId").AttemptedValue), name = collection.GetValue("name").AttemptedValue
                };

                var result = categoryService.UpdateCategory(category);

                return(RedirectToAction("Index"));
            }
            catch
            {
                throw;
                //return View();
            }
        }
        public async Task <ActionResult> SearchByTurnover(FormCollection collection)
        {
            List <Product> _pb   = new List <Product>();
            int            val   = int.Parse(collection.GetValue("turnover").AttemptedValue);
            string         query = collection["filter"].ToString();
            int            temp  = 0;

            if (query == "greaterthan")
            {
                temp = 1;
                _pb  = await Product.searchByTurnover(val, temp);
            }
            else if (query == "lessthan")
            {
                _pb = await Product.searchByTurnover(val, temp);
            }
            ViewBag.ListProducts = _pb;
            return(View("ShowExcelFile"));
        }
Esempio n. 12
0
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                User user = new User()
                {
                    Id = 1, Name = "John"
                };                                                //Use Identity to get user
                Album album = new Album(user, collection.GetValue("Test").ToString());

                var status = _servicefacade.CreateAlbum(album);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Esempio n. 13
0
        public ActionResult ManagerMark(FormCollection collection)
        {
            try
            {
                string sswitch = Request.Form["switch"];

                IList <CLogMarkInfo> result = TempData["infos"] as IList <CLogMarkInfo>;
                TempData["infos"] = result;

                string[]    stringsplit = collection.GetValue("Guid").AttemptedValue.Split(',');
                List <uint> ls          = new List <uint>();
                foreach (var item in stringsplit)
                {
                    if (0 == item.CompareTo("false") || 0 == item.CompareTo("true"))
                    {
                    }
                    else
                    {
                        ls.Add(uint.Parse(item));
                    }
                }
                if (ls.Count == 0)
                {
                    return(RedirectToAction("ListInfos"));
                }

                if (null != sswitch)
                {
                    CLog_WuQi log = CLog_WuQi.GetLog();
                    foreach (var item in ls)
                    {
                        log.ChangeMarkState((int)item);
                    }
                }

                return(RedirectToAction("ListInfos"));
            }
            catch (System.Exception e)
            {
                ViewData["msg"] = CExceptionContainer_WuQi.ProcessException(e);
                return(View("Error"));
            }
        }
Esempio n. 14
0
        public ActionResult filter(FormCollection fc)
        {
            productList newPD = new productList(new unitOfWork(new KEY_TeamMVCEntities()));

            newPD.setSubcategoryID(listEngine.getSubcategoryID());
            int    startYear;
            string syear = fc.GetValue("startYear").AttemptedValue;

            if (fc.GetValue("startYear").AttemptedValue != "" && Convert.ToInt32(fc.GetValue("startYear").AttemptedValue) != 0)
            {
                startYear = Convert.ToInt32(fc.GetValue("startYear").AttemptedValue);
            }
            else
            {
                startYear = 0;
            }
            int endYear;// = Convert.ToInt32(fc.GetValue("endYear").AttemptedValue);

            if (fc.GetValue("endYear").AttemptedValue != "" && Convert.ToInt32(fc.GetValue("endYear").AttemptedValue) != 0)
            {
                endYear = Convert.ToInt32(fc.GetValue("endYear").AttemptedValue);
            }
            else
            {
                endYear = 0;
            }
            List <string> propertyList = listEngine.getFilterProperties();

            if (startYear != 0 && endYear != 0 && endYear >= startYear)
            {
                newPD.tsfilter.Add("ModelYear", new int[] { startYear, endYear });
            }
            for (int i = 1; i <= propertyList.Count; i++)
            {
                newPD.tsfilter.Add(propertyList[i - 1], new int[] { Convert.ToInt32(fc.GetValue("minAmount_" + i.ToString()).AttemptedValue), Convert.ToInt32(fc.GetValue("maxAmount_" + i.ToString()).AttemptedValue) });
            }
            newPD.setDisplayList(newPD.getProductsByFilter(newPD.getSubcategoryID(), (Dictionary <string, int[]>)newPD.tsfilter));
            TempData["outputList"] = newPD;
            return(RedirectToAction("list", "Product"));
        }
Esempio n. 15
0
        public ActionResult Details(int id, FormCollection formCollection)
        {
            int entrepreneur_id = 0;
            int investor_id     = 0;

            if (Session["Entrepreneur_Id"] != null)
            {
                entrepreneur_id = int.Parse(Session["Entrepreneur_Id"].ToString());
            }
            if (Session["Investor_Id"] != null)
            {
                investor_id = int.Parse(Session["Investor_Id"].ToString());
            }
            Dictionary <string, string> objDict = new Dictionary <string, string>();

            foreach (string key in formCollection)
            {
                objDict.Add(key, formCollection.GetValue(key).AttemptedValue);
            }

            // Hackey fix for the acceptance of the proc
            if (objDict.ContainsKey("User_Accepts_PROC"))
            {
                if (objDict["User_Accepts_PROC"] == "True" || objDict["User_Accepts_PROC"] == "False")
                {
                    objDict.Remove("User_Accepts_PROC");
                }
            }
            else if (!objDict.ContainsKey("User_Accepts_PROC"))
            {
                objDict.Add("User_Accepts_PROC", "off");
            }
            if (new ServiceReference1.Service1Client().update_PROC(id, objDict, entrepreneur_id, investor_id))
            {
                return(Redirect(string.Format("/PROC/Details/{0}", id)));
            }
            else
            {
                // do something i guess.
                return(Redirect(string.Format("/PROC/Details/{0}", id)));
            }
        }
Esempio n. 16
0
        public ActionResult DeleteProfiles(FormCollection form)
        {
            var deletedList = new List <int>();

            foreach (var key in form.AllKeys.Where(x => x.StartsWith("IsSelected-")))
            {
                if ((bool)form.GetValue(key).ConvertTo(typeof(bool)))
                {
                    var profileId = 0;
                    if (int.TryParse(key.Replace("IsSelected-", ""), out profileId))
                    {
                        deletedList.Add(profileId);
                    }
                }
            }

            if (deletedList.Count > 0)
            {
                var profileBoxes = _profileBoxService.GetProfileBoxByIds(deletedList);


                foreach (var p in profileBoxes)
                {
                    if (p.StatusId != (short)ABO.Core.ProfileBoxStatus.NeedToDiscard)
                    {
                        ErrorNotification(_resourceManager.GetString("ProfileBox.DiscardError"));
                        return(Redirect(Request.RawUrl));
                    }
                }
                try
                {
                    _profileBoxService.DeleteProfileBoxs(deletedList);
                    SuccessNotification(_resourceManager.GetString("Profile.SuccessToDeleteProfileBoxes"));
                }
                catch (Exception ex)
                {
                    _logger.WriteLog("Failed to delete profiles.", ex);
                    ErrorNotification(_resourceManager.GetString("Profile.FailedToDeleteProfileBoxes"));
                }
            }
            return(Redirect(Request.RawUrl));
        }
Esempio n. 17
0
        public ViewResult NhomNguoiDung(string id, FormCollection forms)
        {
            int MaNhomNguoiDung         = int.Parse(forms.GetValue("ListNhomNguoiDung").AttemptedValue.ToString());
            ChiTietNhomNguoiDung nhomND = new ChiTietNhomNguoiDung();

            nhomND.MaNhomNguoiDung = MaNhomNguoiDung;
            nhomND.Username        = id;
            nhomND.MoTa            = "ko co j";
            List <ChiTietNhomNguoiDung> listNhom = db.ChiTietNhomNguoiDungs.Where(a => a.Username.Trim() == id.Trim()).Where(a => a.MaNhomNguoiDung == MaNhomNguoiDung).ToList();

            if (listNhom != null && listNhom.Count == 0)
            {
                db.ChiTietNhomNguoiDungs.Add(nhomND);
                db.SaveChanges();
            }
            TaiKhoan taikhoan = db.TaiKhoans.Find(id);

            ViewBag.NhomNguoiDung = db.NhomNguoiDungs.ToList();
            return(View(taikhoan));
        }
Esempio n. 18
0
        public ActionResult compareProducts(FormCollection fc)
        {
            //listEngine = TempData["outputList"] as productList;
            productCompare    pc   = new productCompare(new unitOfWork(new KEY_TeamMVCEntities()));
            List <tblProduct> list = new List <tblProduct>();

            //var id1 = fc.GetValue("product1").AttemptedValue;
            //var id2 = fc.GetValue("product2").AttemptedValue;
            //var id3 = fc.GetValue("product3").AttemptedValue;
            foreach (var product in productList)
            {
                if (fc.GetValue("product" + product.ID).AttemptedValue.Contains("true"))
                {
                    list.Add(pc.getUOW().getProductRepo().get(product.ID));
                }
            }
            pc.setCompareList(list);
            TempData["compareList"] = pc;
            return(RedirectToAction("compare", "Compare"));
        }
Esempio n. 19
0
        public ActionResult Solve(FormCollection fc)
        {
            AbstractAlgorithm algorithm = null;

            switch (fc.GetValue("Algorithm").AttemptedValue)
            {
            case "KernighanLin":
                GraphProblemDb.CurrentProblem.Algorithm = Algorithm.KernighanLin;
                algorithm = new KernighanLin();
                GraphProblemDb.CurrentProblem = algorithm.FindCommunityStructure(GraphProblemDb.CurrentProblem.Graph);
                break;

            case "GirvanNewman":
                GraphProblemDb.CurrentProblem.Algorithm = Algorithm.GirvanNewman;
                algorithm = new GirvanNewman();
                GraphProblemDb.CurrentProblem = algorithm.FindCommunityStructure(GraphProblemDb.CurrentProblem.Graph);
                break;
            }
            return(RedirectToAction("GraphListResult", "GraphListResult", GraphProblemDb.CurrentProblem));
        }
Esempio n. 20
0
        public ActionResult AddToCart(int id, FormCollection fc)
        {
            int quantity;

            if (fc.GetValue("quantity") != null)
            {
                quantity = Int32.Parse(fc["quantity"]);
            }
            else
            {
                quantity = 1;
            }
            using (DemirStoreDBEntities dbModel = new DemirStoreDBEntities())
            {
                if (Session["cart"] == null)
                {
                    List <ShoppingCart> cart    = new List <ShoppingCart>();
                    tblProduct          product = dbModel.tblProduct.Find(id);
                    if (product.Stock > 0 && quantity < product.Stock)
                    {
                        cart.Add(new ShoppingCart(dbModel.tblProduct.Find(id), quantity));
                        Session["cart"] = cart;
                    }
                }
                else
                {
                    List <ShoppingCart> cart = (List <ShoppingCart>)Session["cart"];
                    int index = isExisting(id);
                    if (index == -1)
                    {
                        cart.Add(new ShoppingCart(dbModel.tblProduct.Find(id), quantity));
                    }
                    else
                    {
                        cart[index].Quantity = cart[index].Quantity + quantity;
                    }
                    Session["cart"] = cart;
                }
                return(View("Cart"));
            }
        }
Esempio n. 21
0
        public ActionResult Edit(AdminEditPageViewModel vm, FormCollection forms, string userName)
        {
            CmsPage pageFromDb = pageService.Load(vm.Page.Id);

            // workaround: update status should be before update model. It's because of defect in asp.net mvc 2
            UpdatePageStatus(pageFromDb, forms.ToValueProvider());
            UpdateModel(pageFromDb, "Page", forms.ToValueProvider());
            pageFromDb.TagString = forms.GetValue("Tags");
            if (pageFromDb.IsValid)
            {
                pageService.Save(pageFromDb, userName);
                TempData["SuccessResult"] = "Items was successfully saved";
                return(RedirectToAction("Edit", new { id = pageFromDb.Id }));
            }

            ModelState.AddModelErrors(pageFromDb.GetRuleViolations());

            return(View(new AdminEditPageViewModel {
                Page = pageFromDb, PageStatuses = GetStatuses()
            }));
        }
Esempio n. 22
0
        public ActionResult InventorySetter(FormCollection forms)
        {
            int SaleID = int.Parse(Request["SaleID"]);

            foreach (string category in forms.AllKeys)
            {
                double qty = double.Parse(forms.GetValue(category)
                                          .AttemptedValue);
                int parse = 0;
                if (int.TryParse(category, out parse))
                {
                    CreateDailyStock(SaleID, parse, qty); //add to db
                }
            }
            var sale = GetDatedSale(SaleID);

            sale.IsInventorySet = true;

            db.SaveChanges();
            return(DetermineSaleDay(sale));
        }
Esempio n. 23
0
 public void SaveBanner(FormCollection form, string fileName, ResultObject result_object)
 {
     this.Model.page_id   = Convert.ToInt32(form.GetValue("page_id").AttemptedValue);
     this.Model.banner_id = Convert.ToInt32(form.GetValue("banner_id").AttemptedValue);
     if (form.GetValue("header_text") != null)
     {
         this.Model.headertext = string.IsNullOrEmpty(form.GetValue("header_text").AttemptedValue) ? "" : form.GetValue("header_text").AttemptedValue;
     }
     if (form.GetValue("sub_text") != null)
     {
         this.Model.subtext = string.IsNullOrEmpty(form.GetValue("sub_text").AttemptedValue) ? "" : form.GetValue("sub_text").AttemptedValue;
     }
     this.Model.image_url    = fileName;
     result_object.ipAddress = Dns.GetHostByName(Dns.GetHostName()).AddressList[0].ToString();
     _pageAction_BL.SaveBanner(this.Model, result_object);
 }
Esempio n. 24
0
        public ActionResult ManagerException(FormCollection collection)
        {
            string sdelete = Request.Form["delete"];

            if (null != sdelete)
            {
                CExceptionContainer_WuQi.ClearInfos();
                IList <CExceptionInfo_WuQi> elist = CExceptionContainer_WuQi.GetInfos();
                if (null != elist)
                {
                    TempData["infos"] = elist;
                    return(RedirectToAction("Exceptioninfos"));
                }
            }
            IList <CExceptionInfo_WuQi> result = TempData["infos"] as IList <CExceptionInfo_WuQi>;

            TempData["infos"] = result;

            string[]   stringsplit = collection.GetValue("Guid").AttemptedValue.Split(',');
            List <int> ls          = new List <int>();

            foreach (var item in stringsplit)
            {
                if (0 == item.CompareTo("false") || 0 == item.CompareTo("true"))
                {
                }
                else
                {
                    ls.Add(int.Parse(item));
                }
            }
            if (ls.Count == 0)
            {
                return(RedirectToAction("Exceptioninfos"));
            }



            return(RedirectToAction("Exceptioninfos"));
        }
Esempio n. 25
0
        public ActionResult AccessEditor(Guid?RoleID, FormCollection collection)
        {
            var pages =
                collection.GetValue("PageListPlain")
                .AttemptedValue.Split <int>(";")
                .Where(x => x > 0)
                .Select(x => CMSPage.FullPageTable.FirstOrDefault(z => z.ID == x))
                .Where(x => x != null).ToList();


            var pagesIdsForAdd = pages.SelectMany(x => x.FullChildrenList).Union(pages.Select(x => x.ID)).ToList();
            var pagesIdsForDel = CMSPage.FullPageTable.Select(x => x.ID).Except(pagesIdsForAdd);

            var roleID = (RoleID == new Guid() ? null : RoleID);

            var relsForDel =
                db.CMSPageRoleRels.Where(
                    x => pagesIdsForDel.Contains(x.PageID) && (roleID == null ? !x.RoleID.HasValue : x.RoleID == roleID));

            db.CMSPageRoleRels.DeleteAllOnSubmit(relsForDel);
            db.SubmitChanges();

            foreach (var id in pagesIdsForAdd)
            {
                var rel =
                    db.CMSPageRoleRels.FirstOrDefault(
                        x => x.PageID == id && (roleID == null ? !x.RoleID.HasValue : x.RoleID == roleID));
                if (rel == null)
                {
                    rel = new CMSPageRoleRel()
                    {
                        PageID = id, RoleID = roleID
                    };
                    db.CMSPageRoleRels.InsertOnSubmit(rel);
                }
            }
            db.SubmitChanges();
            ModelState.AddModelError("", "Данные сохранены");
            return(AccessEditor(roleID));// RedirectToAction("AccessEditor", new { RoleID = roleID });
        }
        public ActionResult Index(FormCollection formCollection)
        {
            Dictionary <string, string> objDict = new Dictionary <string, string>();

            foreach (string key in formCollection)
            {
                objDict.Add(key, formCollection.GetValue(key).AttemptedValue);
            }
            string user_id = HttpContext.GetOwinContext().Authentication.User.FindFirst(ClaimTypes.Sid).Value;
            int    ent_id  = int.Parse(Session["Entrepreneur_Id"].ToString());

            if (objDict.ContainsKey("Project_Name") && objDict.ContainsKey("Project_Description") && objDict.ContainsKey("Investment_Amount"))
            {
                int project_id = new ServiceReference1.Service1Client().create_Project(user_id, ent_id, objDict);
                return(Redirect(string.Format("/Project/Index/{0}", project_id)));
            }
            else
            {
                ModelState.AddModelError("Project_Create_error", new Exception("Failed to include a project name a project description or an investment ammount"));
                return(View(new Models.EntrepreneurIndexModel(user_id, ent_id)));
            }
        }
Esempio n. 27
0
        public static void CreateRecord <T>(FormCollection form, T myClass)
        {
            PropertyInfo[] propertyInfos = typeof(T).GetProperties();

            foreach (PropertyInfo propertyInfo in propertyInfos)
            {
                for (int i = 0; i < form.AllKeys.Count(); i++)
                {
                    if (propertyInfo.Name == form.AllKeys.ElementAt(i))
                    {
                        System.Type type = propertyInfo.GetType();

                        object[] ob = (object[])form.GetValue(form.AllKeys.ElementAt(i)).RawValue;

                        object convrt = Convert.ChangeType(ob[0], propertyInfo.PropertyType);

                        propertyInfo.SetValue(myClass, convrt, null);
                        break;
                    }
                }
            }
        }
Esempio n. 28
0
        public ContentResult Delete(FormCollection form)
        {
            JObject json = new JObject();

            json["error"]   = false;
            json["message"] = "";

            string[] keys = new string[] { "id" };

            if (!this.CheckLogin(AccountType.Applicant) &&
                ((Employee)this.GetAccount().Profile).Department.Type == DepartmentType.HumanResources)
            {
                if (this.HasValues(form, keys))
                {
                    try
                    {
                        JobPosting post = new JobPosting(Int32.Parse(form.GetValue("id").AttemptedValue));
                        post.Delete();
                    }
                    catch (Exception e)
                    {
                        json["error"]   = true;
                        json["message"] = e.Message;
                    }
                }
                else
                {
                    json["error"]   = true;
                    json["message"] = "Missing Job Posting ID";
                }
            }
            else
            {
                json["error"]   = true;
                json["message"] = "You are not authorized to continue";
            }

            return(Content(json.ToString(), "application/json"));
        }
Esempio n. 29
0
        /// <summary>
        /// Helper method to create a root model for a tree
        /// </summary>
        /// <returns></returns>
        protected virtual TreeNode CreateRootNode(FormCollection queryStrings)
        {
            var jsonUrl  = Url.GetTreeUrl(GetType(), RootNodeId, queryStrings);
            var isDialog = queryStrings.GetValue <bool>(TreeQueryStringParameters.DialogMode);
            var node     = new TreeNode(RootNodeId, BackOfficeRequestContext.RegisteredComponents.MenuItems, jsonUrl)
            {
                HasChildren = true,
                EditorUrl   = queryStrings.HasKey(TreeQueryStringParameters.OnNodeClick)      //has a node click handler?
                                    ? queryStrings.Get(TreeQueryStringParameters.OnNodeClick) //return node click handler
                                    : isDialog                                                //is in dialog mode without a click handler ?
                                          ? "#"                                               //return empty string, otherwise, return an editor URL:
                                          : Url.GetCurrentDashboardUrl(),
                Title = NodeDisplayName
            };

            //add the tree id to the root
            node.AdditionalData.Add("treeId", TreeId.ToString("N"));

            //add the tree-root css class
            node.Style.AddCustom("tree-root");

            //node.AdditionalData.Add("id", node.HiveId.ToString());
            //node.AdditionalData.Add("title", node.Title);

            // Add additional data
            foreach (var key in queryStrings.AllKeys)
            {
                node.AdditionalData.Add(key, queryStrings[key]);
            }

            //check if the tree is searchable and add that to the meta data as well
            if (this is ISearchableTree)
            {
                node.AdditionalData.Add("searchable", "true");
            }

            return(node);
        }
Esempio n. 30
0
        public ActionResult Index(FormCollection form)
        {
            if (form != null)
            {
                var filterBy = form.GetValue("filterBy");

                if (filterBy != null)
                {
                    int temp = (int)filterBy.ConvertTo(typeof(int));
                    if (temp != 0)
                    {
                        ViewBag.centreDeSkis = uow.CentreDeSkiRepository.Get(filter: x => x.RegionID == temp && x.Region.SkieurID == uow.CurrentUserID).OrderBy(x => x.Nom);
                        ViewBag.RegionID     = temp;
                    }
                    else
                    {
                        ViewBag.centreDeSkis = uow.CentreDeSkiRepository.GetForSkieur(uow.CurrentUserID).OrderBy(x => x.Nom);
                        ViewBag.RegionID     = temp;
                    }
                }
                else
                {
                    ViewBag.centreDeSkis = uow.CentreDeSkiRepository.GetForSkieur(uow.CurrentUserID).OrderBy(x => x.Nom);
                    ViewBag.RegionID     = 0;
                }
            }
            else
            {
                ViewBag.centreDeSkis = uow.CentreDeSkiRepository.GetForSkieur(uow.CurrentUserID).OrderBy(x => x.Nom);
                ViewBag.RegionID     = 0;
            }

            ViewBag.sorties = uow.SortieRepository.GetForSkieur(uow.CurrentUserID);
            ViewBag.saisons = uow.SaisonRepository.GetForSkieur(uow.CurrentUserID).OrderBy(x => x.AnneeDebutSaison);
            ViewBag.regions = uow.RegionRepository.GetForSkieur(uow.CurrentUserID);

            return(View());
        }
        public void GetValue_KeyDoesNotExist_ReturnsNull()
        {
            // Arrange
            FormCollection formCollection = new FormCollection();

            // Act
            ValueProviderResult vpResult = formCollection.GetValue("");

            // Assert
            Assert.Null(vpResult);
        }
        public void GetValue_KeyExists_ReturnsResult()
        {
            // Arrange
            FormCollection formCollection = new FormCollection()
            {
                { "foo", "1" },
                { "foo", "2" }
            };

            // Act
            ValueProviderResult vpResult = formCollection.GetValue("foo");

            // Assert
            Assert.NotNull(vpResult);
            Assert.Equal(new[] { "1", "2" }, (string[])vpResult.RawValue);
            Assert.Equal("1,2", vpResult.AttemptedValue);
            Assert.Equal(CultureInfo.CurrentCulture, vpResult.Culture);
        }
        public void GetValue_ThrowsIfNameIsNull()
        {
            // Arrange
            FormCollection formCollection = new FormCollection();

            // Act & assert
            Assert.ThrowsArgumentNull(
                delegate { formCollection.GetValue(null); }, "name");
        }