Example #1
0
        public JsonResult SaveRoles(FormCollection form)
        {
            var usr = Membership.GetUser(form[1]);
            int count;

            if (usr != null && Int32.TryParse(form[0], out count))
            {
                count += 2;
                for (int i = 2; i < count; i++)
                {
                    if (form[i].Equals("true", StringComparison.InvariantCultureIgnoreCase))
                    {
                        if (!Roles.IsUserInRole(usr.UserName, form.GetKey(i)))
                        {
                            Roles.AddUserToRole(usr.UserName, form.GetKey(i));
                        }
                    }
                    else
                    {
                        if (Roles.IsUserInRole(usr.UserName, form.GetKey(i)))
                        {
                            Roles.RemoveUserFromRole(usr.UserName, form.GetKey(i));
                        }
                    }
                }
                return(Json(true));
            }
            return(Json(false));
        }
Example #2
0
        public ActionResult AddToRow(FormCollection fc)
        {
            using (TrailerEntities db = new TrailerEntities())
            {
                string[] input       = fc.AllKeys;
                var      locationID  = fc["locationNumber"];
                var      rowNumber   = Convert.ToInt32(fc["rowNumber"]);
                var      partNumbers = fc["partNumbers"].Split(',');

                List <string> uniquePartNumbers = new List <string>();
                foreach (var part in partNumbers)
                {
                    if (!uniquePartNumbers.Contains(part))
                    {
                        uniquePartNumbers.Add(part);
                    }
                }

                var location = db.ActiveLocationRows.FirstOrDefault(r => r.LocationNumber == locationID && r.RowNumber == rowNumber);
                location.NumberOfPartNumbers = uniquePartNumbers.Count;
                location.NumberOfStacks      = 0;
                location.PalletCount         = 0;

                var stacks = db.InventoryRowStacks.Where(s => s.InventoryRowGUID == location.InventoryRowGUID);
                foreach (InventoryRowStack stack in stacks)
                {
                    db.InventoryRowStacks.Remove(stack);
                }

                for (var x = 3; x < fc.Count; x++)
                {
                    var key         = fc.GetKey(x);
                    var dashIndex   = Convert.ToInt32(key.IndexOf('-'));
                    var partIndex   = Convert.ToInt32(key.Substring(0, dashIndex)) - 1;
                    var stackNumber = Convert.ToInt32(key.Substring((dashIndex + 1), (key.Length - 1 - dashIndex)));

                    var quantity = Convert.ToInt32(fc[key]);
                    location.PalletCount += quantity;

                    InventoryRowStack newStack = new InventoryRowStack()
                    {
                        InventoryRowGUID = location.InventoryRowGUID,
                        PartNumber       = partNumbers[partIndex],
                        StackQuantity    = quantity,
                        StackNumber      = stackNumber,
                    };

                    db.InventoryRowStacks.Add(newStack);
                }
                var lastStack     = fc.GetKey(fc.Count - 1);
                var lastDashIndex = lastStack.IndexOf('-');
                var totalStacks   = Convert.ToInt32(fc.GetKey(fc.Count - 1).Substring(lastDashIndex + 1, (lastStack.Length - 1 - lastDashIndex)));
                location.NumberOfStacks = totalStacks;

                db.SaveChanges();
                return(RedirectToAction(actionName: "ActiveLocationRows", controllerName: "Inventory", routeValues: new { locationID }));
            }
        }
Example #3
0
        public ActionResult Index(FormCollection us)
        {
            var st = us.GetKey(1);

            FC = us;
            if (st.CompareTo("Create") != 0)
            {
                var client = new MvcUniJudje.WebReference.ServiceForAdmin();
                MvcUniJudje.WebReference.UserDTO[] UDTO = client.GetUsers(Session["session_key"].ToString());
                int ij = 0;
                for (int i = 0, j = 0; i < UDTO.Count() & j < 100; i++, j++)
                {
                    var s = FC[(UDTO[i].Id.ToString())].Remove(2);
                    if (s.Equals("tr"))
                    {
                        ij++;
                    }
                }
                if (ij == 0)
                {
                    ModelState.AddModelError("Create", "Не выбраны пользователи.");
                }

                if (ModelState.IsValid)
                {
                    return(RedirectToAction(st));
                }
                return(View(Enumerable.Range(0, UDTO.Length).Select(i => new User {
                    ID = UDTO[i].Id, Name = UDTO[i].Name, Login = UDTO[i].Login, Locking = (UDTO[i].BlockedTo != null ? true : false), Date = UDTO[i].BlockedTo, DateRegistration = UDTO[i].DateRegistration
                })));
            }
            return(RedirectToAction(st));
        }
Example #4
0
        public async Task <ActionResult> Nuevo(FormCollection collection)
        {
            string fk_rol = Request.Form["fkrol"];

            var contador = collection.Count;
            int i        = 2; // lo dejo en 2 para que no recorra el token y el rol que llegan el array.

            while (i < contador)
            {
                string keyNombre = collection.GetKey(i);

                if (keyNombre.Substring(0, 3) == "mod")
                {
                    var KeyValor = collection.Get(i);
                    //var crea = String.Concat("select " + Request.Form["prcrea[0_" + KeyValor + "]"]);
                    var crea     = (Request.Form["prcrea[0_" + KeyValor + "]"] != null)? "true":"false";
                    var modifica = (Request.Form["prmodifica[0_" + KeyValor + "]"] != null)? "true":"false";
                    var elimina  = (Request.Form["prelimina[0_" + KeyValor + "]"] != null)? "true":"false";
                    db.SP_Insert_Nivel_Permiso_Modulo(fk_rol, KeyValor, crea, modifica, elimina);
                    await db.SaveChangesAsync();
                }

                i++;
            }

            return(View());
        }
        public ActionResult Index(FormCollection us)
        {
            var st = us.GetKey(0);

            FC = us;
            if (st.CompareTo("Create") != 0)
            {
                var client = new MvcUniJudje.WebReference.ServiceForAdmin();
                MvcUniJudje.WebReference.GroupDTO[] GDTO = client.GetAllGroups(Session["session_key"].ToString());
                int ij = 0;
                for (int i = 0; i < GDTO.Count(); i++)
                {
                    var s = FC[(GDTO[i].Id.ToString())].Remove(2);
                    if (s.Equals("tr"))
                    {
                        ij++;
                    }
                }
                if (ij == 0)
                {
                    ModelState.AddModelError("UnSelectGroup", "Не выбраны группы.");
                }

                if (ModelState.IsValid)
                {
                    return(RedirectToAction(st));
                }
                return(View(GDTO));
            }
            return(RedirectToAction(st));
        }
