Beispiel #1
0
        public WritePolygonNodes(ESRIData.Dataset dataset,TempData.TempFile pTempFile, VCTFile pVCTFile, int nNewEntityID)
        {
            m_dataset = dataset;
            m_pTempFile = pTempFile;
            m_VCTFile = pVCTFile;
            m_nNewEntityID = nNewEntityID;
            m_nLayerCount = m_dataset.GetLayerCount();

            //WriteCommplete = null;
        }
        public GamePage()
        {
            InitializeComponent();
            tmpData = new TempData();

            MakeBoard();
            MoveDone();

            playerWhiteInfoTitle.Text = tmpData.playerWhite;
            playerBlackInfoTitle.Text = tmpData.playerBlack;
            piecesCountWhite.Text = tmpData.whitePieces.ToString();
            kingsCountWhite.Text = tmpData.whiteKing.ToString();
            piecesCountBlack.Text = tmpData.blackPieces.ToString();
            kingsCountBlack.Text = tmpData.blackKing.ToString();

            timer = new DispatcherTimer();
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Tick += timer_Tick;
            timer.Start();
        }
Beispiel #3
0
        public async Task <IActionResult> AddToRole(AddUserToRoleFormModel model)
        {
            var roleExists = await this.roleManager.RoleExistsAsync(model.Role);

            var user = await this.userManager.FindByIdAsync(model.UserId);

            var userExists = user != null;

            if (!roleExists || !userExists)
            {
                ModelState.AddModelError(string.Empty, "Invalid identity details.");
            }

            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Index)));
            }

            await this.userManager.AddToRoleAsync(user, model.Role);

            TempData.AddSuccessMessage($"Потребителят {user.UserName} е добавен успешно в ролята {model.Role}");

            return(RedirectToAction(nameof(Index)));
        }
Beispiel #4
0
        public async Task <IActionResult> EditByStudent(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }
            string c = null;

            if (TempData["selectedStudent"] != null)
            {
                c = TempData["selectedStudent"].ToString();
            }
            TempData.Keep();
            var enrollment = await _context.Enrollments
                             .Include(e => e.Course)
                             .Include(e => e.Student)
                             .FirstOrDefaultAsync(m => m.EnrollmentID == id);

            if (enrollment == null)
            {
                return(NotFound());
            }
            return(View(enrollment));
        }
Beispiel #5
0
        public override ActionResult Index()
        {
            var model = new DemoViewModel();

            if (TempData.ContainsKey("Deferred"))
            {
                TempData.Remove("Deferred");
                model = TempData["DeferredModel"] as DemoViewModel;
                var state = TempData["DeferredState"] as ModelStateDictionary;
                foreach (var kvp in state)
                {
                    ModelState[kvp.Key] = kvp.Value;
                }
            }

            if (User.Identity.IsAuthenticated)
            {
                return(PartialView("Authenticated", model));
            }
            else
            {
                return(PartialView("Unauthenticated", model));
            }
        }
Beispiel #6
0
        public async Task <IActionResult> OnGetAsync(Guid?outgoingPaymentId)
        {
            if (outgoingPaymentId == null)
            {
                return(NotFound());
            }

            OutgoingPayment = await _context.OutgoingPayments
                              .Include(p => p.PaymentForm)
                              .Include(p => p.PaymentType)
                              .Include(p => p.PartnerCompany)
                              .FirstOrDefaultAsync(m => m.Id == outgoingPaymentId);

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

            ViewData["OrderId"]          = TempData.Peek("OrderId");
            ViewData["PaymentFormId"]    = new SelectList(_context.PaymentForms, "Id", "Name");
            ViewData["PaymentTypeId"]    = new SelectList(_context.PaymentTypes, "Id", "Name");
            ViewData["PartnerCompanyId"] = new SelectList(_context.PartnerCompanies, "Id", "Name");
            return(Page());
        }
        public async Task <IActionResult> Add(string areaname, int?Id, int cityId)
        {
            var area = new Area();

            area.Name   = areaname;
            area.Id     = Id.Value;
            area.CityId = cityId;
            string c             = JsonConvert.SerializeObject(area);
            var    stringContent = new StringContent(c, UnicodeEncoding.UTF8, "application/json");
            Uri    u             = new Uri(AppConstants.BaseUrl + "api/areasapi/" + c);
            var    client        = new HttpClient();
            var    response      = await client.PostAsync(u, stringContent);

            if (response.IsSuccessStatusCode)
            {
                TempData[AppConstants.SuccessMessage] = "Successfully Saved";
                TempData.Peek(AppConstants.SuccessMessage);
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(NotFound());
            }
        }
