public ActionResult Index(FormCollection formValues)
        {
            formValues.Remove(formValues.Keys[0]);

            //get the current semester
            //String semester = db.Current_Semester
            String semester = "SP11";

            //update the database
            foreach (String key in formValues.Keys)
            {
                if (formValues[key].Contains("true"))
                {
                    int class_id = Convert.ToInt32(key.Split('/')[0]);
                    String student_id = key.Split('/')[1];
                    try
                    {
                        db.Takes.First(a => a.class_id == class_id && a.student_id == student_id && a.semester_id == semester).waitlist_status = false;
                    }
                    catch { }
                }
            }
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        public ActionResult Index(FormCollection formValues)
        {
            formValues.Remove(formValues.Keys[0]);

            //get the current semester
            //String semester = db.Current_Semester
            String semester = "SP11";

            //update the database
            foreach (String id in formValues.Keys)
            {
                int class_id = Convert.ToInt32(id.Split('/')[0]);
                String student_id = id.Split('/')[1];

                try
                {
                    int new_grade = Convert.ToInt32(formValues[id]);
                    if (new_grade < 0 || new_grade > 100) { throw new Exception(); }
                    db.Takes.First(a => a.class_id == class_id && a.student_id == student_id && a.semester_id == semester).grade =
                        new_grade;
                } catch { }
            }
            db.SaveChanges();

            return RedirectToAction("Index");
        }
        public SocketLabsEvent(FormCollection formCollection)
            : this()
        {
            ServerId = Convert.ToInt64(formCollection["ServerId"]);
            Address = formCollection["Address"];

            EventType type;

            if (Enum.TryParse(formCollection["Type"], true, out type))
            {
                formCollection.Remove("Type");
            }
            else
            {
                type = EventType.Unknown;
            }

            Type = type;

            DateTime = Convert.ToDateTime(formCollection["DateTime"]);
            MailingId = formCollection["MailingId"];
            MessageId = formCollection["MessageId"];
            SecretKey = formCollection["SecretKey"];

            formCollection.Remove("ServerId");
            formCollection.Remove("Address");
            formCollection.Remove("DateTime");
            formCollection.Remove("MailingId");
            formCollection.Remove("MessageId");
            formCollection.Remove("SecretKey");

            ExtraData = formCollection.AllKeys.ToDictionary(k => k, v => formCollection[v]);
        }
Beispiel #4
0
        private ReportResultContext UpdateForm(FormCollection form)
        {
            var headerId = int.Parse(form["headerID"]);
            var locationId = form["locationID"];
            var pageSize = int.Parse(form["pageSize"]);
            var pageIndex = int.Parse(form["pageIndex"]);

            form.Remove("headerID");
            form.Remove("locationID");
            form.Remove("pageSize");
            form.Remove("pageIndex");

            return new ReportResultContext()
            {
                HeaderId = headerId,
                LocationId = locationId,
                PageIndex = pageIndex,
                PageSize = pageSize
            };
        }
 public virtual string PostSurvey(FormCollection formValues, string UserId)
 {
     int i = 0;
     string result = "";
     result += "User Id of Awesomeness: " + UserId + "<br />";
     formValues.Remove("UserId");
     foreach (var key in formValues.AllKeys) {
         result += "Index: " + i.ToString() + " Key: " + key + " Value: " + formValues[key] + ". <br />";
         i++;
     }
     return result;
 }
        /// <summary>
        /// 通用编辑与新增
        /// </summary>
        /// <param name="fc"></param>
        /// <returns></returns>
        public virtual string Edit(System.Web.Mvc.FormCollection fc)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var entity = context.Set <T>().Find(fc["ID"]);

                    if (string.IsNullOrEmpty(fc["ID"]) && entity == null)
                    {
                        fc.Remove("ID");
                        entity = new T();
                        TryUpdateModel(entity, fc);
                        context.Set <T>().Add(entity);
                        context.SaveChanges();
                        ReturnData result = new ReturnData(200, "编辑成功");
                        return(result.ToJson());
                    }
                    else
                    {
                        TryUpdateModel(entity, fc);
                        context.SaveChanges();
                        ReturnData result = new ReturnData(200, "编辑成功");
                        return(result.ToJson());
                    }
                }
                catch (DbUpdateConcurrencyException ex)
                {
                    ReturnData result = new ReturnData(500, ex.Message);
                    return(result.ToJson());
                }
                catch (Exception ex)
                {
                    ReturnData result = new ReturnData(500, ex.Message);
                    return(result.ToJson());
                }
            }
            else
            {
                ReturnData result = new ReturnData(500, "false");
                return(result.ToJson());
            }
        }
        /// <summary>
        /// Check if the querystring directive of TreeQueryStringParameters.RenderParent is true, if so then
        /// set the _dynamicRootNodeId value to the one being requested and only return the root node, otherwise
        /// proceed as normal.
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="queryStrings"></param>
        /// <param name="actualRootNodeId"> </param>
        /// <param name="nodeCollection"> </param>
        /// <param name="createRootNode"> </param>
        /// <param name="returnResult"> </param>
        /// <param name="returnDefaultResult"> </param>
        /// <returns></returns>
        internal RebelTreeResult GetTreeData(
            HiveId parentId, 
            FormCollection queryStrings, 
            HiveId actualRootNodeId,
            TreeNodeCollection nodeCollection,
            Func<FormCollection, TreeNode> createRootNode,
            Func<RebelTreeResult> returnResult,
            Func<HiveId, FormCollection, RebelTreeResult> returnDefaultResult)
        {
            if (queryStrings.GetValue<bool>(TreeQueryStringParameters.RenderParent))
            {
                //if the requested node does not equal the root node set, then set the _dynamicRootNodeId
                if (!parentId.Value.Equals(actualRootNodeId.Value))
                {
                    _dynamicRootNodeId = parentId;
                }
                //need to remove the query strings we don't want passed down to the children.
                queryStrings.Remove(TreeQueryStringParameters.RenderParent);
                nodeCollection.Add(createRootNode(queryStrings));
                return returnResult();
            }

            return returnDefaultResult(parentId, queryStrings);
        }
        /// <summary>
        /// Search a new inspection Report
        /// </summary>
        /// <param name="page">Page</param>
        /// <param name="inspectionReportId">Id of inspection report</param>
        /// <param name="collection">Form collection</param>
        /// <returns>PartialViewResult</returns>
        public PartialViewResult SearchInspectionReport(int? page, string inspectionReportId, FormCollection collection)
        {
            Guid businessApplicationId = new Guid(Convert.ToString(Session["BusinessAplicationId"]));
            Guid serviceOrderReportId = new Guid(Session["serviceOrderReportId"].ToString());

            collection.Remove("InspectionReportId");
            collection.Remove("selectedInspectionReports");
            _collection = collection;
            _inspectionReportId = inspectionReportId;

            List<string> fielsdWithLike = new List<string>();
            foreach (string name in collection.AllKeys.Where(name => name.Contains("IsLike")))
            {
                fielsdWithLike.Add(name.Replace("IsLike", ""));
                collection.Remove(name);
            }

            ParameterSearchInspectionReport parameters = new ParameterSearchInspectionReport
            {
                BusinessApplicationId = businessApplicationId,
                Collection = collection,
                InspectionReportName = inspectionReportId,
                ServiceOrderId = serviceOrderReportId,
                UserName = UserName,
                RolesForUser = Roles.GetRolesForUser(UserName).ToList(),
                PageSize = Cotecna.Vestalis.Web.Properties.Settings.Default.PageSize,
                SelectedPage = page == null ? 1 : page.Value,
                IsClient = User.IsInRole("Client"),
                FieldsWithLike = fielsdWithLike
            };

            DynamicDataGrid model = InspectionReportBusiness.SearchInspectionReportList(parameters);
            model.Captions = _captions;
            model.UserLevel = InspectionReportBusiness.GetRoleLevel(Roles.GetRolesForUser(UserName), businessApplicationId);
            Session.Add("DataRowsInspectionReport", model.DataRows);

            return PartialView("_InspectionReportGrid", model);
        }