Example #6
0
 public ActionResult blogedit(FormCollection fc, int BlogID)
 {
     for (int i = 1; i < fc.AllKeys.Length; i++)
     {
         string key   = fc.GetKey(i);
         string value = fc.Get(key);
         if (value.Trim().Equals(""))
         {
             return(Content("<script>alert('" + key + "不能为空,请重新输入!');window.open('" + Url.Content("~/UserBlog/seeblogdetails?BlogID=" + BlogID + "") + "', '_self')</script>"));
         }
     }
     try
     {
         Models.Blog editblog = db.Blogs.Find(BlogID);
         editblog.BlogTitle       = fc["title"];
         editblog.BlogContent     = fc["editor"];
         editblog.Classification  = fc["classification"];
         editblog.ModifyTime      = DateTime.Now;
         db.Entry(editblog).State = EntityState.Modified;
         db.SaveChanges();
     }
     catch (Exception e)
     {
         return(Content("<script>alert('修改过程好像有点问题!');window.open('" + Url.Content("~/UserBlog/seeblogdetails?BlogID=" + BlogID + "") + "', '_self')</script>"));
     }
     return(Content("<script>alert('修改成功');window.open('" + Url.Content("~/UserBlog/seeblogdetails?BlogID=" + BlogID + "") + "', '_self')</script>"));
 }
Example #7
0
        public ActionResult AddReport(FormCollection model)
        {
            var reportmodel = new Report();

            reportmodel.id_product    = model.GetValue(model.GetKey(1)).AttemptedValue;
            reportmodel.Email_send    = model.GetValue(model.GetKey(3)).AttemptedValue;
            reportmodel.Notes         = model.GetValue(model.GetKey(4)).AttemptedValue;
            reportmodel.Status_report = Status.Status_Contact.E_Waitting.ToString();
            var Db      = new Model1();
            var product = Db.products.FirstOrDefault(s => s.ID == reportmodel.id_product);

            reportmodel.products = product;
            Db.Report.Add(reportmodel);
            Db.SaveChanges();
            return(RedirectToAction("ReportSuccess"));
        }
Example #8
0
        public ActionResult NewItem(FormCollection coleccion)
        {
            var cuantos   = coleccion.Count;
            var idHosp    = Convert.ToInt32(coleccion.Get(0));
            var inicio    = Utilidades.DiasHoras.TimeToDecimal(coleccion.Get(cuantos - 4));
            var fin       = Utilidades.DiasHoras.TimeToDecimal(coleccion.Get(cuantos - 3));
            var paralelas = Convert.ToInt32(coleccion.Get(cuantos - 2));
            var porhora   = Convert.ToInt32(coleccion.Get(cuantos - 1));

            for (var i = 1; i < cuantos - 4; i++)
            {
                var turno = new Turno
                {
                    idHospital = idHosp,
                    dia        = Convert.ToInt32(coleccion.GetKey(i)),
                    inicio     = inicio,
                    fin        = fin,
                    paralelas  = paralelas,
                    porhora    = porhora
                };

                DbContext.Turno.Add(turno);
            }
            DbContext.SaveChanges();

            return(RedirectToAction("index"));
        }
        public List <IncomingCourierDetailsVM> GetCourierDetails(FormCollection fc, Guid companyId)
        {
            List <IncomingCourierDetailsVM> incomingCourierDetailsVMLst = new List <IncomingCourierDetailsVM>();
            int rowId = 0;

            for (int f = 0; f < fc.Count; f++)
            {
                string currentKey = fc.GetKey(f);
                if (currentKey.Contains("Date_" + rowId))
                {
                    IncomingCourierDetailsVM incomingCourierDetailsVM = new IncomingCourierDetailsVM();
                    incomingCourierDetailsVM.CompanyID       = companyId;
                    incomingCourierDetailsVM.Date            = DateTime.Parse(fc["Date_" + rowId]);
                    incomingCourierDetailsVM.SINo            = (fc["SINo_" + rowId]);
                    incomingCourierDetailsVM.Remarks         = fc["Remarks_" + rowId];
                    incomingCourierDetailsVM.DocDetail       = fc["DocDetail_" + rowId];
                    incomingCourierDetailsVM.FileName        = (fc["FileName_" + rowId]);
                    incomingCourierDetailsVM.FilePath        = (fc["FilePath_" + rowId]);
                    incomingCourierDetailsVM.MasterID        = Convert.ToInt32((fc["MasterID_" + rowId]));
                    incomingCourierDetailsVM.Qty             = Convert.ToDecimal(fc["Qty_" + rowId]);
                    incomingCourierDetailsVM.RefNo           = (fc["RefNo_" + rowId]);
                    incomingCourierDetailsVM.ArraySubItem    = fc["arraySubItem_" + rowId];
                    incomingCourierDetailsVM.IsSubDetail     = false;
                    incomingCourierDetailsVM.ParentDetailsID = 0;
                    incomingCourierDetailsVM.CreatedBy       = 12;
                    incomingCourierDetailsVM.CreationDate    = DateTime.Now;
                    incomingCourierDetailsVM.UpdatedBy       = 12;
                    incomingCourierDetailsVM.UpdatedDate     = DateTime.Now;
                    incomingCourierDetailsVM.SubDetails      = GetSubDetails(incomingCourierDetailsVM);
                    incomingCourierDetailsVMLst.Add(incomingCourierDetailsVM);
                }
                rowId++;
            }
            return(incomingCourierDetailsVMLst);
        }
