public IHttpActionResult PutComment(int id, Comment comment) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != comment.Id) { return(BadRequest()); } //db.Entry(comment).State = EntityState.Modified; db.Comments.AddOrUpdate(comment); ContextHelper.SaveChanges(db); //db.SaveChanges(); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CommentExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public void Fires_create_method_and_passes_down_affiliate_id_if_exists() { const string expectedUsername = "******"; const string expectedPassword = "******"; const string expectedAffiliatePartnerId = "712"; var oAuthAccessToken = new OAuthAccessToken(); _oAuthAuthentication.Stub(x => x.ForUser(null, null)).IgnoreArguments().Return(oAuthAccessToken); var serviceBase = MockRepository.GenerateStub <IServiceBase>(); var formData = new NameValueCollection { { "affiliatePartner", expectedAffiliatePartnerId } }; var loggedInContext = ContextHelper.LoggedInContext(formData); serviceBase.Stub(x => x.RequestContext).Return(loggedInContext); var sevenDigitalCredentialsAuthProvider = new SevenDigitalCredentialsAuthProvider(_oAuthAuthentication, _userApi); sevenDigitalCredentialsAuthProvider.TryAuthenticate(serviceBase, expectedUsername, expectedPassword); _userApi.AssertWasCalled(x => x.Create(expectedUsername, expectedPassword, expectedAffiliatePartnerId)); _oAuthAuthentication.AssertWasCalled(x => x.ForUser(HttpUtility.UrlEncode(expectedUsername), HttpUtility.UrlEncode(expectedPassword))); }
public PagedListContainer <T> GenerateList <T>(Type t, int count = 20, int page = 0, string text = "", Func <object, T>?Converter = null) where T : class { Converter ??= new Func <object, T>((o) => (T)o); PropertyInfo?Key = ContextHelper.GetKeyForType(t); if (Key is null) { throw new Exception($"Unable to find Key for type {t}"); } PagedListContainer <T> pagedList = new PagedListContainer <T>(); QueryResults DBResult; if (this.ServiceProvider.GetRepositoryForType <IKeyedObjectRepository>(t) is IKeyedObjectRepository TypedRepository) { DBResult = this.GetType().GetMethod(nameof(AdminController.QueryDatabase)).MakeGenericMethod(t).Invoke(this, new object[] { count, page, text }) as QueryResults; DBResult.Results = DBResult.Results.Select(Converter); } else { throw new Exception("Can not access data source for objects that dont derive from KeyedObjectType in this version"); } pagedList.Page = page; pagedList.Items.AddRange(DBResult.Results.Cast <T>()); pagedList.Count = count; pagedList.TotalCount = DBResult.TotalCount; return(pagedList); }
public void Intercept(IInvocation anInvocation) { try { this.State.StackInterception(); anInvocation.Proceed(); this.State.UnstackInterception(); if (!this.State.CanFinishInterception || !ShouldSaveChangesGeneratedBy(anInvocation)) { return; } ContextHelper.SaveChanges(); } catch (Exception ex) { this.State.UnstackInterception(); //TODO: Log something here throw ex; } }
public IActionResult SignUp(SignUpModel model) { if (ModelState.IsValid) { if (AuthenticationHelper.TrySignUp(model, out var user)) { // tmp direct login using (var context = ContextHelper.OpenContext()) { var contextUser = context.User.FirstOrDefault(u => u.UserId == user.UserId); if (contextUser != null) { contextUser.LastLogin = DateTime.Now; context.SaveChanges(); } } HttpContext.Session.SetObject("User", user); return(RedirectToAction("Events", "Home")); } } return(View(model)); }
public void DeleteStudent_WhenParametersAreCorrect() { //Arrange var contextMock = new Mock <ITAILSEntities>(); var students = ContextHelper.GetQueryableMockDbSet <Student> (new Student { Id = 1, FirstName = "Ivan", LastName = "Ivanov", Username = "******" }); var deleteStudentCommand = new DeleteStudentByIdCommand(contextMock.Object); var paramsList = new List <string>() { "1" }; contextMock.SetupGet(x => x.Students).Returns(students); //Act deleteStudentCommand.Execute(paramsList); //Assert contextMock.Verify(x => x.SaveChanges(), Times.Once); //contextMock.Verify(x => x.Students.Remove(It.IsAny<Student>()), Times.Once); //Assert.AreEqual(contextMock.Object.Students.Count<Student>(), 0); }
private void tsmiBackup_Click(object sender, EventArgs e) { //\WEB-INF\classes\config\webtop-config.xml //\WEB-INF\etc\settings-conf-upsv2.xml CheckBox cbTmp = (CheckBox)cmsWebSite.SourceControl; string dirPath = Application.StartupPath + "\\tomcatconfig\\" + cbTmp.Text + "\\remote\\"; if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load((string)cbTmp.Tag); Context ct = ContextHelper.parse(xmlDoc); if (ct == null) { return; } File.Copy(ct.docBase + "\\WEB-INF\\classes\\config\\webtop-config.xml", dirPath + "webtop-config.xml", true); File.Copy(ct.docBase + "\\WEB-INF\\etc\\settings-conf-upsv2.xml", dirPath + "settings-conf-upsv2.xml", true); MessageBox.Show("备份完成!"); }
public void Test_GetContextDataStack_WrongTypeInSlot() { string slotName = "Test slot name " + Guid.NewGuid(); Assert.That( ContextHelper <string> .Context.Value.ContainsKey(slotName), Is.False, "Existing data"); try { ContextHelper <Tuple <long> > .GetContextDataStack(slotName).Push(new Tuple <long>(1)); Assert.That(() => ContextHelper <string> .GetContextDataStack(slotName), Is.Empty); } finally { ConcurrentStack <string> value; ContextHelper <string> .Context.Value.TryRemove(slotName, out value); ConcurrentStack <Tuple <long> > tupleValue; ContextHelper <Tuple <long> > .Context.Value.TryRemove(slotName, out tupleValue); } }
public void TestParentContainerChildAdapter() { IDIContext context = ContextHelper.CreateContext(); context.m().Bind <IContainer>(() => new Container()); context.m().Bind <IAdapter>(() => new DefaultAdapter()); IDIContext childContext = ContextHelper.CreateContext(context); childContext.m().Bind <IAdapter>(() => new CustomAdapter()); // Resolving container from the parent context // Expecting DefaultAdapter IContainer container = context.Resolve <IContainer> (); Assert.IsAssignableFrom <Container> (container); Assert.IsAssignableFrom <DefaultAdapter> (container.adapter); // Resolving container from the child context // Expecting CustomAdapter container = childContext.Resolve <IContainer> (); Assert.IsAssignableFrom <Container> (container); Assert.IsAssignableFrom <CustomAdapter> (container.adapter); }
public static async Task RollbackTransaction() { var context = ContextHelper.GetContext(); if (!context.HasTransaction) { return; } var trans = context.trans; var conn = trans.Connection; context.trans = null; try { await trans.RollbackAsync(); } finally { conn.Close(); conn.Dispose(); } }
public IQueryable <Author> GetAuthor(string name) { try { MediaLibContainer context = ContextHelper <MediaLibContainer> .GetCurrentContext(); var auth = from author in context.PersonSet.OfType <Author>() where name.Contains(author.FirstName) && name.Contains(author.LastName) select author; if (auth.Count() == 0) { auth = from author in context.PersonSet.OfType <Author>() where name.Contains(author.FirstName) || name.Contains(author.LastName) select author; } return(auth); } catch (Exception) { return(null); } }
public static List <Vendor> LoadByName(string vName, bool activeOnly) { try { //VendorList = Where(v => v.vendor_name.ToLower().Contains(vName.ToLower()) && v.organization_id == 1); using (PurchasingContext Context = ContextHelper.GetDBContext()) { var vendorQuery = Context.VendorDatas .Where(v => v.vendor_name.ToLower().Contains(vName.ToLower())) .Where(v => v.organization_id == 1); if (activeOnly) { vendorQuery = vendorQuery.Where(v => v.active == activeOnly); } return(vendorQuery.Select(v => new Vendor(v)).ToList()); } } catch (Exception ex) { throw new VendorException("An error has occurred when loading the vendor list by name.", ex); } }
public void Update_WhenModulesPermissionDidntChange_DoesNotUpdateIt() { using (var context = ContextHelper.Create()) { var user = context.AddUser(); var module = context.AddUserModule(); var granter = context.AddUser(); var model = GetValidUpdateUserData(user); var moduleModel = GetValidUserModule(module); moduleModel.GranterId = granter.Id; model.Modules.Add(moduleModel); var service = Factory.CreateUserService(context); Helper.Suppress(() => service.Update(model, null)); var userModuleFrromDb = context.UserModules.First(); Assert.AreNotEqual(userModuleFrromDb.GranterId, granter.Id); } }
public override SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery, IDictionary <string, IFilter> enabledFilters) { System.Type type = GetCriteriaClass(criteria); ISearchFactoryImplementor searchFactory = ContextHelper.GetSearchFactory(GetSession(criteria)); ISet <System.Type> types; IndexSearcher searcher = FullTextSearchHelper.BuildSearcher(searchFactory, out types, type); if (searcher == null) { throw new SearchException("Could not find a searcher for class: " + type.FullName); } Lucene.Net.Search.Query query = FullTextSearchHelper.FilterQueryByClasses(types, luceneQuery); Hits hits = searcher.Search(query); List <object> ids = new List <object>(); for (int i = 0; i < hits.Length(); i++) { object id = DocumentBuilder.GetDocumentId(searchFactory, type, hits.Doc(i)); ids.Add(id); } base.Values = ids.ToArray(); return(base.ToSqlString(criteria, criteriaQuery, enabledFilters)); }
public void GetUserBooksByBookIdShouldReturnThreeUserBooks() { MediaLibContainer context = ContextHelper <MediaLibContainer> .GetCurrentContext(); User user = context.UserSet.First <User>(); Book book = TestUtil.generateBook(); UserBook userBook1 = TestUtil.generateUserBook(book); userBook1.User = user; AddUserMedia(userBook1); UserBook userBook2 = TestUtil.generateUserBook(book); userBook2.User = user; AddUserMedia(userBook2); UserBook userBook3 = TestUtil.generateUserBook(book); userBook3.User = user; AddUserMedia(userBook3); IQueryable <UserBook> userBooks = userBookDao.GetUserBooksByBookId(user.Username, book.Id); Assert.AreEqual(3, userBooks.Count <UserBook>()); }
public void Test_IsSet_WrongTypeInSlot() { Assert.That(ContextHelper <string> .GetContextDataStack(SlotName), Is.Empty, "Existing data"); try { ConcurrentStack <string> stack; ContextHelper <string> .Context.Value.TryRemove(SlotName, out stack); ContextHelper <Tuple <long> > .GetContextDataStack(SlotName).Push(new Tuple <long>(123)); Assert.That(() => ContextHelper <string> .IsSet(SlotName), Is.False); } finally { ConcurrentStack <string> value; ContextHelper <string> .Context.Value.TryRemove(SlotName, out value); ConcurrentStack <Tuple <long> > tupleValue; ContextHelper <Tuple <long> > .Context.Value.TryRemove(SlotName, out tupleValue); } }
public void TestSeveralRequirementsSameType() { IDIContext context = ContextHelper.CreateContext(); context.m().Bind <IMyOtherClass>(() => new MyClassSameTypeRequirements()); IMyOtherClass obj = context.Resolve <IMyOtherClass>(() => Construction .ForType <IOrange>(new Orange()).AndType <IApple>(new Apple()) ); Assert.That(obj.orange is Orange); Assert.That(obj.anotherOrange is Orange); Assert.AreSame(obj.orange, obj.anotherOrange); Assert.That(obj.apple is Apple); obj = context.Resolve <IMyOtherClass>(() => Construction .ForType <IOrange>("orange", new Orange()).AndType <IApple>(new Apple()) .AndType <IOrange>("anotherOrange", new DefaultOrange()) ); Assert.That(obj.orange is Orange); Assert.That(obj.anotherOrange is DefaultOrange); Assert.That(obj.apple is Apple); }
public Boolean ConfirmBasket(Basket parameters) { using (var context = ContextHelper.GetContext()) { var product = new Product(); var basket = context.Baskets .Where(x => x.BasketId == parameters.BasketId && x.UserId == Session.CurrentUser.UserId && x.Status == 1) .FirstOrDefault(); if (basket == null) { return(false); } // confirmed and paid // onaylandı ve ödendi basket.Status = 2; context.Baskets.Update(basket); context.SaveChanges(); return(true); } }
// • DeclineInvite <teamName> public string Execute(string[] args) { Checker.CheckLength(1, args); User currentUser = AuthenticationManager.GetCurrentUser(); string teamName = args[0]; if (!Checker.IsTeamExisting(teamName)) { throw new ArgumentException(string.Format(Constants.ErrorMessages.TeamNotFound, teamName)); } if (!Checker.IsInviteExisting(teamName, currentUser)) { throw new ArgumentException(string.Format(Constants.ErrorMessages.InviteNotFound, teamName)); } ContextHelper.DeclineInvite(teamName, currentUser); string result = string.Format(Constants.SuccessMessages.SuccessfullyDeclinedInvitation, teamName); return(result); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, webnetlabb3Context context) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //Context helper settings //Debug = console output ContextHelper.Debug = true; //Refresh = Update all dates on screenings. ContextHelper.Refresh = false; //Run ContextHelper.Check(context).Wait(); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }
public void OrdersCanBeWrittenToDatabaseWithNewUser() { using (var contextHelper = new ContextHelper <ApplicationDbContext>()) { contextHelper.Context.Orders.Count().ShouldBe(0); contextHelper.Context.Users.Count().ShouldBe(0); contextHelper.Context.Users.Add(CreateValidEntities.User(5)); contextHelper.Context.SaveChanges(); var order = CreateValidEntities.Order(1); order.Creator = CreateValidEntities.User(3); contextHelper.Context.Orders.Add(order); contextHelper.Context.SaveChanges(); var updatedOrders = contextHelper.Context.Orders.Include(a => a.Creator).ToList(); contextHelper.Context.Users.Count().ShouldBe(2); updatedOrders.Count().ShouldBe(1); updatedOrders[0].Creator.FirstName.ShouldBe("FirstName3"); } }
public void GetUserVideoByVideoIdShouldReturnThreeUserVideos() { MediaLibContainer context = ContextHelper <MediaLibContainer> .GetCurrentContext(); User user = context.UserSet.First <User>(); Movie movie = TestUtil.generateMovie(); UserMovie userMovie1 = TestUtil.generateUserMovie(movie); userMovie1.User = user; AddUserMedia(userMovie1); UserMovie userMovie2 = TestUtil.generateUserMovie(movie); userMovie2.User = user; AddUserMedia(userMovie2); UserMovie userMovie3 = TestUtil.generateUserMovie(movie); userMovie3.User = user; AddUserMedia(userMovie3); IQueryable <UserMovie> userMovies = userMovieDao.GetUserMovieByMovieId(user.Username, movie.Id); Assert.AreEqual(3, userMovies.Count <UserMovie>()); }
// • Disband <teamName> public string Execute(string[] args) { Checker.CheckLength(1, args); User currentUser = AuthenticationManager.GetCurrentUser(); string teamName = args[0]; if (!Checker.IsTeamExisting(teamName)) { throw new ArgumentException(string.Format(Constants.ErrorMessages.TeamNotFound, teamName)); } if (!Checker.IsUserCreatorOfTeam(teamName, currentUser)) { throw new InvalidOperationException(Constants.ErrorMessages.NotAllowed); } ContextHelper.DisbandTeam(teamName); string result = string.Format(Constants.SuccessMessages.SuccessfullyDisbandedTeam, teamName); return(result); }
/// <summary> /// Ensures dashboard initialization. /// </summary> public void SetupDashboard() { // Register placeholder for context menu ICMSPage page = Page as ICMSPage; if (page != null) { page.ContextMenuContainer = plcCtx; } if (PortalPageInstance == null) { throw new Exception("[DashboardControl.SetupDashboard] Portal page instance must be set."); } // Default settings for drag and drop for dashboard manPortal.HighlightDropableAreas = HighlightDropableAreas; manPortal.ActivateZoneBorder = ActivateZoneBorder; string dashboardName = QueryHelper.GetString("DashboardName", PersonalizationInfoProvider.UNDEFINEDDASHBOARD); // Set culture CultureInfo ci = CultureHelper.PreferredUICultureInfo; Thread.CurrentThread.CurrentCulture = ci; Thread.CurrentThread.CurrentUICulture = ci; // Init the page components PortalPageInstance.PageManager = manPortal; manPortal.SetMainPagePlaceholder(plc); string templateName = QueryHelper.GetString("templatename", String.Empty); PageTemplateInfo pti = PageTemplateInfoProvider.GetPageTemplateInfo(templateName); if (pti != null) { if (pti.PageTemplateType != PageTemplateTypeEnum.Dashboard) { RedirectToAccessDenied("dashboard.invalidpagetemplate"); } // Prepare virtual page info PageInfo pi = PageInfoProvider.GetVirtualPageInfo(pti.PageTemplateId); pi.DocumentNamePath = "/" + templateName; CMSContext.CurrentPageInfo = pi; // Set the design mode PortalContext.SetRequestViewMode(ViewModeEnum.DashboardWidgets); PortalContext.DashboardName = dashboardName; ContextHelper.Add("DisplayContentInDesignMode", "0", true, false, false, DateTime.MinValue); PortalPageInstance.ManagersContainer = plcManagers; PortalPageInstance.ScriptManagerControl = manScript; } else { RedirectToInformation(GetString("dashboard.notemplate")); } }
public ActionResult Login(int?TypeFlag, string UserName, string UserPassword) { UserName = UserName.Trim(); UserPassword = UserPassword.Trim(); //Code = Code.Trim().ToLower(); ; var ctx = ContextHelper.Create(); var UserSession = AccountHelper.GetUser(); var SysLog = new SysLog(); var User = ctx.User.FirstOrDefault(x => x.UserName == UserName && x.DeleteFlag == false); if (User != null) { if (User.UserPassword == UserPassword) { HttpContext.Application.Lock(); string SessionID = Session.SessionID; string CurrentUser = "******" + User.UserName; // HttpContext.Application.Add(CurrentUser,SessionID); HttpContext.Application.Set(CurrentUser, SessionID); HttpContext.Application.UnLock(); AccountHelper.SaveUser(User); //if (Code == Session["VCode"].ToString().ToLower()) //{ //} //else //{ // ViewBag.Message = "验证码输入错误!"; // ViewBag.UserName = UserName.Trim(); // ViewBag.UserPassword = UserPassword.Trim(); // return View(); //} if (User.TypeFlag == Enum.UserTypeFlag.外部) { User.LastTime = User.LogTime; User.LogTime = DateTime.Now; SysLog.Name = User.Name; SysLog.Title = User.UserName; SysLog.LogTime = DateTime.Now; ctx.SysLog.Add(SysLog); ctx.SaveChanges(); return(RedirectToAction("Index", "Home")); } else { User.LastTime = User.LogTime; User.LogTime = DateTime.Now; SysLog.Name = User.Name; SysLog.Title = User.UserName; SysLog.LogTime = DateTime.Now; ctx.SysLog.Add(SysLog); User.LastTime = User.LogTime; User.LogTime = DateTime.Now; ctx.SaveChanges(); return(RedirectToAction("Index", "Home", new { Area = "Manage" })); } } else { ViewBag.Message = "用户名或者密码错误!"; return(View()); } } else { ViewBag.Message = "用户名或者密码错误!"; return(View()); } }
public CvController() { StripperContext context = ContextHelper.GetContext(); Repo = new CvRepository(context); }
private async Task InitXamService() { try { //ElectronNET implementation does not rely on any JS Interop, nor Xamarin/Mono context EXCEPT if 'useWasm' is enabled if ((ContextHelper.IsBlazorMobile() || (ContextHelper.IsElectronNET() && ContextHelper.IsUsingWASM())) && await Runtime.InvokeAsync <bool>("BlazorXamarin.RuntimeCheck") || ContextHelper.IsElectronNET()) { //This must be called before GetRuntimePlatform, as GetRuntimePlatform is considered as a BlazorAppLaunched event //We are here workarounding a race condition when using ElectronNET. Using Electron here. if (ContextHelper.IsElectronNET()) { string currentURL = await Runtime.InvokeAsync <string>("BlazorXamarin.ElectronGetCurrentURL"); string UserDataPath = await Runtime.InvokeAsync <string>("BlazorXamarin.ElectronGetUserDataPath"); //Before calling StartupMetadataForElectron and call the initialization event from GetRuntimePlatform //we want to ensure that the 'HybridSupport.IsElectronActive' value is ready remotly, to ensure //to finish to install ElectronNET Hooks bool isElectronActive = false; int waitingCounter = 0; while (waitingCounter < 10) { //We will do 10 attempts. If unable to honor the result, we will continue and ignore this if (isElectronActive = await xamService.IsElectronActive()) { break; } waitingCounter++; await Task.Delay(200); } xamService.WriteLine($"HybridSupport.IsElectronActive returned: {isElectronActive.ToString()}"); if (ContextHelper.IsUsingWASM()) { xamService.WriteLine("INFO: Using WASM engine on ElectronNET as 'useWasm' was set to true in 'UseBlazorMobileWithElectronNET' method"); } await xamService.StartupMetadataForElectron(currentURL, UserDataPath); } BlazorDevice.RuntimePlatform = await xamService.GetRuntimePlatform(); } else { //If service return false we return the Browser default value BlazorDevice.RuntimePlatform = BlazorDevice.Browser; } BlazorMobileSuccess = true; } catch (Exception ex) { xamService.WriteLine(ex.Message); BlazorDevice.RuntimePlatform = BlazorDevice.Browser; BlazorMobileSuccess = false; } }
/// <summary> /// Has the context been set, i.e. are we in a using block? /// </summary> /// <param name="cacheName"> /// The name of the cache to check for. /// </param> /// <returns> /// True if the context has been set, false otherwise. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="cacheName" /> cannot be null, empty or whitespace. /// </exception> public static bool IsSet(string cacheName) { if (string.IsNullOrWhiteSpace(cacheName)) { throw new ArgumentNullException("cacheName"); } return(ContextHelper <RedisCacheMemoryStoreSuppressionContext> .IsSet(BuildSlotName( cacheName )) || ContextHelper <RedisCacheMemoryStoreSuppressionContext> .IsSet(BuildSlotName( Global ))); }
public GetPostsQueryHandlerTests(ITestOutputHelper output) { _output = output; th = new ContextHelper().BuildPgHelper(); sut = new GetPosts.Handler(th.Context); }
//------- target mode ------ // Set the context for the path. Use this method in "target" mode // to connect the path to a rootItem for a short time: // using (path.SetContext(myItem)) // { // ... call target-mode convenience methods ... // } internal IDisposable SetContext(object rootItem) { if (_contextHelper == null) _contextHelper = new ContextHelper(this); _contextHelper.SetContext(rootItem); return _contextHelper; }
public static Waffle Waffle(this Faker faker) { return(ContextHelper.GetOrSet(faker, () => new Waffle())); }
public ContextSourceProxy() { contextHelper_ = new ContextHelper(); }