protected override void Before_all_specs() { SetupDatabase(ShopGunSpecBase.Database.ShopGun, typeof(Base).Assembly); var ingredient1 = new Ingredient {IngredientName = "Hop", LastUpdated = DateTime.Now}; var ingredient2 = new Ingredient {IngredientName = "Malt", LastUpdated = DateTime.Now}; var ingredient3 = new Ingredient {IngredientName = "Water", LastUpdated = DateTime.Now }; _ingredientRepository = new Repository<Ingredient>(GetNewDataContext()); _ingredientRepository.Add(ingredient1); _ingredientRepository.Add(ingredient2); _ingredientRepository.Add(ingredient3); _ingredientRepository.Persist(); _product = ProductBuilder.BuildProduct(); _product.AddIngredient(ingredient1); _product.AddIngredient(ingredient2); _product.AddIngredient(ingredient3); _productRepository = new Repository<Product>(GetNewDataContext()); _productRepository.Add(_product); _productRepository.Persist(); base.Before_each_spec(); }
protected override void Before_all_specs() { SetupDatabase(ShopGunSpecBase.Database.ShopGun, typeof(Base).Assembly); IConfiguration configuration = new BasicConfiguration(); var container = configuration.Container; _ingredientRepository = new IngredientRepository(GetNewDataContext()); _semaphoreRepository = new Repository<Semaphore>(GetNewDataContext()); _mentorRepository = new Repository<Mentor>(GetNewDataContext()); _ingredientAdviceRepository = new Repository<IngredientAdvice>(GetNewDataContext()); _ingredientAdviceDomainService = new IngredientAdviceDomainService(_ingredientRepository, _ingredientAdviceRepository, GetNewDataContext()); _mentor = MentorBuilder.BuildMentor(); _mentorRepository.Add(_mentor); _mentorRepository.Persist(); _redSemaphore = SemaphoreBuilder.BuildRedSemaphore(); _semaphoreRepository.Add(_redSemaphore); _greenSemaphore = SemaphoreBuilder.BuildGreenSemaphore(); _semaphoreRepository.Add(_greenSemaphore); _semaphoreRepository.Persist(); _ingredient = IngredientBuilder.BuildIngredient(); _ingredientRepository.Add(_ingredient); _ingredientRepository.Persist(); base.Before_each_spec(); }
public void Add_Should_Result_In_Proper_Total_Items(IRepository<Contact, string> repository) { repository.Add(new Contact { Name = "Test User" }); var result = repository.GetAll(); result.Count().ShouldEqual(1); }
public void Add(BusinessObjects.GroupRelation entity) { //Add GroupRelation using (_GroupRelationRepository = new GenericRepository<DAL.DataEntities.GroupRelation>()) { _GroupRelationRepository.Add((DAL.DataEntities.GroupRelation)entity.InnerEntity); _GroupRelationRepository.SaveChanges(); } //Add GroupRelations_To_Features using (_GroupRelationsToFeaturesRepository = new GenericRepository<DAL.DataEntities.GroupRelation_To_Feature>()) { foreach (int childFeatureID in entity.ChildFeatureIDs) { DAL.DataEntities.GroupRelation_To_Feature grToFeature = new DAL.DataEntities.GroupRelation_To_Feature(); grToFeature.GroupRelationID = entity.ID; grToFeature.ParentFeatureID = entity.ParentFeatureID; grToFeature.ChildFeatureID = childFeatureID; _GroupRelationsToFeaturesRepository.Add(grToFeature); } _GroupRelationsToFeaturesRepository.SaveChanges(); } }
protected override bool ExecuteWithData(string cmd, IRepository repo, Player player) { var name = cmd.Split(new[] { ' ' }, 2)[1]; repo.Add(new GameObject { Name = name, Location = player }); console.WriteLine("You create a {0}.", name); return true; }
static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<Customer>().As<ICustomer>(); builder.RegisterType<LineItem>().As<ILineItem>(); builder.RegisterType<Order>().As<IOrder>(); builder.RegisterType<Product>().As<IProduct>(); Container = builder.Build(); _customerRepo = new Repository<Customer>(); _customerRepo.Add(new Customer { FirstName = "Chris", LastName = "Cais" }); _customerRepo.Add(new Customer { FirstName = "James", LastName = "Harden" }); _customerRepo.Save(); }
public string UploadFile(byte[] fileBytes, string fileName) { var strArr = fileName.Split('.'); if (strArr.Length < 2) { throw new ArgumentException(nameof(fileName)); } var fileNameBuilder = new StringBuilder(); for (var i = 0; i < strArr.Length - 1; i++) { fileNameBuilder.Append(strArr[i]); } var file = fileNameBuilder.ToString(); var fileExt = strArr.Last(); if (string.IsNullOrWhiteSpace(file) || string.IsNullOrWhiteSpace(fileExt)) { throw new ArgumentException(nameof(fileName)); } var storageNode = _fastDfsClient.GetStorageNode(_groupName); var fileDfsInfo = new FileDfsInfo { Id = Guid.NewGuid(), DfsFileName = _fastDfsClient.UploadFile(storageNode, fileBytes, fileExt), FileName = fileName, UtcCreateTime = DateTime.Now }; _repository?.Add(fileDfsInfo); return(fileDfsInfo.DfsFileName); }
public PSTutorialFlags(account account, IRepository<character_tutorial> characterTutorials) : base(WorldOpcodes.SMSG_TUTORIAL_FLAGS) { character_tutorial characterTutorial = characterTutorials.SingleOrDefault(ct => ct.account == account.id); if (characterTutorial == null) { characterTutorial = new character_tutorial() { account = account.id, tut0 = 0, tut1 = 0, tut2 = 0, tut3 = 0, tut4 = 0, tut5 = 0, tut6 = 0, tut7 = 0 }; characterTutorials.Add(characterTutorial); } this.Write((byte)characterTutorial.tut0); this.Write((byte)characterTutorial.tut1); this.Write((byte)characterTutorial.tut2); this.Write((byte)characterTutorial.tut3); this.Write((byte)characterTutorial.tut4); this.Write((byte)characterTutorial.tut5); this.Write((byte)characterTutorial.tut6); this.Write((byte)characterTutorial.tut7); }
private static Setting InitializeSetting(string settingName, IRepository repository) { var setting = new Setting { Name = settingName.Encrypt() }; repository.Add<Setting>(setting); repository.Save(); return setting; }
public void Add(BusinessObjects.FeatureSelection entity) { using (_FeatureSelectionRepository = new GenericRepository<DAL.DataEntities.FeatureSelection>()) { //Add the FeatureSelection _FeatureSelectionRepository.Add((DAL.DataEntities.FeatureSelection)entity.InnerEntity); _FeatureSelectionRepository.SaveChanges(); //Add AttributeValues using (_AttributeValuesRepository = new GenericRepository<DAL.DataEntities.AttributeValue>()) { for (int i = entity.AttributeValues.Count - 1; i >= 0; i--) { BLL.BusinessObjects.AttributeValue BLLAttributeValue = entity.AttributeValues[i]; BLLAttributeValue.FeatureSelectionID = entity.ID; //Add if (BLLAttributeValue.ToBeDeleted == false && BLLAttributeValue.ID == 0) { _AttributeValuesRepository.Add((DAL.DataEntities.AttributeValue)BLLAttributeValue.InnerEntity); } } _AttributeValuesRepository.SaveChanges(); } } }
private void RegistrationEvent(IActivityRegister activityRegister, IRepository repository, ActivityTypes activityType) { if (repository == null) throw new ArgumentNullException(nameof(repository)); var activity = ActivityCreate(activityRegister.ObjectInfo, activityType); repository.Add(activity); }
public void Add(BusinessObjects.Model entity) { using (_ModelRepository = new GenericRepository<DAL.DataEntities.Model>()) { _ModelRepository.Add((DAL.DataEntities.Model)entity.InnerEntity); _ModelRepository.SaveChanges(); } }
public void Update_Should_Save_Modified_Business_Name(IRepository<Contact, string> repository) { var contact = new Contact { Name = "Test User" }; repository.Add(contact); var contact2 = new Contact { Name = "Test User 2" }; repository.Add(contact2); contact.Name = "Test User - Updated"; repository.Update(contact); var updated = repository.Get(contact.ContactId); var notUpdated = repository.Get(contact2.ContactId); updated.Name.ShouldEqual("Test User - Updated"); notUpdated.Name.ShouldEqual("Test User 2"); }
public void Add(BusinessObjects.Constraint entity) { using (_ConstraintRepository = new GenericRepository<DAL.DataEntities.Constraint>()) { _ConstraintRepository.Add((DAL.DataEntities.Constraint)entity.InnerEntity); _ConstraintRepository.SaveChanges(); } }
protected override bool ExecuteWithData(string cmd, IRepository repo, Player player) { var name = cmd.Split(new[] { ' ' }, 2); var room = new Room() { Name = name[1].Trim() }; repo.Add(room); console.WriteLine("Room created"); return true; }
public void Add(BusinessObjects.Relation entity) { using (_RelationRepository = new GenericRepository<DAL.DataEntities.Relation>()) { _RelationRepository.Add((DAL.DataEntities.Relation)entity.InnerEntity); _RelationRepository.SaveChanges(); } }
public void Add(BusinessObjects.CustomRule entity) { using (_CustomRuleRepository = new GenericRepository<DAL.DataEntities.CustomRule>()) { _CustomRuleRepository.Add((DAL.DataEntities.CustomRule)entity.InnerEntity); _CustomRuleRepository.SaveChanges(); } }
public void Get_With_String_Selector_Should_Return_Item_If_Item_Exists(IRepository<Contact, string> repository) { var contact = new Contact { Name = "Test User" }; repository.Add(contact); var result = repository.Get(contact.ContactId, c => c.Name); result.ShouldEqual("Test User"); }
public void Add(BLL.BusinessObjects.UITemplate entity) { using (_UITemplateRepository = new GenericRepository<DAL.DataEntities.UITemplate>()) { _UITemplateRepository.Add((DAL.DataEntities.UITemplate)entity.InnerEntity); _UITemplateRepository.SaveChanges(); } }
public void Get_With_Anonymous_Class_Selector_Should_Return_Item_If_Item_Exists(IRepository<Contact, string> repository) { var contact = new Contact { Name = "Test User", ContactTypeId = 2 }; repository.Add(contact); var result = repository.Get(contact.ContactId, c => new { c.ContactTypeId, c.Name }); result.ContactTypeId.ShouldEqual(2); result.Name.ShouldEqual("Test User"); }
public void Get_Should_Return_Item_If_Item_Exists(IRepository<Contact, string> repository) { var contact = new Contact { Name = "Test User", ContactTypeId = 1 }; repository.Add(contact); var result = repository.Get(contact.ContactId); result.Name.ShouldEqual(contact.Name); result.ContactTypeId.ShouldEqual(contact.ContactTypeId); }
public void Add(BusinessObjects.Attribute entity) { using (_AttributeRepository = new GenericRepository<DAL.DataEntities.Attribute>()) { //Add the Attribute _AttributeRepository.Add((DAL.DataEntities.Attribute)entity.InnerEntity); _AttributeRepository.SaveChanges(); } }
public void Add(BusinessObjects.Feature entity) { using (_FeatureRepository = new GenericRepository<DAL.DataEntities.Feature>()) { //Add the Feature _FeatureRepository.Add((DAL.DataEntities.Feature)entity.InnerEntity); _FeatureRepository.SaveChanges(); } }
public void Average_With_Specification_Should_Return_Average(IRepository<Contact, string> repository) { for (var i = 1; i <= 3; i++) { var contact = new Contact { Name = "Test User " + i, ContactTypeId =i}; repository.Add(contact); } repository.Average(new Specification<Contact>(x => x.ContactTypeId > 1), x => x.ContactTypeId).ShouldEqual(2.5); }
protected override bool ExecuteWithData(string cmd, IRepository repo, Player player) { var name = cmd.Split(new[] { ' ' }, 2)[1]; var room = new Room() { Name = name }; repo.Add(room); return true; }
protected virtual ObservableChangeTracker GetChangeTracker(IRepository repository) { var retVal = new ObservableChangeTracker { RemoveAction = x => repository.Remove(x), AddAction = x => repository.Add(x) }; return retVal; }
public void Average_Decimal_With_Predicate_Should_Return_Average(IRepository<Contact, string> repository) { for (var i = 1; i <= 3; i++) { var contact = new Contact { Name = "Test User " + i, ContactTypeId = i, SumDecimal = 0.5m + i }; repository.Add(contact); } repository.Average(x => x.ContactTypeId > 1, x => x.SumDecimal).ShouldEqual(3m); }
public void Delete_By_Params_Should_Remove_Multiple_Items(IRepository<Contact, string> repository) { var contact1 = new Contact {Name = "Contact 1", ContactTypeId = 1}; var contact2 = new Contact {Name = "Contact 2", ContactTypeId = 1}; var contact3 = new Contact {Name = "Contact 3", ContactTypeId = 3}; repository.Add(contact1); repository.Add(contact2); repository.Add(contact3); var items = repository.GetAll().ToList(); items.Count().ShouldEqual(3); repository.Delete(contact1.ContactId, contact2.ContactId); items = repository.GetAll().ToList(); items.Count().ShouldEqual(1); items.First().Name.ShouldEqual("Contact 3"); }
public void Average_All_Should_Return_Average(IRepository<Contact, string> repository) { for (var i = 1; i <= 3; i++) { var contact = new Contact { Name = "Test User " + i, ContactTypeId =i}; repository.Add(contact); } repository.Average(x => x.ContactTypeId).ShouldEqual(2.0); }
public MatchModule(IRepository<Match> matchRepository, IRepository<Country> countryRepository) : base("/matches") { Get["/"] = parameters => { var matches = matchRepository.FindAll(); var resource = matches.ToArray().Select( m => new MatchResource { Id = m.Id, Date = m.Date, Team1CountryId = m.Team1.Country.Id, Team2CountryId = m.Team2.Country.Id }); return Response.AsJson(resource); }; Post["/"] = parameters => { var resource = this.Bind<MatchResource>(); var country1 = countryRepository.GetById(resource.Team1CountryId); if (country1 == null) return HttpStatusCode.BadRequest; var country2 = countryRepository.GetById(resource.Team2CountryId); if (country2 == null) return HttpStatusCode.BadRequest; var match = Match.Create( resource.Date, country1, country2); matchRepository.Add(match); return Response.AsRedirect("/matches/" + match.Id); }; Get["/{id}"] = parameters => { var match = matchRepository.GetById((int)parameters.Id); if (match == null) return HttpStatusCode.NotFound; return Response.AsJson(new { Date = match.Date, Team1 = match.Team1, Team2 = match.Team2 }); }; }
public void FindAll_Should_Return_All_Items_Which_Satisfy_Composite_Specification(IRepository<Contact, string> repository) { for (int i = 1; i <= 3; i++) { var contact = new Contact { Name = "Test User " + i }; repository.Add(contact); } var result = repository.FindAll(new Specification<Contact>(p => p.Name == "Test User 1").OrElse(new Specification<Contact>(p => p.Name == "Test User 2"))); result.Count().ShouldEqual(2); }
public void Add(LabelDao dao) { Label entity = _converter.DaoToEntity(dao); _repository.Add(entity); }
public void Add(BlogImageViewModel blogImage) { _blogImageRepository.Add(_mapper.Map <BlogImage>(blogImage)); }
public virtual async Task <TEntity> Post([FromBody] TEntity entity) { var newEntity = await _repository.Add(entity); return(newEntity); }
public virtual T Add <T>(T entity) where T : class { return(Repository.Add(entity)); }
public void Add(AgentEntity entity) { _repository.Add(entity); AgentAdded.Raise(this, entity); }
public void Add(T item) { Repository.Add(item); }
public async Task <Media> SaveMediaAsync(Stream mediaBinaryStream, string fileName, string mimeType = null) { var hsMd5 = string.Empty; var size = 0; Media media = null; var filePath = Path.Combine(GlobalConfiguration.WebRootPath, MediaRootFoler, fileName); using (var output = new FileStream(filePath, FileMode.Create)) { //if (!File.Exists(filePath)) await mediaBinaryStream.CopyToAsync(output); var bytes = new byte[mediaBinaryStream.Length]; mediaBinaryStream.Read(bytes, 0, bytes.Length); hsMd5 = Md5Helper.Encrypt(bytes); size = bytes.Length; } if (!string.IsNullOrWhiteSpace(hsMd5)) { media = await _mediaRepository.Query(c => c.Md5 == hsMd5 || c.FileName == fileName).FirstOrDefaultAsync(); } if (media == null) { media = new Media() { MediaType = MediaType.File, FileName = fileName, FileSize = size, Hash = "", Url = $"{host.Trim('/')}/{MediaRootFoler}/{fileName}", Path = $"/{MediaRootFoler}/{fileName}", Host = host, Md5 = hsMd5 }; if (!string.IsNullOrWhiteSpace(mimeType)) { mimeType = mimeType.Trim().ToLower(); if (mimeType.StartsWith("video")) { media.MediaType = MediaType.Video; } else if (mimeType.StartsWith("image")) { media.MediaType = MediaType.Image; } else { media.MediaType = MediaType.File; } } _mediaRepository.Add(media); } else { media.Url = $"{host.Trim('/')}/{MediaRootFoler}/{fileName}"; media.Path = $"/{MediaRootFoler}/{fileName}"; media.Host = host; } await _mediaRepository.SaveChangesAsync(); return(media); }
public void AddPlan(EventPlanning plan) { _plannerRepository.Add(plan); }
public void SaveSiteInfo(SiteIISLog siteIISLog) { IISLogRepository.Add(siteIISLog, true); }
public void Add(T entity) { _.Add(entity); }
public void Add(TEntity obj) { _repository.Add(obj); }
public static async Task SeedUsers(UserManager <User> _adminManager, IRepository _repo) { var email = "*****@*****.**"; if (await _adminManager.FindByEmailAsync(email) == null) { var password = "******"; var admin = new User { FirstName = "Admin", LastName = "Joestar", Email = email, UserName = email, }; await _adminManager.CreateAsync(admin, password); await _adminManager.AddToRoleAsync(admin, "Admin"); var adminEntity = new Admin() { User = admin }; var customer = new Customer { FirstName = "Jon", LastName = "Snow", CNP = "1233211233212", City = "Los Santos", Address = "Grove St.", ZipCode = "4204" }; var customerUser = new User { FirstName = "Jon", LastName = "Snow", Email = "*****@*****.**", UserName = "******" }; await _adminManager.CreateAsync(customerUser, "Drag0ns"); await _adminManager.AddToRoleAsync(customerUser, "Customer"); customer.User = customerUser; var loanOfficer = new LoanOfficer { FirstName = "Private", LastName = "Ryan", City = "'Murica", Address = "Freedom st.", ZipCode = "8008" }; var loanUser = new User { FirstName = "Private", LastName = "Ryan", Email = "*****@*****.**", UserName = "******" }; await _adminManager.CreateAsync(loanUser, "pr0tection"); await _adminManager.AddToRoleAsync(loanUser, "LoanOfficer"); loanOfficer.User = loanUser; await _repo.Add(loanOfficer); await _repo.Add(adminEntity); await _repo.Add(customer); } }
public async Task <CommandResult <ObjectReceivingResultDto> > AddReceiving(AddReceivingDto addReceivingDto) { if (addReceivingDto == null || addReceivingDto.RegistrationToken.IsNullOrEmpty()) { return(new CommandResult <ObjectReceivingResultDto>(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.NULL", Message = "Please send valid data", StatusCode = System.Net.HttpStatusCode.BadRequest, })); } var(login, user) = await userDataManager.AddCurrentUserIfNeeded(); if (login is null) { return(new CommandResult <ObjectReceivingResultDto>(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.UNAUTHOROIZED", Message = "You are not authorized to make this request", StatusCode = System.Net.HttpStatusCode.Unauthorized })); } var authResult = _ownershipAuthorization.IsAuthorized(tt => tt.Type == TokenType.Receiving && tt.Token == addReceivingDto.RegistrationToken, tt => tt.Registration.Object.OwnerUser); if (!authResult) { return(new CommandResult <ObjectReceivingResultDto>(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.UNAUTHOROIZED", Message = "You are not authorized to make this request", StatusCode = System.Net.HttpStatusCode.Unauthorized })); } var theToken = (from t in _tokensRepo.Table where t.Token == addReceivingDto.RegistrationToken && t.Type == TokenType.Receiving select t).FirstOrDefault(); if (theToken == null) { return(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.NOT.EXISTS", Message = "The QR code provided is faulty", StatusCode = System.Net.HttpStatusCode.BadRequest }.ToCommand <ObjectReceivingResultDto>()); } if (!(theToken.UseAfterUtc < DateTime.UtcNow && theToken.UseBeforeUtc > DateTime.UtcNow)) { return(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.TOKEN.EXPIRED", Message = "The QR code provided is too old", StatusCode = System.Net.HttpStatusCode.BadRequest }.ToCommand <ObjectReceivingResultDto>()); } if (theToken.Status != TokenStatus.Ok) { return(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.TOKEN.INVALID", Message = "The QR code provided is too old", StatusCode = System.Net.HttpStatusCode.BadRequest }.ToCommand <ObjectReceivingResultDto>()); } var theRegistration = (from rg in _registrationsRepo.Table where rg.Tokens.Any(rt => rt.Token == addReceivingDto.RegistrationToken) select rg).FirstOrDefault(); if (theRegistration is null) { return(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.NOT.EXISTS", Message = "The QR code provided is faulty", StatusCode = System.Net.HttpStatusCode.BadRequest }.ToCommand <ObjectReceivingResultDto>()); } if (theRegistration.ObjectReceiving is object) { return(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.TOKEN.USED", Message = "The QR code provided is already used", StatusCode = System.Net.HttpStatusCode.BadRequest }.ToCommand <ObjectReceivingResultDto>()); } var objectRegistrations = from rg in _registrationsRepo.Table where rg.ObjectId == theRegistration.ObjectId select rg; // if not all of them returned or not received if (!objectRegistrations.All(or => or.ObjectReceiving == null || or.ObjectReceiving.ObjectReturning != null)) { return(new ErrorMessage { ErrorCode = "TRANSACTION.RECEIVING.ADD.OBJECT.TAKEN", Message = "Do you even have the object?", StatusCode = System.Net.HttpStatusCode.BadRequest }.ToCommand <ObjectReceivingResultDto>()); } theToken.Status = TokenStatus.Used; var receiving = new ObjectReceiving { ReceivedAtUtc = DateTime.UtcNow, GiverLoginId = login.LoginId, RecipientLoginId = theToken.IssuerLoginId, HourlyCharge = 0f, ObjectRegistrationId = theRegistration.ObjectRegistrationId, ObjectReceivingId = Guid.NewGuid(), }; _receivingsRepo.Add(receiving); // this will save theToken.Status also await _receivingsRepo.SaveChangesAsync(); var evnt = new TransactionReceivedIntegrationEvent { Id = Guid.NewGuid(), OccuredAt = DateTime.UtcNow, ReceivedAtUtc = receiving.ReceivedAtUtc, ReceivingId = receiving.ObjectReceivingId, RegistrationId = receiving.ObjectRegistrationId, }; _eventBus.Publish(evnt); // Publish the event return(new CommandResult <ObjectReceivingResultDto>(new ObjectReceivingResultDto { ObjectId = _objectRepo.Get(theRegistration.ObjectId).OriginalObjectId, ReceivedAtUtc = receiving.ReceivedAtUtc, RegistrationId = theRegistration.ObjectRegistrationId, ShouldBeReturnedAfterReceving = theRegistration.ShouldReturnItAfter, })); }
/// <summary> /// Initializes a new instance of the <see cref="Sessions"/> class. /// </summary> /// <param name="accessRepo">Supplied through DI.</param> /// <param name="sessionRepo">Supplied through DI.</param> /// <param name="personRepo">Supplied through DI.</param> /// <param name="captureRepo">Supplied through DI.</param> /// <param name="logger">Supplied through DI.</param> /// <param name="date">Supplied through DI.</param> public Sessions( IRepository <AccessTokenSchema> accessRepo, IRepository <SessionSchema> sessionRepo, IRepository <PersonSchema> personRepo, IRepository <BsonDocument> captureRepo, ILogger logger, IDateExtra date) : base("/sessions") { this.Before += PreSecurity.CheckAccess(accessRepo, date); this.Post <PostSessions>("/", async(req, res) => { // Has to exist due to PreSecurity Check string token = req.Cookies["ExperienceCapture-Access-Token"]; var accessTokenDoc = await accessRepo.FindOne( Builders <AccessTokenSchema> .Filter .Where(a => a.Hash == PasswordHasher.Hash(token))); var filterUser = Builders <PersonSchema> .Filter.Where(p => p.InternalId == accessTokenDoc.User); var user = await personRepo .FindOne(filterUser); string shortID = Generate.GetRandomId(4); var sessionDoc = new SessionSchema { InternalId = ObjectId.GenerateNewId(), Id = shortID, User = user, // Copying user data instead of referencing so it can never change in the session CreatedAt = new BsonDateTime(date.UtcNow), Tags = new List <string>(), }; // Retry generating a short id until it is unique bool isUnique = true; do { try { sessionDoc.Id = shortID; await sessionRepo.Add(sessionDoc); isUnique = true; } catch (MongoWriteException e) { // Re-throw any other type of exception except non-unique keys if (e.WriteError.Code != 11000) { throw e; } shortID = Generate.GetRandomId(4); isUnique = false; } }while (!isUnique); // isOngoing is a proxy variable and will always start out as true sessionDoc.IsOngoing = true; sessionDoc.InternalId = null; sessionDoc.User.InternalId = null; captureRepo.Configure($"sessions.{shortID}"); // Secondary index or else Mongo will fail on large queries // It has a limit for max number of documents on properties // Without an index, see https://docs.mongodb.com/manual/reference/limits/#Sort-Operations var index = Builders <BsonDocument> .IndexKeys; var key = index.Ascending("frameInfo.realtimeSinceStartup"); await captureRepo.Index(key); string json = JsonQuery.FulfilEncoding(req.Query, sessionDoc); if (json != null) { await res.FromJson(json); return; } await res.FromBson(sessionDoc); }); this.Get <GetSessions>("/", async(req, res) => { var builder = Builders <SessionSchema> .Filter; // Note: only use `&=` for adding to the filter, // Or else the filter cannot handle multiple query string options FilterDefinition <SessionSchema> filter = builder.Empty; var startMin = new BsonDateTime(date.UtcNow.AddSeconds(-300)); // 5 minutes var closeMin = new BsonDateTime(date.UtcNow.AddSeconds(-5)); // 5 seconds var hasTags = req.Query.AsMultiple <string>("hasTags").ToList(); if (hasTags.Count > 0) { foreach (var tag in hasTags) { filter &= builder.Where(s => s.Tags.Contains(tag)); } } var lacksTags = req.Query.AsMultiple <string>("lacksTags").ToList(); if (lacksTags.Count > 0) { foreach (var tag in lacksTags) { filter &= builder.Where(s => !s.Tags.Contains(tag)); } } // Three potential options: null, true, or false if (req.Query.As <bool?>("isOngoing") != null) { bool isOngoing = req.Query.As <bool>("isOngoing"); if (isOngoing) { filter &= builder.Where(s => s.IsOpen == true) & ((builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.CreatedAt > startMin)) | (builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.LastCaptureAt > closeMin))); } else { filter &= builder.Where(s => s.IsOpen == false) | ((builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.CreatedAt < startMin)) | (builder.Eq(s => s.LastCaptureAt, BsonNull.Value) & builder.Where(s => s.LastCaptureAt < closeMin))); } } var page = req.Query.As <int?>("page") ?? 1; if (page < 1) { // Page query needs to be possible res.StatusCode = Status400BadRequest; return; } var direction = req.Query.As <string>("sort"); SortDefinition <SessionSchema> sorter; if (direction == null) { sorter = Builders <SessionSchema> .Sort.Descending(s => s.CreatedAt); } else { if (Enum.TryParse(typeof(SortOptions), direction, true, out object options)) { sorter = ((SortOptions)options).ToDefinition(); } else { res.StatusCode = Status400BadRequest; return; } } var sessionDocs = await sessionRepo .FindAll(filter, sorter, page); var sessionsDocsWithOngoing = sessionDocs.Select((s) => { bool isStarted = false; if (s.LastCaptureAt != BsonNull.Value) { isStarted = true; } bool isOngoing; if (s.IsOpen) { isOngoing = (!isStarted && startMin < s.CreatedAt) || (isStarted && closeMin < s.LastCaptureAt); } else { isOngoing = false; } s.IsOngoing = isOngoing; s.InternalId = null; s.User.InternalId = null; return(s); }); var count = await sessionRepo.FindThenCount(filter); var clientValues = new SessionsResponce { // Bson documents can't start with an array like Json, so a wrapping object is used instead ContentList = sessionsDocsWithOngoing.ToList(), PageTotal = (long)Math.Ceiling((double)count / 10d), }; string json = JsonQuery.FulfilEncoding(req.Query, clientValues); if (json != null) { await res.FromJson(json); return; } await res.FromBson(clientValues); }); this.Post <PostSession>("/{id}", async(req, res) => { string shortID = req.RouteValues.As <string>("id"); var sessionDoc = await sessionRepo .FindById(shortID); if (sessionDoc == null) { res.StatusCode = Status404NotFound; return; } if (!sessionDoc.IsOpen) { res.StatusCode = Status400BadRequest; return; } BsonDocument document; if (JsonQuery.CheckDecoding(req.Query)) { using (var ms = new MemoryStream()) { await req.Body.CopyToAsync(ms); ms.Position = 0; try { document = BsonSerializer.Deserialize <BsonDocument>(ms); } catch (Exception err) { logger.LogError(err.Message); res.StatusCode = Status400BadRequest; return; } } } else { string json = await req.Body.AsStringAsync(); try { document = BsonDocument.Parse(json); } catch (Exception err) { logger.LogError(err.Message); res.StatusCode = Status400BadRequest; return; } } // Manual validation, because Fluent Validation would remove extra properties if (!document.Contains("frameInfo") || document["frameInfo"].BsonType != BsonType.Document || !document["frameInfo"].AsBsonDocument.Contains("realtimeSinceStartup") || document["frameInfo"]["realtimeSinceStartup"].BsonType != BsonType.Double) { res.StatusCode = Status400BadRequest; return; } captureRepo.Configure($"sessions.{shortID}"); await captureRepo.Add(document); var filter = Builders <SessionSchema> .Filter.Where(s => s.Id == shortID); // This lastCaptureAt is undefined on the session document until the first call of this endpoint // Export flags are reset so the session can be re-exported var update = Builders <SessionSchema> .Update .Set(s => s.LastCaptureAt, new BsonDateTime(date.UtcNow)) .Set(s => s.ExportState, ExportOptions.NotStarted); await sessionRepo.Update(filter, update); await res.FromString(); }); this.Get <GetSession>("/{id}", async(req, res) => { string shortID = req.RouteValues.As <string>("id"); var sessionDoc = await sessionRepo .FindById(shortID); if (sessionDoc == null) { res.StatusCode = Status404NotFound; return; } var startRange = new BsonDateTime(date.UtcNow.AddSeconds(-300)); // 5 minutes var closeRange = new BsonDateTime(date.UtcNow.AddSeconds(-5)); // 5 seconds bool isStarted = false; // Check if key exists if (sessionDoc.LastCaptureAt != BsonNull.Value) { isStarted = true; } bool isOngoing; if (sessionDoc.IsOpen) { isOngoing = (!isStarted && startRange.CompareTo(sessionDoc.CreatedAt) < 0) || (isStarted && closeRange.CompareTo(sessionDoc.LastCaptureAt) < 0); } else { isOngoing = false; } sessionDoc.IsOngoing = isOngoing; sessionDoc.InternalId = null; sessionDoc.User.InternalId = null; string json = JsonQuery.FulfilEncoding(req.Query, sessionDoc); if (json != null) { await res.FromJson(json); return; } await res.FromBson(sessionDoc); }); this.Delete <DeleteSession>("/{id}", async(req, res) => { string shortID = req.RouteValues.As <string>("id"); var filter = Builders <SessionSchema> .Filter.Where(s => s.Id == shortID); var sessionDoc = await sessionRepo .FindById(shortID); if (sessionDoc == null) { res.StatusCode = Status404NotFound; return; } var update = Builders <SessionSchema> .Update .Set(s => s.IsOpen, false); await sessionRepo.Update(filter, update); await res.FromString(); }); }
public void Add(Count entity) { _repository.Add(entity); }
public async Task <IActionResult> Charge(string stripeEmail, string stripeToken) { var stripeProvider = await _paymentProviderRepository.Query().FirstOrDefaultAsync(x => x.Id == PaymentProviderHelper.StripeProviderId); var stripeSetting = JsonConvert.DeserializeObject <StripeConfigForm>(stripeProvider.AdditionalSettings); var stripeChargeService = new ChargeService(stripeSetting.PrivateKey); var currentUser = await _workContext.GetCurrentUser(); var cart = await _cartService.GetActiveCart(currentUser.Id); if (cart == null) { return(NotFound()); } var orderCreationResult = await _orderService.CreateOrder(cart.Id, "Stripe", 0, OrderStatus.PendingPayment); if (!orderCreationResult.Success) { TempData["Error"] = orderCreationResult.Error; return(Redirect("~/checkout/payment")); } var order = orderCreationResult.Value; var zeroDecimalOrderAmount = order.OrderTotal; if (!CurrencyHelper.IsZeroDecimalCurrencies()) { zeroDecimalOrderAmount = zeroDecimalOrderAmount * 100; } var regionInfo = new RegionInfo(CultureInfo.CurrentCulture.LCID); var payment = new Payment() { OrderId = order.Id, Amount = order.OrderTotal, PaymentMethod = "Stripe", CreatedOn = DateTimeOffset.UtcNow }; try { var charge = stripeChargeService.Create(new ChargeCreateOptions { Amount = (int)zeroDecimalOrderAmount, Description = "Sample Charge", Currency = regionInfo.ISOCurrencySymbol, SourceId = stripeToken }); payment.GatewayTransactionId = charge.Id; payment.Status = PaymentStatus.Succeeded; order.OrderStatus = OrderStatus.PaymentReceived; _paymentRepository.Add(payment); await _paymentRepository.SaveChangesAsync(); return(Redirect("~/checkout/congratulation")); } catch (StripeException ex) { payment.Status = PaymentStatus.Failed; payment.FailureMessage = ex.StripeError.Message; order.OrderStatus = OrderStatus.PaymentFailed; _paymentRepository.Add(payment); await _paymentRepository.SaveChangesAsync(); TempData["Error"] = ex.StripeError.Message; return(Redirect("~/checkout/payment")); } }
public void Create(Error error) { _errorRepository.Add(error); }
public CalculationProduct Create(CalculationProduct pt) { pt.ObjectState = ObjectState.Added; _CalculationProductRepository.Add(pt); return(pt); }
public UserBookMark Create(UserBookMark pt) { pt.ObjectState = ObjectState.Added; _userBookMarkRepository.Add(pt); return(pt); }
public Task Handle(MeetingCreated @event, CancellationToken cancellationToken) { var meeting = new Meeting(@event.MeetingId, @event.Name); return(repository.Add(meeting, cancellationToken)); }
public void Add(Company company) { _companyRepository.Add(company); }
public void Add(UserHistory user) { _repositoryUserHistory.Add(user); _repositoryUserHistory.SaveChanges(); }
public virtual void Add(T entity) { _repository.Add(entity); _unitOfWork.SaveChanges(); DomainEvents.Dispatch(new EntityCreatedEvent <T>(entity)); }
public void Create(Country country) { _countryRepository.Add(country); }
public void AddBook(Book book) { bookRepository.Add(book); }
public bool Add(Usuario entity) { return(_usuarioRepository.Add(entity)); }
public async Task <IActionResult> PostRental([FromBody] Rental rental) { return(ApiOk(await _repo.Add(rental))); }
public void AddItem(News entity) { _galleryrepo.Add(entity); }
public JobOrderHeaderStatus Create(JobOrderHeaderStatus pt) { pt.ObjectState = ObjectState.Added; _JobOrderHeaderStatusRepository.Add(pt); return(pt); }