Example #10
0
        public ActionResult Write(Models.Blog blog, FormCollection fc)
        {
            for (int i = 1; i < fc.AllKeys.Length; i++)
            {
                string key   = fc.GetKey(i);
                string value = fc.Get(key);
                if (value.Trim().Equals(""))
                {
                    return(Content("<script>alert('" + key + "不能为空,请重新输入!');window.open('" + Url.Content("~/User/Write") + "', '_self')</script>"));
                }
            }

            try
            {
                blog.BlogTitle      = fc["title"];
                blog.BlogContent    = fc["editor"];
                blog.Classification = fc["classification"];
                blog.BloggerID      = Session["UserID"].ToString();
                blog.CreateTime     = DateTime.Now;
                blog.ModifyTime     = DateTime.Now;
                db.Blogs.Add(blog);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                return(Content("<script>alert('输入好像有点问题!');window.open('" + Url.Content("~/User/Write") + "', '_self')</script>"));
            }
            return(Content("<script>alert('发表成功');window.open('" + Url.Content("~/User/Index") + "', '_self')</script>"));
        }
Example #11
0
 public ActionResult Password(Pass pass, FormCollection us)
 {
     if (us.GetKey(1) == "Show")
     {
         if (pass.Key == "" || pass.Key == null)
         {
             ModelState.AddModelError("Password", "Введите ключ");
         }
         if (ModelState.IsValid)
         {
             var client = new MvcUniJudje.WebReference.ServiceForAdmin();
             MvcUniJudje.Models.Login log = new MvcUniJudje.Models.Login();
             if (client.GetUserPassword(Session["session_key"].ToString(), pass.id, true, pass.Key).IsNormalized())
             {
                 ModelState.AddModelError("Password", "Некорректный ключ");
             }
             else
             {
                 ViewBag.Password = client.GetUserPassword(Session["session_key"].ToString(), pass.id, true, pass.Key);
             }
         }
     }
     else
     if (us.GetKey(0) == "NewPass")
     {
         var client = new MvcUniJudje.WebReference.ServiceForAdmin();
         MvcUniJudje.Models.Login log = new MvcUniJudje.Models.Login();
         ViewBag.NewPassword = client.GenerateNewUserPassword(Session["session_key"].ToString(), pass.id, true);
     }
     else
     if (us.GetKey(1) == "NewPassSave")
     {
         var client = new MvcUniJudje.WebReference.ServiceForAdmin();
         MvcUniJudje.Models.Login log = new MvcUniJudje.Models.Login();
         var s = us["passwo"].Trim();
         if (s.Length >= 6)
         {
             client.SendPasswordOnEmail(Session["session_key"].ToString(), s, pass.id, true);
             return(RedirectToAction("Index"));
         }
         ViewBag.NewPassword = s;
         ModelState.AddModelError("Password", "Пароль должен быть не менее 6 символов");
     }
     return(View(pass));
 }
Example #12
0
        public ActionResult Remove(FormCollection form) {
            if (!Services.Authorizer.Authorize(Orchard.Themes.Permissions.ApplyTheme, T("Cannot manage themes")))
                return new HttpUnauthorizedResult();

            var id = int.Parse(form.GetKey(0).Substring(1));
            _settingsService.Remove(id);

            return RedirectToAction("Index");
        }
Example #13
0
        //genera la lista con lo roles asignados al usuario
        private List <RolUsuario> addRolUsuario(FormCollection form, string UsuarioId)
        {
            List <RolUsuario> RolUsuarioList = new List <RolUsuario>();

            for (int i = 1; i < form.Count; i++)
            {
                int  RolId;
                bool flagrol = int.TryParse(form.GetKey(i), out RolId);
                if (flagrol)
                {
                    RolUsuario rolusuario = new RolUsuario();
                    rolusuario.UsuarioId = UsuarioId;
                    rolusuario.RolId     = int.Parse(form.GetKey(i).ToString());
                    RolUsuarioList.Add(rolusuario);
                }
            }

            return(RolUsuarioList);
        }
Example #14
0
        /// <summary>
        /// FormCollection转到Hashtable
        /// </summary>
        /// <param name="collection">界面传过来的FormCollection</param>
        /// <returns>转换后的Hashtable</returns>
        public static Hashtable FormCollectionToHashtable(FormCollection collection)
        {
            Hashtable ht = new Hashtable();

            for (int i = 0; i < collection.Count; i++)
            {
                ht.Add(collection.GetKey(i), CharacterUtil.SQLEncode(collection.GetValue(collection.GetKey(i)).AttemptedValue));
            }
            return(ht);
        }
