Example #1
0
        public override async Task <ResponseViewModel> Save(CodeViewModel code)
        {
            var response = new ResponseViewModel();

            try
            {
                var entity = await DbContext.EngineOilCodes.FindAsync(code.Id);

                if (entity == null)
                {
                    entity      = new EngineOilCode();
                    entity.Code = code.Code;
                    DbContext.EngineOilCodes.Add(entity);
                }
                else
                {
                    entity.Code = code.Code;
                    DbContext.EngineOilCodes.Update(entity);
                }

                await DbContext.SaveChangesAsync();

                response.IsSuccess = true;
                response.Message   = "Engine oil code saved.";
            }
            catch (Exception ex)
            {
                response.IsSuccess = false;
                response.Message   = "Error occured while saving the engine oil code.";
            }

            return(response);
        }
Example #2
0
        public ActionResult Compile(CodeViewModel code)
        {
            CompilerResultViewModel result = null;
            string baseUrl = Directory.GetCurrentDirectory();
            string path    = Path.Combine(baseUrl, "Code.cpp");

            try
            {
                writeCodeInFile(path, code.Code);
                Process myProcess = new Process();
                myProcess.StartInfo.UseShellExecute = false;
                // You can start any process, HelloWorld is a do-nothing example.
                myProcess.StartInfo.FileName       = Path.Combine(baseUrl, "Batch.bat");
                myProcess.StartInfo.CreateNoWindow = true;
                myProcess.Start();
                myProcess.WaitForExit();

                result        = new CompilerResultViewModel();
                result.Result = "";
                string testUrl = Path.Combine(baseUrl, "result.txt");
                using (StreamReader file = new StreamReader(testUrl))
                {
                    result.Result = file.ReadToEnd();
                }
            }
            catch { }
            return(Ok(result));
        }
        public void GetClassDefinition_MultiProperty_Test()
        {
            // arrange
            var expected = "public class Sample { public int Age { get; set; } public string Name { get; set; } public string Phone { get; set; } }";
            var m        = new CodeViewModel {
                Name   = "Sample",
                Fields = new List <FieldViewModel>
                {
                    new FieldViewModel {
                        Type = "int", Name = "Age"
                    },
                    new FieldViewModel {
                        Type = "string", Name = "Name"
                    },
                    new FieldViewModel {
                        Type = "string", Name = "Phone"
                    }
                }
            };
            //var mockService = new Mock<ICodeService<CodeViewModel>>();
            //CodeService service = new CodeService(mockService.Object);
            CodeService service = new CodeService();

            // act
            var actual = service.GetClassDefinition(m);

            // assert
            actual = ReplaceCodeWhitespace(actual);
            Assert.AreEqual(expected, actual);
        }
Example #4
0
        public async Task <bool> Create(HttpContext context, CodeViewModel codeModel)
        {
            if (_cartRepository.All().Any(c => c.Id.Equals(codeModel.Id)))
            {
                return(true);
            }

            var cart = new Cart
            {
                Id           = codeModel.Id,
                IsAuthorized = codeModel.IsAuthorized
            };

            await _cartRepository.AddAsync(cart);

            await _cartRepository.SaveChangesAsync();

            var model = new CartViewModel()
            {
                Id = codeModel.Id
            };

            if (context.Session.Get <CartViewModel>(codeModel.Id) == null)
            {
                context.Session.Set <CartViewModel>(codeModel.Id, model);
            }


            var sessionModel = context.Session.Get <CartViewModel>(codeModel.Id);

            return(sessionModel != null);
        }
        public async Task <ActionResult> SendCode(string code)
        {
            // 1. Retrieve user
            var authenticatedUser = await _authenticationService.GetAuthenticatedUser(this, Host.Constants.CookieNames.TwoFactorCookieName).ConfigureAwait(false);

            if (authenticatedUser == null || authenticatedUser.Identity == null || !authenticatedUser.Identity.IsAuthenticated)
            {
                throw new IdentityServerException(Core.Errors.ErrorCodes.UnhandledExceptionCode, Core.Errors.ErrorDescriptions.TwoFactorAuthenticationCannotBePerformed);
            }

            // 2. Return translated view.
            var resourceOwner = await _userActions.GetUser(authenticatedUser).ConfigureAwait(false);

            var service   = _twoFactorAuthenticationHandler.Get(resourceOwner.TwoFactorAuthentication);
            var viewModel = new CodeViewModel
            {
                AuthRequestCode = code,
                ClaimName       = service.RequiredClaim
            };
            var claim = resourceOwner.Claims.FirstOrDefault(c => c.Type == service.RequiredClaim);

            if (claim != null)
            {
                viewModel.ClaimValue = claim.Value;
            }

            ViewBag.IsAuthenticated = false;
            await TranslateView(DefaultLanguage).ConfigureAwait(false);

            return(View(viewModel));
        }