Beispiel #8
0
        public IActionResult DrinkDetails(string id)
        {
            TempData.Remove("surplus");
            TempData.Remove("missing");
            TempData.Remove("Low");
            TempData.Remove("partial");
            TempData.Remove("partialAlt");
            Rootobject c = new Rootobject();

            try
            {
                c = cocktailDAL.GetIdDataString(id);//Returns a list of drinks even though we are pulling the rootobject by ID
            }
            catch (Exception e)
            {
                TempData["error"] = e;
                return(View("error"));
            }

            TempData.Remove("error");
            Drink drink = c.drinks[0];//Grabs the single drink out of the array of drinks

            return(View(drink));
        }
        public IActionResult ActivitiesMapping(int[] idProcesses)
        {
            if (idProcesses.Length != 1)
            {
                if (idProcesses.Length > 1)
                {
                    TempData.AddErrorMessage(WebConstants.SelectSingleProcess);
                }

                return(RedirectToAction(nameof(Index)));
            }

            var idSelection = idProcesses[0];

            var process = this.processList.ById(idSelection);

            var model = new ProcessActivityMappingViewModel
            {
                IdSelectedProcess = process.IdProcess,
                SelectedProcess   = process.Process + " /" + process.ProcessMap + "/(" + process.IdProcess + ")"
            };

            var activities = this.activityList
                             .All()
                             .OrderBy(a => a.Activity)
                             .Select(s => new SelectListItem
            {
                Value = s.IdActivity.ToString(),
                Text  = s.Activity
            });

            model.Activities   = activities;
            model.IdActivities = this.activityList.Ids(idSelection);

            return(View(model));
        }
        public ActionResult Restore(int?id, int?questionId)
        {
            if (id == null || questionId == null)
            {
                return(BadRequest());
            }

            bool success = this.commentService.Restore(id.Value);

            if (!success)
            {
                return(BadRequest());
            }

            TempData.AddSuccessMessage(string.Format(
                                           WebConstants.SuccessfullEntityOperation,
                                           Comment,
                                           WebConstants.Restored));

            return(RedirectToAction(
                       Details,
                       Questions,
                       new { id = questionId, area = string.Empty }));
        }
        public ActionResult Setup()
        {
            // dispose of quickly
            using (FM_Datastore_Entities_EF db_manager = new FM_Datastore_Entities_EF())
            {
                if (db_manager.Users.Count() != 0)
                {
                    return(new HttpNotFoundResult());
                }

                //remove after databaseModel.sql
                if (db_manager.Roles.Count() == 0)
                {
                    foreach (var item in AppSettings.Roles.ComboBox)
                    {
                        db_manager.Roles.Add(new Role()
                        {
                            Name = item.Value
                        });
                    }
                }
            }
            if (TempData.ContainsKey("Setup") && Session["SetupUser"] == null)
            {
                return(new HttpNotFoundResult());
            }
            if (!TempData.Keys.Contains("Setup"))
            {
                TempData.Add("Setup", true);
            }
            Session.Add("SetupUser", true);
            return(View(new SetupViewModel()
            {
                Role = AppSettings.Roles.CONGRESS
            }));
        }
        public async Task <IActionResult> OnPostAsync(int ProjectId)
        {
            Projects = TempData.Get <IReadOnlyList <ProjectViewModel> >("Projects");

            if (Projects == null)
            {
                Projects = await _projectsViewModelService.GetProjects();

                TempData.Set("Projects", Projects);
                return(Page());
            }

            foreach (var project in Projects)
            {
                if (ProjectId == project.Id)
                {
                    HttpContext.Session.SetInt32("projectId", ProjectId);
                    return(RedirectToPage("/Dashboard"));
                }
            }

            TempData.Keep();
            return(Page());
        }
        public ActionResult Index()
        {
            SaveTextViewModel viewModel;

            if (TempData.ContainsKey(nameof(TempDataKeys.ViewModel)))
            {
                viewModel = (SaveTextViewModel)TempData[nameof(TempDataKeys.ViewModel)];
            }
            else
            {
                using (IContext ormContext = PersistenceHelper.CreateContext())
                {
                    SaveTextPresenter presenter = CreatePresenter(ormContext);
                    viewModel = presenter.Show();
                }
            }

            foreach (string message in viewModel.ValidationMessages)
            {
                ModelState.AddModelError(nameof(message), message);
            }

            return(View(viewModel));
        }
        public JsonResult UpdateExamples(string CurrentColumn)
        {
            string    strValue = string.Empty;
            DataTable dt       = new DataTable();

            if (TempData["Data"] != null)
            {
                dt = (TempData["Data"] as DataTable).AsEnumerable().Take(1).CopyToDataTable();
            }
            if (dt != null)
            {
                if (dt.Rows.Count > 0)
                {
                    if (Convert.ToInt32(CurrentColumn) > 0)
                    {
                        strValue = Convert.ToString(dt.Rows[0][Convert.ToInt32(CurrentColumn) - 1]);
                    }
                }
            }
            TempData.Keep();
            return(new JsonResult {
                Data = strValue
            });
        }