Example #15
0
        public ActionResult Register(UserAccount userAccountModel, FormCollection fc)
        {
            for (int i = 1; i < fc.AllKeys.Length; i++)
            {
                string key   = fc.GetKey(i);
                string value = fc.Get(key);
                if (value.Trim().Equals(""))
                {
                    return(Content("<script>alert('标记为 * 的输入框不能为空,请重新输入!');window.open('" + Url.Content("~/Account/Register") + "', '_self')</script>"));
                }
            }

            if (fc["confirmPassword"].Equals(fc["password"]))
            {
                //UpdateModel<UserAccount>(userAccountModel);
                this.TryUpdateModel <UserAccount>(userAccountModel);
                var users = db.UserAccounts.Where(m => m.UserID == userAccountModel.UserID);
                if (users.Count() == 0)//查无此人
                {
                    if (ModelState.IsValid)
                    {
                        userAccountModel.UserID         = fc["userID"];
                        userAccountModel.UserName       = fc["userName"];
                        userAccountModel.Password       = fc["password"];
                        userAccountModel.UserImage      = "defaultUserImage.jpg";
                        userAccountModel.PhoneNumber    = null;
                        userAccountModel.Identification = "user";
                        userAccountModel.status         = true;
                        db.UserAccounts.Add(userAccountModel);
                        //try
                        //{
                        db.SaveChanges();
                        //}
                        //catch (Exception ex)
                        //{
                        //    throw;
                        //}
                        Session["UserID"]         = userAccountModel.UserID;
                        Session["UserName"]       = userAccountModel.UserName;
                        Session["Identification"] = userAccountModel.Identification;
                        return(Content("<script>alert('注册成功!');window.open('" + Url.Content("~/Home/Index") + "', '_self')</script>"));
                    }
                }
                else
                {
                    return(Content("<script>alert('该用户名已存在!');window.open('" + Url.Content("~/Account/Register") + "', '_self')</script>"));
                }
            }
            else
            {
                return(Content("<script>alert('两次输入的密码不一致!');window.open('" + Url.Content("~/Account/Register") + "', '_self')</script>"));
            }

            return(View(userAccountModel));
        }
Example #16
0
        public ActionResult EditPassword(UserAccount userAccountModel, FormCollection fc)
        {
            for (int i = 1; i < fc.AllKeys.Length; i++)
            {
                string key   = fc.GetKey(i);
                string value = fc.Get(key);
                if (value.Trim().Equals(""))
                {
                    return(Content("<script>alert('标记为 * 的输入框不能为空,请重新输入!');window.open('" + Url.Content("~/User/EditPassword") + "', '_self')</script>"));
                }
            }
            if (fc["password_new"].Equals(fc["password_new2"]))//两次输入密码一致
            {
                userAccountModel = db.UserAccounts.Find(Session["UserID"]);
                string password = userAccountModel.Password;
                if (fc["password_old"].Equals(password))//原密码输入正确
                {
                    if (ModelState.IsValid)
                    {
                        //db.UserAccounts.Remove(userAccountModel);
                        //db.SaveChanges();
                        //userAccountModel.UserID = Session["UserID"].ToString();
                        //userAccountModel.UserName = Session["UserName"].ToString();
                        userAccountModel.Password = fc["password_new"];
                        //userAccountModel.UserImage = Session["UserImage"].ToString();
                        //userAccountModel.PhoneNumber = Session["PhoneNumber"].ToString();
                        //userAccountModel.Identification = "user";
                        //db.UserAccounts.Add(userAccountModel);
                        db.Entry(userAccountModel).State = EntityState.Modified;
                        db.SaveChanges();

                        Session["UserID"]         = userAccountModel.UserID;
                        Session["UserName"]       = userAccountModel.UserName;
                        Session["Identification"] = userAccountModel.Identification;
                        return(Content("<script>alert('修改密码成功!');window.open('" + Url.Content("~/Home/Index") + "', '_self')</script>"));
                    }
                }
                else
                {
                    return(Content("<script>alert('原密码输入错误!');window.open('" + Url.Content("~/User/EditPassword") + "', '_self')</script>"));
                }
            }
            else
            {
                return(Content("<script>alert('两次输入的密码不一致!');window.open('" + Url.Content("~/User/EditPassword") + "', '_self')</script>"));
            }

            return(View());
        }
        public ActionResult Save(FormCollection collection)
        {
            string[] arr;
            int      restricted = 0, permission = 0;
            Group    group = new Group();

            for (int i = 0; i < collection.Count; i++)
            {
                arr = collection.GetKey(i).Split('-');
                if (arr[1] == EnumPermission.Allow.ToString())
                {
                    permission = 1;
                }
                else if (arr[1] == EnumPermission.Inherit.ToString())
                {
                    permission = 0;
                }
                else if (arr[1] == EnumPermission.Deny.ToString())
                {
                    permission = 2;
                }
                else if (arr[1] == "Restricted")
                {
                    restricted = 1;
                }
                group = (Group)Session["CurrentGroup"];
                if (ConvertHelper.Convert <int>(arr[0], 0) == 0)
                {
                    DatabaseObject.db.Groupspermission.Add(new GroupPermission
                    {
                        FunctionName = arr[2], Active = 1, CreateDate = DateTime.Now, Focus = 0, SortIndex = 0, OwnerID = LoginToken.LoginUser.ID,
                        Objectname   = Session["SelectedValue"].ToString(), GroupID = group.ID, Permission = permission, Restricted = restricted
                    });
                    DatabaseObject.db.SaveChanges();
                }
                else if (ConvertHelper.Convert <int>(arr[0], 0) > 0)
                {
                    var permGroup = DatabaseObject.db.Groupspermission.Find(Convert.ToInt64(arr[0]));
                    permGroup.Permission = permission;
                    permGroup.Restricted = restricted;
                    permGroup.ModifierID = LoginToken.LoginUser.ID;
                    permGroup.ModifyDate = DateTime.Now;
                    DatabaseObject.db.Entry(permGroup).State = EntityState.Modified;
                    DatabaseObject.db.SaveChanges();
                }
            }
            return(RedirectToAction("Permission", new { id = group.ID }));
        }