Beispiel #9
0
        public ActionResult Profile(FormCollection _vars)
        {
            var user = Membership.GetUser(Guid.Parse(_vars["UserGuid"]));
            var prfMgr = new UserProfileManager(user);

            UserProfileViewModel viewModel = new UserProfileViewModel() {
                AccountProperties = new UserProfileManager(user).UserProfile.Properties,
                UserId = (Guid)user.ProviderUserKey,
                Email = user.Email,
            };

            user.Email = _vars["Email"];

            string currPwd = _vars["CurrentPassword"];
            string newPwd = _vars["NewPassword"];
            string newPwdConfirmation = _vars["NewPasswordConfirmation"];

            if (!string.IsNullOrWhiteSpace(currPwd)) {
                // attempt to change the user's password
                if (string.IsNullOrWhiteSpace(newPwd)) {
                    ModelState.AddModelError("NewPassword", "Você deve digitar a nova senha.");
                    return View(viewModel);
                }
                if (string.IsNullOrWhiteSpace(newPwdConfirmation)) {
                    ModelState.AddModelError("NewPassword", "Você deve digitar a confirmação da nova senha.");
                    return View(viewModel);
                }
                if (newPwdConfirmation != newPwd) {
                    ModelState.AddModelError("NewPassword", "A nova senha e a confirmação devem ser iguais.");
                    ModelState.AddModelError("NewPasswordConfirmation", "A nova senha e a confirmação devem ser iguais.");
                    return View(viewModel);
                }

                if (!user.ChangePassword(currPwd, newPwd)) {
                    ModelState.AddModelError("CurrentPassword", "Não foi possível trocar sua senha. Verifique sua senha atual e tente novamente.");
                    return View(viewModel);
                }
            }

            if (_vars["Administrator"] != null) {
                if (!Roles.IsUserInRole(user.UserName, "administrators")) {
                    Roles.AddUserToRole(user.UserName, "administrators");
                }
            }
            else if (Roles.IsUserInRole(user.UserName, "administrators")) {
                Roles.RemoveUserFromRole(user.UserName, "administrators");
            }

            _vars.Remove("UserGuid");
            _vars.Remove("Email");
            _vars.Remove("CurrentPassword");
            _vars.Remove("NewPassword");
            _vars.Remove("NewPasswordConfirmation");
            _vars.Remove("Administrator");

            foreach (string key in _vars.Keys) {
                prfMgr.SetUserProfileProperty(key, _vars[key]);
            }

            try {
                Membership.UpdateUser(user);
            }
            catch (ProviderException e) {
                ModelState.AddModelError("Email", "Ocorreu um erro atualizar seus dados. " + e.Message);
                return View(viewModel);
            }

            TempData["Message"] = "Dados salvos com sucesso.";
            return RedirectToAction("Index", "Home");
        }
        /// <summary>
        /// Delete the service Order
        /// </summary>
        /// <param name="collection">Service order identifier</param>
        /// <returns></returns>
        public PartialViewResult ValidatePublishInspectionReports(FormCollection collection)
        {
            ValueProviderResult val = collection.GetValue("serviceOrderId");
            Guid serviceOrderId = new Guid(val.AttemptedValue);
            collection.Remove("serviceOrderId");

            ServiceOrderBusiness.PublishValidateAllInspectionReports(serviceOrderId, Roles.GetRolesForUser(UserName).ToList(), UserName);

            return SearchOrder(null, collection);
        }
        public ActionResult SaveServiceOrder(FormCollection collection)
        {
            ValueProviderResult val = collection.GetValue("serviceOrderId");
            string serviceOrderId = val.AttemptedValue;
            collection.Remove("serviceOrderId");

            Form formRetrieved = (Form)Session["FormNew"];
            ValidateForm(formRetrieved, collection);
            ValidateBusinessRules(formRetrieved, collection);

            if (ModelState.IsValid)
            {
                Guid businessApplicationId = new Guid(Convert.ToString(Session["BusinessAplicationId"]));
                if (!string.IsNullOrEmpty(serviceOrderId))
                {
                    ServiceOrderBusiness.EditServiceOrder(collection, businessApplicationId, UserName, new Guid(serviceOrderId));
                }
                else
                {
                    ServiceOrderBusiness.AddServiceOrder(collection, businessApplicationId, UserName);
                }
                return RedirectToAction("Index");
            }
            else
            {
                return View("ServiceOrder", formRetrieved);
            }
        }
        public ActionResult EditOld(Guid id, Guid contractUriId, FormCollection collection)
        {
            //Save Action
            //If id == null then insert
            try
            {
                ViewData["selectedTab"] = int.Parse(collection.GetValue("selectedTab").AttemptedValue);
                collection.Remove("selectedTab");
                bool addNewUserContractRedirect = false;
                if (id == Guid.Empty)
                    addNewUserContractRedirect = true;

                if (!addNewUserContractRedirect)
                {
                    var model = db.UserContractRedirects.FirstOrDefault(u => u.Id == id);
                    model.Enabled = collection.GetValue("Actief").AttemptedValue.Contains("true");
                    model.Name = collection.GetValue("Name").AttemptedValue;
                    //From Date
                    if (collection.GetValue("StartDatumActive").AttemptedValue.Contains("true"))
                    {
                        //We need to take the value of the date picker and store it in the model
                        string dpStartValue = collection.GetValue("dpStartDate").AttemptedValue;
                        if (!String.IsNullOrEmpty(dpStartValue) && !String.IsNullOrWhiteSpace(dpStartValue))
                            model.DateTimeValueStart = DataHelper.ParseDate(dpStartValue);
                        else
                            model.DateTimeValueStart = null;
                    }
                    else
                        model.DateTimeValueStart = null;
                    //To Date
                    if (collection.GetValue("StopDatumActive").AttemptedValue.Contains("true"))
                    {
                        string dpStopValue = collection.GetValue("dpEndDate").AttemptedValue;
                        if (!String.IsNullOrEmpty(dpStopValue) && !String.IsNullOrWhiteSpace(dpStopValue))
                            model.DateTimeValueStop = DataHelper.ParseDate(dpStopValue);
                        else
                            model.DateTimeValueStop = null;
                    }
                    else
                        model.DateTimeValueStop = null;

                    //Weekday
                    if (collection.GetValue("WeekdayActive").AttemptedValue.Contains("true"))
                    {
                        string weekdayValue = collection.GetValue("ddlWeekday").AttemptedValue;
                        if (!String.IsNullOrEmpty(weekdayValue) && !String.IsNullOrWhiteSpace(weekdayValue))
                        {
                            int day = int.Parse(weekdayValue);
                            if (day > 0 && day < 10)
                                model.DayOfTheWeekValue = day;
                            else
                                model.DayOfTheWeekValue = null;
                        }
                    }
                    else
                        model.DayOfTheWeekValue = null;

                    //Between from
                    if (collection.GetValue("BeginTimeActive").AttemptedValue.Contains("true"))
                    {
                        string tpBeginTime = collection.GetValue("tpBeginTime").AttemptedValue;
                        int? hour;
                        int? minute;
                        DataHelper.ParseTime(tpBeginTime, out hour, out minute);
                        model.TimeOfDayHourStart = hour;
                        model.TimeOfDayMinuteStart = minute;
                    }
                    else
                        model.BeginTime = null;

                    //Between To
                    if (collection.GetValue("EndTimeActive").AttemptedValue.Contains("true"))
                    {
                        string tpEndTime = collection.GetValue("tpEndTime").AttemptedValue;
                        int? hour;
                        int? minute;
                        DataHelper.ParseTime(tpEndTime, out hour, out minute);
                        model.TimeOfDayHourEnd = hour;
                        model.TimeOfDayMinuteEnd = minute;
                    }
                    else
                        model.EndTime = null;
                    //Counter
                    if (collection.GetValue("CounterActive").AttemptedValue.Contains("true"))
                    {
                        string numCounter = collection.GetValue("numCounter").AttemptedValue;
                        if (!String.IsNullOrEmpty(numCounter) && !String.IsNullOrWhiteSpace(numCounter))
                        {
                            int counterValue = int.Parse(numCounter);
                            if (counterValue > 0)
                                model.Counter = counterValue;
                            else
                                model.Counter = null;
                        }
                        else
                            model.Counter = null;
                    }
                    else
                        model.Counter = null;

                    //Update
                    db.SaveChanges();
                    //return RedirectToAction("Edit", "ContractUri", new { id = model.UserContractUri, contractId = model.UserContractUri1.UserContractId });
                    return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

                }
                else
                {
                    var model = new UserContractRedirect();
                    model.Id = Guid.NewGuid();
                    model.UserContractUri = contractUriId;

                    model.Enabled = collection.GetValue("Actief").AttemptedValue.Contains("true");
                    model.Name = collection.GetValue("Name").AttemptedValue;
                    //From Date
                    if (collection.GetValue("StartDatumActive").AttemptedValue.Contains("true"))
                    {
                        //We need to take the value of the date picker and store it in the model
                        string dpStartValue = collection.GetValue("dpStartDate").AttemptedValue;
                        if (!String.IsNullOrEmpty(dpStartValue) && !String.IsNullOrWhiteSpace(dpStartValue))
                            model.DateTimeValueStart = DataHelper.ParseDate(dpStartValue);
                        else
                            model.DateTimeValueStart = null;
                    }
                    else
                        model.DateTimeValueStart = null;
                    //To Date
                    if (collection.GetValue("StopDatumActive").AttemptedValue.Contains("true"))
                    {
                        string dpStopValue = collection.GetValue("dpEndDate").AttemptedValue;
                        if (!String.IsNullOrEmpty(dpStopValue) && !String.IsNullOrWhiteSpace(dpStopValue))
                            model.DateTimeValueStop = DataHelper.ParseDate(dpStopValue);
                        else
                            model.DateTimeValueStop = null;
                    }
                    else
                        model.DateTimeValueStop = null;

                    //Weekday
                    if (collection.GetValue("WeekdayActive").AttemptedValue.Contains("true"))
                    {
                        string weekdayValue = collection.GetValue("ddlWeekday").AttemptedValue;
                        if (!String.IsNullOrEmpty(weekdayValue) && !String.IsNullOrWhiteSpace(weekdayValue))
                        {
                            int day = int.Parse(weekdayValue);
                            if (day > 0 && day < 10)
                                model.DayOfTheWeekValue = day;
                            else
                                model.DayOfTheWeekValue = null;
                        }
                    }
                    else
                        model.DayOfTheWeekValue = null;

                    //Between from
                    if (collection.GetValue("BeginTimeActive").AttemptedValue.Contains("true"))
                    {
                        string tpBeginTime = collection.GetValue("tpBeginTime").AttemptedValue;
                        int? hour;
                        int? minute;
                        DataHelper.ParseTime(tpBeginTime, out hour, out minute);
                        model.TimeOfDayHourStart = hour;
                        model.TimeOfDayMinuteStart = minute;
                    }
                    else
                        model.BeginTime = null;

                    //Between To
                    if (collection.GetValue("EndTimeActive").AttemptedValue.Contains("true"))
                    {
                        string tpEndTime = collection.GetValue("tpEndTime").AttemptedValue;
                        int? hour;
                        int? minute;
                        DataHelper.ParseTime(tpEndTime, out hour, out minute);
                        model.TimeOfDayHourEnd = hour;
                        model.TimeOfDayMinuteEnd = minute;
                    }
                    else
                        model.EndTime = null;
                    //Counter
                    if (collection.GetValue("CounterActive").AttemptedValue.Contains("true"))
                    {
                        string numCounter = collection.GetValue("numCounter").AttemptedValue;
                        if (!String.IsNullOrEmpty(numCounter) && !String.IsNullOrWhiteSpace(numCounter))
                        {
                            int counterValue = int.Parse(numCounter);
                            if (counterValue > 0)
                                model.Counter = counterValue;
                            else
                                model.Counter = null;
                        }
                        else
                            model.Counter = null;
                    }
                    else
                        model.Counter = null;

                    //Update
                    db.UserContractRedirects.Add(model);
                    db.SaveChanges();
                    //return RedirectToAction("Edit", "ContractUri", new { id = model.UserContractUri, contractId = model.UserContractUri1.UserContractId });
                    return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

                }
            }
            catch (Exception)
            {
                //return RedirectToAction("Edit", new { id = Guid.Empty, contractUriId });
                return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

            }
        }
        public ActionResult Edit(Guid id, Guid contractUriId, UserContractRedirectModel returnModel, FormCollection collection)
        {
            //Save Action
            //If id == null then insert
            try
            {
                ViewData["selectedTab"] = int.Parse(collection.GetValue("selectedTab").AttemptedValue);
                collection.Remove("selectedTab");
                bool addNewUserContractRedirect = false;
                if (id == Guid.Empty)
                    addNewUserContractRedirect = true;

                if (!addNewUserContractRedirect)
                {
                    var model = db.UserContractRedirects.FirstOrDefault(u => u.Id == id);
                    //model.Enabled = returnModel.UserContractRedirect.Enabled;
                    //model.Name = returnModel.UserContractRedirect.Name;
                    model.Enabled = returnModel.UserContractRedirect.Actief;
                    model.Name = returnModel.UserContractRedirect.Name;

                    //From Date
                    if (collection.GetValue("UserContractRedirect.StartDatumActive").AttemptedValue.Contains("true"))
                    {
                        //We need to take the value of the date picker and store it in the model

                            model.DateTimeValueStart = returnModel.UserContractRedirect.DateTimeValueStart;
                    }
                    else
                        model.DateTimeValueStart = null;
                    //To Date
                    if (collection.GetValue("UserContractRedirect.StopDatumActive").AttemptedValue.Contains("true"))
                    {
                        model.DateTimeValueStop = returnModel.UserContractRedirect.DateTimeValueStop;
                    }
                    else
                        model.DateTimeValueStop = null;

                    //Weekday
                    if (collection.GetValue("UserContractRedirect.WeekdayActive").AttemptedValue.Contains("true"))
                    {
                        string weekdayValue = collection.GetValue("ddlWeekday").AttemptedValue;
                        if (!String.IsNullOrEmpty(weekdayValue) && !String.IsNullOrWhiteSpace(weekdayValue))
                        {
                            int day = int.Parse(weekdayValue);
                            if (day > 0 && day < 10)
                                model.DayOfTheWeekValue = day;
                            else
                                model.DayOfTheWeekValue = null;
                        }
                    }
                    else
                        model.DayOfTheWeekValue = null;

                    //Between from
                    if (collection.GetValue("UserContractRedirect.BeginTimeActive").AttemptedValue.Contains("true"))
                    {
                        model.BeginTime = returnModel.UserContractRedirect.BeginTime;
                    }
                    else
                        model.BeginTime = null;

                    //Between To
                    if (collection.GetValue("UserContractRedirect.EndTimeActive").AttemptedValue.Contains("true"))
                    {
                        model.EndTime = returnModel.UserContractRedirect.EndTime;
                    }
                    else
                        model.EndTime = null;

                    //Update
                    var ruleValues = model.RuleParameterValues.ToList();
                    foreach (var ruleValue in ruleValues)
                    {
                        model.RuleParameterValues.Remove(ruleValue);
                    }
                    foreach (var parameter in returnModel.ParameterModel)
                    {
                        if (parameter.SelectedValue != null)
                        {
                            var guid = parameter.SelectedValue.Id;

                            var selectedValue = db.RuleParameterValues.SingleOrDefault(row => row.Id == guid);
                            if (selectedValue != null)
                            {
                                model.RuleParameterValues.Add(selectedValue);
                            }
                        }
                    }

                    var redirectValues = model.RedirectTypeValues.ToList();
                    foreach (var redirectValue in redirectValues)
                    {
                        model.RedirectTypeValues.Remove(redirectValue);
                    }
                    foreach (var redirect in returnModel.RedirectTypeModel)
                    {
                        if (redirect.SelectedValue != null)
                        {
                            var guid = redirect.SelectedValue.Id;

                            var selectedValue = db.RedirectTypeValues.SingleOrDefault(row => row.Id == guid);
                            if (selectedValue != null)
                            {
                                model.RedirectTypeValues.Add(selectedValue);
                            }
                        }
                    }

                    db.SaveChanges();
                    //return RedirectToAction("Edit", "ContractUri", new { id = model.UserContractUri, contractId = model.UserContractUri1.UserContractId });
                    return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

                }
                else
                {
                    //contractUriId = returnModel.UserContractRedirect.UserContractUri1.Id;

                    var model = new UserContractRedirect();
                    model.Id = Guid.NewGuid();
                    model.UserContractUri = contractUriId;
                    model.UserContractUri1 = db.UserContractUris.SingleOrDefault(row => row.Id == contractUriId);

                    if (String.IsNullOrWhiteSpace(model.UserAgent))
                    {
                        model.UserAgent = "";
                    }

                    //model.Enabled = returnModel.UserContractRedirect.Enabled;
                    //model.Name = returnModel.UserContractRedirect.Name;
                    model.Enabled = collection.GetValue("UserContractRedirect.Actief").AttemptedValue.Contains("true");
                    model.Name = collection.GetValue("UserContractRedirect.Name").AttemptedValue;

                    //From Date
                    if (collection.GetValue("UserContractRedirect.StartDatumActive").AttemptedValue.Contains("true"))
                    {
                        //We need to take the value of the date picker and store it in the model

                        model.DateTimeValueStart = returnModel.UserContractRedirect.DateTimeValueStart;
                    }
                    else
                        model.DateTimeValueStart = null;
                    //To Date
                    if (collection.GetValue("UserContractRedirect.StopDatumActive").AttemptedValue.Contains("true"))
                    {
                        model.DateTimeValueStop = returnModel.UserContractRedirect.DateTimeValueStop;
                    }
                    else
                        model.DateTimeValueStop = null;

                    //Weekday
                    if (collection.GetValue("UserContractRedirect.WeekdayActive").AttemptedValue.Contains("true"))
                    {
                        string weekdayValue = collection.GetValue("ddlWeekday").AttemptedValue;
                        if (!String.IsNullOrEmpty(weekdayValue) && !String.IsNullOrWhiteSpace(weekdayValue))
                        {
                            int day = int.Parse(weekdayValue);
                            if (day > 0 && day < 10)
                                model.DayOfTheWeekValue = day;
                            else
                                model.DayOfTheWeekValue = null;
                        }
                    }
                    else
                        model.DayOfTheWeekValue = null;

                    //Between from
                    if (collection.GetValue("UserContractRedirect.BeginTimeActive").AttemptedValue.Contains("true"))
                    {
                        model.BeginTime = returnModel.UserContractRedirect.BeginTime;
                    }
                    else
                        model.BeginTime = null;

                    //Between To
                    if (collection.GetValue("UserContractRedirect.EndTimeActive").AttemptedValue.Contains("true"))
                    {
                        model.EndTime = returnModel.UserContractRedirect.EndTime;
                    }
                    else
                        model.EndTime = null;

                    var ruleValues = model.RuleParameterValues.ToList();
                    foreach (var ruleValue in ruleValues)
                    {
                        model.RuleParameterValues.Remove(ruleValue);
                    }
                    foreach (var parameter in returnModel.ParameterModel)
                    {
                        if (parameter.SelectedValue != null)
                        {
                            var guid = parameter.SelectedValue.Id;

                            var selectedValue = db.RuleParameterValues.SingleOrDefault(row => row.Id == guid);
                            if (selectedValue != null)
                            {
                                model.RuleParameterValues.Add(selectedValue);
                            }
                        }
                    }

                    var redirectValues = model.RedirectTypeValues.ToList();
                    foreach (var redirectValue in redirectValues)
                    {
                        model.RedirectTypeValues.Remove(redirectValue);
                    }
                    foreach (var redirect in returnModel.RedirectTypeModel)
                    {
                        if (redirect.SelectedValue != null)
                        {
                            var guid = redirect.SelectedValue.Id;

                            var selectedValue = db.RedirectTypeValues.SingleOrDefault(row => row.Id == guid);
                            if (selectedValue != null)
                            {
                                model.RedirectTypeValues.Add(selectedValue);
                            }
                        }
                    }

                    //Update
                    db.UserContractRedirects.Add(model);
                    db.SaveChanges();
                    //return RedirectToAction("Edit", "ContractUri", new { id = model.UserContractUri, contractId = model.UserContractUri1.UserContractId });
                    return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

                }
            }
            catch (DbEntityValidationException ex)
            {
                //return RedirectToAction("Edit", new { id, contractUriId });
                return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

            }
        }
        public ActionResult Edit(Guid? id, Guid? contractId, FormCollection collection, UserContractUri modelUri)
        {
            //Save Action
            //If id == null then insert
            if (!ModelState.IsValid)
            {
                return View(modelUri);
            }
            try
            {
                ViewData["selectedTab"] = int.Parse(collection.GetValue("selectedTab").AttemptedValue);
                collection.Remove("selectedTab");
                bool addNewUserContractUri = false;
                if (id.HasValue)
                {
                    if (id.Value == Guid.Empty)
                        addNewUserContractUri = true;
                }
                else
                    addNewUserContractUri = true;

                if (!addNewUserContractUri)
                {
                    var model = db.UserContractUris.FirstOrDefault(u => u.Id == id);
                    model.Enabled = modelUri.Actief;
                    model.Name = modelUri.Name;
                    model.Uri = modelUri.Uri;
                    model.RandomFunction = modelUri.RandomFunction;

                    db.SaveChanges();
                    return View(model);
                }
                else
                {
                    UserContractUri model = new UserContractUri();
                    var contract = db.UserContracts.First(c => c.Id == contractId);
                    model.Id = Guid.NewGuid();
                    model.UserContractId = contract.Id;
                    model.Enabled = modelUri.Actief;
                    model.Name = modelUri.Name;
                    model.Uri = modelUri.Uri;
                    model.RandomFunction = modelUri.RandomFunction;

                    db.UserContractUris.Add(model);
                    db.SaveChanges();
                    //return RedirectToAction("Edit", new {id = model.Id, contractId = model.UserContractId});
                    //return RedirectToAction("Edit", "Contract", new { id = contract.Id, userId = contract.UserId });
                    return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

                }
            }
            catch(Exception ex)
            {
                //return RedirectToAction("Edit", new { id = Guid.Empty, contractId = contractId });
                return BreadCrum.RedirectToPreviousAction(Session, ControllerName);

            }
        }
        public PartialViewResult UnPublishInspectionReport(FormCollection collection)
        {
            ValueProviderResult val = collection.GetValue("inspectionReportItemId");
            Guid inspectionReportItemId = new Guid(val.AttemptedValue);
            collection.Remove("inspectionReportItemId");
            string inspectionReportName = Session["InspectionReportName"].ToString();

            InspectionReportBusiness.UnPublishInspectionReport(inspectionReportItemId, UserName, Roles.GetRolesForUser(UserName).ToList());

            return SearchInspectionReport(null, inspectionReportName, collection);
        }
        /// <summary>
        /// Get the needed data for writing the excel file
        /// </summary>
        /// <param name="collection">The collection sent by the form</param>
        /// <param name="businessApplicationId">Id of business application</param>
        /// <param name="serviceOrderReportId">Id of service order</param>
        /// <returns>DynamicDataGrid</returns>
        private DynamicDataGrid GetModelExportExcel(FormCollection collection, Guid businessApplicationId, Guid serviceOrderReportId)
        {
            if (collection.ToFilledDictionary().Keys.Contains("InspectionReportId"))
                collection.Remove("InspectionReportId");
            if (collection.ToFilledDictionary().Keys.Contains("selectedInspectionReports"))
                collection.Remove("selectedInspectionReports");

            List<string> fielsdWithLike = new List<string>();
            foreach (string name in collection.AllKeys.Where(name => name.Contains("IsLike")))
            {
                fielsdWithLike.Add(name.Replace("IsLike", ""));
                collection.Remove(name);
            }

            //set the parameters for search

            ParameterSearchInspectionReport parameters = new ParameterSearchInspectionReport
                                                             {
                                                                 BusinessApplicationId = businessApplicationId,
                                                                 Collection = collection,
                                                                 InspectionReportName = _inspectionReportId,
                                                                 ServiceOrderId = serviceOrderReportId,
                                                                 UserName = UserName,
                                                                 RolesForUser = Roles.GetRolesForUser(UserName).ToList(),
                                                                 PageSize = 0,
                                                                 SelectedPage = 0,
                                                                 IsClient = User.IsInRole("Client"),
                                                                 IsExport = true,
                                                                 Captions = _captions,
                                                                 FieldsWithLike = fielsdWithLike
                                                             };

            //get the data
            return InspectionReportBusiness.SearchInspectionReportList(parameters);
        }