Beispiel #15
0
        public ActionResult CadastroNotaFiscal(int idPedido)
        {
            var pedido = _pedidoRepo.PedidoById(idPedido);

            List <ItemPedido> itensPedido = new List <ItemPedido>();

            TempData["Pedido"]   = Newtonsoft.Json.JsonConvert.SerializeObject(GetItensPedidoNF(idPedido));
            TempData["idPedido"] = idPedido;
            TempData.Keep("Pedido");
            TempData.Keep("idPedido");

            TempData["ItensNota"] = Newtonsoft.Json.JsonConvert.SerializeObject(_itemNotaRepo.ItemNotaByPedido(idPedido));
            TempData.Keep("ItensNota");

            if (pedido.NFEmitida == true)
            {
                Response.WriteAsync("<script language='javascript'>alert('NF ja emitida para este pedido')</script>");
                return(RedirectToAction("Index", "Pedido"));
            }
            else
            {
                return(PartialView("EmitirNota"));
            }
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.UserName, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    if (TempData.Peek("AssociateCharacterWithRegistration") != null)
                    {
                        try
                        {
                            CharacterDetails character = JsonConvert.DeserializeObject <CharacterDetails>(TempData["AssociateCharacterWithRegistration"].ToString());
                            _profileManager.AssociateCharacter(user, character);
                        }
                        catch (Exception)
                        {
                            _logger.LogError("Unable to associate character when logging in with existing account");
                        }
                    }

                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }

            return(View(model));
        }
Beispiel #17
0
        /*
         * This method detects any messages that have been passed through the TempData scope
         * and re-adds it to the controller before the next action executes.
         */
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            IEnumerable <ResponseMessage> _messages = TempData.Get <IEnumerable <ResponseMessage> >("Messages");

            if (_messages != null)
            {
                // Attempt to cleanup any duplicate messages after redirects
                this.Messages = _messages.Select(k => new ResponseMessage()
                {
                    MessageType = k.MessageType,
                    Header      = k.Header,
                    Message     = k.Message
                }).Distinct().ToList();
                TempData["Messages"] = null;
            }
            else
            {
                if (this.Messages == null)
                {
                    this.Messages = new List <ResponseMessage>();
                }
            }
        }
        public ActionResult Save(Usuario usuario)
        {
            string errores = "";

            try
            {
                // Es valido
                if (ModelState.IsValid)
                {
                    ServiceUsuario _ServiceUsuario = new ServiceUsuario();
                    _ServiceUsuario.Save(usuario);
                }
                else
                {
                    // Valida Errores si Javascript está deshabilitado
                    //Util.ValidateErrors(this);

                    TempData["Message"] = "Error al procesar los datos! " + errores;
                    TempData.Keep();

                    return(View("Create", usuario));
                }

                // redirigir
                return(RedirectToAction("List"));
            }
            catch (Exception ex)
            {
                // Salvar el error en un archivo
                Log.Error(ex, MethodBase.GetCurrentMethod());
                TempData["Message"] = "Error al procesar los datos! " + ex.Message;
                TempData.Keep();
                // Redireccion a la captura del Error
                return(RedirectToAction("Default", "Error"));
            }
        }