Example #18
0
        public ActionResult EditarHospital(HospitalesVista model, HttpPostedFileBase fichero, FormCollection coleccion)
        {
            try
            {
                var hospitalAEditar = new DatosProfesionales {
                    idDatosPro = Convert.ToInt32(model.IdHospital)
                };
                hospitalAEditar = DbContext.DatosProfesionales.Find(hospitalAEditar.idDatosPro);

                hospitalAEditar.nombre    = model.Nombre;
                hospitalAEditar.telefono  = model.Telefono;
                hospitalAEditar.direccion = model.Direccion;
                hospitalAEditar.email     = model.Email;
                hospitalAEditar.texto     = model.Texto;

                if (fichero != null && fichero.ContentLength > 0)
                {
                    //guardamos el fichero de la foto con nombre hosp + id
                    var nombreFichero = fichero.FileName;
                    var extension     = nombreFichero.Substring(nombreFichero.LastIndexOf(".", StringComparison.CurrentCulture));
                    var rutacompleta  = Server.MapPath("~/uploads/fotos") + @"\" + model.IdHospital + extension;
                    fichero.SaveAs(rutacompleta);
                    hospitalAEditar.foto = "~/uploads/fotos/" + model.IdHospital + extension;
                }

                //nos cargamos todas previamente
                foreach (var co in hospitalAEditar.Companias.ToList())
                {
                    hospitalAEditar.Companias.Remove(co);
                }

                for (var i = 6; i < coleccion.Count; i++)
                {
                    var id = Convert.ToInt32(coleccion.GetKey(i));
                    var co = DbContext.Companias.Find(id);
                    hospitalAEditar.Companias.Add(co);
                }

                DbContext.SaveChanges();

                return(RedirectToAction("index"));
            }
            catch (Exception e)
            {
                //algo deberiamos hacer si falla..pero si no podemos enviar un email...chungo..
                return(Json(string.Format("error editando hospital {0}", e.Message), JsonRequestBehavior.AllowGet));
            }
        }
Example #19
0
        public ActionResult EditEnvironmentColors(FormCollection collection)
        {
            var colors = new Dictionary <string, string>();

            for (var i = 0; i < collection.Count; i++)
            {
                var key   = collection.GetKey(i);
                var value = collection.ToValueProvider().GetValue(key);
                colors.Add(key, value.AttemptedValue.Replace("#", ""));
            }

            _initiativeBusiness.UpdateEnvironmentColors(User.Identity.GetUserId(), colors);


            return(RedirectToAction("Index", "Manage"));
        }