Example #6
0
 public void GenerateCode([FromBody] CodeViewModel model)
 {
     using (var dataAccess = DataAccessService.GetDataAccess <ICodeDataAccess>())
     {
         dataAccess.GenerateCode(model.LockId, model.Config);
     }
 }
Example #7
0
 public void EditCode([FromBody] CodeViewModel model)
 {
     using (var dataAccess = DataAccessService.GetDataAccess <ICodeDataAccess>())
     {
         dataAccess.EditCode(model);
     }
 }
Example #8
0
        public IActionResult Create(CodeViewModel model)
        {
            _code = model;

            if (_code.Guest != null)
            {
                bool isValid = true;

                isValid = _cartsService.GetValidate(HttpContext, _code.Guest);

                if (isValid)
                {
                    _code.Id      = _code.Guest;
                    _code.Message = null;
                }
                else
                {
                    _code.Message = Constants.INVALID_CODE_MESSAGE;
                    _code.Guest   = null;
                    return(RedirectToAction("Code", _code));
                }
            }
            else
            {
                bool isCreated = _cartsService.Create(HttpContext, _code).Result;

                if (!isCreated && TempData["Product"] == null)
                {
                    return(RedirectToAction("Index", "Home"));
                }
            }

            return(RedirectToAction("Index", _code));
        }
Example #9
0
 public CartController(ICartsService cartsService, UserManager <IdentityUser> userManager, CodeViewModel code, SignInManager <IdentityUser> signInManager)
 {
     _cartsService  = cartsService;
     _userManager   = userManager;
     _code          = code;
     _signInManager = signInManager;
 }
Example #10
0
        public ActionResult Compile(CodeViewModel code)
        {
            var result = MyCompiler.Compile(code.CodeStr).ToString();

            Console.WriteLine(result);
            return(Ok(result));
        }
        public void EditCode(CodeViewModel model)
        {
            var oldCode = (from elem in GetCodes()
                           where elem.Id == model.Id
                           select elem).FirstOrDefault();
            var newCode = oldCode;

            newCode.LockId = model.LockId ?? newCode.LockId;
            newCode.Config = model.Config ?? newCode.Config;
            using (var conn = new NpgsqlConnection(Configuration.GetConnectionString("DefaultConnection")))
            {
                var query = @"select from edit_code(:id, :code, :lock_id, :config)";
                conn.Open();
                try
                {
                    var pgcom = new NpgsqlCommand(query, conn);
                    pgcom.CommandType = CommandType.Text;
                    pgcom.Parameters.AddWithValue("id", newCode.Id);
                    pgcom.Parameters.AddWithValue("code", newCode.CodeVal);
                    pgcom.Parameters.AddWithValue("lock_id", newCode.LockId);
                    pgcom.Parameters.AddWithValue("config", newCode.Config);
                    var pgreader = pgcom.ExecuteReader();
                }
                finally
                {
                    conn.Close();
                }
            }
        }
