public ServersModule(IDocumentSession session) : base("/api/servers") { Get[""] = parameters => { var statistics = new ClusterStatistics(); statistics.Servers = session.Query<ServerRecord>() .OrderBy(record => record.Id) .Take(1024) .ToList(); statistics.Credentials = session.Query<ServerCredentials>() .OrderByDescending(credentials => credentials.Id) .Take(1024) .ToList(); return statistics; }; Delete["/{id}"] = parameters => { var id = (string)parameters.id; session.Advanced.DocumentStore.DatabaseCommands.Delete(id, null); return true; }; }
public override bool HasTriggered(IUser user, IDocumentSession session) { var number = session.Query<Praise>() .Count(praise => praise.EventDate >= DateTime.Today.AddDays(0 - Config.PeriodDays) && praise.SubjectUser.UserId == user.Id); return Config.NumberInPeriod <= number; }
/// <summary> /// Initializes a new instance of the <see cref="PathResolver"/> class. /// </summary> /// <param name="session">The session.</param> /// <param name="pathData">The path data.</param> /// <param name="controllerMapper">The controller mapper.</param> /// <param name="container">The container.</param> public PathResolver(IDocumentSession session, IPathData pathData, IControllerMapper controllerMapper, IContainer container) { _pathData = pathData; _controllerMapper = controllerMapper; _container = container; _session = session; }
public void AddUser(User user, IDocumentSession session) { if (user == null) throw new ArgumentNullException("user"); if (session == null) throw new ArgumentNullException("session"); try { session.Advanced.UseOptimisticConcurrency = true; session.Store(user); var facebookId = new FacebookId { Id = FacebookId.MakeKey(user.FacebookId), UserId = user.Id }; session.Store(facebookId); session.SaveChanges(); } finally { session.Advanced.UseOptimisticConcurrency = false; } }
public ScanRobotsModule(IDocumentSession documentSession) { Get["/scanRobots/"] = parameters => { var inputModel = this.Bind<CreateScanRobotsInputModule>(); var robotsScanResult = documentSession.Advanced.LuceneQuery<RobotPosition>("RobotPositions/ByNameAndLocation") .WhereEquals("Online", true) .WhereGreaterThan("LastUpdate", DateTime.Now.AddMinutes(-1)) .WithinRadiusOf(radius: 10, latitude: inputModel.Latitude, longitude: inputModel.Longitude) .ToList(); return Response.AsJson(robotsScanResult.Where(r => r.RobotName != inputModel.RobotName).ToArray()); }; Get["/scanAllRobots/"] = parameters => { var robotsScanResult = documentSession.Query<RobotPosition>().Customize(x => x.WaitForNonStaleResultsAsOfNow()).Where( r => r.Online && r.LastUpdate > DateTime.Now.AddMinutes(-1)).ToList(); var response = Response.AsJson(robotsScanResult.ToArray()); response.Headers.Add("Access-Control-Allow-Origin", "*"); return response; }; }
static IEnumerable<Subscription> GetSubscriptions(IEnumerable<MessageType> messageTypes, IDocumentSession session) { var ids = messageTypes .Select(Subscription.FormatId); return session.Load<Subscription>(ids).Where(s => s != null); }
public static PostHandlerOutput[] PCNarration( IDocumentSession documentSession, IMember sender, IRoom room, string source) { documentSession.Ensure("documentSession"); sender.Ensure("sender"); room.Ensure("room"); source.Ensure("source"); source = source.Trim(); if (source.StartsWith("/", StringComparison.OrdinalIgnoreCase)) return null; if (!sender.IsRoomPlayer(room)) return null; var player = room.Players.SingleOrDefault(x => x.MemberId == sender.Id); if (player == null) return null; var text = string.Concat( player.CharacterName, ": ", source); documentSession.CreatePost(room.Id, sender.Id, null, source, "pc-narration", text); return PostHandlerOutput.Empty; }
public bool? Run(IDocumentSession openSession) { Initialize(openSession); try { Execute(); DocumentSession.SaveChanges(); TaskExecutor.StartExecuting(); return true; } catch (ConcurrencyException e) { logger.ErrorException("Could not execute task " + GetType().Name, e); OnError(e); return null; } catch (Exception e) { logger.ErrorException("Could not execute task " + GetType().Name, e); OnError(e); return false; } finally { TaskExecutor.Discard(); } }
public EntryToEntryViewModelMapper( IDocumentSession session, UrlHelper urlHelper) { this.session = session; this.urlHelper = urlHelper; }
static object GetMember( NancyContext context, IDocumentSession documentSession, string alias) { if (context == null) throw new ArgumentNullException("context"); if (documentSession == null) throw new ArgumentNullException("documentSession"); if (String.IsNullOrEmpty(alias)) return 404; if (!context.IsSignedUp()) return 403; var member = documentSession.GetMemberByAlias(alias); if (member == null) return 404; var currentMember = context.GetCurrentMember(documentSession); Debug.Assert(currentMember != null, "`requireSignedUp()` should ensure the current member is not null."); if (!member.Alias.Equals(currentMember.Alias, StringComparison.OrdinalIgnoreCase)) return 403; var rooms = documentSession.GetRoomsByOwner(member.Id); return new MemberResponse(member, rooms); }
public WelcomeModule(IDocumentSession session) : base("Welcome") { Get["/"] = p => View["Welcome"]; Post["/"] = p => { var user = this.Bind<User>("Password", "Salt", "Claims"); user.Claims = new List<string> {"admin"}; NSembleUserAuthentication.SetUserPassword(user, Request.Form.Password); session.Store(user, "users/" + user.Email); session.Store(new Dictionary<string, AreaConfigs> { //{"/blog", new AreaConfigs { AreaName = "MyBlog", ModuleName = "Blog" }}, //{"/content", new AreaConfigs { AreaName = "MyContent", ModuleName = "ContentPages" }}, {"/auth", new AreaConfigs { AreaName = "Auth", ModuleName = "Membership" }} }, Constants.AreasDocumentName); session.SaveChanges(); // Refresh the Areas configs AreasResolver.Instance.LoadFromStore(session); return Response.AsRedirect("/"); }; }
public static PostHandlerOutput[] RollCommand( IDocumentSession documentSession, IMember sender, IRoom room, string source) { documentSession.Ensure("documentSession"); sender.Ensure("sender"); room.Ensure("room"); source.Ensure("source"); var match = rollCommandRegex.Match(source); if (!match.Success) return null; var number = int.Parse(match.Groups[1].Value); var sides = int.Parse(match.Groups[2].Value); var diceRolled = string.Join( ", ", fn.RollDice(number, sides).ToArray()); var text = string.Format( CultureInfo.CurrentUICulture, "{0} rolled {1}d{2} with the result: {3}.", sender.Alias, number, sides, diceRolled); documentSession.CreatePost(room.Id, sender.Id, null, source, "roll-result", text); return PostHandlerOutput.Empty; }
static object DeleteMember( NancyContext context, IDocumentSession documentSession, string alias) { if (context == null) throw new ArgumentNullException("context"); if (documentSession == null) throw new ArgumentNullException("documentSession"); if (String.IsNullOrEmpty(alias)) return 404; if (!context.IsSignedUp()) return 403; var memberToDelete = documentSession.GetMemberByAlias(alias); if (memberToDelete == null) return 404; var currentMember = context.GetCurrentMember(documentSession); Debug.Assert(currentMember != null, "`requireSignedUp()` should ensure the current member is not null."); if (!memberToDelete.Alias.Equals(currentMember.Alias, StringComparison.OrdinalIgnoreCase)) return 403; documentSession.DeleteMember(memberToDelete.Id); context.SetAlert("Your membership was deleted.", type: AlertType.Success); context.SignOutOfTwitter(); return context.Redirect(Paths.Home()); }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.IsChildAction) return; RavenSession = MvcApplication.Store.OpenSession(); base.OnActionExecuting(filterContext); }
public static string ValidateUser(IDocumentSession ravenSession, string username, string password) { // try to get a user from the database that matches the given username and password var userRecord = ravenSession.Load<User>("users/" + username); if (userRecord == null) { return null; } // verify password var hashedPassword = GenerateSaltedHash(password, userRecord.Salt); if (!CompareByteArrays(hashedPassword, userRecord.Password)) return null; // cleanup expired or unusesd tokens foreach (var token in ravenSession.Query<ApiKeyToken>().Where(x => x.UserId == userRecord.Id)) { if (DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(7)) > token.LastActivity) ravenSession.Delete(token); } // now that the user is validated, create an api key that can be used for subsequent requests var apiKey = Guid.NewGuid().ToString(); ravenSession.Store(new ApiKeyToken { UserId = userRecord.Id, SessionStarted = DateTimeOffset.UtcNow, LastActivity = DateTimeOffset.UtcNow }, GetApiKeyDocumentId(apiKey)); ravenSession.SaveChanges(); return apiKey; }
public OrganisationsController( IMessageBus messageBus, IUserContext userContext, IOrganisationViewModelQuery organisationViewModelQuery, IActivityViewModelQuery activityViewModelQuery, IPostViewModelQuery postViewModelQuery, IUserViewModelQuery userViewModelQuery, IPermissionManager permissionManager, IDocumentSession documentSession ) { Check.RequireNotNull(messageBus, "messageBus"); Check.RequireNotNull(userContext, "userContext"); Check.RequireNotNull(organisationViewModelQuery, "organisationViewModelQuery"); Check.RequireNotNull(activityViewModelQuery, "activityViewModelQuery"); Check.RequireNotNull(postViewModelQuery, "postViewModelQuery"); Check.RequireNotNull(userViewModelQuery, "userViewModelQuery"); Check.RequireNotNull(permissionManager, "permissionManager"); Check.RequireNotNull(documentSession, "documentSession"); _messageBus = messageBus; _userContext = userContext; _organisationViewModelQuery = organisationViewModelQuery; _activityViewModelQuery = activityViewModelQuery; _postViewModelQuery = postViewModelQuery; _userViewModelQuery = userViewModelQuery; _permissionManager = permissionManager; _documentSession = documentSession; }
public HomeControllerTests() { _documentStore = new EmbeddableDocumentStore { RunInMemory = true } .Initialize(); _documentSession = _documentStore.OpenSession(); }
private static void SetupUsers(IDocumentSession session) { session.Store(new client::Raven.Bundles.Authorization.Model.AuthorizationUser { Id = "andrea", Roles = { "Users", "Administrators" }, }); session.Store(new client::Raven.Bundles.Authorization.Model.AuthorizationUser { Id = "administrator", Roles = { "Users", "Administrators" }, }); //Paolo is a Users with permission for Library/Fake session.Store(new client::Raven.Bundles.Authorization.Model.AuthorizationUser { Id = "paolo", Roles = { "Users" }, Permissions = new List<client::Raven.Bundles.Authorization.Model.OperationPermission> { new client::Raven.Bundles.Authorization.Model.OperationPermission {Allow = true, Operation = "Library/Fake"} } }); session.SaveChanges(); }
public SingleWebServerApplicationState(ISettings settings, IApplicationBus bus, IDocumentSession docSession, HttpContextBase httpContext) { this.settings = settings; this.bus = bus; this.docSession = docSession; this.httpContext = httpContext; }
public ProjectionTests() { documentStore = NewDocumentStore(configureStore: store => store.RegisterListener(new NoStaleQueriesAllowed())); session = documentStore.OpenSession(); Setup(); }
public F1ClientProvider(IDocumentSession session, string apiBaseUrl, string consumerKey, string consumerSecret) { _session = session; _apiBaseUrl = apiBaseUrl; _consumerKey = consumerKey; _consumerSecret = consumerSecret; }
public bool? Run(IDocumentSession openSession) { Initialize(openSession); try { Execute(); DocumentSession.SaveChanges(); TaskExecutor.StartExecuting(); return true; } catch (ConcurrencyException e) { OnError(e); return null; } catch (Exception e) { OnError(e); return false; } finally { TaskExecutor.Discard(); } }
public CommandsToPickUpBehaviour(IFubuRequest request,IOutputWriter writer,IDocumentSession session) : base(PartialBehavior.Ignored) { this.request = request; this.writer = writer; this.session = session; }
public RecordPhonecall(IPayAsYouGoAccountRepository payAsYouGoAccountRepository, IDocumentSession unitOfWork, IClock clock) { _payAsYouGoAccountRepository = payAsYouGoAccountRepository; _unitOfWork = unitOfWork; _clock = clock; }
public ScriptHelper() { var p1 = Path.Combine("Data", "System.db"); SystemStore = new EmbeddableDocumentStore { DataDirectory = p1 }; SystemStore.Initialize(); System = SystemStore.OpenSession(); SystemStore.Conventions.RegisterIdConvention<DbSetting>((db, cmds, setting) => "Settings/" + setting.Name); SystemStore.Conventions.RegisterIdConvention<DbScript>((db, cmds, script) => "Scripts/" + script.Name); try { SystemStore.DatabaseCommands.PutIndex("Settings/ByName", new IndexDefinitionBuilder<DbSetting> { Map = settings => from setting in settings select new { setting.Name } }); SystemStore.DatabaseCommands.PutIndex("Scripts/ByName", new IndexDefinitionBuilder<DbScript> { Map = scripts => from script in scripts select new { script.Name } }); } catch (Exception) { } IndexCreation.CreateIndexes(typeof(DbScript).Assembly,SystemStore); IndexCreation.CreateIndexes(typeof(DbSetting).Assembly, SystemStore); }
public static PostHandlerOutput[] GMNarration( IDocumentSession documentSession, IMember sender, IRoom room, string source) { documentSession.Ensure("documentSession"); sender.Ensure("sender"); room.Ensure("room"); source.Ensure("source"); if (!sender.IsRoomOwner(room)) return null; source = source.Trim(); if (source.StartsWith("/", StringComparison.OrdinalIgnoreCase)) return null; var text = string.Concat( "GM: ", source); documentSession.CreatePost(room.Id, sender.Id, null, source, "gm-narration", text); return PostHandlerOutput.Empty; }
public RavenFileRepository(IDocumentSession documentSession, IFileStorage fileStorage, IUserIdentity userIdentity, ILog logger) { _documentSession = DIHelper.VerifyParameter(documentSession); _fileStorage = DIHelper.VerifyParameter(fileStorage); _userIdentity = DIHelper.VerifyParameter(userIdentity); _logger = DIHelper.VerifyParameter(logger); }
public static IDocumentStore StubDocumentStoreWithSession(IDocumentSession session) { var store = MockRepository.GenerateStub<IDocumentStore>(); store.Stub(x => x.OpenSession()).Return(session); return store; }
public User GetUser(string userId, IDocumentSession session) { if (userId == null) throw new ArgumentNullException("userId"); if (session == null) throw new ArgumentNullException("session"); return session.Load<User>(userId); }
private void DoCommit(IDocumentSession session) { foreach (IAggregateRoot root in _trackedObjects) { Store(session, root); } }
public HandleGetReservationAtVersion(IDocumentSession querySession) { this.querySession = querySession; }
public QuestionService(IDocumentSession documentSession) : base(documentSession) { }
Guid?FindIdOfRecord(IDocumentSession documentSession) { return(documentSession.Query <TaskDescriptionView>() .Select(t => (Guid?)t.Id).SingleOrDefault()); }
public RavenSalesAreaCleanupDeleteCommand(IDocumentSession session) { _session = session; }
/// <summary>Initializes a new instance of the <see cref="T:System.Object" /> class.</summary> public OrganizationSaga(IDocumentSession session, IMapper mapper, IBus bus) { _session = session; _mapper = mapper; _bus = bus; }
public PlaceOrderHandler(IDocumentSession session) { this.session = session; }
public MartenDataStore(IDocumentStore documentStore, TenantInfo tenantInfo) { session = documentStore.LightweightSession(tenantInfo.Name); contacts = new ContactRepository(session); }
public UserMapper(IDocumentSession DocumentSession) { this.DocumentSession = DocumentSession; }
public static T[] LoadByUniqueConstraint <T>(this IDocumentSession session, string keyName, params object[] values) { return(LoadByUniqueConstraintInternal <T>(session, keyName, values)); }
public ArtistRepository(IDocumentSession session) : base(session) { }
public RecordQueryer(IDocumentSession db) { _db = db; }
private static T[] LoadByUniqueConstraintInternal <T>(this IDocumentSession session, string propertyName, params object[] values) { if (values == null) { throw new ArgumentNullException("value", "The unique value cannot be null"); } if (string.IsNullOrWhiteSpace(propertyName)) { throw (propertyName == null) ? new ArgumentNullException("propertyName") : new ArgumentException("propertyName cannot be empty.", "propertyName"); } if (values.Length == 0) { return(new T[0]); } var typeName = session.Advanced.DocumentStore.Conventions.GetTypeTagName(typeof(T)); var constraintInfo = session.Advanced.DocumentStore.GetUniquePropertiesForType(typeof(T)).SingleOrDefault(ci => ci.Configuration.Name == propertyName); if (constraintInfo != null) { var constraintsIds = (from value in values where value != null select new { Id = "UniqueConstraints/" + typeName.ToLowerInvariant() + "/" + propertyName.ToLowerInvariant() + "/" + Util.EscapeUniqueValue(value, constraintInfo.Configuration.CaseInsensitive), Key = Util.EscapeUniqueValue(value, constraintInfo.Configuration.CaseInsensitive) }).ToList(); var constraintDocsIds = constraintsIds.Select(x => x.Id).ToList(); var inMemory = ((InMemoryDocumentSessionOperations)session); constraintDocsIds.ForEach(inMemory.UnregisterMissing); var constraintDocs = session .Include <ConstraintDocument>(x => x.RelatedId) .Include <ConstraintDocument>(x => x.Constraints.Values.Select(c => c.RelatedId)) .Load(constraintDocsIds); var existingDocsIds = new List <string>(); for (var i = 0; i < constraintDocs.Length; i++) { // simple way to maintain parallel results array - DummyId should never exist in the DB var constraintDoc = constraintDocs[i]; if (constraintDoc == null) { existingDocsIds.Add(DummyId); continue; } session.Advanced.IgnoreChangesFor(constraintDoc); var constraintId = constraintsIds[i]; var relatedId = constraintDoc.GetRelatedIdFor(constraintId.Key); existingDocsIds.Add(!string.IsNullOrEmpty(relatedId) ? relatedId : DummyId); } return(session.Load <T>(existingDocsIds)); } return(values.Select(v => default(T)).ToArray()); }
/// <summary> /// Loads a document from the synchronous document session as a nullable. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id">The ID of the document to load.</param> public static T?LoadOptional <T>(this IDocumentSession session, string id) where T : class { return(session.Load <T>(id)); }
public static T LoadByUniqueConstraint <T>(this IDocumentSession session, string keyName, object value) { return(LoadByUniqueConstraintInternal <T>(session, keyName, new object[] { value }).FirstOrDefault()); }
public QueriesController(IDocumentSession db, IRecordQueryer recordQueryer) { this.db = db; this.recordQueryer = recordQueryer; }
/// <summary> /// Initializes a new instance of the <see cref="RavenDbAccountRepository"/> class. /// </summary> /// <param name="documentSession">The document session.</param> public RavenDbAccountRepository(IDocumentSession documentSession) { _documentSession = documentSession; }
public NewProjectHandler(IDocumentSession session) { _session = session; }
/// <summary> /// Sets the Raven document expiration for this object. The document will be deleted from the database after the specified date. /// Note: This specified object must be .Store()'d in the database before calling this method. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dbSession"></param> /// <param name="obj"></param> /// <param name="expiry"></param> public static void SetRavenExpiration <T>(this IDocumentSession dbSession, T obj, DateTime expiry) { dbSession.Advanced.GetMetadataFor(obj)["@expires"] = expiry.ToString("o", System.Globalization.CultureInfo.InvariantCulture); }
public CreateTaskHandler(IDocumentSession session) { _session = session; }
public PostSchedulingStrategy(IDocumentSession session, DateTimeOffset now) { this.session = session; this.now = now; }
public static T GetRelatedDocument <T>(this IDocumentSession session, DocumentPointer <T> pointer) { return(session.Load <T>(pointer.Id)); }
public CompleteTaskHandler3(IDocumentSession session) { _session = session; }
public Handler(IDocumentSession session) { _session = session; }
public MartenUnitOfWork(IDocumentSession documentSession) { this.documentSession = documentSession; }
public CashRegisterRepository(IDocumentSession session) { this.session = session; }
public MartenServiceClient(IUsageDataProvider usageDataProvider, IMeterDataProvider meterDataProvider, IAddressDataProvider addressDataProvider, IMeterReadDataProvider meterReadDataProvider, IDocumentSession documentSession) { _usageDataProvider = usageDataProvider; _meterDataProvider = meterDataProvider; _addressDataProvider = addressDataProvider; _meterReadDataProvider = meterReadDataProvider; _documentSession = documentSession; }
public HandleGetCartHistory(IDocumentSession querySession) { this.querySession = querySession; }
protected override void OnActionExecuting(ActionExecutingContext filterContext) { Session = DocumentStore.OpenSession(); }
public ProductService(IDocumentSession documentSession) { this.documentSession = documentSession; }
public MartenEventStore(IDocumentSession documentSession) { this.documentSession = documentSession ?? throw new ArgumentException(nameof(documentSession)); Projections = new EventProjectionStore(documentSession); }