Example #20
0
        public static long ConfigureRoleTransaction(FormCollection frmCollection, long createdBy)
        {
            var userRoleId = Convert.ToInt64(frmCollection["hdnUserRoleID"]);

            using (var db = new DBEntities())
            {
                //Delete existing rights for the selected User Role
                var rights = from ur in db.UserRights
                             where ur.RoleMasterId == userRoleId
                             select ur;
                db.UserRights.RemoveRange(rights);
                db.SaveChanges();

                //We have the checked checkbox list HERE
                for (var i = 1; i < frmCollection.Count; i++)
                {
                    var linkId    = Convert.ToInt64(frmCollection.GetKey(i).Split('_')[1]);
                    var userRight =
                        db.UserRights.FirstOrDefault(s => s.LinkId == linkId && s.RoleMasterId == userRoleId);

                    if (userRight != null)
                    {
                        //Update rights as per new configurtation for the selected User Role
                        userRight.IsAccess        = true;
                        db.Entry(userRight).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                    else
                    {
                        //Insert rights as per new configurtation for the selected User Role
                        userRight = new UserRight
                        {
                            RoleMasterId = userRoleId,
                            LinkId       = linkId,
                            CreatedBy    = createdBy,
                            CreatedDate  = DateTime.Now,
                            IsAccess     = true
                        };
                        db.UserRights.Add(userRight);
                        db.SaveChanges();
                    }
                }
            }

            return(userRoleId);
        }
Example #21
0
        public async Task <ActionResult> EditUserRole(FormCollection collection)
        {
            var user = await UserManager.FindByIdAsync(collection["Id"]);

            foreach (var identityUserRole in user.Roles.ToList())
            {
                await UserManager.RemoveFromRoleAsync(user.Id, RoleManager.FindById(identityUserRole.RoleId).Name);
            }
            for (int i = 0; i < collection.Count - 1; i++)
            {
                var role = await RoleManager.FindByIdAsync(collection.GetKey(i));

                await UserManager.AddToRoleAsync(user.Id, role.Name);
            }

            return(RedirectToAction("UserRoles"));
        }
Example #22
0
        /// <summary>
        /// Method accepts POST form Data. This method filters the
        /// incoming data for commands and sends it to the C# Server.
        /// it separates the normal commands from the commands with special treatment.
        /// </summary>
        /// <param name="formCollection">Form data send via POST</param>

        public string JansIsEenHeld(FormCollection formCollection)
        {
            string getString = "?";

            for (int i = 0; i < formCollection.Count; i++)
            {
                getString += formCollection.GetKey(i);
                getString += "=";
                getString += formCollection.Get(i);
                log.CreateEventLog("Post command recieved: " + formCollection.Get(i));
                if ((i + 1) != formCollection.Count)
                {
                    getString += "&";
                }
            }
            return(SendCommand(getString).ToString());
        }
Example #23
0
        public ScheduleTableCreate FormToTable(FormCollection scheduleRows, out bool isValid)
        {
            var result = new ScheduleTableCreate
            {
                IsWeekOdd         = bool.Parse(scheduleRows[2]),
                GroupId           = int.Parse(scheduleRows[1]),
                ScheduleTableRows = new List <ScheduleTable>()
            };

            isValid = true;

            for (var i = 3; i < scheduleRows.Count; i++)
            {
                //if (scheduleRows.GetKey(i).EndsWith("ScheduleTableId")) i++;
                var id = 0; // * 0 == id -> не существует *
                if (scheduleRows.GetKey(i).EndsWith("ScheduleTableId"))
                {
                    int.TryParse(scheduleRows[i++], out id);
                }

                var item = new ScheduleTable
                {
                    ScheduleTableId = id,

                    Date = DateTime.Now,

                    Auditory    = scheduleRows[i++].Trim(),
                    LectorName  = scheduleRows[i++].Trim(),
                    SubjectName = scheduleRows[i++].Trim(),
                    LessonType  = int.Parse(scheduleRows[i++]),
                    LessonId    = int.Parse(scheduleRows[i++]),
                    GroupId     = int.Parse(scheduleRows[i++]),
                    WeekdayId   = int.Parse(scheduleRows[i]),
                    IsWeekOdd   = result.IsWeekOdd
                };

                if (item.Auditory.Trim() == string.Empty || item.SubjectName.Trim() == string.Empty)
                {
                    isValid = false;
                }

                result.ScheduleTableRows.Add(item);
            }

            return(result);
        }
        public ActionResult Posts(FormCollection form)
        {
            var post_id = Guid.Parse(form.GetValues("Post_Id")[0]); //?
            var action  = form.GetKey(1);

            if (action == "LikeButton")
            {
                _postManager.LikePost(post_id, user.User_Id);
            }
            else if (action == "DislikeButton")
            {
                _postManager.DislikePost(post_id, user.User_Id);
            }
            else if (action == "CommentButton")
            {
                TempData["post_id"] = post_id;
                return(Redirect("~/Posts/AddComment"));
            }
            ViewBag.Posts = _postManager.GetUserStream(user.User_Id);
            return(View());
        }
Example #25
0
        public ActionResult EditPage(CmsPage page, FormCollection form)
        {
            var oldProperties = _context.CmsProperties.Where(p => p.PageId == page.PageId).ToList();

            foreach (var prop in oldProperties)
            {
                for (int i = 0; i < form.Keys.Count; i++)                  //for at få indekseret vores properties index
                {
                    if (form.GetKey(i) != prop.Alias)
                    {
                        continue;
                    }
                    //If key and prop equals
                    prop.Value = form[i];
                    _context.Entry(prop).State = EntityState.Modified;
                }
            }
            _context.Entry(page).State = EntityState.Modified;
            _context.SaveChanges();

            return(RedirectToAction("EditPage", new { id = page.PageId }));
        }
        public async Task <int> SampleCondition(FormCollection sampleCondition)
        {
            if (ModelState.IsValid)
            {
                var model = new Dictionary <string, string>();

                for (int i = 0; i < sampleCondition.Count; i++)
                {
                    if (int.TryParse((string)sampleCondition.GetKey(i), out int key))
                    {
                        var wot = db.WorkOrderTests.Find(key);
                        wot.Condition       = sampleCondition.Get(i);
                        db.Entry(wot).State = EntityState.Modified;
                    }
                }
                await db.SaveChangesAsync();

                return(1);
            }

            ViewBag.Accession_Status = new SelectList(db.Departments.Where(e => e.DepartmentRadPath.Equals(main_department_id)), "Id", "Department_Code");
            return(0);
        }
Example #27
0
        public void AddUploadFile(FormCollection collection, Product product)
        {
            int    startNo      = 8;
            string temp         = collection.GetKey(startNo);
            int    index        = temp.LastIndexOf('.');
            int    uploadFileID = 0;

            if (index > 0 && int.TryParse(temp.Substring(index + 1), out uploadFileID))
            {
                string temp1 = collection.Get(temp);
                if (temp.StartsWith("Product.&.") && temp1.StartsWith("true"))
                {
                    RemoveUploadFile(product);

                    ProductUploadFile puf = new ProductUploadFile();
                    puf.UploadFileID = uploadFileID;
                    product.ProductUploadFiles.Add(puf);
                }
                else if (temp.StartsWith("Product.") && temp1.StartsWith("false"))
                {
                    RemoveUploadFile(product);
                }
            }
        }
Example #28
0
        public ActionResult Survey(FormCollection frm)
        {
            SurveyBL _surBL = new SurveyBL();

            decimal surveyId = 1; // Make sure you get the Survey Id from the table or session
            List <SurveyQuestionModel> lstQuestions = _surBL.getQuestions(surveyId);

            List <SurveyTakenModel> lst = new List <SurveyTakenModel>();


            var starsId = Session["StarsIdProfile"].ToString();
            var pacode  = Session["w_pacode"].ToString();
            var wslx    = Session["w_user"].ToString();


            for (int i = 0; i <= frm.Count - 1; i++)
            {
                string type = "";
                //string test1 = frm.GetValue(Convert.ToString(frm[i])).AttemptedValue;
                // string[] arr1 = frm.GetValues(i);
                foreach (var item in lstQuestions)
                {
                    if (item.QUESTION_ID == Convert.ToDecimal(frm.GetKey(i)))
                    {
                        type = item.QUESTION_TYPE;
                        break;
                    }
                }
                if (type == "FI")
                {
                    string[] arr = frm.GetValue(Convert.ToString(frm.GetKey(i))).AttemptedValue.Split(',');
                    lst.Add(new SurveyTakenModel()
                    {
                        STARS_ID    = starsId,
                        SURVEY_ID   = surveyId,
                        QUESTION_ID = Convert.ToDecimal(frm.GetKey(i).ToString()),
                        ANSWER_ID   = 1,
                        ANSWER_MSG  = arr[0].ToString(),
                        CREATED_BY  = wslx
                    });
                }
                else if (type == "MS")
                {
                    string[] arr = frm.GetValue(Convert.ToString(frm.GetKey(i))).AttemptedValue.Split(',');
                    if (arr.Count() > 0)
                    {
                        for (int j = 0; j <= arr.Count() - 1; j = j + 2)
                        {
                            lst.Add(new SurveyTakenModel()
                            {
                                STARS_ID    = starsId,
                                SURVEY_ID   = surveyId,
                                QUESTION_ID = Convert.ToDecimal(arr[j].ToString()),
                                ANSWER_ID   = Convert.ToDecimal(arr[j + 1].ToString()),
                                ANSWER_MSG  = string.Empty,
                                CREATED_BY  = wslx
                            });
                        }
                    }
                }

                else
                {
                    string[] arr = frm.GetValue(Convert.ToString(frm.GetKey(i))).AttemptedValue.Split(',');

                    lst.Add(new SurveyTakenModel()
                    {
                        STARS_ID    = starsId,
                        SURVEY_ID   = surveyId,
                        QUESTION_ID = Convert.ToDecimal(arr[0].ToString()),
                        ANSWER_ID   = Convert.ToDecimal(arr[1].ToString()),
                        ANSWER_MSG  = string.Empty,
                        CREATED_BY  = wslx
                    });
                }
            }
            SurveyCompledModel _surveyModel = new SurveyCompledModel();

            _surveyModel.COMPLETED_DATE = DateTime.Now;
            _surveyModel.PA_CODE        = pacode;
            _surveyModel.STARS_ID       = starsId;
            _surveyModel.SURVEY_ID      = surveyId;
            _surveyModel.CREATED_DATE   = DateTime.Now;
            _surveyModel.CREATED_BY     = wslx;

            if (_surBL.SaveSurvey(lst, _surveyModel))
            {
                return(RedirectToAction("Confirmation", "Resources"));
            }
            return(RedirectToAction("Survey", "Resources"));
            //return RedirectToAction("Welcome", "LBC");
        }
        public ViewResult TemplateCommitted(FormCollection values)
        {
            Template template = new Template();

            //A load of values we've got over here.
            var    appSettings = ConfigurationManager.AppSettings;
            string inPath      = appSettings["In"];
            string outPath     = appSettings["Out"];
            string donePath    = appSettings["Done"];

            template.printMode               = values["printMode"];
            template.selectedEdition         = values["Edition"];
            template.selectedPublication     = values["selctPub"];
            template.numberOfPages           = Int32.Parse(values["NrPages"]);
            template.selectedTemplate        = values["selctTemp"];
            template.selectedPublicationPath = values["selctPubPath"];

            //Moves the pages and their location into an dictionary.
            int i = 0;
            Dictionary <string, string> pagesLocation = new Dictionary <string, string>();

            while (i < values.Count && i < template.numberOfPages * 4)
            {
                string tempKey   = values.GetKey(i);
                string tempValue = values.Get(i);
                //All the variables that aren't pages in the Formcollection values needs to be added to here or they'll be counted as pages.
                if (tempValue.Length > 0 && tempValue != "0" && !tempKey.Contains("selctPub") && !tempKey.Contains("printMode") && !tempKey.Contains("Edition") && !tempKey.Contains("NrPages") && !tempKey.Contains("selctTemp") && !tempKey.Contains("selctPubPath"))
                {
                    if (!pagesLocation.ContainsKey(tempValue))
                    {
                        pagesLocation.Add(tempValue, tempKey);
                    }
                }

                i++;
            }
            template.pagesAndLocation = pagesLocation;

            /* Load the XML for the selected publication into a DOM.
             * The pages  in <pages> will be looped through in ascending order and filled with the information from pagesLocation.*/
            string xmlLocation;

            if (template.selectedPublicationPath == "Done")
            {
                xmlLocation = Path.Combine(donePath, template.selectedPublication);
            }
            else
            {
                xmlLocation = Path.Combine(inPath, template.selectedPublication);
            }


            XmlDocument publicationXML = new XmlDocument();

            publicationXML.Load(xmlLocation);
            XmlNode productionRunNode = publicationXML.SelectSingleNode("Planning/productionRuns");

            productionRunNode = productionRunNode.FirstChild;

            while (productionRunNode.SelectSingleNode("name").InnerText != template.selectedEdition)
            {
                productionRunNode = productionRunNode.NextSibling;
            }

            XmlNode currentNode = productionRunNode.SelectSingleNode("plates");

            currentNode = currentNode.FirstChild;
            /* If the production is Straight. */
            if (template.pagesAndLocation.Count * 2 == template.numberOfPages)
            {
                for (int j = 1; j < template.pagesAndLocation.Count + 1; j++)
                {
                    for (int k = 0; k < 8; k++)
                    {
                        string currentColour = GetColourOfNode(currentNode);
                        if (currentColour.Contains("ERROR"))
                        {
                            template.failureOrSuccess = currentColour;
                            return(View(template));
                        }

                        string pagesLocationWithDouble = template.pagesAndLocation[j.ToString()];

                        //fix so double production has both highs and lows.
                        if (pagesLocationWithDouble.Contains("H"))
                        {
                            template.pagesAndLocation[j.ToString()] = pagesLocationWithDouble.Replace("H", "L");
                        }
                        else
                        {
                            template.pagesAndLocation[j.ToString()] = pagesLocationWithDouble.Replace("L", "H");
                        }

                        publicationXML = AddPage(publicationXML, currentNode, pagesLocationWithDouble, currentColour);
                        currentNode    = currentNode.NextSibling;
                    }
                }

                StreamWriter sw = new StreamWriter(Path.Combine(outPath, template.selectedPublication));
                sw.NewLine = "\n";
                publicationXML.Save(sw);
                sw.Close();

                template.failureOrSuccess = "Produkten skickad till Arkitex.";
            }
            /*If the productions is Collect*/
            else if (template.pagesAndLocation.Count == template.numberOfPages)
            {
                for (int j = 1; j < template.pagesAndLocation.Count + 1; j++)
                {
                    //Loops through all the plate elements in plates and assign their new values.
                    for (int k = 0; k < 4; k++)
                    {
                        string currentColour = GetColourOfNode(currentNode);
                        if (currentColour.Contains("ERROR"))
                        {
                            template.failureOrSuccess = currentColour;
                            return(View(template));
                        }
                        publicationXML = AddPage(publicationXML, currentNode, template.pagesAndLocation[j.ToString()], currentColour);
                        currentNode    = currentNode.NextSibling;
                    }

                    StreamWriter sw = new StreamWriter(Path.Combine(outPath, template.selectedPublication));
                    sw.NewLine = "\n";
                    publicationXML.Save(sw);
                    sw.Close();

                    template.failureOrSuccess = "Produkten skickad till Arkitex.";
                }
            }
            else
            {
                template.failureOrSuccess = "ERROR - Sidantalet i templates stämmer inte överrens med sidantalet i den valda produkten";
            }

            if (!template.failureOrSuccess.Contains("ERROR"))
            {
                //Publications that have been sent to Arkitex and the files in the current in folder are moved to the "Done" folder to mark them as such.
                string sourceFile = Path.Combine(inPath, template.selectedPublication);
                string doneFile   = Path.Combine(donePath, template.selectedPublication);
                if (template.selectedPublicationPath == "Current")
                {
                    try
                    {
                        System.IO.File.Move(sourceFile, doneFile);
                    }
                    catch (IOException)
                    {
                        template.failureOrSuccess = "Templaten skickades till Arkitex men kunde inte flyttas till de redan gjorda templatsen.";
                    }
                }
            }

            //Send the XML to the prepress-system and set the view to reflect the success or failure of this operation.
            return(View(template));
        }
        public int ResultsEntry(FormCollection testEntry)
        {
            if (ModelState.IsValid)
            {
                var model = new Dictionary <string, string>();

                var DoctorsList = new Dictionary <string, int>();

                var wo = db.WorkOrders.Find(Convert.ToInt32(testEntry.Get("WorkOrder")));

                //if (wo.Accession_Status.Equals(db.Status.FirstOrDefault(e => e.StatusValue.Equals("Authorized")).Id))
                //{
                //    return 2;
                //}

                for (int i = 0; i < testEntry.Count; i++)
                {
                    if (testEntry.GetKey(i).StartsWith("Doctor"))
                    {
                        string departmentName = testEntry.GetKey(i).Replace("Doctor", "");
                        int    doctorId       = Convert.ToInt32(testEntry.Get(i).Trim());

                        DoctorsList.Add(departmentName, doctorId);
                    }


                    if (testEntry.GetKey(i).StartsWith("Test"))
                    {
                        int id  = Convert.ToInt32(testEntry.GetKey(i).Replace("Test", ""));
                        var wot = db.WorkOrderTests.Find(id);

                        //if (wot.Status != db.Status.FirstOrDefault(e => e.StatusValue.Equals("Authorized")).Id)
                        {
                            var res = testEntry.Get(i).Trim();

                            if (wot.Results != null && (wot.Results.Trim() != "" || !wot.Results.Trim().Equals(res)))
                            {
                                wot.Doctor = DoctorsList.SingleOrDefault(e => e.Key == wot.LabTest.Department1.Department1).Value;
                            }

                            wot.Results         = testEntry.Get(i);
                            db.Entry(wot).State = EntityState.Modified;
                        }
                    }
                    else if (testEntry.GetKey(i).StartsWith("Par"))
                    {
                        var tp = Convert.ToInt32(testEntry.GetKey(i).Replace("Par", ""));

                        var wotp = db.WorkOrderTestParameters.Find(tp);
                        //if (wotp != null)
                        //{

                        //if (wotp.WorkOrderTest1.Status != db.Status.FirstOrDefault(e => e.StatusValue.Equals("Authorized")).Id)
                        {
                            if (wotp.Results.Trim() != null && (wotp.Results.Trim() != "" ||
                                                                !wotp.Results.Trim().Equals(testEntry.Get(i).Trim())))
                            {
                                wotp.WorkOrderTest1.Doctor = DoctorsList.SingleOrDefault(e => e.Key ==
                                                                                         wotp.WorkOrderTest1.LabTest.Department1.Department1).Value;
                            }

                            wotp.Results         = testEntry.Get(i);
                            db.Entry(wotp).State = EntityState.Modified;
                        }



                        //}
                        //else
                        //{
                        //    wotp = new WorkOrderTestParameter() {
                        //        WorkOrderTest = 3,
                        //        Parameter = tp,
                        //        Results = testEntry.Get(i),
                        //        CreatedUtc = DateTime.Now
                        //    };

                        //    db.WorkOrderTestParameters.Add(wotp);
                        //}
                    }

                    if (testEntry.GetKey(i).StartsWith("Auth"))
                    {
                        string testIdtext = testEntry.GetKey(i).Replace("Auth", "");
                        int    testId     = Convert.ToInt32(testIdtext);

                        int res = AutorizeTestResults(testId);
                    }
                }
                db.SaveChanges();
                updateTestStatus(wo);
                return(1);
            }

            ViewBag.Accession_Status = new SelectList(db.Departments, "Id", "Department_Code");
            return(0);
        }