Example #12
0
        public async Task <IActionResult> Create(CodeViewModel model)
        {
            if (ModelState.IsValid)
            {
                var code = model.Code;
                var tags = new List <Tag>();
                if (!string.IsNullOrEmpty(model.SelectedTags))
                {
                    tags = (await tagsService.ParseTags(model.SelectedTags)).ToList();
                }

                code.CodeTags = tags.Select(t => new CodeTag
                {
                    TagId = t.Id
                }).ToList();
                code.User = await userManager.GetUserAsync(User);

                code.Created = DateTime.Now;

                await codeRepository.CreateAsync(code);

                return(RedirectToAction("Detail", new { id = code.Id }));
            }
            Console.WriteLine(ModelState.ErrorCount);

            ModelState.AddModelError("", "Vyplňte všechna povinná pole prosím.");

            return(View(model));
        }
        public static CompilerResultViewModel CompileCPlusPlusCode(CodeViewModel code)
        {
            var createRquestt = new RestRequest("Compile", Method.POST)
            {
                RequestFormat = DataFormat.Json
            };

            createRquestt.AddHeader("Content-Type", "application/json");
            createRquestt.AddHeader("Accept", "application/json");
            createRquestt.AddBody(code);
            try
            {
                var createRestResponset = CompilerNetworkClient.Instance.Execute(createRquestt);
                var response            = createRestResponset.Content;
                var responseObject      = JsonConvert.DeserializeObject <CompilerResultViewModel>(response);
                return(responseObject);
            }
            catch (Exception ex)
            {
                CompilerResultViewModel compilerResult = new CompilerResultViewModel();
                compilerResult.Error      = ex.Message;
                compilerResult.Result     = ex.Message;
                compilerResult.StatusCode = 404;
                return(compilerResult);
            }
        }
        public static void SeedOperators(IOperatorManager operatorManager, ICodeManager codeManager, ITariffManager tariffManager)
        {
            if (operatorManager.GetByName("Vodafone") == null)
            {
                OperatorViewModel oper1 = new OperatorViewModel();
                oper1.Name = "Vodafone";
                operatorManager.Add(oper1);
                oper1 = operatorManager.GetByName("Vodafone");

                CodeViewModel code1 = new CodeViewModel()
                {
                    OperatorId = oper1.Id, OperatorCode = "+38099"
                };
                CodeViewModel code2 = new CodeViewModel()
                {
                    OperatorId = oper1.Id, OperatorCode = "+38066"
                };
                CodeViewModel code3 = new CodeViewModel()
                {
                    OperatorId = oper1.Id, OperatorCode = "+38050"
                };

                codeManager.Add(code1);
                codeManager.Add(code2);
                codeManager.Add(code3);

                SeedTariffs(tariffManager, oper1.Id);
            }

            if (operatorManager.GetByName("Kyivstar") == null)
            {
                OperatorViewModel oper2 = new OperatorViewModel();
                oper2.Name = "Kyivstar";
                operatorManager.Add(oper2);
                oper2 = operatorManager.GetByName("Kyivstar");

                CodeViewModel code4 = new CodeViewModel()
                {
                    OperatorId = oper2.Id, OperatorCode = "+38097"
                };
                CodeViewModel code5 = new CodeViewModel()
                {
                    OperatorId = oper2.Id, OperatorCode = "+38067"
                };
                CodeViewModel code6 = new CodeViewModel()
                {
                    OperatorId = oper2.Id, OperatorCode = "+38096"
                };

                codeManager.Add(code4);
                codeManager.Add(code5);
                codeManager.Add(code6);

                SeedTariffs(tariffManager, oper2.Id);
            }
        }
        // (小程序端接口)  获取 该值班信息的认领人信息
        public List <MydutyClaimInfoSearchMiddleModel> GetDutyListByID(CodeViewModel code)
        {
            List <MydutyClaimInfoSearchMiddleModel> middleModels = new List <MydutyClaimInfoSearchMiddleModel>();
            var list = _IMydutyClaimInfoRepository.GetByOndutyClaims_InfoID(code.code);

            list         = list.Where(o => o.status == "1").ToList();
            middleModels = _IMapper.Map <List <MydutyClaim_Info>, List <MydutyClaimInfoSearchMiddleModel> >(list);

            return(middleModels);
        }
Example #16
0
        public ActionResult Run(CodeViewModel vm)
        {
            _logRepository.Insert(new Log {
                InputCode = vm.InputCode, IpAddress = Request.UserHostAddress
            });

            return(new ContentResult {
                Content = CompileHelper.CompileAndRun(vm.InputCode)
            });
        }
Example #17
0
        public IActionResult EnterCode(CodeViewModel model)
        {
            if (ModelState.IsValid &&
                model.ActualCode.Equals(_authorizationService.GetRecoveryCode(Encoding.ASCII.GetString(HttpContext.Session.Get("email")))))
            {
                return(RedirectToAction("RecoverPassword"));
            }

            _toastNotification.AddErrorToastMessage("Incorrect code inputted.");
            return(View(model));
        }
Example #18
0
        public Code()
        {
            InitializeComponent();
            model = this.DataContext as CodeViewModel;

            DispatcherTimer LiveTime = new DispatcherTimer();

            LiveTime.Interval = TimeSpan.FromSeconds(1);
            LiveTime.Tick    += timer_Tick;
            LiveTime.Start();
        }
