Пример #1
0
        public ActionResult Ajouter(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                bool isSith;

                if (collection.GetValues("IsSith").First() == "true")
                {
                    isSith = true;
                }
                else isSith = false;

                /*ViewBag.caracForce = client.GetCaracteristiques().Where(c => c.Nom == collection.GetValues("Force").First());
                Console.WriteLine(client.GetCaracteristiques().Where(c => c.Nom == collection.GetValues("Force").First()));*/
                /*if (Request.Form["force"] != null)
                {
                    Console.WriteLine("HAHAHAHAHAHAHAHAH" + Request.Form["force"]);
                }
                else Console.WriteLine("KOUKOU");*/

                /*ViewBag.test = client.GetCaracteristiques().Where(c => c.Nom == Request.Form["force"]);*/

                client.AddJedi(collection.GetValues("Nom").First(), isSith, null, null,null,null);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        public ActionResult LoGon2(FormCollection forms)
        {
            string username = forms.GetValues("navbar_username")[0];
            string password = forms.GetValues("navbar_password")[0];
            bool remember = bool.Parse(forms.GetValues("navbar_remeber")[0]);
            string url = forms.GetValues("navbar_url")[0];

            if (MembershipService.ValidateUser(username, password))
            {
                FormsService.SignIn(username, remember);
                if (!String.IsNullOrEmpty(url))
                {
                    return Redirect(url);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            return Redirect(url);
        }
        public ActionResult getDeclareInfo(FormCollection collect)
        {
            Model.declareViewModel d_project = new Model.declareViewModel();
            d_project.project_name=Request["project_name"];
            d_project.declarant_id = (string)SessionHelper.Get("ID");
               // d_project.declarant_id = (string)Session["ID"];
            d_project.phone = Request["mainer_phone"];
            d_project.email=Request["mainer_email"];
            d_project.leader=Request["mainer_name"];
            d_project.p_type=Request["p_type"];
            d_project.now_level=Request["now_level"];
            d_project.target_level=Request["target_level"];
            d_project.s_time=Convert.ToDateTime(Request["s_time"]);
            d_project.f_time = Convert.ToDateTime(Request["f_time"]);
            d_project.money = Convert.ToInt16(Request["money"]);
            d_project.p_id = BLL.ProjectServer.getProjectNum() + 1;
            d_project.create_time = DateTime.Now;
            //d_project.belongs=(string)Session["belongs"];
            d_project.belongs = SessionHelper.Get("p_belongs");
            string[] ts_time = collect.GetValues("ts_time");
            string[] tf_time = collect.GetValues("tf_time");
            string[] t_content = collect.GetValues("t_content");
            string[] member2 = collect.GetValues("member");
              d_project.member = new List<Member>();
            foreach (string m in member2)
            {

                Model.Member mem=new Model.Member();
                mem.nickname = m;
                mem.project_id = BLL.ProjectServer.getProjectNum()+1;
                d_project.member.Add(mem);
            }
              d_project.task = new List<Task>();
            for(int i=1;i<=ts_time.Count();i++){

                Task t = new Task();
                t.t_id = i;
                t.s_time=Convert.ToDateTime(ts_time[i-1]);
                t.f_time=Convert.ToDateTime(tf_time[i-1]);
                t.task_content=t_content[i-1];
                d_project.task.Add(t);

            }

            HttpPostedFileBase paper_file=Request.Files["paper_file"];
            HttpPostedFileBase report_file = Request.Files["report_file"];
            HttpPostedFileBase whole_file = Request.Files["whole_file"];

            d_project.report_file = "~/Upload/" + d_project.p_id + "/" +"report/"+ report_file.FileName;
            d_project.paper_file = "~/Upload/" + d_project.p_id + "/" + "paper/"+paper_file.FileName;
            d_project.whole_file = "~/Upload/" + d_project.p_id + "/" + "wholefile/"+whole_file.FileName;

                if (BLL.DeclareService.declareProject(d_project))
                {
                    Common.UpLoadServer.UploadFile(d_project, report_file, report_file, whole_file);
                }
                return Content("a");
        }
Пример #4
0
        public ActionResult Save(FormCollection form)
        {
            List<string> names, dates, descriptions, costs;

            //Get values
            names = new List<string>(form.GetValues("name[]"));
            dates = new List<string>(form.GetValues("date[]"));
            descriptions = new List<string>(form.GetValues("description[]"));
            costs = new List<string>(form.GetValues("cost[]"));

            string formName = string.Empty;
            //Create new form

            if (!string.IsNullOrEmpty(form["formName"]))
            {
               formName = form["formName"];
            }

                 // TODO: validation
                double totalCost = costs.Sum(c => double.Parse(c));
       
            Models.Form newForm = new Models.Form();
            newForm = FormHelper.Create(formName,totalCost);

          
           

            
            using (ExpenseEntities db = new ExpenseEntities())
            {
                Models.Expense expense;
                for (int i = 0; i < names.Count; i++)
                {
                    
                    expense = new Models.Expense();
                    expense.Id = Guid.NewGuid();
                    expense.Name = names[i];
                    expense.Date = DateTime.Parse(dates[i]);
                    expense.Description = descriptions[i];
                    expense.Cost = int.Parse(costs[i]);
                    expense.FormId = newForm.Id;
                    expense.StateId = newForm.StateId;
                    db.Expenses.Add(expense);
                }
                          
                db.SaveChanges();
            }
           



            return RedirectToAction("New","Expense");
        }
Пример #5
0
        public ActionResult Editer(int id, FormCollection collection)
        {
            try
            {
                client.modMatch(id, int.Parse(collection.GetValues("IdJediVainqueur").First()), collection.GetValues("Jedi1").First(), collection.GetValues("Jedi2").First(), collection.GetValues("Stade").First());

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
Пример #6
0
        public ActionResult Editer(int id, FormCollection collection)
        {
            try
            {
                client.modStade(id, int.Parse(collection.GetValues("NbPlaces").First()), collection.GetValues("Nom").First(), collection.GetValues("Planete").First(), null, null, null, null);

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
Пример #7
0
        /// <summary>
        /// validiert die Formulareingaben auf Korrektheit
        /// </summary>
        /// <param name="formData">FormCollection mit den Formulareingaben aus dem Create-Formular</param>
        /// <param name="numExercises">Anzahl der Uebungen im Plan</param>
        /// <returns>true oder false</returns>
        public bool ValidateSessionFormData(FormCollection formData, int numExercises)
        {
            // workoutID und anzahl der Workouts muss numerisch sein
            byte dayID = 0;
            int workoutID = -1;
            if (!Byte.TryParse(formData.Get("dayID"), out dayID) || !Int32.TryParse(formData.Get("workoutID"), out workoutID)) return false;

            DateTime workoutDate = DateTime.MinValue;
            if (formData.Get("session-date").Trim() == "" || !DateTime.TryParse(formData.Get("session-date"), out workoutDate) || workoutDate == DateTime.MinValue)
            {
                return false;
            }

            // pruefen, dass alle Wiederholungs- und Gewichtszahlen numerisch und in einem gewissen Rahmen liegen
            int tmp = -1;
            double dtmp = -1.0;
            string[] weight, reps;
            for (int i = 0; i < numExercises; i++)
            {
                reps = formData.GetValues("reps-" + i);
                weight = formData.GetValues("weight-" + i);
                if ((reps != null || weight != null) && reps.Length != weight.Length) return false;

                for (int j = 0; j < reps.Length; j++)
                {
                    if (!String.IsNullOrEmpty(reps[j].Trim()) && (!Int32.TryParse(reps[j], out tmp) || tmp < 0 || tmp > 1000)) return false;
                    if (!String.IsNullOrEmpty(reps[j].Trim()) && (!Double.TryParse(weight[j], out dtmp) || dtmp < 0.0 || dtmp > 1000.0)) return false;
                    if ((String.IsNullOrEmpty(reps[j].Trim()) && !String.IsNullOrEmpty(weight[j].Trim())) || (!String.IsNullOrEmpty(reps[j].Trim()) && String.IsNullOrEmpty(weight[j].Trim()))) return false;
                }
            }

            return true;
        }
Пример #8
0
		public ActionResult Create(FormCollection collection) {
			try {
				ServiceReference.JediWS jedi = new JediWS();
				List<CaracteristiqueWS> caracList = new List<CaracteristiqueWS>();

				using(ServiceReference.ServiceClient service = new ServiceClient()) {
					service.getCaracteristiques().ForEach(x => {
						if(x.Type == ServiceReference.ETypeCaracteristiqueWS.Jedi) {
							caracList.Add(x);
						}
					});

					/* Item1. sur le champs du jedi parce que on a un tuple */
					jedi.Id = 0; // Car creation
					jedi.Nom = Convert.ToString(collection.Get("Item1.Nom"));
					jedi.IsSith = Convert.ToBoolean(collection.Get("Item1.IsSith") != "false"); // Pour que ca marche bien
					jedi.Caracteristiques = new List<CaracteristiqueWS>(); // Pour init

					string[] checkboxes = collection.GetValues("caracteristiques");
					if(checkboxes != null) {
						foreach(string s in checkboxes) {
							//On a que les ids des box selected, on ajoute les caracteristiques
							Int32 caracId = Convert.ToInt32(s);
							jedi.Caracteristiques.Add(caracList.First(x => x.Id == caracId));
						}
					}

					service.addJedi(jedi); // Ajout du jedi
				}

				return RedirectToAction("Index"); // Retour a l'index
			} catch {
				return RedirectToAction("Index");
			}
		}
Пример #9
0
		public ActionResult Create(FormCollection collection) {
			try {
				ServiceReference.StadeWS stade = new StadeWS();
				List<CaracteristiqueWS> caracList = new List<CaracteristiqueWS>();

				using(ServiceReference.ServiceClient service = new ServiceClient()) {
					service.getCaracteristiques().ForEach(x => {
						if(x.Type == ServiceReference.ETypeCaracteristiqueWS.Stade) {
							caracList.Add(x);
						}
					});

					/* Item1 parce qu'on a un Tuple */
					stade.Id = 0;
					stade.Planete = Convert.ToString(collection.Get("Item1.Planete"));
					stade.NbPlaces = Convert.ToInt32(collection.Get("Item1.NbPlaces"));
					stade.Caracteristiques = new List<CaracteristiqueWS>();

					string[] checkboxes = collection.GetValues("caracteristiques");
					if(checkboxes != null) {
						foreach(string s in checkboxes) {
							Int32 caracId = Convert.ToInt32(s);
							stade.Caracteristiques.Add(caracList.First(x => x.Id == caracId));
						}
					}

					service.addStade(stade);
				}
				return RedirectToAction("Index");
			} catch {
				return RedirectToAction("Index");
			}
		}
Пример #10
0
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                model = new Categorias(Session);
                Categoria Categoria = new Categoria();
                Categoria.Nome = collection["Nome"];

                string[] Subcategorias = collection.GetValues("Subcategoria");

                List<Categoria> ListSubcategoria = new List<Categoria>();

                foreach (string nome in Subcategorias)
                {
                    if (String.IsNullOrWhiteSpace(nome)) continue;

                    Categoria Subcategoria = new Categoria();
                    Subcategoria.Nome = nome;

                    if (!String.IsNullOrWhiteSpace(Subcategoria.Nome))
                        ListSubcategoria.Add(Subcategoria);
                }
                Categoria.SubCategorias = ListSubcategoria.ToArray();

                model.Create(Categoria);
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
Пример #11
0
        public ActionResult Create(FormCollection form)
        {
            var userId = Int32.Parse(form["userId"]);
            var siteName = form["sites"];

            var ctx = new App_Data.StackFlairDataContext();
            var site = ctx.StackSites.Where(s => s.Url == siteName).Single();

            var associationId = StackyWrapper.GetAssociationId(userId, site);
            var options = "";
            if (form.GetValues("beta").Contains("true")) { options += ",noBeta";  }
            if (!form.GetValues("combined").Contains("true")) { options += ",only=" + site.KeyName; };
            if (!form["themes"].Equals("default")) { options += ",theme=" + form["themes"]; }
            if (!string.IsNullOrEmpty(options)) { options = "/options/" + options.Substring(1); }
            string url = "~/Generate" + options + "/" + associationId.ToString() + "." + form["format"];
            //return Content(url);
            return Redirect(url);
            //return View("Default");
        }
Пример #12
0
        /// <summary>
        /// liest die einzelnen Saetze einer Session aus der FormCollection aus und speichert sie in der Datenbank
        /// </summary>
        /// <param name="formData">FormCollection mit den Daten aus dem Formular</param>  
        /// <param name="numExercises">number of exercises in the workout plan</param>
        public void SaveSets(FormCollection formData, ml_Session session, int numExercises)
        {
            int workoutID = Convert.ToInt32(formData.Get("workoutID").ToString());
            byte dayID = Convert.ToByte(formData.Get("dayID"));

            string[] weight, reps;
            for (int i = 0; i < numExercises; i++)
            {
                reps = formData.GetValues("reps-" + i);
                weight = formData.GetValues("weight-" + i);

                // einzelne Saetze speichern
                for (int j = 0; j < reps.Length; j++)
                {
                    if (String.IsNullOrEmpty(weight[j].Trim()) || String.IsNullOrEmpty(reps[j].Trim())) continue;
                    saveSet(session.ID, i, j, Convert.ToDouble(weight[j]), Convert.ToInt32(reps[j]));
                }
            }
        }
 public virtual ActionResult Index(FormCollection formCollection)
 {
     var selectedValues = formCollection.GetValues("selectCheckBox");
     if (selectedValues != null && selectedValues.Count() > 1)
     {
         var selectedIds = selectedValues.Select(int.Parse).ToList();
         TempData["selectedIds"] = selectedIds;
         return RedirectToAction(MVC.TeamGeneration.Display());
     }
     return RedirectToAction(MVC.TeamGeneration.Index());
 }
Пример #14
0
        public ActionResult Assignment(FormCollection collection)
        {
            string[] assignments = collection.GetValues("assignment");
            foreach (string item in assignments)
            {
                string str = item;
            }
            ViewBag.Attendees = attendeeService.GetAll();
            ViewBag.SupportTeams = service.GetAll();

            return View();
        }
        public ActionResult Index(FormCollection values)
        {
            var viewModel = new SearchViewModel();
            if (values.GetValues("IsWalkingDistance") != null)
            {
                setFormValues(values, viewModel);
            }
            else
                viewModel.Styles = GetStyleListOptions();

            return View(viewModel);
        }
Пример #16
0
        public ActionResult Archive(FormCollection form)
        {
            if (ModelState.IsValid)
            {
                var filesselected = form.GetValues("Select");
                List<Int64> fileidList = new List<Int64>();
                if (filesselected != null && filesselected.ToList().Count>0)
                {
                    foreach (var fileid in filesselected)
                        fileidList.Add(Convert.ToInt64(fileid));

                    var archivedfiles = from filetable in db.DX_FILES where fileidList.Contains(filetable.fileid) select filetable;
                    if (archivedfiles != null && archivedfiles.ToList().Count > 0)
                    {
                        foreach (DX_FILES file in archivedfiles)
                        {

                            if (file.islocked == false)
                            {
                                archivedfiles.ToList().ForEach(fm => fm.isarchived = true);
                            }
                            else
                            {
                                ModelState.AddModelError("", "The file is checked-out by someone you cannot archive it at this time");
                                return RedirectToAction("ListDocuments");
                            }
                        }
                        try
                        {
                            db.SaveChanges();
                        }
                        catch
                        {
                            ModelState.AddModelError("", "Some Error occured. Try after sometime!");
                        }
                    }
                    if (archivedfiles.ToList().Count < fileidList.Count)
                    {
                        ModelState.AddModelError("", "Some of the files got deleted so it was unable to archive them");
                        return RedirectToAction("ListDocuments");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "No Files Selected");
                    return RedirectToAction("ListDocuments");
                }
            }

            return RedirectToAction("ListDocuments");
        }
Пример #17
0
 public ActionResult AddressAndPayment(FormCollection values)
 {
     var order = new Order();
     TryUpdateModel(order);
     string BDTAll = "";
     string[] BDTs = values.GetValues("BestDeliverTime");
     if (BDTs != null)
     {
         foreach (var BDT in BDTs)
         {
             BDTAll = BDTAll + BDT;
         }
     }
     order.BestDeliverTime = BDTAll;
     //var BDT = "";
     //for (int k = 0; k < Request.Form.AllKeys.Length ; k++ )
     //{
     //    if (Request.Form.GetKey(k) == "BestDeliverTime")
     //    {
     //        BDT = BDT + Request.Form.GetValues(k);
     //    }
     //}
     //order.BestDeliverTime = BDT;
     try
     {
         //if (string.Equals(values["PromoCode"], PromoCode, StringComparison.OrdinalIgnoreCase) == false)
         //{
         //    return View(order);
         //}
         //else
         //{
             //order.Username = User.Identity.Name;
             order.OrderDate = DateTime.Now;
             //Save Order
             storeDB.Orders.Add(order);
             storeDB.SaveChanges();
             //Process the order
             var cart = ShoppingCart.GetCart(this.HttpContext);
             cart.CreateOrder(order);
             storeDB.SaveChanges();
             return RedirectToAction("Complete");
         //}
     }
     catch
     {
         //Invalid - redisplay with errors
         return View(order);
     }
 }
        /// <summary>
        /// Action when user upload a solution to analyze
        /// </summary>
        /// <param name="forms"></param>
        /// <returns></returns>
        public ActionResult UploadSolution(FormCollection forms)
        {
            var file = Request.Files["Solution"];
            _userID = forms.GetValues("UserID")[0];
            var result = true;
            var errorText = "";
            var view = "Index";
            EnumViewModel viewModel = EnumViewModel.HOME_UPLOAD;

            if (file.ContentLength != 0)
            {
                // Upload solution to host
                result = UploadFile(file, "/Content/Projects/" + _userID + "/", ref errorText);
            }

            if (result)
            {
                view = "DanhSachSoln";
                viewModel = EnumViewModel.HOME_UPLOAD_SUCCESSFULL;
                // Analyze project
                lstSol = new List<string>();
                var solnName = file.FileName.Split(new char[] { '.' })[0];
                GetFiles(Server.MapPath("/Content/Projects/" + _userID + "/" + solnName), WebConfiguration.ProjectType, ref lstSol);
                _solnPath = this.lstSol[0];
                // Init Solution
                _solStructure = new SolnStructure
                {
                    Name = solnName,
                    Projects = new List<ProjStructure>(),
                    Path = Path.GetDirectoryName(_solnPath)
                };
                // Analyze other projects in solution
                result = Analyzeprojects(ref errorText);
                if (result)
                {
                    Insert_Soln();
                }
            }
            
            var data = new DataTransferViewModel
            {
                IDNguoiDang = Guid.Parse(_userID),
                Added = result,
                ErrorText = errorText,
                EnumViewModelType = viewModel
            };
            return View(view, CreateViewModel(data));
        }
Пример #19
0
        public ActionResult HAttendeeFilter(FormCollection collection)
        {
            string[] periods = collection.GetValues("timeStart");
            int timeStartHour = Convert.ToInt32(periods[0].Substring(0, periods[0].IndexOf(':')));
            int timeStartMin = Convert.ToInt32(periods[0].Substring(periods[0].IndexOf(':') + 1, 2).Trim());
            ViewBag.timeStart = new DateTime(DateTime.Now.Year, 1, 1, timeStartHour, timeStartMin, 0);
            periods = collection.GetValues("timeEnd");
            int timeEndHour = Convert.ToInt32(periods[0].Substring(0, periods[0].IndexOf(':')));
            int timeEndMin = Convert.ToInt32(periods[0].Substring(periods[0].IndexOf(':') + 1, 2).Trim());
            ViewBag.timeEnd = new DateTime(DateTime.Now.Year, 1, 1, timeEndHour, timeEndMin, 0);
            ViewBag.StartDate = settingService.GetStartDate();

            string[] strs = collection.GetValues("attendee");
            attendeeService.UpdateAttendeesToShow(strs);
            return View(attendeeService.GetAll());
        }
        public ActionResult Add(AddOrEditViewModel<ScheduledEvents> model, FormCollection collection)
        {
            int Entity_ExetimeType = 0;
            if (collection.GetValues("Entity.ExetimeType") != null)
            {
                Entity_ExetimeType = int.Parse(collection.GetValue("Entity.ExetimeType").AttemptedValue);
            }

            #region MyRegion
            ScheduleConfigInfo sci = ScheduleConfigs.GetConfig();
            foreach (EventInfo ev1 in sci.Events)
            {
                if (ev1.Key == model.Entity.Key.Trim())
                {
                    ModelState.AddModelError("Key", "消息:计划任务名称已经存在!");
                    return RedirectToAction("Index", new { currentPageNum = model.CurrentPageNum, pageSize = model.PageSize });
                }
            }

            EventInfo ev = new EventInfo();
            ev.Key = model.Entity.Key;
            ev.Enabled = true;
            ev.IsSystemEvent = false;
            ev.ScheduleType = model.Entity.ScheduleType.ToString();
            model.Entity.ExetimeType = Entity_ExetimeType == 0 ? false : true;

            if (model.Entity.ExetimeType)
            {
                ev.TimeOfDay = model.Entity.hour * 60 + model.Entity.minute;
                ev.Minutes = sci.TimerMinutesInterval;
            }
            else
            {
                ev.Minutes = model.Entity.timeserval;
                ev.TimeOfDay = -1;
            }
            EventInfo[] es = new EventInfo[sci.Events.Length + 1];
            for (int i = 0; i < sci.Events.Length; i++)
            {
                es[i] = sci.Events[i];
            }
            es[es.Length - 1] = ev;
            sci.Events = es;
            ScheduleConfigs.SaveConfig(sci);
            #endregion
            return RedirectToAction("Index", new { currentPageNum = model.CurrentPageNum, pageSize = model.PageSize });
        }
        public ActionResult Index(FormCollection form)
        {
            var attendanceList = form.GetValues(0);
            var students = db.Students.OrderBy(x => x.LastName).ThenBy(x => x.FirstName);
            var i = 0;

            foreach(var student in students)
            {
                foreach(var attendance in student.Attendances.OrderByDescending(a => a.AttendanceDate))
                {
                    var attended = bool.Parse(attendanceList.ElementAt(i++));
                    if (attended)
                    {
                        i++;
                    }
                    attendance.Attended = attended;
                }
            }
            db.SaveChanges();

            return RedirectToAction("index");
        }
Пример #22
0
        public ActionResult Approve(FormCollection coll)
        {
            bool approve = true;
            ValueProviderResult result = coll.GetValue("Approve");
            if (result == null)
            {
                approve = false;
            }

            string[] ids = coll.GetValues("Select");
            if (ids.Length > 0)
            {
                foreach (string id in ids)
                {
                    if (approve)
                    {
                        CommentComp.Approve(id);
                    }
                    else
                    {
                        CommentComp.Delete(id);
                    }
                }

                if (approve)
                {
                    this.TempData["Message"] = "评论审核通过";
                }
                else
                {
                    this.TempData["Message"] = "评论审核未通过";
                }
            }

            return this.RedirectToAction("Moderate");
        }
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                DBContex.clientes.Add(new Cliente()
                {
                    idCuenta = Convert.ToInt32(collection.GetValues("idCuenta")[0]),
                    nombre=collection.GetValues("nombre")[0].ToString(),
                    apellidos=collection.GetValues("apellidos")[0].ToString(),
                    edad= Convert.ToInt32(collection.GetValues("edad")[0]),
                    telefono = collection.GetValues("telefono")[0].ToString(),
                    email = collection.GetValues("email")[0].ToString()
                });
                
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                return View();
            }
        }
 public void UpdateMedicalProfileForPatient(FormCollection formCollection)
 {
     int medicalProfileTemplateId = Int32.Parse(formCollection["medicalProfileTemplateId"]);
     int patientId = Int32.Parse(formCollection["patientId"]);
     var medicalProfile = _db.MedicalProfiles.Where(
             x => ((x.MedicalProfileTemplateId == medicalProfileTemplateId)
             && (x.PatientId == patientId))).FirstOrDefault();
     foreach (string _formData in formCollection)
     {
         if (!_formData.Equals("medicalProfileTemplateId") && !_formData.Equals("patientId"))
         {
             Debug.WriteLine("Element: " + _formData + ". Form data: " + formCollection[_formData]);
             int customSnippetId = Int32.Parse(_formData);
             if (customSnippetId > 0)
             {
                 var customSnippetValue = _db.CustomSnippetValues.Where(
                     x => (x.CustomSnippetId == customSnippetId)
                         && (x.MedicalProfileId == medicalProfile.MedicalProfileId)
                     ).FirstOrDefault();
                 if (customSnippetValue == null)
                 {
                     customSnippetValue = new CustomSnippetValue
                     {
                         MedicalProfileId = medicalProfile.MedicalProfileId,
                         CustomSnippetId = customSnippetId
                     };
                     _db.CustomSnippetValues.Add(customSnippetValue);
                 }
                 string[] value = formCollection.GetValues(_formData);
                 if (value.Length == 1)
                 {
                     customSnippetValue.Value = value[0];
                 }
                 else
                 {
                     customSnippetValue.Value = String.Join("~~", value);
                 }
                 _db.SaveChanges();
             }
         }
     }
 }
Пример #25
0
        public ActionResult index(FormCollection collection)
        {
            // Check if the customer is signed in
            if (Request.Cookies.Get("CustomerCookie") == null)
            {
                return RedirectToAction("login", "customer");
            }

            // Get the current domain
            Domain currentDomain = Tools.GetCurrentDomain();

            // Get the language
            Language currentLanguage = Language.GetOneById(currentDomain.front_end_language);

            // Get the currency 
            Currency currency = Currency.GetOneById(currentDomain.currency);
            currency = currency != null ? currency : new Currency();

            // Get the document type
            byte document_type = 1;
            if(collection["btnRequest"] != null)
            {
                document_type = 0;
            }

            // Get all the form values
            Int32 customerId = Convert.ToInt32(collection["hiddenCustomerId"]);
            byte customerType = Convert.ToByte(collection["hiddenCustomerType"]);
            byte vatCode = Convert.ToByte(collection["hiddenVatCode"]);
            string[] additionalServiceIds = collection.GetValues("cbService");
            Int32 paymentOptionId = Convert.ToInt32(collection["radioPaymentOption"]);
            string email = collection["txtEmail"];
            string orgNumber = collection["txtOrgNumber"];
            string vatNumber = "";
            string contactName = collection["txtContactName"];
            string phoneNumber = collection["txtPhoneNumber"];
            string mobilePhoneNumber = collection["txtMobilePhoneNumber"];
            string invoiceName = collection["txtInvoiceName"];
            string invoiceAddress1 = collection["txtInvoiceAddress1"];
            string invoiceAddress2 = collection["txtInvoiceAddress2"];
            string invoicePostCode = collection["txtInvoicePostCode"];
            string invoiceCity = collection["txtInvoiceCity"];
            Int32 invoiceCountryId = Convert.ToInt32(collection["selectInvoiceCountry"]);
            string deliveryName = collection["txtDeliveryName"];
            string deliveryAddress1 = collection["txtDeliveryAddress1"];
            string deliveryAddress2 = collection["txtDeliveryAddress2"];
            string deliveryPostCode = collection["txtDeliveryPostCode"];
            string deliveryCity = collection["txtDeliveryCity"];
            Int32 deliveryCountryId = Convert.ToInt32(collection["selectDeliveryCountry"]);
            Country deliveryCountry = Country.GetOneById(deliveryCountryId, currentDomain.front_end_language);
            DateTime desired_date_of_delivery = DateTime.MinValue;
            DateTime.TryParse(collection["txtDesiredDateOfDelivery"], out desired_date_of_delivery);
            string discount_code_id = collection["hiddenDiscountCodeId"];

            // Set values depending of the customer type, 0: Company
            if(customerType == 0)
            {
                vatNumber = collection["txtVatNumber"];    
            }

            // Create the customer
            Customer customer = new Customer();
            customer.id = customerId;
            customer.email = email.Length > 100 ? email.Substring(0, 100) : email;
            customer.customer_type = customerType;
            customer.org_number = orgNumber.Length > 20 ? orgNumber.Substring(0, 20) : orgNumber;
            customer.vat_number = vatNumber.Length > 20 ? vatNumber.Substring(0, 20) : vatNumber;
            customer.contact_name = contactName.Length > 100 ? contactName.Substring(0, 100) : contactName;
            customer.phone_number = phoneNumber.Length > 100 ? phoneNumber.Substring(0, 100) : phoneNumber;
            customer.mobile_phone_number = mobilePhoneNumber.Length > 100 ? mobilePhoneNumber.Substring(0, 100) : mobilePhoneNumber;
            customer.invoice_name = invoiceName.Length > 100 ? invoiceName.Substring(0, 100) : invoiceName;
            customer.invoice_address_1 = invoiceAddress1.Length > 100 ? invoiceAddress1.Substring(0, 100) : invoiceAddress1;
            customer.invoice_address_2 = invoiceAddress2.Length > 100 ? invoiceAddress2.Substring(0, 100) : invoiceAddress2;
            customer.invoice_post_code = invoicePostCode.Length > 100 ? invoicePostCode.Substring(0, 100) : invoicePostCode;
            customer.invoice_city = invoiceCity.Length > 100 ? invoiceCity.Substring(0, 100) : invoiceCity;
            customer.invoice_country = invoiceCountryId;
            customer.delivery_name = deliveryName.Length > 100 ? deliveryName.Substring(0, 100) : deliveryName;
            customer.delivery_address_1 = deliveryAddress1.Length > 100 ? deliveryAddress1.Substring(0, 100) : deliveryAddress1;
            customer.delivery_address_2 = deliveryAddress2.Length > 100 ? deliveryAddress2.Substring(0, 100) : deliveryAddress2;
            customer.delivery_post_code = deliveryPostCode.Length > 100 ? deliveryPostCode.Substring(0, 100) : deliveryPostCode;
            customer.delivery_city = deliveryCity.Length > 100 ? deliveryCity.Substring(0, 100) : deliveryCity;
            customer.delivery_country = deliveryCountryId;

            // Create the order
            Order order = new Order();
            order.document_type = document_type;
            order.customer_id = customer.id;
            order.order_date = DateTime.UtcNow;
            order.company_id = currentDomain.company_id;
            order.country_code = currentLanguage.country_code;
            order.language_code = currentLanguage.language_code;
            order.currency_code = currency.currency_code;
            order.conversion_rate = (currency.conversion_rate / currency.currency_base);
            order.customer_type = customer.customer_type;
            order.customer_org_number = customer.org_number;
            order.customer_vat_number = customer.vat_number;
            order.customer_name = customer.contact_name;
            order.customer_email = customer.email;
            order.customer_phone = customer.phone_number;
            order.customer_mobile_phone = customer.mobile_phone_number;
            order.invoice_name = customer.invoice_name;
            order.invoice_address_1 = customer.invoice_address_1;
            order.invoice_address_2 = customer.invoice_address_2;
            order.invoice_post_code = customer.invoice_post_code;
            order.invoice_city = customer.invoice_city;
            order.invoice_country_id = invoiceCountryId;
            order.delivery_name = customer.delivery_name;
            order.delivery_address_1 = customer.delivery_address_1;
            order.delivery_address_2 = customer.delivery_address_2;
            order.delivery_post_code = customer.delivery_post_code;
            order.delivery_city = customer.delivery_city;
            order.delivery_country_id = deliveryCountryId;
            order.vat_code = vatCode;
            order.payment_option = paymentOptionId;
            order.payment_status = "payment_status_pending";
            order.exported_to_erp = false;
            order.order_status = "order_status_pending";
            order.desired_date_of_delivery = AnnytabDataValidation.TruncateDateTime(desired_date_of_delivery);
            order.discount_code = discount_code_id;

            // Calculate the decimal multiplier
            Int32 decimalMultiplier = (Int32)Math.Pow(10, currency.decimals);

            // Get the cart items
            List<CartItem> cartItems = CartItem.GetCartItems(currentDomain.front_end_language);
            Dictionary<string, decimal> cartAmounts = CartItem.GetCartAmounts(cartItems, currentDomain.front_end_language, vatCode, decimalMultiplier);

            // Create order rows
            List<OrderRow> orderRows = CartItem.GetOrderRows(cartItems, order.vat_code, currentDomain.front_end_language, decimalMultiplier);

            // Get additional services
            List<AdditionalService> additionalServices = AdditionalService.GetAllActive(currentDomain.front_end_language, "id", "ASC");
            Int32 additionalServiceIdsCount = additionalServiceIds != null ? additionalServiceIds.Length : 0;

            // Loop additional services
            for(int i = 0; i < additionalServices.Count; i++)
            {
                // Check if the service is selected
                for (int j = 0; j < additionalServiceIdsCount; j++)
                {
                    // Convert the id
                    Int32 serviceId = Convert.ToInt32(additionalServiceIds[j]);

                    // The service is selected
                    if(additionalServices[i].id == serviceId)
                    {
                        // Set the service as selected
                        additionalServices[i].selected = true;

                        // Calculate the fee
                        decimal fee = additionalServices[i].price_based_on_mount_time == true ? additionalServices[i].fee * cartAmounts["total_mount_time"] : additionalServices[i].fee;
                        fee *= (currency.currency_base / currency.conversion_rate);
                        fee = Math.Round(fee * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;

                        // Get the value added tax percent
                        ValueAddedTax vat = ValueAddedTax.GetOneById(additionalServices[i].value_added_tax_id);

                        // Create a order row
                        OrderRow orderRow = new OrderRow();
                        orderRow.product_code = additionalServices[i].product_code;
                        orderRow.manufacturer_code = "";
                        orderRow.product_id = 0;
                        orderRow.product_name = additionalServices[i].name;
                        orderRow.vat_percent = order.vat_code != 0 ? 0 : vat.value;
                        orderRow.quantity = 1;
                        orderRow.unit_id = additionalServices[i].unit_id;
                        orderRow.unit_price = fee;
                        orderRow.account_code = additionalServices[i].account_code;
                        orderRow.supplier_erp_id = "";
                        orderRow.sort_order = (Int16)orderRows.Count();

                        // Add the order row
                        orderRows.Add(orderRow);
                    }
                }
            }

            // Get the payment fee
            PaymentOption paymentOption = PaymentOption.GetOneById(order.payment_option, currentDomain.front_end_language);
            paymentOption = paymentOption != null ? paymentOption : new PaymentOption();

            if (paymentOption.fee > 0)
            {
                // Get the value added tax percent
                ValueAddedTax vat = ValueAddedTax.GetOneById(paymentOption.value_added_tax_id);

                // Calculate the fee
                decimal fee = paymentOption.fee * (currency.currency_base / currency.conversion_rate);
                fee = Math.Round(fee * decimalMultiplier, MidpointRounding.AwayFromZero) / decimalMultiplier;

                // Create a order row
                OrderRow orderRow = new OrderRow();
                orderRow.product_code = paymentOption.product_code;
                orderRow.manufacturer_code = "";
                orderRow.product_id = 0;
                orderRow.product_name = paymentOption.name;
                orderRow.vat_percent = order.vat_code != 0 ? 0 : vat.value;
                orderRow.quantity = 1;
                orderRow.unit_id = paymentOption.unit_id;
                orderRow.unit_price = fee;
                orderRow.account_code = paymentOption.account_code;
                orderRow.supplier_erp_id = "";
                orderRow.sort_order = (Int16)orderRows.Count();

                // Add the order row
                orderRows.Add(orderRow);
            }

            // Get translated texts
            KeyStringList translatedTexts = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC");

            // Create a error message
            string errorMessage = string.Empty;

            // Check for errors
            if (AnnytabDataValidation.IsEmailAddressValid(customer.email) == null)
            {
                errorMessage += "&#149; " + translatedTexts.Get("error_email_valid") + "<br/>";
            }
            if(cartItems.Count <= 0)
            {
                errorMessage += "&#149; " + translatedTexts.Get("error_cart_empty") + "<br/>";
            }
            if (order.payment_option == 0)
            {
                errorMessage += "&#149; " + translatedTexts.Get("error_no_payment_option") + "<br/>";
            }
            if(order.invoice_country_id == 0)
            {
                errorMessage += "&#149; " + String.Format(translatedTexts.Get("error_select_value"), translatedTexts.Get("invoice_address") + ":" + translatedTexts.Get("country").ToLower()) + "<br/>";
            }
            if (order.delivery_country_id == 0)
            {
                errorMessage += "&#149; " + String.Format(translatedTexts.Get("error_select_value"), translatedTexts.Get("delivery_address") + ":" + translatedTexts.Get("country").ToLower()) + "<br/>";
            }

            // Check if there is errors
            if (errorMessage == "")
            {
                // Get the order sums and add them to the order
                Dictionary<string, decimal> orderAmounts = Order.GetOrderAmounts(orderRows, order.vat_code, decimalMultiplier);

                // Add the sums to the order
                order.net_sum = orderAmounts["net_amount"];
                order.vat_sum = orderAmounts["vat_amount"];
                order.rounding_sum = orderAmounts["rounding_amount"];
                order.total_sum = orderAmounts["total_amount"];

                // Add the order
                Int64 insertId = Order.Add(order);
                order.id = Convert.ToInt32(insertId);

                // Update the gift cards amount for the order
                if(order.document_type != 0)
                {
                    order.gift_cards_amount = ProcessGiftCards(order.id, order.total_sum);
                    Order.UpdateGiftCardsAmount(order.id, order.gift_cards_amount);
                }
                
                // Add the order rows
                for (int i = 0; i < orderRows.Count; i++)
                {
                    orderRows[i].order_id = order.id;
                    OrderRow.Add(orderRows[i]);
                }

                // Delete the shopping cart
                CartItem.ClearShoppingCart();

                // Get the confirmation message
                string message = RenderOrderConfirmationView(order.id, this.ControllerContext);

                // Create a session to indicate that ecommerce data should be sent to google
                Session["SendToGoogleEcommerce"] = true;

                // Check if the user wants to send a request
                if (order.document_type == 0)
                {
                    // Send the request email
                    Tools.SendOrderConfirmation(customer.email, translatedTexts.Get("request") + " " + order.id.ToString() + " - " + currentDomain.webshop_name, message);
                    return RedirectToAction("confirmation", "order", new { id = order.id });
                }

                // Send the order confirmation email
                Tools.SendOrderConfirmation(customer.email, translatedTexts.Get("order_confirmation") + " " + order.id.ToString() + " - " + currentDomain.webshop_name, message);

                // Check if the order has been paid by gift cards
                if (order.total_sum <= order.gift_cards_amount)
                {
                    // Update the order status
                    Order.UpdatePaymentStatus(order.id, "payment_status_paid");

                    // Add customer files
                    CustomerFile.AddCustomerFiles(order);

                    // Return the order confirmation
                    return RedirectToAction("confirmation", "order", new { id = order.id });
                }

                // Check the selected payment option
                if(paymentOption.connection == 101)
                {
                    return CreatePaysonPayment(order, orderRows, currentDomain, translatedTexts, "DIRECT");
                }
                if (paymentOption.connection == 102)
                {
                    return CreatePaysonPayment(order, orderRows, currentDomain, translatedTexts, "INVOICE");
                }
                else if (paymentOption.connection == 201)
                {
                    return CreatePayPalPayment(order, orderRows, currentDomain, translatedTexts);
                }
                else if (paymentOption.connection == 301)
                {
                    return CreateSveaPayment(order, orderRows, currentDomain, translatedTexts, "INVOICE");
                }
                else if (paymentOption.connection == 302)
                {
                    return CreateSveaPayment(order, orderRows, currentDomain, translatedTexts, "CREDITCARD");
                }
                else if (paymentOption.connection == 401)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "CREDITCARD");
                }
                else if (paymentOption.connection == 402)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "DIRECTDEBIT");
                }
                else if (paymentOption.connection == 403)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "INVOICE");
                }
                else if (paymentOption.connection == 404)
                {
                    return CreatePayexPayment(order, orderRows, currentDomain, translatedTexts, "MICROACCOUNT");
                }
                else
                {
                    return RedirectToAction("confirmation", "order", new { id = order.id });
                }
            }
            else
            {

                // Create the bread crumb list
                List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2);
                breadCrumbs.Add(new BreadCrumb(translatedTexts.Get("start_page"), "/"));
                breadCrumbs.Add(new BreadCrumb(translatedTexts.Get("check_out"), "/order/"));

                // Set form values
                ViewBag.BreadCrumbs = breadCrumbs;
                ViewBag.ErrorMessage = errorMessage;
                ViewBag.CurrentDomain = currentDomain;
                ViewBag.TranslatedTexts = translatedTexts;
                ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language);
                ViewBag.CurrentCategory = new Category();
                ViewBag.Customer = customer;
                ViewBag.Currency = currency;
                ViewBag.CartItems = cartItems;
                ViewBag.DecimalMultiplier = decimalMultiplier;
                ViewBag.PaymentOptionId = paymentOptionId;
                ViewBag.VatCode = vatCode;
                ViewBag.CartAmounts = cartAmounts;
                ViewBag.PricesIncludesVat = Session["PricesIncludesVat"] != null ? Convert.ToBoolean(Session["PricesIncludesVat"]) : currentDomain.prices_includes_vat;
                ViewBag.CultureInfo = Tools.GetCultureInfo(ViewBag.CurrentLanguage);
                ViewBag.DesiredDateOfDelivery = order.desired_date_of_delivery;
                ViewBag.DiscountCodeId = order.discount_code;
                ViewBag.GiftCards = Session["GiftCards"] != null ? (List<GiftCard>)Session["GiftCards"] : new List<GiftCard>(0);

                // Return the index view
                return currentDomain.custom_theme_id == 0 ? View("index") : View("/Views/theme/checkout.cshtml");
            }

        } // End of the index method
        public ActionResult WriteLetter(FormCollection collection)
        {
            // select id of every checked customer
            int[] checkedCustomersId = collection.GetValues("id_customer").Select(n => Convert.ToInt32(n)).ToArray();

            CustomerService cService = new CustomerService();

            MailWriteLetterViewModel viewModel = new MailWriteLetterViewModel();
            viewModel.CustomersToSend = cService.GetCustomers(c => checkedCustomersId.Contains(c.Id));
            TempData["CustomersToSend"] = viewModel.CustomersToSend;

            return View(viewModel);
        }
