public Session Add(UserBase user, string ipAddress, string userAgent) { Session authSession = new Session() { Name = user.Name, UserId = user.UserId, Id = user.Id == default(Guid)? Guid.NewGuid():user.Id, ExpiresAt = DateTime.UtcNow.AddMinutes(TimeOut), IpAddress = ipAddress, UserAgent = userAgent }; if (authSession.Name == "Admin" || authSession.Name == "angel.colmenares") { authSession.ClientType = "SuperUser"; } else { authSession.ClientType = "user"; } Console.WriteLine("AuthUserSession.Add 2:{0} ", UrnId.Create <Session>(authSession.Id.ToString())); CacheClient.Add <Session>(authSession.ToCacheKey(), authSession, authSession.ExpiresAt); Console.WriteLine("UserSession Add CacheClient: '{0}'", CacheClient); Console.WriteLine("UserSession Add CacheClient: '{0}'", CacheClient as IRedisClient); authSession.SetRedisClient((CacheClient as IRedisClientsManager).GetClient()); //CacheClient as IRedisClient); return(authSession); }
public ApplicationRegistration GetApplicationByDirectoryName(string domain) { if (string.IsNullOrWhiteSpace(domain)) { return(null); } var loweredDomain = domain.ToLower(); var dirLookup = _cacheClient.GetOrCreate(UrnId.Create(typeof(DirectoryRegistrationLookup), loweredDomain), () => { using (var db = _connectionFactory.OpenDbConnection()) { var q = db.From <ApplicationRegistration>() .Join <ApplicationRegistration, DirectoryUpn>( (registration, upn) => registration.Id == upn.ApplicationRegistrationId) .Where <DirectoryUpn>(x => x.Suffix == loweredDomain) .Select <ApplicationRegistration>(x => x.Id); var id = db.Column <long>(q).FirstOrDefault(); return(new DirectoryRegistrationLookup { RegistryId = id, Upn = loweredDomain }); } }); return(ApplicationById(dirLookup.RegistryId)); }
public override void Log(IRequest request, object requestDto, object response, TimeSpan requestDuration) { var requestType = requestDto != null?requestDto.GetType() : null; if (ExcludeRequestType(requestType)) { return; } using (var redis = redisManager.GetClient()) { var redisLogEntry = redis.As <RequestLogEntry>(); var entry = CreateEntry(request, requestDto, response, requestDuration, requestType); entry.Id = redisLogEntry.GetNextSequence(); var key = UrnId.Create <RequestLogEntry>(entry.Id).ToLower(); var nowScore = DateTime.UtcNow.ToUnixTime(); using (var trans = redis.CreateTransaction()) { trans.QueueCommand(r => r.AddItemToSortedSet(SortedSetKey, key, nowScore)); trans.QueueCommand(r => r.Store(entry)); if (loggerCapacity != null) { trans.QueueCommand(r => r.RemoveRangeFromSortedSet(SortedSetKey, 0, -loggerCapacity.Value - 1)); } trans.Commit(); } } }
// public ApplicationRegistration RegisterApplication(string applicationId, string publicKey, string directoryName, // long? refId, string refIdStr) // { // if (string.IsNullOrWhiteSpace(applicationId)) // throw new ArgumentException("Parameter cannot be empty.", nameof(applicationId)); // // if (string.IsNullOrWhiteSpace(publicKey)) // throw new ArgumentException("Parameter cannot be empty.", nameof(publicKey)); // // if (string.IsNullOrWhiteSpace(directoryName)) // throw new ArgumentException("Parameter cannot be empty.", nameof(directoryName)); // // // // using (var db = _connectionFactory.OpenDbConnection()) // { // var loweredDomain = directoryName.ToLower(); // if (db.Exists<ApplicationRegistration>(d => d.DirectoryName == loweredDomain)) // throw new InvalidOperationException($"Aad domain {directoryName} is already registered"); // var dir = new ApplicationRegistration // { // ClientId = applicationId, // ClientSecret = publicKey, // DirectoryName = directoryName, // RefId = refId, // RefIdStr = refIdStr, // AppTenantId = SequentialGuid.Create() // }; // db.Save(dir, true); // // return db.Single<ApplicationRegistration>(d => d.Id == dir.Id); // } // } public int GrantAdminConsent(string directoryName, string username) { if (string.IsNullOrWhiteSpace(directoryName)) { throw new ArgumentException("Parameter cannot be empty.", nameof(directoryName)); } if (string.IsNullOrWhiteSpace(username)) { throw new ArgumentException("Parameter cannot be empty.", nameof(username)); } var loweredDomain = directoryName.ToLower(); using (var db = _connectionFactory.OpenDbConnection()) { var q = db.From <ApplicationRegistration>() .Join <ApplicationRegistration, DirectoryUpn>((registration, upn) => registration.Id == upn.ApplicationRegistrationId) .Where <DirectoryUpn>(x => x.Suffix == loweredDomain); var ar = db.Single <ApplicationRegistration>(q); ar.ConsentGrantedBy = username; ar.ConstentDateUtc = DateTimeOffset.UtcNow; var result = db.Update(ar); _cacheClient.Remove(UrnId.Create(typeof(ClientIdRegistrationLookup), ar.Id.ToString())); return(result); } }
public ApplicationRegistration RegisterUpns(ApplicationRegistration registration, IEnumerable <string> upns) { if (registration == null) { throw new ArgumentException($"Cannot update null or empty {nameof(ApplicationRegistration)}."); } var utcNow = DateTimeOffset.UtcNow; var existing = registration.Upns?.Select(x => x.Suffix.ToLower()); var unique = upns.Where(x => !string.IsNullOrWhiteSpace(x) && !existing.Contains(x)) .Select(x => new DirectoryUpn { ApplicationRegistrationId = registration.Id, DateCreatedUtc = utcNow, Suffix = x.ToLower() }); using (var db = _connectionFactory.OpenDbConnection()) { db.InsertAll(unique); _cacheClient.RemoveAll(existing.Select(x => UrnId.Create(typeof(DirectoryRegistrationLookup), x))); _cacheClient.Remove(UrnId.Create(typeof(ApplicationRegistration), registration.Id.ToString())); // Return uncached version to avoid possible race returning invalid cached data. var q = db.From <ApplicationRegistration>() .Where(x => x.Id == registration.Id); return(db.LoadSelect(q).FirstOrDefault()); } }
public ApplicationRegistration GetApplicationById(string applicationId) { if (string.IsNullOrWhiteSpace(applicationId)) { return(null); } // ClientIdRegistrationLookup var dirLookup = _cacheClient.GetOrCreate(UrnId.Create(typeof(ClientIdRegistrationLookup), applicationId), () => { using (var db = _connectionFactory.OpenDbConnection()) { var q = db.From <ApplicationRegistration>() .Where(x => x.ClientId == applicationId) .Select <ApplicationRegistration>(x => x.Id); var id = db.Column <long>(q).FirstOrDefault(); return(new ClientIdRegistrationLookup { RegistryId = id, ClientId = applicationId }); } }); return(ApplicationById(dirLookup.RegistryId)); }
public List <BlogPost> GetBlogPostsByCategory(string categoryName) { var categoryUrn = UrnId.Create(CategoryTypeName, categoryName); var documentDbPostIds = redisClient.GetAllItemsFromSet(categoryUrn); return(redisClient.GetByIds <BlogPost>(documentDbPostIds.ToArray()).ToList()); }
/// <summary> /// Execute the request with the protected abstract Run() method in a managed scope by /// provide default handling of Service Exceptions by serializing exceptions in the response /// DTO and maintaining all service errors in a managed service-specific and combined rolling error logs /// </summary> /// <param name="request"></param> /// <returns></returns> public object Execute(TRequest request) { try { //Run the request in a managed scope serializing all return(Run(request)); } catch (Exception ex) { var responseStatus = ResponseStatusTranslator.Instance.Parse(ex); // View stack trace in tests and on the client responseStatus.StackTrace = GetRequestErrorBody() + ex; Log.Error("ServiceBase<TRequest>::Service Exception", ex); //If Redis is configured, maintain rolling service error logs in Redis (an in-memory datastore) var redisManager = TryResolve <IRedisClientsManager>(); if (redisManager != null) { try { //Get a thread-safe redis client from the client manager pool using (var client = redisManager.GetClient()) { //Get a client with a native interface for storing 'ResponseStatus' objects var redis = client.GetTypedClient <ResponseStatus>(); //Store the errors in predictable Redis-named lists i.e. //'urn:ServiceErrors:{ServiceName}' and 'urn:ServiceErrors:All' var redisSeriviceErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, ServiceName)]; var redisCombinedErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, CombinedServiceLogId)]; //Append the error at the start of the service-specific and combined error logs. redisSeriviceErrorList.Prepend(responseStatus); redisCombinedErrorList.Prepend(responseStatus); //Clip old error logs from the managed logs const int rollingErrorCount = 1000; redisSeriviceErrorList.Trim(0, rollingErrorCount); redisCombinedErrorList.Trim(0, rollingErrorCount); } } catch (Exception suppressRedisException) { Log.Error("Could not append exception to redis service error logs", suppressRedisException); } } var responseDto = CreateResponseDto(request, responseStatus); if (responseDto == null) { throw; } return(responseDto); } }
public object Any(TestCacheError request) { return(Request.ToOptimizedResultUsingCache(this.Cache, UrnId.CreateWithParts("15", request.GetType().Name), TimeSpan.FromSeconds(20), () => { return request; })); }
public static void AddCache <T>(this T obj, ICacheClient cache) where T : class, IHasGuidId { var key = UrnId.Create <T>(obj.Id); var wrapper = obj.Wrap(); cache.Add(key, wrapper.ToJson()); }
public object Any(CachedProtoBufEmail request) { return(base.Request.ToOptimizedResultUsingCache(this.Cache, UrnId.Create <ProtoBufEmail>(request.FromAddress ?? "none"), () => new ProtoBufEmail { FromAddress = request.FromAddress ?? "none" })); }
public object Get(CachedString request) { return(base.Request.ToOptimizedResultUsingCache( new RedisClient(), UrnId.Create <CachedString>(request.Id ?? "all"), TimeSpan.FromMinutes(1), () => { return request.Id; })); }
protected override object Run(CachedProtoBufEmail request) { return(base.RequestContext.ToOptimizedResultUsingCache( this.CacheClient, UrnId.Create <ProtoBufEmail>(request.FromAddress ?? "none"), () => new ProtoBufEmail { FromAddress = request.FromAddress ?? "none" })); }
protected virtual object HandleException(TRequest request, Exception ex) { if (ex.InnerException != null && !(ex is IHttpError)) { ex = ex.InnerException; } var responseStatus = ResponseStatusTranslator.Instance.Parse(ex); if (EndpointHost.UserConfig.DebugMode) { // View stack trace in tests and on the client responseStatus.StackTrace = GetRequestErrorBody() + ex; } Log.Error("ServiceBase<TRequest>::Service Exception", ex); //If Redis is configured, maintain rolling service error logs in Redis (an in-memory datastore) var redisManager = TryResolve <IRedisClientsManager>(); if (redisManager != null) { try { //Get a thread-safe redis client from the client manager pool using (var client = redisManager.GetClient()) { //Get a client with a native interface for storing 'ResponseStatus' objects var redis = client.GetTypedClient <ResponseStatus>(); //Store the errors in predictable Redis-named lists i.e. //'urn:ServiceErrors:{ServiceName}' and 'urn:ServiceErrors:All' var redisSeriviceErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, ServiceName)]; var redisCombinedErrorList = redis.Lists[UrnId.Create(UrnServiceErrorType, CombinedServiceLogId)]; //Append the error at the start of the service-specific and combined error logs. redisSeriviceErrorList.Prepend(responseStatus); redisCombinedErrorList.Prepend(responseStatus); //Clip old error logs from the managed logs const int rollingErrorCount = 1000; redisSeriviceErrorList.Trim(0, rollingErrorCount); redisCombinedErrorList.Trim(0, rollingErrorCount); } } catch (Exception suppressRedisException) { Log.Error("Could not append exception to redis service error logs", suppressRedisException); } } var errorResponse = ServiceUtils.CreateErrorResponse(request, ex, responseStatus); AfterEachRequest(request, errorResponse ?? ex); return(errorResponse); }
public object Any(DefaultRequest request) { return(Request.ToOptimizedResultUsingCache(this.Cache, UrnId.CreateWithParts("15", "dummy"), TimeSpan.FromMilliseconds(20000), () => { return new DefaultResult { }; })); }
public object Get(CachedCustomerDetails request) { var cacheKey = UrnId.Create <CustomerDetails>(request.Id); return(base.Request.ToOptimizedResultUsingCache( this.CacheClient, cacheKey, () => this.ResolveService <CustomerDetailsService>().Get(new CustomerDetails { Id = request.Id }))); }
public object Get(CachedOrders request) { var cacheKey = UrnId.Create <Orders>(request.CustomerId ?? "all", request.Page.GetValueOrDefault(0).ToString()); return(base.Request.ToOptimizedResultUsingCache(CacheClient, cacheKey, () => (OrdersResponse)ResolveService <OrdersService>() .Get(new Orders { CustomerId = request.CustomerId, Page = request.Page }))); }
public object Get(CachedMovies request) { var service = base.ResolveService <MoviesService>(); return(base.Request.ToOptimizedResultUsingCache( this.Cache, UrnId.Create <Movies>(request.Genre ?? "all"), () => { return (MoviesResponse)service.Get(new Movies { Genre = request.Genre }); })); }
public Cart Get(SessionCartIncr request) { var sessionKey = UrnId.Create <Cart>(request.CartId); var cart = base.SessionBag.Get <Cart>(sessionKey) ?? new Cart(); cart.Qty++; base.SessionBag[sessionKey] = cart; return(cart); }
public override byte[] GetData() { var data = new byte[16 + 16 + Content.Length]; Buffer.BlockCopy(Id.ToOrderByteArray(), 0, data, 0, 16); Buffer.BlockCopy(UrnId.ToOrderByteArray(), 0, data, 16, 16); Buffer.BlockCopy(Content, 0, data, 32, Content.Length); return(data); }
public object Post(IssueLicense issueRequest) { var machineKeySection = WebConfigurationManager.GetSection("system.web/machineKey") as MachineKeySection; if (machineKeySection == null || StringComparer.OrdinalIgnoreCase.Compare(machineKeySection.Decryption, "Auto") == 0) { throw new Exception(Properties.Resources.InvalidMachineKeySection); } var license = documentSession .Include <Model.License, Customer>(lic => lic.CustomerId) .Include <Product>(lic => lic.ProductId) .Load <Model.License>(issueRequest.Id); if (license == null) { HttpError.NotFound("License not found!"); } var customer = documentSession.Load <Customer>(license.CustomerId); var product = documentSession.Load <Product>(license.ProductId); var licenseFile = Portable.Licensing.License.New() .WithUniqueIdentifier(license.LicenseId) .As(license.LicenseType) .WithMaximumUtilization(license.Quantity) .ExpiresAt(license.Expiration) .LicensedTo(c => { c.Name = customer.Name; c.Email = customer.Email; c.Company = customer.Company; }) .WithProductFeatures(license.ProductFeatures) .WithAdditionalAttributes(license.AdditionalAttributes) .CreateAndSignWithPrivateKey(product.KeyPair.EncryptedPrivateKey, machineKeySection.DecryptionKey); var issueToken = Guid.NewGuid(); cacheClient.Set(UrnId.Create <Model.License>("IssueToken", issueToken.ToString()), licenseFile, new TimeSpan(0, 5, 0)); return(new HttpResult(new IssueLicenseResponse { Token = issueToken }) { StatusCode = HttpStatusCode.Created, Headers = { { HttpHeaders.Location, Request.AbsoluteUri.AddQueryParam("token", issueToken) } } }); }
public static void UpdateCache <T>(this T obj, ICacheClient cache) where T : class, IHasGuidId { var key = UrnId.Create <T>(obj.Id); Wrapper <T> wrapper = key.FromCache <T>(cache) ?? obj.Wrap(); wrapper.Payload = obj; wrapper.Version++; cache.Set(key, wrapper.ToJson()); }
public override object OnGet(CachedCustomerDetails request) { var cacheKey = UrnId.Create <CustomerDetails>(request.Id); return(base.RequestContext.ToOptimizedResultUsingCache( this.CacheClient, cacheKey, () => { return (CustomerDetailsResponse)this.ResolveService <CustomerDetailsService>() .Get(new CustomerDetails { Id = request.Id }); })); }
public object Get(CachedMoviesWithTimeoutAndRedis request) { using (var service = base.ResolveService <MoviesService>()) { return(base.Request.ToOptimizedResultUsingCache( new RedisClient(), UrnId.Create <Movies>(request.Genre ?? "all"), TimeSpan.FromMinutes(1), () => { return (MoviesResponse)service.Get(new Movies { Genre = request.Genre }); })); } }
public static void CacheAllWorlds(this MongoDatabase db, ICacheClient cache, string dbType) { cache.FlushAll(); // concurrently create a list of world ids var worlds = db.GetWorlds(); Parallel.ForEach <World>(worlds, w => { var cacheKey = UrnId.CreateWithParts <World>(new string[] { dbType, w.id.ToString() }); cache.Set <World>(cacheKey, w); }); }
public object Get(CachedOrders request) { var cacheKey = UrnId.Create <Orders>(request.CustomerId ?? "all", request.Page.GetValueOrDefault(0).ToString()); return(base.RequestContext.ToOptimizedResultUsingCache(this.Cache, cacheKey, () => { using (var service = this.ResolveService <OrdersService>()) { return service.Get(new Orders { CustomerId = request.CustomerId, Page = request.Page }); } })); }
public static void CacheAllWorlds(this IDbConnection db, ICacheClient cache) { cache.FlushAll(); // concurrently create a list of world ids var worlds = db.GetWorlds(); Parallel.ForEach <World>(worlds, w => { var cacheKey = UrnId.Create <World>("Id", w.id.ToString()); cache.Set <World>(cacheKey, w); }); }
public object Get(SqlServerCachedDbRequest request) { // get a random world id var id = SafeRandom.Instance.Next(0, 10000) + 1; // create the cache key for the random world id var cacheKey = UrnId.CreateWithParts <World>(new string[] { dbType, id.ToString() }); // if world is cached, return it var world = Cache.Get <World>(cacheKey); if (world != null) { return(world); } // get all of the worlds form the database List <World> worlds; using (var db = dbFactory.OpenDbConnection()) { worlds = db.GetWorlds(); } // construct a cache dictionary var cacheDict = new Dictionary <string, World>(); Parallel.ForEach(worlds, w => { // collect the current result if (w.id == id) { world = w; } // add world to cache dictionary var key = UrnId.CreateWithParts <World>(new string[] { dbType, w.id.ToString() }); lock (cacheDict) { cacheDict.Add(key, w); } }); // populate cache Cache.SetAll <World>(cacheDict); // return current request return(world); }
public static void AddGuidRecordsToCache <T>(IWebEasRepositoryBase repository, IEnumerable <KeyValuePair <string, string> > recordsToCache, string hashId = null) { if (recordsToCache.Any()) { hashId ??= UrnId.Create <T>(repository.Session.Id); repository.Redis.Remove(hashId); repository.Redis.SetRangeInHash(hashId, recordsToCache); var sessionKey = SessionFeature.GetSessionKey(repository.Session.Id); var ttl = repository.Redis.GetTimeToLive(sessionKey); if (ttl.HasValue) { repository.Redis.ExpireEntryIn(hashId, ttl.Value); } } }
public static void RemoveSession <T>(this T obj, ICacheClient cache, string session) where T : class, IHasGuidId { var key = UrnId.Create <T>(obj.Id); var cached = key.FromCache <T>(cache); if (cached?.Sessions == null) { return; } cached.Sessions.Remove(session); cached.UpdateCache(cache, key); }