Example #19
0
        public ActionResult <MydutyClaimInfoSearchResModel> GetDutyListByID(CodeViewModel code)
        {
            MydutyClaimInfoSearchResModel searchResModel = new MydutyClaimInfoSearchResModel();
            var lists = normalizationInfoService.GetDutyListByID(code);

            searchResModel.isSuccess = true;
            searchResModel.mydutyClaimInfoSearchMiddleModel = lists;
            searchResModel.baseViewModel.Message            = "查询成功";
            searchResModel.baseViewModel.ResponseCode       = 200;

            return(Ok(searchResModel));
        }
Example #20
0
        public async Task <IActionResult> GetCode(CodeViewModel model)
        {
            if (model.PageId == Guid.Empty)
            {
                ModelState.AddModelError(string.Empty, "Invalid data input");
                return(View(model));
            }

            var page = await _pageRender.GetPageAsync(model.PageId);

            if (page == null)
            {
                ModelState.AddModelError(string.Empty, "Page not found");
                return(View(model));
            }

            if (page.Settings == null)
            {
                page.Settings = new PageSettings();
            }

            switch (model.Type)
            {
            case "css":
                page.Settings.CssCode = model.Code;
                break;

            case "js":
                page.Settings.JsCode = model.Code;
                break;

            case "html":
                page.Settings.HtmlCode = model.Code;
                break;
            }

            try
            {
                _pagesContext.Pages.Update(page);
                _pagesContext.SaveChanges();
                await _cacheService.RemoveAsync($"_page_dynamic_{page.Id}");

                //return RedirectToAction(page.IsLayout ? "Layouts" : "Index");
                return(RedirectToAction("GetCode", new { type = model.Type, id = model.PageId }));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            ModelState.AddModelError(string.Empty, "Invalid data input");
            return(View(model));
        }
Example #21
0
        public ActionResult <UserDepartResModel> Manage_SearchDepart(CodeViewModel code)
        {
            UserDepartResModel u_depart = new UserDepartResModel();
            var u_departMidModel        = normalizationInfoService.GetDepartList(code);

            u_depart.IsSuccess                  = true;
            u_depart.UserDepart                 = u_departMidModel;
            u_depart.baseViewModel.Message      = "查询成功";
            u_depart.baseViewModel.ResponseCode = 200;

            return(Ok(u_depart));
        }
Example #22
0
        public async Task <ActionResult> SendCode(CodeViewModel codeViewModel)
        {
            if (codeViewModel == null)
            {
                throw new ArgumentNullException(nameof(codeViewModel));
            }

            await SetUser();

            if (!ModelState.IsValid)
            {
                await TranslateView(DefaultLanguage);

                return(View(codeViewModel));
            }

            // 1. Check user is authenticated
            var authenticatedUser = await _authenticationService.GetAuthenticatedUser(this, SimpleIdentityServer.Host.Constants.TwoFactorCookieName);

            if (authenticatedUser == null || authenticatedUser.Identity == null || !authenticatedUser.Identity.IsAuthenticated)
            {
                throw new IdentityServerException(
                          SimpleIdentityServer.Core.Errors.ErrorCodes.UnhandledExceptionCode,
                          SimpleIdentityServer.Core.Errors.ErrorDescriptions.TwoFactorAuthenticationCannotBePerformed);
            }

            // 2. Validate the code
            if (!await _authenticateActions.ValidateCode(codeViewModel.Code))
            {
                await TranslateView(DefaultLanguage);

                ModelState.AddModelError("Code", "confirmation code is not valid");
                _simpleIdentityServerEventSource.ConfirmationCodeNotValid(codeViewModel.Code);
                return(View(codeViewModel));
            }

            // 3. Remove the code
            if (!await _authenticateActions.RemoveCode(codeViewModel.Code))
            {
                await TranslateView(DefaultLanguage);

                ModelState.AddModelError("Code", "an error occured while trying to remove the code");
                return(View(codeViewModel));
            }

            // 4. Authenticate the resource owner
            await _authenticationService.SignOutAsync(HttpContext, SimpleIdentityServer.Host.Constants.TwoFactorCookieName, new Microsoft.AspNetCore.Authentication.AuthenticationProperties());

            await SetLocalCookie(authenticatedUser.Claims, Guid.NewGuid().ToString());

            return(RedirectToAction("Index", "User"));
        }
Example #23
0
        public static List <CodeViewModel> CastToCodeViewModel(Codes[] codes)
        {
            List <CodeViewModel> listCodes = new List <CodeViewModel>();

            foreach (var item in codes)
            {
                CodeViewModel code = new CodeViewModel();
                code.Code = item.PinCode;
                code.Id   = item.Id;
                listCodes.Add(code);
            }
            return(listCodes);
        }
Example #24
0
        public void Update_NullOperatorCode_ErrorResult()
        {
            var testCodeViewModel = new CodeViewModel();

            mockUnitOfWork.Setup(m => m.Codes.Get(It.IsAny <Expression <Func <Code, bool> > >(), It.IsAny <Func <IQueryable <Code>,
                                                                                                                 IOrderedQueryable <Code> > >(), It.IsAny <string>())).Returns(new List <Code>());
            mockUnitOfWork.Setup(m => m.Save());

            var result = manager.Update(testCodeViewModel);

            TestContext.WriteLine(result.Details);
            Assert.That(result.Success, Is.False);
        }
Example #25
0
        public void GetById_ExistingId_Code()
        {
            var       testCode          = new Code();
            var       testCodeViewModel = new CodeViewModel();
            const int id = 42;

            mockUnitOfWork.Setup(m => m.Codes.GetById(It.Is <int>(x => x == id))).Returns(testCode);
            mockMapper.Setup(m => m.Map <CodeViewModel>(It.Is <Code>(x => x == testCode))).Returns(testCodeViewModel);

            var result = manager.GetById(id);

            Assert.That(testCodeViewModel, Is.EqualTo(result));
        }
Example #26
0
 public IActionResult Index(CodeViewModel codeViewModel)
 {
     if (!ModelState.IsValid)
     {
         return(View());
     }
     if (codeViewModel.Code != _ctx.OrderCode.First(x => x.Active == true).Password)
     {
         ModelState.AddModelError("error", "Code is invalid");
         return(View());
     }
     SessionHelper.SetObjectAsJson(HttpContext.Session, "validated", _ctx.OrderCode.First(x => x.Active == true).Password);
     return(RedirectToAction("ShortendOrderView", "Home"));
 }
        //获取 小区信息
        public List <UserDepartSearchMidModel> GetDepartList(CodeViewModel code)
        {
            UserDepartResModel returnDepart = new UserDepartResModel();

            List <User_Depart> departAll = _IVolunteerInfoRepository.GetDepartAll();

            var departList = _IMapper.Map <List <User_Depart>, List <UserDepartSearchMidModel> >(departAll);

            List <UserDepartSearchMidModel> result = new List <UserDepartSearchMidModel>();

            result.AddRange(departList.Where(p => p.ParentId == code.code).ToList());

            return(result);
        }
Example #28
0
        public async Task <ActionResult> GetCodes()
        {
            var list  = new List <CodeViewModel>();
            var items = await dataservice.GetCodesListAsync();

            foreach (var item in items)
            {
                var codeModel = new CodeViewModel();
                codeModel.Code = item.PinCode;
                codeModel.Id   = item.Id;
                list.Add(codeModel);
            }
            return(Json(list, JsonRequestBehavior.AllowGet));
        }
Example #29
0
        public async Task <ActionResult> Edit(int id)
        {
            var code = await dataservice.GetCodeAsync(id);

            if (code == null)
            {
                return(HttpNotFound());
            }

            var viewModel = new CodeViewModel();

            viewModel.Code = code.PinCode;
            viewModel.Id   = code.Id;

            return(View("CodeForm", viewModel));
        }
Example #30
0
        public void Add_DBError_ErrorResult()
        {
            var testingCode = new CodeViewModel {
                OperatorCode = "+36778"
            };

            mockUnitOfWork.Setup(m => m.Codes.Get(It.IsAny <Expression <Func <Code, bool> > >(), It.IsAny <Func <IQueryable <Code>,
                                                                                                                 IOrderedQueryable <Code> > >(), It.IsAny <string>()))
            .Returns(new List <Code>());
            mockUnitOfWork.Setup(m => m.Save()).Throws(new DataException());

            var result = manager.Add(testingCode);

            TestContext.WriteLine(result.Details);
            Assert.That(result.Success, Is.False);
        }