Пример #27
0
 public JsonResult DeleteMul(FormCollection del)
 {
     var res = false;
     var message = "";
     var selectedList = del.GetValues("selectRow");
     if (selectedList != null && selectedList.Count() > 0)
     {
         res = actionClassService.Delete(selectedList.ToIntList(), null);
     }
     return Json(new { success = res, message = message });
 }
Пример #28
0
        public ActionResult GroupMembership(string id, FormCollection fields)
        {
            INestedRoleProvider nested = Roles.Provider as INestedRoleProvider;

              if (!CanUserEditRoleMembership(id))
              {
            return CreateLoginRedirect();
              }

              if (!string.IsNullOrEmpty(fields["AddGroup"]))
              {
            if (nested == null)
            {
              throw new InvalidOperationException("Configuration is using a RoleProvider that doesn't support nested groups");
            }

            foreach (string child in fields.GetValues("OtherGroups"))
            {
              nested.AddRoleToRole(child, id);
            }
              }
              else if (!string.IsNullOrEmpty(fields["RemoveGroup"]))
              {
            if (nested == null)
            {
              throw new InvalidOperationException("Configuration is using a RoleProvider that doesn't support nested groups");
            }

            foreach (string child in fields.GetValues("CurrentGroups"))
            {
              nested.RemoveRoleFromRole(child, id);
            }
              }
              else if (!string.IsNullOrEmpty(fields["AddUser"]))
              {
            Roles.AddUsersToRole(fields.GetValues("OtherUsers"), id);
              }
              else if (!string.IsNullOrEmpty(fields["RemoveUser"]))
              {
            Roles.RemoveUsersFromRole(fields.GetValues("CurrentUsers"), id);
              }

              return RedirectToAction("GroupMembership", new { id = id });
        }