Beispiel #19
0
        public async Task <IActionResult> SubmitExam(int id, IFormFile exam)
        {
            if (!exam.FileName.EndsWith(".zip") ||
                exam.Length > DataConstants.CourseExamSubmissionFileLength)
            {
                TempData.AddErrorMessage("Your submission should a '.zip' file with no more tha 2 MB in size!");

                return(RedirectToAction(nameof(Details), new { id }));
            }

            var fileContents = await exam.ToByteArrayAsync();

            var userId = this.userManager.GetUserId(User);

            var success = await this.courses.SaveExamSubmission(id, userId, fileContents);

            if (!success)
            {
                return(BadRequest());
            }

            TempData.AddSuccessMessage("Exam submission saved successfully!");
            return(RedirectToAction(nameof(Details), new { id }));
        }
Beispiel #20
0
        public IActionResult ProductDelete(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            var entity = _productService.GetById((int)id);

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

            _productService.Delete(entity);

            TempData.Put("message", new AlertMessage()
            {
                Title     = "Info",
                Message   = $"{entity.Name} isimli ürün silindi.",
                AlertType = "danger"
            });
            return(RedirectToAction("ProductList"));
        }
 public async Task<IActionResult> CreateAsync(Portfoliopage entity, IFormFile file)
 {
     if (file != null && file.ContentType.Contains("image"))
     {
         var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\Site\\img", file.FileName);
         using (var stream = new FileStream(path, FileMode.Create))
         {
             await file.CopyToAsync(stream);
         }
         entity.BackgroundImage = file.FileName;
     }
     if (ModelState.IsValid)
     {             
         _portfoliopageService.Create(entity);
         TempData.Put("message", new ResultMessage()
         {
             Title = "Bildirim",
             Message = "Projelerim Sayfası başarılı bir şekilde oluşturuldu.",
             Css = "success"
         });
         return RedirectToAction("Index");
     }
     return View(entity);
 }
        public ActionResult CreateSchool(School userInput)
        {
            ViewBag.Board = new SelectList(db.BoardTypes, "Id", "Name");
            ViewBag.Types = new SelectList(db.SchoolTypes, "Id", "Name");

            if (userInput.IsGPA && (userInput.PercentageMarks < 0 || userInput.PercentageMarks > 10))
            {
                ModelState.AddModelError("PercentageMarks", "GPA not in range");
                ViewBag.Board = new SelectList(db.BoardTypes, "Id", "Name");
                ViewBag.Types = new SelectList(db.SchoolTypes, "Id", "Name");
                return(View(userInput));
            }

            else if (userInput.PercentageMarks < 0 || userInput.PercentageMarks > 100)
            {
                ModelState.AddModelError("PercentageMarks", "Percentage not in range");
                ViewBag.Board = new SelectList(db.BoardTypes, "Id", "Name");
                ViewBag.Types = new SelectList(db.SchoolTypes, "Id", "Name");
                return(View(userInput));
            }

            if (ModelState.IsValid)
            {
                List <School> schoolList = TempData.Peek("SchoolList") == null ? new List <School>() : (List <School>)TempData.Peek("SchoolList");
                userInput.BoardType  = db.BoardTypes.Where(x => x.Id == userInput.Board).First();
                userInput.SchoolType = db.SchoolTypes.Where(x => x.Id == userInput.SchoolTypeId).First();
                userInput.Id         = Guid.NewGuid();
                if (userInput.IsGPA)
                {
                    userInput.PercentageMarks = userInput.PercentageMarks * new decimal(9.5);
                }
                schoolList.Add(userInput);
                TempData["SchoolList"] = schoolList;
            }
            return(View());
        }
