Exemple #1
0
 public static void registerDep(IRef aref)
 {
     var v = REGISTER_DEP.deref();
     if(v != null)
     {
         ((RegisterDep)v).register(aref);
     }
 }
Exemple #2
0
 /// Construct a multifunction.
 /// </summary>
 /// <param name="name">The name</param>
 /// <param name="dispatchFn">The dispatch function.</param>
 /// <param name="defaultDispatchVal">The default dispatch value.</param>
 /// <param name="hierarchy">The hierarchy for this multifunction</param>
 public MultiFn(string name, IFn dispatchFn, object defaultDispatchVal, IRef hierarchy)
 {
     _name = name;
     _dispatchFn = dispatchFn;
     _defaultDispatchVal = defaultDispatchVal;
     _methodTable = PersistentHashMap.EMPTY;
     _methodCache = MethodTable;
     _preferTable = PersistentHashMap.EMPTY;
     _hierarchy = hierarchy;
     _cachedHierarchy = null;
 }
Exemple #3
0
        /// <inheritdoc />
        public void DrawBitmap(IRef <IBitmapImpl> source, double opacity, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode)
        {
            var drawableImage = (IDrawableBitmapImpl)source.Item;
            var s             = sourceRect.ToSKRect();
            var d             = destRect.ToSKRect();

            using (var paint =
                       new SKPaint
            {
                Color = new SKColor(255, 255, 255, (byte)(255 * opacity * _currentOpacity))
            })
            {
                paint.FilterQuality = bitmapInterpolationMode.ToSKFilterQuality();
                paint.BlendMode     = _currentBlendingMode.ToSKBlendMode();

                drawableImage.Draw(this, s, d, paint);
            }
        }