Пример #29
0
        public ActionResult Index(int user,string command, FormCollection collection)
        {
            TimeRegViewModel model;
            DateTime selectedDate = DateTime.Parse(collection["Date"]);
            int week = Util.WeekInYear(selectedDate);
            TimeforingRepository repo = new TimeforingRepository();
            //string command = collection["command"];
            bool showDoneTasks = collection["ShowDoneTasks"].Contains("true");

            if (command == "update" )
            {
                model = new TimeRegViewModel(user, week, selectedDate, "Oppdatert",showDoneTasks );
                return View(model);
            }
            else //save
            {
                Task currTask;
                string[] timerBrukt = collection.GetValues("TimerBrukt");

                string[] timerIgjen = collection.GetValues("TimerIgjen");
                string[] taskIds = collection.GetValues("TaskId");

                //var userDateRegs = repo.GetHourRegsForUserDateSprint (user,d,sprint );
                var userDateRegs = repo.GetHourRegs().Where(r => r.User.UserID == user && r.Date == selectedDate).Select(r => r);
                if (userDateRegs.Count() > 0) // skal oppdatere
                {

                    for (int i = 0; i < taskIds.Count(); i++)
                    {
                        int taskId = int.Parse(taskIds[i]);
                        var currHourReg = from h in userDateRegs
                                          where h.TaskID == taskId
                                          select h;

                        currTask = repo.GetTask(taskId);
                        HourReg hourReg;
                        if (currHourReg.Count() > 0)
                        { //update
                            hourReg = currHourReg.ToList().ElementAt(0);
                        }
                        else
                        { // new
                            hourReg = new HourReg();
                        }
                        hourReg.Date = selectedDate;
                        hourReg.SprintID = (int)currTask.SprintID;
                        hourReg.TaskID = currTask.TaskID;
                        hourReg.TimeLeft = Double.Parse(timerIgjen[i]);
                        hourReg.TimeSpent = Double.Parse(timerBrukt[i]);
                        hourReg.UserID = user;

                        currTask.TimeLeft = Double.Parse(timerIgjen[i]);

                        if (currHourReg.Count() == 0) //new
                            repo.AddHourReg(hourReg);
                    }
                }
                else
                {

                    for (int i = 0; i < taskIds.Count(); i++)
                    {
                        int taskId = int.Parse(taskIds[i]);
                        currTask = repo.GetTask(taskId);
                        HourReg h = new HourReg();
                        h.Date = selectedDate;
                        h.SprintID = (int)currTask.SprintID;
                        h.TaskID = currTask.TaskID;
                        h.TimeLeft = Double.Parse(timerIgjen[i]);
                        h.TimeSpent = Double.Parse(timerBrukt[i]);
                        h.UserID = user;
                        currTask.TimeLeft = Double.Parse(timerIgjen[i]);
                        repo.AddHourReg(h);
                    }
                }
                repo.Save();

            }
            model = new TimeRegViewModel(user, week, selectedDate, "Lagret",showDoneTasks );
            return View(model);
        }
 public ActionResult ThisWeeksPlayers(FormCollection form)
 {
     var checkedValues = form.GetValues("selectChkBx");
     if (checkedValues != null)
     {
         List<OPUSPlayerInfoList> players = new List<OPUSPlayerInfoList>();
         foreach (var id in checkedValues)
         {
             int id1 = Convert.ToInt32(id);
             var player = db1.OpusPlayers.First(u => u.PlayerID == id1);
             players.Add(new OPUSPlayerInfoList { ID = player.PlayerID, Name = player.NameRank, OverallPercentWon = player.OverallPercentWon, Rank = player.Rank });
         }
         List<OPUSPlayerInfoList> vPlayers = players.OrderBy(x => x.Rank).ToList();
         TempData["PlayerWebGridInfo"] = vPlayers;
         TempData["ThisWeeksPlayers"] = new SelectList(players.OrderBy(x => x.Rank), "ID", "Name");
     }
     return RedirectToAction("index");
 }