Beispiel #23
0
        public async Task <IActionResult> Details(int id, string name, string returnUrl, int page = MinPage)
        {
            bool isSupplementExisting = await this.supplementService.IsSupplementExistingById(id, false);

            if (!isSupplementExisting)
            {
                TempData.AddErrorMessage(string.Format(EntityNotFound, SupplementEntity));

                return(this.RedirectToHomeIndex());
            }

            if (page < MinPage)
            {
                return(RedirectToAction(nameof(Details), new { id, name }));
            }

            PagingElementViewModel <SupplementDetailsServiceModel> model = new PagingElementViewModel <SupplementDetailsServiceModel>
            {
                Element    = await this.supplementService.GetDetailsByIdAsync(id, page),
                Pagination = new PaginationViewModel
                {
                    TotalElements = await this.supplementService.TotalCommentsAsync(id, false),
                    PageSize      = CommentPageSize,
                    CurrentPage   = page
                }
            };

            if (page > MinPage && page > model.Pagination.TotalPages)
            {
                return(RedirectToAction(nameof(Details), new { id, name }));
            }

            returnUrl = SetOrUpdateReturnUrl(returnUrl);

            return(View(model));
        }
Beispiel #24
0
        public async Task <IActionResult> ResetPassword(ResetPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                TempData.Put("message", new ResultMessage()
                {
                    Css = "danger", Title = "Error", Message = "An unknown error occured, please try again."
                });
                return(View(model));
            }
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                TempData.Put("message", new ResultMessage()
                {
                    Css = "danger", Title = "Error", Message = "Data is not valid."
                });
                return(RedirectToAction("index", "home"));
            }
            var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);

            if (result.Succeeded)
            {
                TempData.Put("message", new ResultMessage()
                {
                    Css = "info", Title = "Information", Message = "Your Password has changed, please log in."
                });
                return(RedirectToAction("login", "account"));
            }
            TempData.Put("message", new ResultMessage()
            {
                Css = "danger", Title = "Error", Message = "Data is not valid."
            });
            return(View(model));
        }
        // GET: Pagos
        public ActionResult Index(int id)
        {
            var lista = repositorioPago.ObtenerTodosPorContratoId(id);

            if (lista.Count() == 0)
            {
                TempData["Mensaje"] = "No se registran pagos realizados para este contrato";
                return(RedirectToAction("Index", "Contratos"));
            }
            else
            {
                if (TempData.ContainsKey("Error"))
                {
                    ViewBag.Error = TempData["Error"];
                }
                if (TempData.ContainsKey("Mensaje"))
                {
                    ViewBag.Mensaje = TempData["Mensaje"];
                }

                ViewBag.Contrato = lista[0].Contrato;
                return(View(lista));
            }
        }
        public async Task <IActionResult> Start(int id)
        {
            if (!await this.tournaments.ContainsAsync(id))
            {
                return(NotFound());
            }

            if (this.tournaments.HasStarted(id) ||
                this.tournaments.HasEnded(id))
            {
                TempData.AddErrorMessage(ErrorMessages.TournamentStarted);
            }
            else
            {
                await this.moderatorTournaments.StartAsync(id);

                TempData.AddSuccessMessage(SuccessMessages.TournamentStarted);
            }

            return(RedirectToAction(
                       nameof(TournamentsController.Manage),
                       "Tournaments",
                       new { area = Areas.Moderator, id }));
        }
        public ActionResult TestViewData()
        {
            List <SelectListItem> roles = new List <SelectListItem> {
                new SelectListItem {
                    Text = "Admin", Value = "1"
                },
                new SelectListItem {
                    Text = "Staff", Value = "2"
                },
                new SelectListItem {
                    Text = "Customer Serice", Value = "3"
                },
                new SelectListItem {
                    Text = "Teller", Value = "4"
                }
            };

            ViewBag.Roles = roles;
            ViewData.Add("user", "galihanggara");

            TempData.Add("temp", "Test Temporary");

            return(View("Index"));
        }
        public ActionResult Quiz(CauHoi q)
        {
            q.DanAnDung = TempData["DapAnDung"].ToString();
            string dem = null;

            if (q.A != null)
            {
                dem = "A";
            }
            else if (q.B != null)
            {
                dem = "B";
            }
            else if (q.C != null)
            {
                dem = "C";
            }
            else if (q.D != null)
            {
                dem = "D";
            }

            if (dem != null)
            {
                if (dem.Equals(q.DanAnDung))
                {
                    TempData["score"] = Convert.ToInt32(TempData["score"]) + 10;
                }
            }

            TempData["loadQuestions"] = 0;

            TempData.Keep();

            return(RedirectToAction("Quiz"));
        }
        public async Task <List <Policies> > GetPoliciesByNationalId()
        {
            string nationalId = TempData["NationalId"].ToString();
            string yob        = TempData["YOB"].ToString();

            TempData.Keep("YOB");
            TempData.Keep("NationalId");
            var result = new List <Policies>();

            if (nationalId != null && yob != null)
            {
                var clsInput = new ClsInput();
                clsInput.code       = "CI";
                clsInput.nationalID = nationalId;
                //DateTime date = DateTime.Parse(yob);
                //DateTime date = Convert.ToDateTime(yob);
                DateTime dt   = Convert.ToDateTime(yob);
                int      year = dt.Year;
                clsInput.yearOfBirth = year.ToString();
                clsInput.insPolicyNo = "";
                result = await _policyHandler.GetPoliciesByNationalId(clsInput);
            }
            return(result);
        }
        public async Task <IActionResult> Restore(int id)
        {
            bool isSupplementExistingById = await this.supplementService.IsSupplementExistingById(id, true);

            if (!isSupplementExistingById)
            {
                TempData.AddErrorMessage(string.Format(EntityNotFound, SupplementEntity));

                return(this.RedirectToSupplementsIndex(true));
            }

            string restoreResult = await this.managerSupplementService.RestoreAsync(id);

            if (restoreResult == string.Empty)
            {
                TempData.AddSuccessMessage(string.Format(EntityRestored, SupplementEntity));
            }
            else
            {
                TempData.AddErrorMessage(string.Format(EntityNotRestored, SupplementEntity) + restoreResult);
            }

            return(this.RedirectToSupplementsIndex(true));
        }
        // GET: Cart
        public ActionResult Index(int?id)
        {
            if (!car.CheckAccessPermission("Order", "IsRead"))
            {
                string URL = Request.UrlReferrer.ToString();
                Content("<script language='javascript' type='text/javascript'>alert('You have no access!');</script>");
                return(Redirect(URL));
            }

            int?orderID = (id != null) ? id : TempData.Peek("OrderID") as int?;
            var prods   = (from m in db.Products
                           select new
            {
                ProductID = m.ProductID,
                Name = m.Name
            }).ToList();
            var jsonSerialiser = new JavaScriptSerializer();
            var prodslst       = (from c in prods select c.Name).ToList();

            ViewBag.ProductlistJson = jsonSerialiser.Serialize(prodslst);
            ViewBag.ProductID       = new SelectList(prods, "ProductID", "Name");
            ViewBag.OrderID         = orderID;
            return(View());
        }