Exemple #4
0
 public static async Task <HttpResponseMessage> CreateAsync(
     [Property(Name = IdPropertyName)] IRef <TableBackup> tableBackupRef,
     [Property(Name = WhenPropertyName)] DateTime when,
     [Property(Name = TableNamePropertyName)] string tableName,
     [Property(Name = IdPropertyName)] IRef <RepositoryBackup> repositoryBackupRef,
     [Resource] TableBackup tableBackup,
     RequestMessage <TableBackup> requestQuery,
     HttpRequestMessage request,
     EastFive.Analytics.ILogger logger,
     CreatedBodyResponse <InvocationMessage> onCreated,
     AlreadyExistsResponse onAlreadyExists)
 {
     return(await await tableBackup.StorageCreateAsync(
                async (entity) =>
     {
         var invocationMessage = await requestQuery
                                 .ById(tableBackupRef)
                                 .HttpPatch(default)
        /// <summary>
        /// Draws a bitmap image.
        /// </summary>
        /// <param name="source">The bitmap image.</param>
        /// <param name="opacityMask">The opacity mask to draw with.</param>
        /// <param name="opacityMaskRect">The destination rect for the opacity mask.</param>
        /// <param name="destRect">The rect in the output to draw to.</param>
        public void DrawImage(IRef <IBitmapImpl> source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect)
        {
            using (var d2dSource = ((BitmapImpl)source.Item).GetDirect2DBitmap(_deviceContext))
                using (var sourceBrush = new BitmapBrush(_deviceContext, d2dSource.Value))
                    using (var d2dOpacityMask = CreateBrush(opacityMask, opacityMaskRect.Size))
                        using (var geometry = new SharpDX.Direct2D1.RectangleGeometry(_deviceContext.Factory, destRect.ToDirect2D()))
                        {
                            if (d2dOpacityMask.PlatformBrush != null)
                            {
                                d2dOpacityMask.PlatformBrush.Transform = Matrix.CreateTranslation(opacityMaskRect.Position).ToDirect2D();
                            }

                            _deviceContext.FillGeometry(
                                geometry,
                                sourceBrush,
                                d2dOpacityMask.PlatformBrush);
                        }
        }
        private void RenderOverlay(Scene scene, IDrawingContextImpl parentContent)
        {
            if (DrawDirtyRects)
            {
                var overlay = GetOverlay(parentContent, scene.Size, scene.Scaling);

                using (var context = overlay.Item.CreateDrawingContext(this))
                {
                    context.Clear(Colors.Transparent);
                    RenderDirtyRects(context);
                }
            }
            else
            {
                _overlay?.Dispose();
                _overlay = null;
            }
        }
Exemple #7
0
 public static Task <HttpResponseMessage> UpdateBodyAsync(
     [UpdateId(Name = SessionIdPropertyName)] IRef <Session> sessionRef,
     [PropertyOptional(Name = AuthorizationPropertyName)] IRefOptional <Authorization> authorizationRefMaybe,
     Api.Azure.AzureApplication application,
     ContentTypeResponse <Session> onUpdated,
     NotFoundResponse onNotFound,
     ForbiddenResponse forbidden,
     ConfigurationFailureResponse onConfigurationFailure,
     GeneralConflictResponse onFailure)
 {
     return(sessionRef.StorageUpdateAsync(
                (sessionStorage, saveSessionAsync) =>
     {
         return Security.AppSettings.TokenScope.ConfigurationUri(
             scope =>
         {
             return Security.SessionServer.Configuration.AppSettings.TokenExpirationInMinutes.ConfigurationDouble(
                 async(tokenExpirationInMinutes) =>
             {
                 return await await GetClaimsAsync(application, authorizationRefMaybe,
                                                   async(claims, accountIdMaybe, authorized) =>
                 {
                     sessionStorage.authorization = authorizationRefMaybe;
                     sessionStorage.authorized = authorized;
                     sessionStorage.account = accountIdMaybe;
                     return await BlackBarLabs.Security.Tokens.JwtTools.CreateToken(sessionRef.id,
                                                                                    scope, TimeSpan.FromMinutes(tokenExpirationInMinutes), claims,
                                                                                    async(tokenNew) =>
                     {
                         sessionStorage.token = tokenNew;
                         await saveSessionAsync(sessionStorage);
                         return onUpdated(sessionStorage);
                     },
                                                                                    (missingConfig) => onConfigurationFailure("Missing", missingConfig).AsTask(),
                                                                                    (configName, issue) => onConfigurationFailure(configName, issue).AsTask());
                 },
                                                   why => onFailure(why).AsTask());
             },
                 why => onConfigurationFailure("Missing", why).AsTask());
         },
             (why) => onConfigurationFailure("Missing", why).AsTask());
     },
                onNotFound: () => onNotFound()));
 }
Exemple #8
0
        /// <summary>
        ///     Add a new reference to be tracked
        /// </summary>
        /// <param name="refId">The ID of the reference</param>
        /// <param name="_ref">The object we're tracking</param>
        /// <param name="incrementCount">If true, we increment the <see cref="refCounts" /> at this ID</param>
        public void Add(int refId, IRef _ref, bool incrementCount = true)
        {
            int previousCount;

            if (!refs.ContainsKey(refId))
            {
                refs[refId]   = _ref;
                previousCount = 0;
            }
            else
            {
                previousCount = refCounts[refId];
            }

            if (incrementCount)
            {
                refCounts[refId] = previousCount + 1;
            }
        }
Exemple #9
0
 public static Task <IHttpResponse> HttpGetAsync <TResource>(
     this IRef <TResource> resourceRef,
     ContentTypeResponse <TResource> onFound,
     NotFoundResponse onNotFound,
     Func <TResource, TResource> mutation = default)
     where TResource : IReferenceable
 {
     return(resourceRef.StorageGetAsync(
                (resource) =>
     {
         if (mutation.IsDefaultOrNull())
         {
             return onFound(resource);
         }
         var updatedResource = mutation(resource);
         return onFound(updatedResource);
     },
                () => onNotFound()));
 }
Exemple #10
0
 public static async Task <IHttpResponse> CreateAsync(
     [Property(Name = IdPropertyName)] IRef <TableBackupOperation> tableBackupOperationRef,
     [Property(Name = WhenPropertyName)] DateTime when,
     [Property(Name = TableBackupPropertyName)] IRef <TableBackup> tableBackupRef,
     [Property(Name = OperationSetPropertyName)] string operationSet,
     [Resource] TableBackupOperation tableBackup,
     RequestMessage <TableBackupOperation> requestQuery,
     IHttpRequest request,
     EastFive.Api.Security security,
     EastFive.Analytics.ILogger logger,
     CreatedBodyResponse <InvocationMessage> onCreated,
     AlreadyExistsResponse onAlreadyExists)
 {
     return(await await tableBackup.StorageCreateAsync(
                async (discard) =>
     {
         var invocationMessage = await requestQuery
                                 .ById(tableBackupOperationRef)
                                 .HttpPatch(default)
Exemple #11
0
        /// <summary>
        ///     Remove all references contained in <see cref="deletedRefs"></see> from the tracking maps (<see cref="refs" /> and
        ///     <see cref="refCounts" />). Clears <see cref="deletedRefs" /> afterwards
        /// </summary>
        public void GarbageCollection()
        {
            int totalDeletedRefs = deletedRefs.Count;

            for (int i = 0; i < totalDeletedRefs; i++)
            {
                int refId = deletedRefs[i];

                if (refCounts[refId] <= 0)
                {
                    IRef _ref = refs[refId];
                    if (_ref is Schema)
                    {
                        foreach (KeyValuePair <string, System.Type> field in ((Schema)_ref).GetFieldChildTypes())
                        {
                            object fieldValue = ((Schema)_ref)[field.Key];
                            if (
                                fieldValue is IRef &&
                                Remove(((IRef)fieldValue).__refId))
                            {
                                totalDeletedRefs++;
                            }
                        }
                    }
                    else if (_ref is ISchemaCollection && ((ISchemaCollection)_ref).HasSchemaChild)
                    {
                        IDictionary items = ((ISchemaCollection)_ref).GetItems();
                        foreach (IRef item in items.Values)
                        {
                            if (Remove(item.__refId))
                            {
                                totalDeletedRefs++;
                            }
                        }
                    }

                    refs.Remove(refId);
                    refCounts.Remove(refId);
                }
            }

            deletedRefs.Clear();
        }
Exemple #12
0
 public static Task <HttpResponseMessage> GetByRequestIdAsync(
     [QueryParameter(Name = SessionIdPropertyName, CheckFileName = true)] IRef <Session> sessionRef,
     [QueryParameter(Name = "request_id")] IRef <Authorization> authorization,
     EastFive.Api.SessionToken security,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     ContentTypeResponse <Session> onUpdated,
     NotFoundResponse onNotFound,
     ForbiddenResponse forbidden,
     ConfigurationFailureResponse onConfigurationFailure,
     GeneralConflictResponse onFailure)
 {
     return(UpdateBodyAsync(sessionRef, authorization.Optional(),
                            application,
                            onUpdated,
                            onNotFound,
                            forbidden,
                            onConfigurationFailure,
                            onFailure));
 }
Exemple #13
0
        /// <summary>
        /// Disposes of the renderer and detaches from the render loop.
        /// </summary>
        public void Dispose()
        {
            lock (_sceneLock)
            {
                if (_disposed)
                {
                    return;
                }
                _disposed = true;
                var scene = _scene;
                _scene = null;
                scene?.Dispose();
            }

            Stop();
            // Wait for any in-progress rendering to complete
            lock (_renderLoopIsRenderingLock){}
            DisposeRenderTarget();
        }
        public static async Task <HttpResponseMessage> QueryByIntegrationAsync(
            [QueryParameter(Name = "integration")] IRef <Integration> integrationRef,
            Api.Azure.AzureApplication application, EastFive.Api.SessionToken security,
            MultipartResponseAsync <Method> onContent,
            UnauthorizedResponse onUnauthorized,
            ReferencedDocumentNotFoundResponse <Integration> onIntegrationNotFound)
        {
            return(await await integrationRef.StorageGetAsync(
                       async (integration) =>
            {
                var accountId = integration.accountId;
                if (!await application.CanAdministerCredentialAsync(accountId, security))
                {
                    return onUnauthorized();
                }

                var integrationProviders = application.LoginProviders
                                           .Where(loginProvider => loginProvider.Value.GetType().IsSubClassOfGeneric(typeof(IProvideIntegration)))
                                           .Select(
                    async loginProvider =>
                {
                    var integrationProvider = loginProvider.Value as IProvideIntegration;
                    var supportsIntegration = await integrationProvider.SupportsIntegrationAsync(accountId);
                    return supportsIntegration.PairWithValue(loginProvider);
                })
                                           .Await()
                                           .Where(kvp => kvp.Key)
                                           .SelectValues()
                                           .Select(
                    (loginProvider) =>
                {
                    var integrationProvider = loginProvider.Value as IProvideIntegration;
                    return new Method
                    {
                        authenticationId = new Ref <Method>(loginProvider.Value.Id),
                        name = integrationProvider.GetDefaultName(new Dictionary <string, string>()),
                    };
                });
                return await onContent(integrationProviders);
            },
                       () => onIntegrationNotFound().AsTask()));
        }
        public static async Task <IntermediaryItem> MakeIntermediaryItemAsync(
            IRef <ExampleParentItem> exampleParentItemRef,
            int children)
        {
            var ii       = MakeIntermediaryItem(exampleParentItemRef);
            var iiStored = await ii.StorageCreateAsync(
                tr => tr.Entity);

            ExampleLinkedStorage [] childrenMade = await Enumerable
                                                   .Range(0, children)
                                                   .Select(
                i =>
            {
                return(ExampleLinkedStorage.MakeAsync(ii.intermediaryItemRef));
            })
                                                   .AsyncEnumerable()
                                                   .ToArrayAsync();

            return(iiStored);
        }
Exemple #16
0
 public static async Task <HttpResponseMessage> GetAsync(
     [QueryParameter(Name = AuthenticationPropertyName)] IRef <Authentication> authenticationRef,
     [Accepts(Media = "text/html")] MediaTypeWithQualityHeaderValue accept,
     HttpRequestMessage request,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     ContentTypeResponse <Authentication> onFound,
     HtmlResponse onHtmlWanted,
     NotFoundResponse onNotFound)
 {
     if (!accept.IsDefaultOrNull())
     {
         return(onHtmlWanted(EastFive.Azure.Properties.Resources.loginHtml));
     }
     return(await authenticationRef.StorageGetAsync(
                (authentication) =>
     {
         return onFound(authentication);
     },
                () => onNotFound()));
 }
 public static Task <HttpResponseMessage> GetAsync(
     [QueryParameter(CheckFileName = true, Name = AuthorizationIdPropertyName)] IRef <Authorization> authorizationRef,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     EastFive.Api.SessionToken?securityMaybe,
     ContentTypeResponse <Authorization> onFound,
     NotFoundResponse onNotFound,
     UnauthorizedResponse onUnauthorized,
     BadRequestResponse onBadRequest)
 {
     return(authorizationRef.StorageUpdateAsync(
                async(authorization, saveAsync) =>
     {
         if (authorization.deleted.HasValue)
         {
             return onNotFound();
         }
         if (authorization.authorized)
         {
             authorization.LocationAuthentication = default(Uri);
         }
         if (!securityMaybe.HasValue)
         {
             if (authorization.authorized)
             {
                 if (authorization.expired)
                 {
                     return onBadRequest();
                 }
                 if (authorization.lastModified - DateTime.UtcNow > TimeSpan.FromMinutes(1.0))
                 {
                     return onBadRequest();
                 }
                 authorization.expired = true;
                 await saveAsync(authorization);
                 return onFound(authorization);
             }
         }
         return onFound(authorization);
     },
                () => onNotFound()));
 }
Exemple #18
0
        public static Task <TResult> LoadImageAsync <TResult>(this IRef <Content> contentRef,
                                                              Func <System.Drawing.Image, string, TResult> onFound,
                                                              Func <TResult> onNotFound,
                                                              Func <Stream, string, TResult> onInvalidImage = default)
        {
            return(contentRef.id.BlobLoadStreamAsync("content",
                                                     (imageStream, contentType) =>
            {
                //var image = System.Drawing.Image.FromStream(imageStream);
                if (imageStream.TryReadImage(out Image image))
                {
                    return onFound(image, contentType);
                }

                if (onInvalidImage.IsDefaultOrNull())
                {
                    return onNotFound();
                }

                return onInvalidImage(imageStream, contentType);
            },
 public static IEnumerableAsync <KeyValuePair <XIntegration, Authorization> > GetParametersByAccountId(
     IRef <Method> methodId, Guid accountId)
 {
     return(accountId
            .StorageGetByIdProperty((XIntegration intgration) => intgration.accountId)
            .Where(integration => integration.Method != null)
            .Where(integration => integration.Method.id == methodId.id)
            .Where(integration => integration.authorization.HasValue)
            .Select(
                integration =>
     {
         return integration.authorization.StorageGetAsync(
             authorization =>
         {
             return authorization.PairWithKey(integration);
         },
             () => default(KeyValuePair <XIntegration, Authorization>?));
     })
            .Await()
            .SelectWhereHasValue());
 }
        public virtual PlaceResult Place(IPlayer player, IRef referee)
        {
            string placePos = player.getMove("Select place position: ");

            if (!referee.isValidPlacement(placePos, player, this))
            {
                return(PlaceResult.Invalid);
            }

            board[placePos].changeState(player.playerID);
            player.Placed();

            if (isInMill(placePos))
            {
                return(PlaceResult.MillMade);
            }
            else
            {
                return(PlaceResult.Done);
            }
        }
        public virtual MoveResult Move(IPlayer player, IRef referee)
        {
            string piecePos = player.getMove("Enter piece to move: ");

            if (!referee.isValidPickUp(piecePos, player, this))
            {
                return(MoveResult.InvalidPickUp);
            }
            string placePos = player.getMove($@"Place {piecePos} at position: ");

            if (!referee.isValidPutDown(piecePos, placePos, player, this))
            {
                return(MoveResult.InvalidPutDown);
            }
            board[piecePos].changeState(Player.None);
            board[placePos].changeState(player.playerID);
            if (isInMill(placePos))
            {
                return(MoveResult.MillMade);
            }
            return(MoveResult.Done);
        }
        public async static Task <IHttpResponse> AuthorizeAsync(
            [QueryParameter(Name = "session")]
            IRef <Session> sessionRef,

            [UpdateId(Name = AuthorizationIdPropertyName)]
            IRef <Authorization> authorizationRef,

            [Property(Name = ParametersPropertyName)]
            IDictionary <string, string> parameters,

            Api.Azure.AzureApplication application,
            IInvokeApplication endpoints,
            IHttpRequest request,
            CreatedBodyResponse <Session> onCreated,
            NotFoundResponse onAuthorizationDoesNotExist,
            ForbiddenResponse onAuthorizationFailed,
            ServiceUnavailableResponse onServiceUnavailable,
            ForbiddenResponse onInvalidMethod,
            GeneralConflictResponse onFailure)
        {
            return(await await authorizationRef.StorageGetAsync(
                       (authorization) =>
            {
                return AuthenticateWithSessionAsync(authorizationRef, sessionRef,
                                                    authorization.Method, parameters,
                                                    application, endpoints, request,
                                                    onAuthorized: (sessionCreated, redirect) =>
                {
                    var response = onCreated(sessionCreated, contentType: "application/json");
                    response.SetLocation(redirect);
                    return response;
                },
                                                    onAuthorizationDoesNotExist: () => onAuthorizationDoesNotExist(),
                                                    onServiceUnavailable: (why) => onServiceUnavailable().AddReason(why),
                                                    onInvalidMethod: (why) => onInvalidMethod().AddReason(why),
                                                    onAuthorizationFailed: why => onAuthorizationFailed().AddReason(why));
            },
                       () => onAuthorizationDoesNotExist().AsTask()));
        }
Exemple #23
0
        public static async Task <IHttpResponse> LaunchAsync(

            [Api.Meta.Flows.WorkflowParameter(Value = "{{AuthenticationMethod}}")]
            [QueryParameter(Name = "method")] IRef <Method> methodRef,

            RequestMessage <AccountRequest> api,
            IHttpRequest request,
            IAzureApplication application,
            IProvideUrl urlHelper,
            [Api.Meta.Flows.WorkflowVariableRedirectUrl(
                 VariableName = Workflows.AuthorizationFlow.Variables.RedirectUrl)]
            RedirectResponse onLaunched,
            BadRequestResponse onInvalidMethod)
        {
            return(await await Method.ById(methodRef, application,
                                           async method =>
            {
                var authRef = Ref <Authorization> .SecureRef();
                var authorization = new Authorization
                {
                    authorizationRef = authRef,
                    LocationAuthenticationReturn = api
                                                   // .Where(query => query.authorization == authRef)
                                                   .HttpAction(ResponseAction)
                                                   .CompileRequest(request)
                                                   .RequestUri,
                    Method = methodRef,
                };

                return await await authorization.StorageCreateAsync(
                    async(discard) =>
                {
                    var redir = await method.GetLoginUrlAsync(
                        application, urlHelper, authRef.id);
                    return onLaunched(redir);
                });
            },
                                           () => onInvalidMethod().AsTask()));
        }
Exemple #24
0
        public static Task <IHttpResponse> HttpPatchAsync <TResource>(
            this IRef <TResource> resourceRef,
            MutateResource <TResource> modifyResource,
            ContentTypeResponse <TResource> onUpdated,
            NotFoundResponse onNotFound,
            Func <TResource, TResource> additionalMutations = default)
            where TResource : IReferenceable
        {
            return(resourceRef.StorageUpdateAsync(
                       async(resource, saveAsync) =>
            {
                var resourceToSave = modifyResource(resource);
                if (additionalMutations.IsNotDefaultOrNull())
                {
                    resourceToSave = additionalMutations(resourceToSave);
                }

                await saveAsync(resource);
                return onUpdated(resource);
            },
                       () => onNotFound()));
        }
        public static async Task <TResult> DeleteInternalAsync <TResult>(
            IRef <Integration> integrationRef, Api.Azure.AzureApplication application,
            Func <TResult> onDeleted,
            Func <TResult> onNotFound)
        {
            var integrationMaybe = await integrationRef.StorageGetAsync(i => i, () => default(Integration?));

            if (!integrationMaybe.HasValue)
            {
                return(onNotFound());
            }

            var integration = integrationMaybe.Value;

            return(await await integrationRef.StorageDeleteAsync(
                       onDeleted: async(discard) =>
            {
                if (integration.authorization.HasValue)
                {
                    var authorizationId = integration.authorization.id.Value;
                    var authorizationLookupRef = authorizationId.AsRef <AuthorizationIntegrationLookup>();
                    await authorizationLookupRef.StorageDeleteAsync(
                        onDeleted: (discard) => true);
                }
                var accountIntegrationRef = integration.accountId.AsRef <AccountIntegrationLookup>();
                await accountIntegrationRef.StorageUpdateAsync(
                    async(accountLookup, saveAsync) =>
                {
                    accountLookup.integrationRefs = accountLookup.integrationRefs.ids
                                                    .Where(id => id != integration.id)
                                                    .AsRefs <Integration>();
                    await saveAsync(accountLookup);
                    return true;
                });
                return onDeleted();
            },
                       () => onNotFound().AsTask()));
        }
        public static async Task <IHttpResponse> DeleteAsync(
            [UpdateId(Name = IntegrationIdPropertyName)] IRef <XIntegration> integrationRef,
            IAuthApplication application, EastFive.Api.SessionToken security,
            NoContentResponse onDeleted,
            NotFoundResponse onNotFound,
            ForbiddenResponse onForbidden)
        {
            var integrationMaybe = await integrationRef.StorageGetAsync(i => i, () => default(XIntegration?));

            if (!integrationMaybe.HasValue)
            {
                return(onNotFound());
            }

            var integration = integrationMaybe.Value;

            if (!await application.CanAdministerCredentialAsync(integration.accountId, security))
            {
                return(onForbidden());
            }

            return(await DeleteInternalAsync(integrationRef, () => onDeleted(), () => onNotFound()));
        }
        public async static Task <IHttpResponse> CreateAuthorizedAsync(
            [UpdateId(Name = AuthorizationIdPropertyName)] IRef <Authorization> authorizationRef,
            [Property(Name = MethodPropertyName)] IRef <Method> methodRef,
            [Property(Name = ParametersPropertyName)] IDictionary <string, string> parameters,
            [Resource] Authorization authorization,
            Api.Azure.AzureApplication application, IProvideUrl urlHelper,
            IInvokeApplication endpoints,
            IHttpRequest request,
            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ForbiddenResponse onAuthorizationFailed,
            ServiceUnavailableResponse onServericeUnavailable,
            ForbiddenResponse onInvalidMethod)
        {
            authorization.accountIdMaybe = default;
            authorization.authorized     = false;
            return(await await Auth.Method.ById(methodRef, application,
                                                (method) =>
            {
                var paramsUpdated = parameters;
                //.Append(
                //    authorizationRef.id.ToString().PairWithKey("state"))
                //.ToDictionary();

                return Redirection.AuthenticationAsync(
                    method,
                    paramsUpdated,
                    application, request, endpoints, request.RequestUri,
                    authorizationRef.Optional(),
                    (redirect, accountIdMaybe, discardModifier) => onCreated(),
                    () => onAuthorizationFailed().AddReason("Authorization was not found"),     // Bad credentials
                    why => onServericeUnavailable().AddReason(why),
                    why => onAuthorizationFailed().AddReason(why));
            },
                                                () => onInvalidMethod().AddReason("The method was not found.").AsTask()));
        }
        public async static Task <IHttpResponse> CreateAsync(
            [Api.Meta.Flows.WorkflowNewId]
            [Property(Name = AuthorizationIdPropertyName)]
            IRef <Authorization> authorizationRef,

            [Api.Meta.Flows.WorkflowParameter(Value = "{{AuthenticationMethod}}")]
            [Property(Name = MethodPropertyName)]
            IRef <Method> method,

            [Api.Meta.Flows.WorkflowParameter(Value = "http://example.com")]
            [Property(Name = LocationAuthorizationReturnPropertyName)]
            Uri locationAuthenticationReturn,

            [Resource] Authorization authorization,
            IAuthApplication application, IProvideUrl urlHelper,
            CreatedBodyResponse <Authorization> onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ReferencedDocumentDoesNotExistsResponse <Method> onAuthenticationDoesNotExist)
        {
            authorization.accountIdMaybe = default;
            authorization.authorized     = false;

            return(await await Auth.Method.ById(method, application,
                                                async (method) =>
            {
                //var authorizationIdSecure = authentication.authenticationId;
                authorization.LocationAuthentication = await method.GetLoginUrlAsync(
                    application, urlHelper, authorizationRef.id);

                //throw new ArgumentNullException();
                return await authorization.StorageCreateAsync(
                    createdId => onCreated(authorization),
                    () => onAlreadyExists());
            },
                                                () => onAuthenticationDoesNotExist().AsTask()));
        }
        public async static Task <HttpResponseMessage> CreateAsync(
            [Property(Name = AuthorizationIdPropertyName)] Guid authorizationId,
            [Property(Name = MethodPropertyName)] IRef <Method> method,
            [Property(Name = LocationAuthorizationReturnPropertyName)] Uri LocationAuthenticationReturn,
            [Resource] Authorization authorization,
            Api.Azure.AzureApplication application, UrlHelper urlHelper,
            CreatedBodyResponse <Authorization> onCreated,
            AlreadyExistsResponse onAlreadyExists,
            ReferencedDocumentDoesNotExistsResponse <Method> onAuthenticationDoesNotExist)
        {
            return(await await Auth.Method.ById(method, application,
                                                async (authentication) =>
            {
                //var authorizationIdSecure = authentication.authenticationId;
                authorization.LocationAuthentication = await authentication.GetLoginUrlAsync(
                    application, urlHelper, authorizationId);

                throw new NotImplementedException();
                return await authorization.StorageCreateAsync(
                    createdId => onCreated(authorization),
                    () => onAlreadyExists());
            },
                                                () => onAuthenticationDoesNotExist().AsTask()));
        }
Exemple #30
0
 private static async Task <TResult> GetSessionAcountAsync <TResult>(IRef <Authorization> authorizationRef,
                                                                     Api.Azure.AzureApplication application,
                                                                     Func <Guid, bool, TResult> onSuccess,
                                                                     Func <string, bool, TResult> onFailure)
 {
     return(await await authorizationRef.StorageGetAsync(
                async (authorization) =>
     {
         var methodRef = authorization.Method;
         return await await Method.ById(methodRef, application,
                                        async method =>
         {
             return await await method.GetAuthorizationKeyAsync(application, authorization.parameters,
                                                                (externalUserKey) =>
             {
                 return Auth.AccountMapping.FindByMethodAndKeyAsync(method.authenticationId, externalUserKey,
                                                                    authorization,
                                                                    accountId => onSuccess(accountId, authorization.authorized),
                                                                    () => onFailure("No mapping to that account.", authorization.authorized));
             },
                                                                (why) => onFailure(why, authorization.authorized).AsTask(),
                                                                () => onFailure("This login method is no longer supported.", false).AsTask());
         },
                                        () =>
         {
             return CheckSuperAdminBeforeFailure(authorizationRef,
                                                 "Authorization method is no longer valid on this system.", authorization.authorized,
                                                 onSuccess, onFailure).AsTask();
         });
     },
                () =>
     {
         return CheckSuperAdminBeforeFailure(authorizationRef, "Authorization not found.", false,
                                             onSuccess, onFailure).AsTask();
     }));
 }
Exemple #31
0
        /// <summary>
        /// Ensures that this node draw operations have been created and are mutable (in case we are using cloned operations).
        /// </summary>
        private void EnsureDrawOperationsCreated()
        {
            if (_drawOperations == null)
            {
                _drawOperations           = new List <IRef <IDrawOperation> >();
                _drawOperationsRefCounter = RefCountable.Create(CreateDisposeDrawOperations(_drawOperations));
                _drawOperationsCloned     = false;
            }
            else if (_drawOperationsCloned)
            {
                var oldDrawOperations = _drawOperations;

                _drawOperations = new List <IRef <IDrawOperation> >(oldDrawOperations.Count);

                foreach (var drawOperation in oldDrawOperations)
                {
                    _drawOperations.Add(drawOperation.Clone());
                }

                _drawOperationsRefCounter.Dispose();
                _drawOperationsRefCounter = RefCountable.Create(CreateDisposeDrawOperations(_drawOperations));
                _drawOperationsCloned     = false;
            }
        }
Exemple #32
0
        public static Task <IHttpResponse> CreateAsync(
            [EastFive.Api.Meta.Flows.WorkflowNewId]
            [WorkflowVariable(Workflows.MonitoringFlow.Variables.CreatedNotification, IdPropertyName)]
            [UpdateId]
            IRef <TeamsNotification> teamsNotificationRef,

            [PropertyOptional(Name = RouteFiltersPropertyName)]
            [WorkflowArrayObjectParameter(Value0 = "/api/*")]
            string routeFilters,

            [PropertyOptional(Name = CollectionPropertyName)]
            [WorkflowParameter(Value = "Collection1", Disabled = true)]
            string collection,

            [Resource] TeamsNotification storyBoard,

            CreatedResponse onCreated,
            AlreadyExistsResponse onAlreadyExists,
            UnauthorizedResponse onUnauthorized)
        {
            return(storyBoard.HttpPostAsync(
                       onCreated,
                       onAlreadyExists));
        }
 public static object refSet(IRef rf, object value, Context cx)
 {
     return rf.Set (cx, value);
 }
 public static object refDel(IRef rf, Context cx)
 {
     return rf.Delete (cx);
 }
Exemple #35
0
 public void Visit(IRef r)
 {
 }
 public static object refGet(IRef rf, Context cx)
 {
     return rf.Get (cx);
 }
Exemple #37
0
 /// Construct a multifunction.
 /// </summary>
 /// <param name="name">The name</param>
 /// <param name="dispatchFn">The dispatch function.</param>
 /// <param name="defaultDispatchVal">The default dispatch value.</param>
 /// <param name="hierarchy">The hierarchy for this multifunction</param>
 public MultiFn(string name, IFn dispatchFn, object defaultDispatchVal, IRef hierarchy)
 {
     _name = name;
     _dispatchFn = dispatchFn;
     _defaultDispatchVal = defaultDispatchVal;
     _methodTable = PersistentHashMap.EMPTY;
     _methodCache = MethodTable;
     _preferTable = PersistentHashMap.EMPTY;
     _hierarchy = hierarchy;
     _cachedHierarchy = null;
     _rw = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion);
 }
 public static object refIncrDecr(IRef rf, Context cx, int incrDecrMask)
 {
     object value = rf.Get (cx);
     bool post = ((incrDecrMask & Node.POST_FLAG) != 0);
     double number;
     if (CliHelper.IsNumber (value)) {
         number = Convert.ToDouble (value);
     }
     else {
         number = ScriptConvert.ToNumber (value);
         if (post) {
             // convert result to number
             value = number;
         }
     }
     if ((incrDecrMask & Node.DECR_FLAG) == 0) {
         ++number;
     }
     else {
         --number;
     }
     rf.Set (cx, number);
     if (post) {
         return value;
     }
     else {
         return number;
     }
 }
 public DirectStreamableObjectChannel(ServerConnector connector, IRef obj)
 {
     this.obj = obj;
     this.connector = connector;
 }
Exemple #40
0
 public void register(IRef aref)
 {
     aref.addWatch(parent.sully, parent.sully);
 }