Beispiel #17
0
        public virtual ActionResult Edit(int id, FormCollection collection)
        {
            DAT_ERRORDETAIL error = _db.DAT_ERRORDETAIL.FirstOrDefault(c => c.ERRORDETAILID == id);
            string lydosua = collection["LyDoSua"];
            collection.Remove("LyDoSua");

            if (lydosua == "")
            {
                ModelState.AddModelError("LyDoSua", "Chưa nhập lý do");
            }
            if (ModelState.IsValid)
            {
                try
                {
                    // TODO: Add update logic here
                    //  db.Entry(error).State =collection EntityState.Modified;

                    UpdateModel(error, collection.ToValueProvider());
                    string log = LogsHelper.GetRecordsForChange(_db.Entry(error));
                    if (error != null)
                    {
                        error.MODIDATE = DateTime.Now;
                        error.MODIUSER = User.Identity.Name;
                        error.ENTERDATE = DateTime.Now;
                        error.DAT_ErrorLog.Add(new DAT_ErrorLog
                        {
                            ErrorID = error.ERRORDETAILID,
                            ngay = DateTime.Now,
                            ThaoTac = "Sua",
                            UserId = User.Identity.Name,
                            DiaChi = Dns.GetHostEntry(ClientHelpers.GetClientIpAddress(Request)).HostName,
                            Ip = ClientHelpers.GetClientIpAddress(Request),
                            Logs = log,
                            LyDo = lydosua
                        });
                    }

                    _db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch
                {
                    return View();
                }
            }
            return View(error);
        }
        public PartialViewResult SearchOrder(int? page, FormCollection collection)
        {
            bool isClient = User.IsInRole("Client");
            Guid businessApplicationId = new Guid(Convert.ToString(Session["BusinessAplicationId"]));
            if (isClient)
            {
                if (collection.AllKeys.Contains("Client")) collection.Remove("Client");
                Guid? parameter = AuthorizationBusiness.GetClientIdByBusinnessApplication(businessApplicationId, UserName);
                collection.Add("Client", parameter.GetValueOrDefault().ToString());
            }
            int currentPage = page == null ? 1 : page.Value;
            int pageSize = Cotecna.Vestalis.Web.Properties.Settings.Default.PageSize;

            List<string> fielsdWithLike = new List<string>();
            foreach (string name in collection.AllKeys.Where(name => name.Contains("IsLike")))
            {
                fielsdWithLike.Add(name.Replace("IsLike", ""));
            }

            ParameterSearchServicerOrder parameters = new ParameterSearchServicerOrder
            {
                FormCollection = collection,
                BusinessApplicationId = businessApplicationId,
                RolesForUser = Roles.GetRolesForUser(UserName).ToList(),
                Page = currentPage,
                PageSize = pageSize,
                IsExport = false,
                IsClient = isClient,
                FielsdWithLike = fielsdWithLike
            };
            DynamicDataGrid model = ServiceOrderBusiness.SearchOrderList(parameters);

            _formCollection = collection;

            model.Captions = _captions;

            return PartialView("_ServiceOrderGrid", model);
        }
        public ActionResult Edit(Guid? id, Guid? userId, FormCollection collection, UserContract userContract)
        {
            //Save Action
            //If id == null then insert
            try
            {
                ViewData["selectedTab"] = int.Parse(collection.GetValue("selectedTab").AttemptedValue);
                collection.Remove("selectedTab");
                var addNewUserContract = !id.HasValue || (id == Guid.Empty);
                if (ModelState.IsValid)
                {
                    if (!addNewUserContract)
                    {
                        if (!userContract.eId.HasValue())
                        {
                            userContract.eId = Utilities.GetRandomSalt(5);
                        }
                        db.Entry(userContract).State = EntityState.Modified;

                        db.SaveChanges();
                        return BreadCrum.RedirectToPreviousAction(Session, ControllerName);
                        //return RedirectToAction("Edit", new { id = model.Id, userId = model.UserId });
                        //return View(model);
                    }
                    else
                    {
                        userContract.Id = Guid.NewGuid();
                        if (!userContract.eId.HasValue())
                        {
                            userContract.eId = Utilities.GetRandomSalt(5);
                        }
                        db.UserContracts.Add(userContract);
                        db.SaveChanges();

                        return BreadCrum.RedirectToPreviousAction(Session, ControllerName);
                        //return RedirectToAction("Edit", new { id = model.Id, userId = model.UserId });
                    }
                }
            }
            catch (Exception ex)
            {
                //return RedirectToAction("Edit", new { id = Guid.Empty, userId = userId });
            }
            var user = db.Users.Find(userContract.UserId);
            userContract.User = user;

            return View(userContract);

            //ViewBag.Contract = new SelectList(db.Contracts, "Id", "Name", userContract.Contract);
            //return BreadCrum.RedirectToPreviousAction(Session, ControllerName);
        }
 private static FormCollection Compatibility(FormCollection collection)
 {
     switch (collection.Count)
     {
         case 7:
             if (!IsDocument(collection)) collection.Add("Document", "");
             return collection;
         case 9:
             if (!IsDocument(collection)) collection.Add("Document", "");
             return collection;
         case 8:
             var animalname = collection[7];
             collection.Remove("AnimalName");
             if (!IsDocument(collection)) collection.Add("Document", "");
             collection.Add("AnimalName", animalname);
             return collection;
         case 6:
             var totalcost = collection[4];
             var animalname1 = collection[5];
             collection.Remove("TotalCost");
             collection.Remove("AnimalName");
             if (!IsDocument(collection)) collection.Add("Document", "");
             collection.Add("TotalCost", totalcost);
             collection.Add("AnimalName", animalname1);
             return collection;
         default:
             return collection;
     }
 }
        public ActionResult InstallApplications(FormCollection form)
        {
            try
            {
                // Get current tab
                string currentTab = form.Get("CurrentTab");

                // All product download urls' versions (selected and not selected both)
                string[] productVersions = form.Get("downloadUrls").Split(',');

                // Remove unnecessary keys in order to preserve proper order
                form.Remove("downloadUrls");
                form.Remove("buttonAccept");
                form.Remove("CurrentTab");

                List<string> productIDs = form.AllKeys.Where(k => !k.StartsWith("Parameter_")).ToList<string>();
                Dictionary<string, string> productsToInstall = new Dictionary<string, string>();

                if (0 < productIDs.Count())
                {
                    // Prepare information about selected product 
                    for (int i = 0; i < productIDs.Count(); i++)
                    {
                        string productID = productIDs[i];
                        if (form.Get(productID).StartsWith("true"))
                        {
                            List<string> parameters = new List<string>();
                            parameters.Add(productVersions[i]);

                            foreach (string k in form.AllKeys.
                                Where(k => k.StartsWith("Parameter_" + productID)).ToArray<string>())
                            {
                                string param = k.Split('=')[1];
                                string value = form.Get(k);
                                parameters.Add(param + "=" + value);
                            }

                            productsToInstall.Add(
                                    productID,
                                    string.Join(",",
                                        parameters.ToArray()
                                    )
                                );
                        }
                    }
                }

                if (null != productsToInstall && 0 < productsToInstall.Count)
                {
                    try
                    {
                        // Install applications
                        IVMManager vmManager = WindowsAzureVMManager.GetVMManager();
                        vmManager.InstallApplications(productsToInstall);
                    }
                    catch (Exception ex)
                    {
                        Trace.TraceError("Unable to install applications: {0}", ex.Message);
                        return RedirectToAction("Error", "Home", new { ErrorMessage = "Unable to install applications." });
                    }
                }

                return RedirectToAction(
                            "ProgressInformation",
                            "Admin",
                            new
                            {
                                ActionName = "Applications",
                                ControllerName = "Applications",
                                ActionSubtabName = "AvailableApplicationsList",
                                CurrentTab = currentTab
                            }
                        );
            }
            catch (Exception ex)
            {
                Trace.TraceError("Unable to gather information to install platform products: {0}", ex.Message);
                return RedirectToAction("Error", "Home", new { ErrorMessage = "Unable to gather information to install platform products." });
            }
        }
        public ActionResult Index(FormCollection menu)
        {
            try
                {
                    if (ModelState.IsValid)
                    {
                        Dictionary<itCart, int> sKorzina = Session["sKorzina"] as Dictionary<itCart, int>;
                        if (sKorzina == null) sKorzina = new Dictionary<itCart, int>(new itCart.itCartComparer());
                        Session["sKorzina"] = sKorzina;
                        menu.Remove("empty");
                        int cntFC = menu.Count;
                        string[] arOptID=new string[cntFC-1];
                        for (int i = 0; i < cntFC - 1; i++)
                            arOptID[i] = menu["item.OptID"].Split(new char[] { ',' })[i];
                        menu.Remove("item.OptID");

                        for (int i = 0; i < menu.Count; i++)
                        {
                            var v = menu[i].Split(new char[] { ',' })[0];

                            if (v == "true")
                            {
                                itCart s=new itCart();
                                var o = Convert.ToInt32(arOptID[i]);
                                var d = Convert.ToInt32(menu.AllKeys[i]);
                                s.drink=d;
                                if (o==0)
                                    s.opt=null;
                                else
                                    s.opt=o;

                                if (sKorzina.ContainsKey(s))  sKorzina[s] = sKorzina[s] + 1;
                                    else sKorzina[s] = 1;
                            }

                        }
                        Session["sKorzina"] = sKorzina;
                        return RedirectToAction("Index");
                    }

                }
                catch (Exception ex)
                {
                    ModelState.AddModelError(string.Empty, ex);
                }

            OptionsDropDownList();
            return View(menu);
        }
        /// <summary>
        /// Validate or publish all inspection reports
        /// </summary>
        /// <param name="collection">Form collection</param>
        /// <returns>PartialViewResult</returns>
        public PartialViewResult PublishValidateSelectedInspectionReports(string selectedInspectionReports,FormCollection collection)
        {
            string inspectionReportName = Session["InspectionReportName"].ToString();
            string selectedOption = string.Empty;
            Guid serviceOrderReportId = new Guid(Session["serviceOrderReportId"].ToString());
            List<Guid?> selectedInspectionReportIds = new List<Guid?>();
            string[] selectedIds = selectedInspectionReports.Split(new string[] { "&&&" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string item in selectedIds)
            {
                selectedInspectionReportIds.Add(new Guid(item));
            }

            if (collection.AllKeys.Contains("inspectionReportItemId"))
                collection.Remove("inspectionReportItemId");

            if (collection.AllKeys.Contains("selectedOption"))
            {
                selectedOption = collection["selectedOption"].ToString();
                collection.Remove("selectedOption");
            }

            bool isPublish = selectedOption == "publish";

            ParameterPublishValidateInspectionReports parameters = new ParameterPublishValidateInspectionReports
            {
                InspectionReportName = inspectionReportName,
                ServiceOrderId = serviceOrderReportId,
                RolesForUser = Roles.GetRolesForUser(UserName).ToList(),
                UserName = UserName,
                IsPublish = isPublish,
                SelectedIds = selectedInspectionReportIds
            };

            InspectionReportBusiness.PublishValidateSelected(parameters);

            return SearchInspectionReport(null, inspectionReportName, collection);
        }
Beispiel #24
0
        /// <summary>
        /// Sanitizes the form collection.
        /// </summary>
        /// <param name="collection">The collection.</param>
        protected virtual void SanitizeFormCollection(FormCollection collection)
        {
            const char ReplacementSymbol = '_';
            var forbidenSymbols = new char[] { '-' };

            if (collection != null)
            {
                var forbidenKeys = collection.AllKeys.Where(k => k.IndexOfAny(forbidenSymbols) >= 0);
                foreach (var key in forbidenKeys)
                {
                    var newKey = key.ToCharArray();
                    for (int i = 0; i < newKey.Length; i++)
                    {
                        if (forbidenSymbols.Contains(newKey[i]))
                        {
                            newKey[i] = ReplacementSymbol;
                        }
                    }

                    collection.Add(new string(newKey), collection[key]);
                    collection.Remove(key);
                }
            }
        }
        public ActionResult SaveInspectionReport(FormCollection collection)
        {
            if (collection.AllKeys.Contains("serviceOrderId")) collection.Remove("serviceOrderId");
            InspectionReportModel model = Session["frmNewInspection"] as InspectionReportModel;
            Guid serviceOrderReportId = new Guid(Session["serviceOrderReportId"].ToString());
            Guid businessApplicationId = new Guid(Convert.ToString(Session["BusinessAplicationId"]));
            Guid inspectionReportItemId = Guid.Empty;
            string publishValidate = string.Empty;
            string myuploader = string.Empty;
            //validate form and business rules
            if (model.ScreenOpenMode != ScreenOpenMode.View)
            {
                ValidateForm(model.FormDefinition, collection);
                ValidateBusinessRules(model.FormDefinition, collection);
            }
            if (ModelState.IsValid)
            {
                //if publish or validate button is clicked, take the value and remove the key from the collection
                if (collection.AllKeys.Contains("PublishValidateOption") && !string.IsNullOrEmpty(collection["PublishValidateOption"]))
                    publishValidate = collection["PublishValidateOption"];
                collection.Remove("PublishValidateOption");

                if(collection.AllKeys.Contains("UploadLib_Uploader_js"))
                    collection.Remove("UploadLib_Uploader_js");

                if (collection.AllKeys.Contains("__RequestVerificationToken"))
                    collection.Remove("__RequestVerificationToken");

                if (collection.AllKeys.Contains("myuploader"))
                {
                    myuploader = collection["myuploader"].ToString();
                    collection.Remove("myuploader");
                }

                //Set parameters for the method
                ParameterSaveInspectionReport parameters = new ParameterSaveInspectionReport
                {
                    BusinessApplicationId = businessApplicationId,
                    FormCollection = collection,
                    InspectionReportName = model.GridColumns.FormName,
                    ServiceOrderId = serviceOrderReportId,
                    UserName = UserName,
                    RolesForUser = Roles.GetRolesForUser(UserName).ToList(),
                    IsClient = User.IsInRole("Client")
                };
                if (model.ScreenOpenMode == ScreenOpenMode.Add)
                   inspectionReportItemId =  InspectionReportBusiness.AddInspectionReport(parameters);
                else if (model.ScreenOpenMode == ScreenOpenMode.Edit)
                {
                    inspectionReportItemId = new Guid(Session["inspectionReportItemId"].ToString());
                    parameters.InspectionReportItemId = inspectionReportItemId;

                    //perform edit operation
                    InspectionReportBusiness.EditInspectionReport(parameters);
                    //publish or validate inspection report item
                    if (!string.IsNullOrEmpty(publishValidate))
                        InspectionReportBusiness.PublishValidateInspectionReport(inspectionReportItemId, UserName);

                }
                else if (model.ScreenOpenMode == ScreenOpenMode.View && !string.IsNullOrEmpty(publishValidate) && publishValidate == "UnPublish")
                {
                    //Get the id of inspection report item
                    inspectionReportItemId = new Guid(Session["inspectionReportItemId"].ToString());
                    //Perform unpublish operation
                    InspectionReportBusiness.UnPublishInspectionReport(inspectionReportItemId, UserName, Roles.GetRolesForUser(UserName).ToList());
                }
                else if (model.ScreenOpenMode == ScreenOpenMode.View && !string.IsNullOrEmpty(publishValidate) && (publishValidate == "Publish" || publishValidate == "Validate"))
                {
                    //Get the id of inspection report item
                    inspectionReportItemId = new Guid(Session["inspectionReportItemId"].ToString());
                    //Perform unpublish operation
                    InspectionReportBusiness.PublishValidateInspectionReport(inspectionReportItemId, UserName);
                }

                if (!string.IsNullOrEmpty(myuploader) && model.ScreenOpenMode == ScreenOpenMode.Add)
                {
                    using (CuteWebUI.MvcUploader uploader = new CuteWebUI.MvcUploader(System.Web.HttpContext.Current))
                    {
                        if (!string.IsNullOrEmpty(myuploader))
                        {
                            List<string> processedfiles = new List<string>();
                            //for multiple files , the value is string : guid/guid/guid
                            foreach (string strguid in myuploader.Split('/'))
                            {
                                //for single file , the value is guid string
                                Guid fileguid = new Guid(strguid);
                                CuteWebUI.MvcUploadFile file = uploader.GetUploadedFile(fileguid);
                                if (file != null)
                                {
                                    //Save the picture in the database
                                    PictureDocumentBusiness.UploadPicture(file, serviceOrderReportId, UserName, inspectionReportItemId);
                                    processedfiles.Add(file.FileName);
                                    file.Delete();
                                }
                            }
                            if (processedfiles.Count > 0)
                                ViewData["UploadedMessage"] = string.Join(",", processedfiles.ToArray()) + " have been processed.";
                        }
                    }
                }

                return RedirectToAction("ChangeReport", "InspectionReport");
            }
            else
            {
                return View("InspectionReport", model);
            }
        }
        //for training
        public ActionResult TrainData(FormCollection form)
        {
            string[] Answers2= new string[92] { "0True", "1True", "2True", "3True", "4True", "5False", "test", "7False", "8False", "9very little", "10False", "11False", "12at the end", "13very little to no time", "14False", "15False", "16Fast", "17False", "18Less than a Year", "19False", "20Every 1-3 weeks", "21Every 1-3 weeks", "22False", "23False", "24False", "25very", "26True", "27very", "28False", "29False", "30little", "31little", "32average amount", "33love it", "34False", "35spread out across country", "36low - Medium", "37High", "38False", "39False", "40True", "41False", "42False", "43low", "44True", "45One", "46False", "47True", "48True", "49True", "50None", "51True", "52True", "53False", "54Medium", "55True", "56True", "57False", "58False", "59False", "60Updated Often", "61False", "62False", "63False", "64Low Budget", "65Low Budget", "66Low Budget", "67Low Budget", "68False", "69False", "70False", "71Small", "72True", "73False", "74Flexable", "75True", "76True", "77True", "78True", "79True", "80True", "81True", "82True", "83True", "84False", "85False", "86False", "87False", "88True", "89False", "90False", "91False" };
            Debug.Print("Answers2: " +Answers2.Length.ToString());
            Debug.Print("Train COUNT IN CONTROLLER");
            string[] Answers = new string[form.Count]; //for now hard code it
            Debug.Print("Form length is: " + form.Count.ToString());
            form.CopyTo(Answers, 0);
            for(int i=0; i<Answers.Length; i++)
            {
                Debug.Write(Answers[i]+", ");
            }
            Debug.Print("Length of form is: ");
            Debug.Print(Answers.Length.ToString());
            if (Answers.Length==93) //if all the questions were answered
            {
                string winner = form[form.Count - 1];
                //Debug.Print("winner: " + winner);
                string key= form.GetKey(form.Count-1);
                form.Remove(form.GetKey(form.Count - 1));//hopefully removing the winner from the form
                Answers = new string[form.Count];
                form.CopyTo(Answers, 0);
                string[] OldAnswers = new string[form.Count];
                Answers.CopyTo(OldAnswers, 0);
                PModel.Answers = PModel.RemoveQuestionIDS(Answers);
                /*Debug.Print("Answers Again: ");
                for (int i = 0; i < Answers.Length; i++) //test
                {
                    Debug.Write(Answers[i] + ",");
                }*/
                int score =PModel.TrainData(winner);

                ViewData["isValid"] = "true";
                ViewData["answers"] = OldAnswers;
                ViewData["questions"] = PModel.Questions;
                ViewData["multAnswers"] = PModel.MultipleChoiceAnswers;
                ViewData["result"] = winner + " has been added to the database with a score of " + score.ToString();
                return View("TrainingData");
            }
            else
            {
                ViewData["questions"] = PModel.Questions;
                ViewData["multAnswers"] = PModel.MultipleChoiceAnswers;
                ViewData["isValid"] = "false";
                ViewData["answers"] = Answers;
                ViewData["result"] = "";
                return View("TrainingData");
            }
        }
Beispiel #27
0
        private JsonResult SaveModules(
            FormCollection _vars,
            SaveModulesOperation _op)
        {
            if(String.IsNullOrEmpty(_vars["userid"])) {
                return Json(new { result = -1, msg = "Erro: Identificação do usuário inválida." });
            }

            Guid userID;
            try {
                userID = new Guid(_vars["userid"]);
            }
            catch(Exception e) {
                return Json(new { result = -1, msg = "Identificação do usuário em formato inválido.\n" + e.Message });
            }

            _vars.Remove("userid");

            Action<Guid, int> del;

            if(_op == SaveModulesOperation.Add) {
                del = ModRepository.AddUserModule;
            }
            else {
                del = ModRepository.RemoveUserModule;
            }

            foreach(string s in _vars) {
                try {
                    del(userID, Int32.Parse(_vars[s]));
                }
                catch(Exception e) {
                    return Json(new { result = -1, msg = "Falha ao adicionar o módulo selecionado.\n" + e.Message });
                }
            }

            return Json(new { result = 0, msg = "Sucesso." });
        }