Beispiel #32
0
 public ActionResult EndreKunde(int kID)
 {
     if (SjekkAdmin())
     {
         if (TempData["Error"] != null)
         {
             ViewBag.Error = TempData["Error"].ToString();
             TempData.Remove("Error");
         }
         if (TempData["Melding"] != null)
         {
             ViewBag.Melding = TempData["Melding"].ToString();
             TempData.Remove("Melding");
         }
         var kunde = _kundeBLL.HentKunde(kID);
         if (kunde != null)
         {
             return(View(kunde));
         }
         TempData["Error"] = "Fant ikke kunden som skulle endres";
         return(RedirectToAction("Dashboard"));
     }
     return(RedirectToAction("Login", "Kunde"));
 }
 public DetailsPage()
 {
     InitializeComponent();
     tmpData = new TempData();
 }
Beispiel #34
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FetchAsync_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // The sender is the BackgroundWorker object we need it to
                // report progress and check for cancellation.
                BackgroundWorker bwAsync = sender as BackgroundWorker;

                // start the wait cursor
                WaitCursor(true);

                TempSet = new MTG.MTGCardSet();
                String SelectedEdition = GetComboBoxValue();

                if (GetComboBoxValue() == MTGEditions.FourthE.ToString().ToLower())
                {
                    SelectedEdition = "Fourth%20Edition";
                }
                else if (GetComboBoxValue() == MTGEditions.TenthE.ToString().ToLower())
                {
                    SelectedEdition = "Tenth%20Edition";
                }


                // create the web page to search...
                // example: 
                //   http://ww2.wizards.com/gatherer/index.aspx?term=&Field_Name=on&Field_Rules=on&Field_Type=on&setfilter=Fourth%20Edition
                String InitialWebPage = "http://ww2.wizards.com/gatherer/index.aspx";
                InitialWebPage += "?term=&Field_Name=on&Field_Rules=on&Field_Type=on&setfilter=" + SelectedEdition;

                // Store the temp data that will be sent to the web page parser                
                TempData temp = new TempData();
                temp._webpage = InitialWebPage;
                temp._mtgedition = SelectedEdition;

                // Now pull back all the card IDs
                WebPageParser.FetchInitialPage(temp);
                
                // update progression
                bwAsync.ReportProgress(0);
                                
                // create a var for all the threads
                Thread[] WebFetchingThreads = new Thread[TempIDs.Count];
                Int32 Page = 0;
                Int32 PagesCompleted = 0;

                // cycle through the pages to get all the scores
                foreach (Int32 id in TempIDs)
                {
                    // update progression
                    bwAsync.ReportProgress(Convert.ToInt32(Page * (100.0 / TempIDs.Count)));                    
                    
                    // create the web page to search...
                    // example: 
                    //  http://ww2.wizards.com/gatherer/CardDetails.aspx?&id=2085
                    String CardWebPage = "http://ww2.wizards.com/gatherer/CardDetails.aspx?&id=";
                    // just fill these in for now
                    CardWebPage += id.ToString();

                    // The constructor for the Thread class requires a ThreadStart 
                    // delegate that represents the method to be executed on the 
                    temp = new TempData();
                    temp._webpage = CardWebPage;
                    temp._mtgedition = SelectedEdition;

                    // Create the thread object, passing in the serverObject.StaticMethod method 
                    // using a ThreadStart delegate.
                    WebFetchingThreads[Page] = new Thread(WebPageParser.FetchCardPage);
                    
                    // Start the thread.
                    // Note that on a uniprocessor, the new thread does not get any processor 
                    // time until the main thread is preempted or yields.
                    WebFetchingThreads[Page].Start(temp);
                                                            
                    // Periodically check if a cancellation request is pending.
                    // If the user clicks cancel the line
                    // m_AsyncWorker.CancelAsync(); if ran above.  This
                    // sets the CancellationPending to true.
                    // You must check this flag in here and react to it.
                    // We react to it by setting e.Cancel to true and leaving.
                    if (bwAsync.CancellationPending)
                    {
                        // stop the job...
                        //Log("Searching stopped!");
                        break;
                    }

                    // Only allow so many pages to be fetched in parallel
                    if ((Page - PagesCompleted) >= (MaxPagesToFetchInParallel - 1))
                    {
                        // wait for the first run thread to return before letting another one start
                        WebFetchingThreads[Page].Join();

                        PagesCompleted++;
                        
                        // update progression
                        bwAsync.ReportProgress(Convert.ToInt32((PagesCompleted) * (100.0 / TempIDs.Count)));
                    }
                    
                    Page++;
                }

                // now wait and make sure that all web pages have returned back
                foreach (Thread t in WebFetchingThreads)
                {                    
                    t.Join();
                }

                bwAsync.ReportProgress(100);
            }
            catch (Exception ex)
            {
                //Log(String.Format("  **ERROR: ", ex.Message));
                MessageBox.Show(String.Format("  **ERROR[FetchAsync_DoWork]: {0}", ex.Message));
            }

            // stop the wait cursor
            WaitCursor(false);
        }