Esempio n. 1
0
        public ActionResult Index()
        {
            IHandlerBuilder builder = new HandlerBuilder();

            builder
                .Use<SignatureCheckHandlerMiddleware>() //验证签名中间件。
                .Use<CreateRequestMessageHandlerMiddleware>() //创建消息中间件(内置消息解密逻辑)。
                .Use<SessionSupportHandlerMiddleware>() //会话支持中间件。
                .Use<IgnoreRepeatMessageHandlerMiddleware>() //忽略重复的消息中间件。
                .Use<TestMessageHandlerMiddleware>() //测试消息处理中间件。
                .Use<GenerateResponseXmlHandlerMiddleware>(); //生成相应XML处理中间件(内置消息加密逻辑)。
            //                            .Use<AgentHandlerMiddleware>(new AgentRequestModel(new Uri("http://localhost:22479/Mutual")));

            var context = new HandlerContext(Request);

            //设置基本信息。
            context
                .SetMessageHandlerBaseInfo(new MessageHandlerBaseInfo(
                    "wxa4ab3e636e2eb702",
                    "q0OlAOdGzpmm5B8HEqycylcn17nUp25HG04dr7KD6ET",
                    "weixin"));

            IWeiXinHandler weiXinHandler = new DefaultWeiXinHandler(builder);
            weiXinHandler.Execute(context);

            return new WeiXinResult(context);
        }
        public async Task<ActionResult> Index()
        {
            IHandlerBuilder builder = new HandlerBuilder();

            builder
#if !DEBUG
                .Use<SignatureCheckHandlerMiddleware>() //验证签名中间件。
#endif
                .Use<CreateRequestMessageHandlerMiddleware>() //创建消息中间件(内置消息解密逻辑)。
                .Use<SessionSupportHandlerMiddleware>() //会话支持中间件。
                .Use<IgnoreRepeatMessageHandlerMiddleware>() //忽略重复的消息中间件。
                .Use<CommandMessageHandlerMiddleware>() //每日精华文章消息处理中间件。
                .Use<GenerateResponseXmlHandlerMiddleware>(); //生成相应XML处理中间件(内置消息加密逻辑)。
            //                            .Use<AgentHandlerMiddleware>(new AgentRequestModel(new Uri("http://localhost:22479/Mutual")));

            var context = new HandlerContext(Request);

            //设置基本信息。
            context
                .SetMessageHandlerBaseInfo(new MessageHandlerBaseInfo(
                    ConfigurationManager.AppSettings["wx:AppId"],
                    ConfigurationManager.AppSettings["wx:AppSecret"],
                    "weixin"));

            IWeiXinHandler weiXinHandler = new DefaultWeiXinHandler(builder);
            await weiXinHandler.Execute(context);

            return new WeiXinResult(context);
        }
Esempio n. 3
0
    public override async Task Handle(HandlerContext <Command> context)
    {
        IQueryable <string> query =
            from rosterMail in CompositionRoot.Databases.Snittlistan.RosterMails
            where rosterMail.RosterKey == context.Payload.RosterKey &&
            rosterMail.PublishedDate == null
            select rosterMail.RosterKey;

        string[] rosterIds = await query.ToArrayAsync();

        Logger.InfoFormat("roster mails found: {@rosterIds}", rosterIds);
        if (rosterIds.Any() == false)
        {
            TenantFeatures features = await CompositionRoot.GetFeatures();

            _ = CompositionRoot.Databases.Snittlistan.RosterMails.Add(
                new(context.Payload.RosterKey));
            PublishRosterMailsTask task = new(
                context.Payload.RosterKey,
                context.Payload.RosterLink,
                context.Payload.UserProfileLink);
            context.PublishMessage(task, DateTime.Now.AddMinutes(features.RosterMailDelayMinutes));
        }
    }
Esempio n. 4
0
        protected async Task CommonValidate(HandlerContext context, CancellationToken cancellationToken)
        {
            var client                   = context.Client;
            var redirectUri              = context.Request.RequestData.GetRedirectUriFromAuthorizationRequest();
            var responseTypes            = context.Request.RequestData.GetResponseTypesFromAuthorizationRequest();
            var responseMode             = context.Request.RequestData.GetResponseModeFromAuthorizationRequest();
            var unsupportedResponseTypes = responseTypes.Where(t => !client.ResponseTypes.Contains(t));
            var redirectionUrls          = await client.GetRedirectionUrls(_httpClientFactory, cancellationToken);

            if (!string.IsNullOrWhiteSpace(redirectUri) && !redirectionUrls.Contains(redirectUri))
            {
                throw new OAuthExceptionBadRequestURIException(redirectUri);
            }

            if (!string.IsNullOrWhiteSpace(responseMode) && !_oauthResponseModes.Any(o => o.ResponseMode == responseMode))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.BAD_RESPONSE_MODE, responseMode));
            }

            if (unsupportedResponseTypes.Any())
            {
                throw new OAuthException(ErrorCodes.UNSUPPORTED_RESPONSE_TYPE, string.Format(ErrorMessages.BAD_RESPONSE_TYPES_CLIENT, string.Join(",", unsupportedResponseTypes)));
            }
        }
Esempio n. 5
0
        public virtual async Task Validate(HandlerContext context, CancellationToken cancellationToken)
        {
            if (context.User == null)
            {
                throw new OAuthLoginRequiredException();
            }

            await CommonValidate(context, cancellationToken);

            var scopes            = context.Request.RequestData.GetScopesFromAuthorizationRequest();
            var unsupportedScopes = scopes.Where(s => !context.Client.AllowedScopes.Any(sc => sc.Name == s));

            if (unsupportedScopes.Any())
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.UNSUPPORTED_SCOPES, string.Join(",", unsupportedScopes)));
            }

            var consent = _userConsentFetcher.FetchFromAuthorizationRequest(context.User, context.Request.RequestData);

            if (consent == null)
            {
                throw new OAuthUserConsentRequiredException();
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> Add([FromBody] JObject jObj)
        {
            try
            {
                var context = new HandlerContext(new HandlerContextRequest(Request.GetAbsoluteUriWithVirtualPath(), string.Empty, null, jObj, null));
                var result  = await _registerRequestHandler.Handle(context);

                return(new ContentResult
                {
                    Content = result.ToString(),
                    ContentType = "application/json",
                    StatusCode = (int)HttpStatusCode.Created
                });
            }
            catch (OAuthException ex)
            {
                var res = new JObject
                {
                    { ErrorResponseParameters.Error, ex.Code },
                    { ErrorResponseParameters.ErrorDescription, ex.Message }
                };
                return(new BadRequestObjectResult(res));
            }
        }
Esempio n. 7
0
        public virtual Expression HandleResultOperator(
            EntityQueryModelVisitor entityQueryModelVisitor,
            ResultOperatorBase resultOperator,
            QueryModel queryModel)
        {
            Check.NotNull(entityQueryModelVisitor, nameof(entityQueryModelVisitor));
            Check.NotNull(resultOperator, nameof(resultOperator));
            Check.NotNull(queryModel, nameof(queryModel));

            var relationalQueryModelVisitor
                = (RelationalQueryModelVisitor)entityQueryModelVisitor;

            var selectExpression
                = relationalQueryModelVisitor
                  .TryGetQuery(queryModel.MainFromClause);

            var handlerContext
                = new HandlerContext(
                      _resultOperatorHandler,
                      relationalQueryModelVisitor,
                      resultOperator,
                      queryModel,
                      selectExpression);

            Func <HandlerContext, Expression> resultHandler;

            if (relationalQueryModelVisitor.RequiresClientFilter ||
                relationalQueryModelVisitor.RequiresClientResultOperator ||
                !_resultHandlers.TryGetValue(resultOperator.GetType(), out resultHandler) ||
                selectExpression == null)
            {
                return(handlerContext.EvalOnClient);
            }

            return(resultHandler(handlerContext));
        }
    public override Task Handle(HandlerContext <Command> context)
    {
        IndexCreator.CreateIndexes(CompositionRoot.DocumentStore);
        User admin = CompositionRoot.DocumentSession.Load <User>(User.AdminId);

        if (admin == null)
        {
            admin = new("", "", context.Payload.Email, context.Payload.Password)
            {
                Id = User.AdminId
            };
            admin.Initialize(t => context.PublishMessage(t));
            admin.Activate();
            CompositionRoot.DocumentSession.Store(admin);
        }
        else
        {
            admin.SetEmail(context.Payload.Email);
            admin.SetPassword(context.Payload.Password);
            admin.Activate();
        }

        return(Task.CompletedTask);
    }
Esempio n. 9
0
        public void ProcessMessage(HandlerContext <RegisterMemberCommand> context)
        {
            Console.WriteLine();
            Console.WriteLine("[MEMBER REGISTERED] : user name = '{0}'", context.Message.UserName);
            Console.WriteLine();

            var memberRegisteredEvent = new MemberRegisteredEvent
            {
                UserName = context.Message.UserName
            };

            context.Publish(memberRegisteredEvent);

            if (!string.IsNullOrEmpty(context.TransportMessage.SenderInboxWorkQueueUri))
            {
                context.Send(new MemberRegisteredEvent
                {
                    UserName = context.Message.UserName
                }, c =>
                {
                    c.Reply();
                });
            }
        }
        public override async Task <AuthorizationResponse> Handle(HandlerContext context, CancellationToken token)
        {
            try
            {
                var result = await base.BuildResponse(context, token);

                var display = context.Request.Data.GetDisplayFromAuthorizationRequest();
                if (!string.IsNullOrWhiteSpace(display))
                {
                    context.Response.Add(AuthorizationRequestParameters.Display, display);
                }

                var sessionState = BuildSessionState(context);
                if (!string.IsNullOrWhiteSpace(sessionState))
                {
                    context.Response.Add(AuthorizationRequestParameters.SessionState, sessionState);
                }

                return(result);
            }
            catch (OAuthUserConsentRequiredException ex)
            {
                context.Request.Data.Remove(AuthorizationRequestParameters.Prompt);
                return(new RedirectActionAuthorizationResponse(ex.ActionName, ex.ControllerName, context.Request.Data));
            }
            catch (OAuthLoginRequiredException ex)
            {
                context.Request.Data.Remove(AuthorizationRequestParameters.Prompt);
                return(new RedirectActionAuthorizationResponse("Index", "Authenticate", context.Request.Data, ex.Area));
            }
            catch (OAuthSelectAccountRequiredException)
            {
                context.Request.Data.Remove(AuthorizationRequestParameters.Prompt);
                return(new RedirectActionAuthorizationResponse("Index", "Accounts", context.Request.Data));
            }
        }
Esempio n. 11
0
        public override async Task Build(IEnumerable <string> scopes, HandlerContext handlerContext, CancellationToken cancellationToken)
        {
            var dic = new JObject();

            if (handlerContext.Request.RequestData != null)
            {
                foreach (var record in handlerContext.Request.RequestData)
                {
                    dic.Add(record.Key, record.Value);
                }
            }

            if (handlerContext.User != null)
            {
                dic.Add(UserClaims.Subject, handlerContext.User.Id);
            }

            var authorizationCode = string.Empty;

            handlerContext.Response.TryGet(AuthorizationResponseParameters.Code, out authorizationCode);
            var refreshToken = await GrantedTokenHelper.AddRefreshToken(handlerContext.Client.ClientId, authorizationCode, dic, handlerContext.Client.RefreshTokenExpirationTimeInSeconds, cancellationToken);

            handlerContext.Response.Add(TokenResponseParameters.RefreshToken, refreshToken);
        }
        public virtual async Task <OAuthClient> GetClient(string clientId, HandlerContext handlerContext, CancellationToken cancellationToken)
        {
            var accessToken = handlerContext.Request.GetToken(AutenticationSchemes.Bearer, AutenticationSchemes.Basic);

            if (string.IsNullOrWhiteSpace(accessToken))
            {
                Logger.LogError("access token is missing");
                throw new OAuthUnauthorizedException(ErrorCodes.INVALID_TOKEN, ErrorMessages.MISSING_ACCESS_TOKEN);
            }

            var clients = await OAuthClientQueryRepository.Find(new Persistence.Parameters.SearchClientParameter
            {
                RegistrationAccessToken = accessToken
            }, cancellationToken);

            if (!clients.Content.Any())
            {
                Logger.LogError($"access token '{accessToken}' is invalid");
                throw new OAuthUnauthorizedException(ErrorCodes.INVALID_TOKEN, ErrorMessages.BAD_ACCESS_TOKEN);
            }

            var client = clients.Content.First();

            if (client.ClientId != clientId)
            {
                client.RegistrationAccessToken = null;
                await OAuthClientCommandRepository.Update(client, cancellationToken);

                await OAuthClientCommandRepository.SaveChanges(cancellationToken);

                Logger.LogError($"access token '{accessToken}' can be used for the client '{client.ClientId}' and not for the client '{clientId}'");
                throw new OAuthUnauthorizedException(ErrorCodes.INVALID_TOKEN, string.Format(ErrorMessages.ACCESS_TOKEN_VALID_CLIENT, client.ClientId, clientId));
            }

            return(client);
        }
        private static Expression HandleSingle(HandlerContext handlerContext)
        {
            handlerContext.SelectExpression.Limit = Expression.Constant(2);

            return(handlerContext.EvalOnClient(requiresClientResultOperator: true));
        }
        private static Expression HandleOfType(HandlerContext handlerContext)
        {
            var ofTypeResultOperator
                = (OfTypeResultOperator)handlerContext.ResultOperator;

            var entityType = handlerContext.Model.FindEntityType(ofTypeResultOperator.SearchedItemType);

            if (entityType == null)
            {
                return(handlerContext.EvalOnClient());
            }

            var concreteEntityTypes
                = entityType.GetConcreteTypesInHierarchy().ToArray();

            if (concreteEntityTypes.Length != 1 ||
                concreteEntityTypes[0].RootType() != concreteEntityTypes[0])
            {
                var relationalMetadataExtensionProvider
                    = handlerContext.RelationalAnnotationProvider;

                var discriminatorProperty
                    = relationalMetadataExtensionProvider.For(concreteEntityTypes[0]).DiscriminatorProperty;

                var projectionIndex
                    = handlerContext.SelectExpression
                      .GetProjectionIndex(discriminatorProperty, handlerContext.QueryModel.MainFromClause);

                if (projectionIndex < 0)
                {
                    projectionIndex
                        = handlerContext.SelectExpression
                          .AddToProjection(
                              relationalMetadataExtensionProvider.For(discriminatorProperty).ColumnName,
                              discriminatorProperty,
                              handlerContext.QueryModel.MainFromClause);
                }

                var discriminatorColumn
                    = handlerContext.SelectExpression.Projection[projectionIndex];

                var discriminatorPredicate
                    = concreteEntityTypes
                      .Select(concreteEntityType =>
                              Expression.Equal(
                                  discriminatorColumn,
                                  Expression.Constant(relationalMetadataExtensionProvider.For(concreteEntityType).DiscriminatorValue)))
                      .Aggregate((current, next) => Expression.OrElse(next, current));

                handlerContext.SelectExpression.Predicate
                    = new DiscriminatorReplacingExpressionVisitor(
                          discriminatorPredicate,
                          handlerContext.QueryModel.MainFromClause)
                      .Visit(handlerContext.SelectExpression.Predicate);
            }

            var shapedQueryMethod = (MethodCallExpression)handlerContext.QueryModelVisitor.Expression;
            var entityShaper      = (EntityShaper)((ConstantExpression)shapedQueryMethod.Arguments[2]).Value;

            return(Expression.Call(
                       shapedQueryMethod.Method
                       .GetGenericMethodDefinition()
                       .MakeGenericMethod(ofTypeResultOperator.SearchedItemType),
                       shapedQueryMethod.Arguments[0],
                       shapedQueryMethod.Arguments[1],
                       Expression.Constant(
                           _createDowncastingShaperMethodInfo
                           .MakeGenericMethod(ofTypeResultOperator.SearchedItemType)
                           .Invoke(null, new object[] { entityShaper }))));
        }
        private static Expression HandleFirst(HandlerContext handlerContext)
        {
            handlerContext.SelectExpression.Limit = Expression.Constant(1);

            return(handlerContext.EvalOnClient(requiresClientResultOperator: false));
        }
        private static Expression HandleContains(HandlerContext handlerContext)
        {
            var filteringVisitor = handlerContext.CreateSqlTranslatingVisitor(bindParentQueries: true);

            var itemResultOperator = (ContainsResultOperator)handlerContext.ResultOperator;

            var item = filteringVisitor.Visit(itemResultOperator.Item);

            if (item != null)
            {
                var itemSelectExpression = item as SelectExpression;

                if (itemSelectExpression != null)
                {
                    var entityType = handlerContext.Model.FindEntityType(handlerContext.QueryModel.MainFromClause.ItemType);

                    if (entityType != null)
                    {
                        var outterSelectExpression = handlerContext.SelectExpressionFactory.Create(handlerContext.QueryModelVisitor.QueryCompilationContext);
                        outterSelectExpression.SetProjectionExpression(Expression.Constant(1));

                        var collectionSelectExpression
                            = handlerContext.SelectExpression.Clone(handlerContext.QueryModelVisitor.QueryCompilationContext.CreateUniqueTableAlias());
                        outterSelectExpression.AddTable(collectionSelectExpression);

                        itemSelectExpression.Alias = handlerContext.QueryModelVisitor.QueryCompilationContext.CreateUniqueTableAlias();
                        var joinExpression = outterSelectExpression.AddInnerJoin(itemSelectExpression);

                        foreach (var property in entityType.FindPrimaryKey().Properties)
                        {
                            itemSelectExpression.AddToProjection(
                                new ColumnExpression(
                                    property.Name,
                                    property,
                                    itemSelectExpression.Tables.First()));

                            collectionSelectExpression.AddToProjection(
                                new ColumnExpression(
                                    property.Name,
                                    property,
                                    collectionSelectExpression.Tables.First()));

                            var predicate = Expression.Equal(
                                new ColumnExpression(
                                    property.Name,
                                    property,
                                    collectionSelectExpression),
                                new ColumnExpression(
                                    property.Name,
                                    property,
                                    itemSelectExpression));

                            joinExpression.Predicate
                                = joinExpression.Predicate == null
                                    ? predicate
                                    : Expression.AndAlso(
                                      joinExpression.Predicate,
                                      predicate);
                        }

                        SetProjectionConditionalExpression(
                            handlerContext,
                            Expression.Condition(
                                new ExistsExpression(outterSelectExpression),
                                Expression.Constant(true),
                                Expression.Constant(false),
                                typeof(bool)));

                        return(TransformClientExpression <bool>(handlerContext));
                    }
                }

                SetProjectionConditionalExpression(
                    handlerContext,
                    Expression.Condition(
                        new InExpression(
                            new AliasExpression(item),
                            handlerContext.SelectExpression.Clone("")),
                        Expression.Constant(true),
                        Expression.Constant(false),
                        typeof(bool)));

                return(TransformClientExpression <bool>(handlerContext));
            }

            return(handlerContext.EvalOnClient());
        }
 public void ProcessMessage(HandlerContext <ReceivePipelineCommand> context)
 {
 }
 public GetAuthorQueryHandler(HandlerContext <AuthorViewModel> context, IAuthorService authorService)
 {
     _context       = context;
     _authorService = authorService;
 }
 public void ProcessMessage(HandlerContext <WorkDoneEvent> context)
 {
     ColoredConsole.WriteLine(ConsoleColor.Blue, context.Message.Comment);
 }
Esempio n. 20
0
 public PublishNewsHandler(HandlerContext <PublishNewsHandler> context,
                           IValidator <PublishNewsCommand>[] validators) : base(context, validators)
 {
 }
Esempio n. 21
0
 private static Expression HandleCast(HandlerContext handlerContext)
 => handlerContext.EvalOnClient(requiresClientResultOperator: false);
Esempio n. 22
0
        protected async Task <bool> CheckRequest(HandlerContext context, string request)
        {
            var openidClient = (OpenIdClient)context.Client;

            if (!_jwtParser.IsJwsToken(request) && !_jwtParser.IsJweToken(request))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_REQUEST_PARAMETER);
            }

            var jws = request;

            if (_jwtParser.IsJweToken(request))
            {
                jws = await _jwtParser.Decrypt(jws);

                if (string.IsNullOrWhiteSpace(jws))
                {
                    throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_JWE_REQUEST_PARAMETER);
                }
            }

            JwsHeader header = null;

            try
            {
                header = _jwtParser.ExtractJwsHeader(jws);
            }
            catch (InvalidOperationException)
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_JWS_REQUEST_PARAMETER);
            }

            if (
                (!string.IsNullOrWhiteSpace(openidClient.RequestObjectSigningAlg) && header.Alg != openidClient.RequestObjectSigningAlg) ||
                (string.IsNullOrWhiteSpace(openidClient.RequestObjectSigningAlg) && header.Alg != NoneSignHandler.ALG_NAME)
                )
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_SIGNATURE_ALG);
            }

            var jwsPayload = await _jwtParser.Unsign(jws, context.Client);

            if (jwsPayload == null)
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_JWS_REQUEST_PARAMETER);
            }

            if (!jwsPayload.ContainsKey(OAuth.DTOs.AuthorizationRequestParameters.ResponseType))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.MISSING_RESPONSE_TYPE_CLAIM);
            }

            if (!jwsPayload.ContainsKey(OAuth.DTOs.AuthorizationRequestParameters.ClientId))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.MISSING_CLIENT_ID_CLAIM);
            }

            if (!jwsPayload[OAuth.DTOs.AuthorizationRequestParameters.ResponseType].ToString().Split(' ').OrderBy(s => s).SequenceEqual(context.Request.Data.GetResponseTypesFromAuthorizationRequest()))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_RESPONSE_TYPE_CLAIM);
            }

            if (jwsPayload[OAuth.DTOs.AuthorizationRequestParameters.ClientId].ToString() != context.Client.ClientId)
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_CLIENT_ID_CLAIM);
            }

            context.Request.SetData(JObject.FromObject(jwsPayload));
            return(true);
        }
Esempio n. 23
0
        public virtual async Task <JObject> Handle(string clientId, HandlerContext handlerContext, CancellationToken cancellationToken)
        {
            var client = await GetClient(clientId, handlerContext, cancellationToken);

            return(BuildResponse(client, handlerContext.Request.IssuerName));
        }
Esempio n. 24
0
        private static Expression HandleFirst(HandlerContext handlerContext)
        {
            handlerContext.SelectExpression.Limit = 1;

            return(handlerContext.EvalOnClient);
        }
Esempio n. 25
0
        private BasicBlock BasicBlockFromIndex(int start, Context context)
        {
            if (start >= context.Block.Count)
                throw new InvalidOperationException("run off of end of instructions");

            var offset = context.Block[start].Offset;
            var i = start;

            Func<int, Instructions> extractInclusive = j => context.Block.Peephole(start, j - start + 1, tracer);
            Func<int, Instructions> extractExclusive = j => context.Block.Peephole(start, j - start, tracer);

            while (i < context.Block.Count)
            {
                var instruction = context.Block[i];

                if (i > start && targets.Contains(instruction.Offset))
                {
                    var jbb = new JumpBasicBlock(nextBlockId++, extractExclusive(i));
                    context.OffsetToBlock.Add(offset, jbb);
                    jbb.Target = BasicBlockFromLocalTarget(instruction.Offset, context);
                    jbb.Target.Sources.Add(jbb);
                    return jbb;
                }
                else
                {
                    switch (instruction.Flavor)
                    {
                    case InstructionFlavor.Misc:
                        {
                            var misci = (MiscInstruction)instruction;
                            switch (misci.Op)
                            {
                            case MiscOp.Throw:
                                {
                                    var nrbb = new NonReturningBasicBlock(nextBlockId++, extractInclusive(i));
                                    context.OffsetToBlock.Add(offset, nrbb);
                                    return nrbb;
                                }
                            case MiscOp.Rethrow:
                                {
                                    var handlerContext = context as HandlerContext;
                                    if (handlerContext == null ||
                                        !(handlerContext.ILHandler is CatchTryInstructionHandler))
                                        throw new InvalidOperationException("rethrow not within catch");
                                    var nrbb = new NonReturningBasicBlock(nextBlockId++, extractInclusive(i));
                                    context.OffsetToBlock.Add(offset, nrbb);
                                    return nrbb;
                                }
                            case MiscOp.Ret:
                            case MiscOp.RetVal:
                                {
                                    if (context is TryContext || context is HandlerContext)
                                        throw new InvalidOperationException("return within a try or handler block");
                                    var nrbb = new NonReturningBasicBlock(nextBlockId++, extractInclusive(i));
                                    context.OffsetToBlock.Add(offset, nrbb);
                                    return nrbb;
                                }
                            case MiscOp.Endfinally:
                                {
                                    var handlerContext = context as HandlerContext;
                                    if (handlerContext == null)
                                        throw new InvalidOperationException
                                            ("endfinally not within fault/finally block");
                                    switch (handlerContext.ILHandler.Flavor)
                                    {
                                    case HandlerFlavor.Catch:
                                    case HandlerFlavor.Filter:
                                        throw new InvalidOperationException
                                            ("endfinally not within fault/finally block");
                                    case HandlerFlavor.Fault:
                                        {
                                            var efbb = new EndFaultBasicBlock
                                                (nextBlockId++,
                                                 extractExclusive(i),
                                                 (TBBFaultHandler)handlerContext.TBBHandler);
                                            context.OffsetToBlock.Add(offset, efbb);
                                            return efbb;
                                        }
                                    case HandlerFlavor.Finally:
                                        {
                                            var efbb = new EndFinallyBasicBlock
                                                (nextBlockId++,
                                                 extractExclusive(i),
                                                 (TBBFinallyHandler)handlerContext.TBBHandler,
                                                 misci.BeforeState.Depth);
                                            context.OffsetToBlock.Add(offset, efbb);
                                            return efbb;
                                        }
                                    default:
                                        throw new ArgumentOutOfRangeException();
                                    }
                                }
                            default:
                                break;
                            }
                            break;
                        }
                    case InstructionFlavor.Branch:
                        {
                            var bri = (BranchInstruction)instruction;
                            switch (bri.Op)
                            {
                            case BranchOp.Br:
                                {
                                    var jbb = new JumpBasicBlock(nextBlockId++, extractExclusive(i));
                                    context.OffsetToBlock.Add(offset, jbb);
                                    jbb.Target = BasicBlockFromLocalTarget(bri.Target, context);
                                    jbb.Target.Sources.Add(jbb);
                                    return jbb;
                                }
                            case BranchOp.Brtrue:
                            case BranchOp.Brfalse:
                            case BranchOp.Breq:
                            case BranchOp.Brne:
                            case BranchOp.BrLt:
                            case BranchOp.BrLe:
                            case BranchOp.BrGt:
                            case BranchOp.BrGe:
                                {
                                    if (i + 1 >= context.Block.Count)
                                        throw new InvalidOperationException("run off end of instructions");
                                    var bbb = new BranchBasicBlock
                                        (nextBlockId++,
                                         extractExclusive(i),
                                         Test.FromBranchOp(bri.Op, bri.IsUnsigned, bri.Type));
                                    context.OffsetToBlock.Add(offset, bbb);
                                    bbb.Target = BasicBlockFromLocalTarget(bri.Target, context);
                                    bbb.Target.Sources.Add(bbb);
                                    bbb.Fallthrough = BasicBlockFromLocalTarget(context.Block[i + 1].Offset, context);
                                    if (!bbb.Fallthrough.Equals(bbb.Target))
                                        bbb.Fallthrough.Sources.Add(bbb);
                                    return bbb;
                                }
                            case BranchOp.Leave:
                                {
                                    var handlerPopCount = default(int);
                                    var stackPopCount = bri.BeforeState.Depth;
                                    var leftContext = default(bool);
                                    var bb = BasicBlockFromTarget
                                        (bri.Target, context, out leftContext, out handlerPopCount);
                                    if (!leftContext)
                                    {
                                        // Not leaving try or handler block, so just empty stack and branch
                                        var lbb = new LeaveBasicBlock
                                            (nextBlockId++, extractExclusive(i), stackPopCount);
                                        context.OffsetToBlock.Add(offset, lbb);
                                        lbb.Target = bb;
                                        lbb.Target.Sources.Add(lbb);
                                        return lbb;
                                    }
                                    else
                                    {
                                        var tryContext = context as TryContext;
                                        if (tryContext != null)
                                        {
                                            // Poping at least one exception handler and branching
                                            var ltbb = new LeaveTryBasicBlock
                                                (nextBlockId++,
                                                 extractExclusive(i),
                                                 tryContext.TryBasicBlock,
                                                 handlerPopCount,
                                                 stackPopCount);
                                            context.OffsetToBlock.Add(offset, ltbb);
                                            ltbb.Target = bb;
                                            ltbb.Target.Sources.Add(ltbb);
                                            return ltbb;
                                        }
                                        else
                                        {
                                            var handlerContext = context as HandlerContext;
                                            if (handlerContext != null)
                                            {
                                                switch (handlerContext.ILHandler.Flavor)
                                                {
                                                case HandlerFlavor.Catch:
                                                    {
                                                        // Poping zero or more exception handlers and branching
                                                        var lcbb = new LeaveCatchBasicBlock
                                                            (nextBlockId++,
                                                             extractExclusive(i),
                                                             (TBBCatchHandler)handlerContext.TBBHandler,
                                                             handlerPopCount,
                                                             stackPopCount);
                                                        lcbb.Target = bb;
                                                        lcbb.Target.Sources.Add(lcbb);
                                                        return lcbb;
                                                    }
                                                case HandlerFlavor.Filter:
                                                    throw new NotSupportedException("filter");
                                                case HandlerFlavor.Fault:
                                                    throw new InvalidOperationException("leaving fault block");
                                                case HandlerFlavor.Finally:
                                                    throw new InvalidOperationException("leaving finally block");
                                                default:
                                                    throw new ArgumentOutOfRangeException();
                                                }
                                            }
                                            else
                                                throw new InvalidOperationException
                                                    ("no try or handler context to leave");
                                        }
                                    }
                                }
                            default:
                                throw new ArgumentOutOfRangeException();
                            }
                        }
                    case InstructionFlavor.Switch:
                        {
                            if (i + 1 >= context.Block.Count)
                                throw new InvalidOperationException("run off end of instructions");
                            var switchi = (SwitchInstruction)instruction;
                            var sbb = new SwitchBasicBlock(nextBlockId++, extractExclusive(i));
                            context.OffsetToBlock.Add(offset, sbb);
                            var seen = new Set<BasicBlock>();
                            foreach (var t in switchi.CaseTargets)
                            {
                                var target = BasicBlockFromLocalTarget(t, context);
                                sbb.CaseTargets.Add(target);
                                if (!seen.Contains(target))
                                {
                                    target.Sources.Add(sbb);
                                    seen.Add(target);
                                }
                            }
                            sbb.Fallthrough = BasicBlockFromLocalTarget(context.Block[i + 1].Offset, context);
                            if (!seen.Contains(sbb.Fallthrough))
                                sbb.Fallthrough.Sources.Add(sbb);
                            return sbb;
                        }
                    case InstructionFlavor.Try:
                        {
                            // Try is known to be a target, thus i == start and extract(i) would yield empty
                            var tryi = (TryInstruction)instruction;
                            var parent = default(TryBasicBlock);
                            var tryContext = context as TryContext;
                            if (tryContext != null)
                                parent = tryContext.TryBasicBlock;
                            else
                            {
                                var handlerContext = context as HandlerContext;
                                if (handlerContext != null)
                                    parent = handlerContext.TryContext.TryBasicBlock;
                            }
                            var tbb = new TryBasicBlock(nextBlockId++, parent, instruction.BeforeState);
                            context.OffsetToBlock.Add(offset, tbb);
                            var subTryContext = new TryContext(tryi.Body, context, tbb);
                            tbb.Body = BasicBlockFromInstructions(subTryContext);
                            tbb.Body.Sources.Add(tbb);
                            foreach (var ilHandler in tryi.Handlers)
                            {
                                var tbbHandler = default(TBBHandler);
                                switch (ilHandler.Flavor)
                                {
                                case HandlerFlavor.Catch:
                                    {
                                        var catchh = (CatchTryInstructionHandler)ilHandler;
                                        tbbHandler = new TBBCatchHandler(tbb, catchh.Type);
                                        break;
                                    }
                                case HandlerFlavor.Filter:
                                    throw new NotSupportedException("filter blocks");
                                case HandlerFlavor.Fault:
                                    {
                                        tbbHandler = new TBBFaultHandler(tbb);
                                        break;
                                    }
                                case HandlerFlavor.Finally:
                                    {
                                        tbbHandler = new TBBFinallyHandler(tbb);
                                        break;
                                    }
                                default:
                                    throw new ArgumentOutOfRangeException();
                                }
                                var subHandlerContext = new HandlerContext
                                    (ilHandler.Body, ilHandler, subTryContext, tbbHandler);
                                tbbHandler.Body = BasicBlockFromInstructions(subHandlerContext);
                                tbbHandler.Body.Sources.Add(tbb);
                                tbb.Handlers.Add(tbbHandler);
                            }
                            return tbb;
                        }
                    default:
                        break;
                    }
                    i++;
                }
            }
            throw new InvalidOperationException("ran off of end of instructions");
        }
Esempio n. 26
0
        private static Expression HandleSingle(HandlerContext handlerContext)
        {
            handlerContext.SelectExpression.Limit = 2;

            return(handlerContext.EvalOnClient);
        }
 public GetGalleryCategoryHandler(HandlerContext <GetGalleryCategoryHandler> context) : base(context)
 {
 }
Esempio n. 28
0
 protected virtual void RedirectToConsentView(HandlerContext context)
 {
     throw new OAuthUserConsentRequiredException();
 }
Esempio n. 29
0
 public override void OnDisconnected(HandlerContext ctx)
 {
 }
Esempio n. 30
0
        public virtual async Task Validate(HandlerContext context, CancellationToken cancellationToken)
        {
            var openidClient = (OpenIdClient)context.Client;
            var clientId     = context.Request.Data.GetClientIdFromAuthorizationRequest();
            var scopes       = context.Request.Data.GetScopesFromAuthorizationRequest();
            var acrValues    = context.Request.Data.GetAcrValuesFromAuthorizationRequest();
            var prompt       = context.Request.Data.GetPromptFromAuthorizationRequest();
            var claims       = context.Request.Data.GetClaimsFromAuthorizationRequest();

            if (!scopes.Any())
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(OAuth.ErrorMessages.MISSING_PARAMETER, OAuth.DTOs.AuthorizationRequestParameters.Scope));
            }

            if (!scopes.Contains(SIDOpenIdConstants.StandardScopes.OpenIdScope.Name))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.OPENID_SCOPE_MISSING);
            }

            var unsupportedScopes = scopes.Where(s => s != SIDOpenIdConstants.StandardScopes.OpenIdScope.Name && !context.Client.AllowedScopes.Any(sc => sc.Name == s));

            if (unsupportedScopes.Any())
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(OAuth.ErrorMessages.UNSUPPORTED_SCOPES, string.Join(",", unsupportedScopes)));
            }

            if (context.User == null)
            {
                if (prompt == PromptParameters.None)
                {
                    throw new OAuthException(ErrorCodes.LOGIN_REQUIRED, OAuth.ErrorMessages.LOGIN_IS_REQUIRED);
                }

                throw new OAuthLoginRequiredException(await GetFirstAmr(acrValues, claims, openidClient, cancellationToken));
            }

            if (!await CheckRequestParameter(context))
            {
                await CheckRequestUriParameter(context);
            }

            var responseTypes = context.Request.Data.GetResponseTypesFromAuthorizationRequest();
            var nonce         = context.Request.Data.GetNonceFromAuthorizationRequest();
            var redirectUri   = context.Request.Data.GetRedirectUriFromAuthorizationRequest();
            var maxAge        = context.Request.Data.GetMaxAgeFromAuthorizationRequest();
            var idTokenHint   = context.Request.Data.GetIdTokenHintFromAuthorizationRequest();

            if (string.IsNullOrWhiteSpace(redirectUri))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(OAuth.ErrorMessages.MISSING_PARAMETER, OAuth.DTOs.AuthorizationRequestParameters.RedirectUri));
            }

            if (responseTypes.Contains(TokenResponseParameters.IdToken) && string.IsNullOrWhiteSpace(nonce))
            {
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(OAuth.ErrorMessages.MISSING_PARAMETER, OpenID.DTOs.AuthorizationRequestParameters.Nonce));
            }

            if (maxAge != null)
            {
                if (DateTime.UtcNow > context.User.AuthenticationTime.Value.AddSeconds(maxAge.Value))
                {
                    throw new OAuthLoginRequiredException(await GetFirstAmr(acrValues, claims, openidClient, cancellationToken));
                }
            }
            else if (openidClient.DefaultMaxAge != null && DateTime.UtcNow > context.User.AuthenticationTime.Value.AddSeconds(openidClient.DefaultMaxAge.Value))
            {
                throw new OAuthLoginRequiredException(await GetFirstAmr(acrValues, claims, openidClient, cancellationToken));
            }

            if (!string.IsNullOrWhiteSpace(idTokenHint))
            {
                var payload = await ExtractIdTokenHint(idTokenHint);

                if (context.User.Id != payload.GetSub())
                {
                    throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_SUBJECT_IDTOKENHINT);
                }

                if (!payload.GetAudiences().Contains(context.Request.IssuerName))
                {
                    throw new OAuthException(ErrorCodes.INVALID_REQUEST, ErrorMessages.INVALID_AUDIENCE_IDTOKENHINT);
                }
            }

            switch (prompt)
            {
            case PromptParameters.Login:
                throw new OAuthLoginRequiredException(await GetFirstAmr(acrValues, claims, openidClient, cancellationToken));

            case PromptParameters.Consent:
                RedirectToConsentView(context);
                break;

            case PromptParameters.SelectAccount:
                throw new OAuthSelectAccountRequiredException();
            }

            if (!context.User.HasOpenIDConsent(clientId, scopes, claims))
            {
                RedirectToConsentView(context);
            }

            if (claims != null)
            {
                var idtokenClaims = claims.Where(cl => cl.Type == AuthorizationRequestClaimTypes.IdToken && cl.IsEssential && Jwt.Constants.USER_CLAIMS.Contains(cl.Name));
                var invalidClaims = idtokenClaims.Where(icl => !context.User.Claims.Any(cl => cl.Type == icl.Name && (icl.Values == null || !icl.Values.Any() || icl.Values.Contains(cl.Value))));
                if (invalidClaims.Any())
                {
                    throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.INVALID_CLAIMS, string.Join(",", invalidClaims.Select(i => i.Name))));
                }
            }
        }
Esempio n. 31
0
        public string Play()
        {
            if (handlerData.ForceFinishOnPlay)
            {
                ProcessUtil.ForceKill(Path.GetFileNameWithoutExtension(handlerData.ExecutableName.ToLower()));
            }

            List <PlayerInfo> players = profile.PlayerData;

            for (int i = 0; i < players.Count; i++)
            {
                players[i].PlayerID = i;
            }

            UserScreen[] all = ScreensUtil.AllScreens();

            string nucleusRootFolder = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

            string tempDir       = GameManager.Instance.GempTempFolder(handlerData);
            string exeFolder     = Path.GetDirectoryName(userGame.ExePath).ToLower();
            string rootFolder    = exeFolder;
            string workingFolder = exeFolder;

            if (!string.IsNullOrEmpty(handlerData.BinariesFolder))
            {
                rootFolder = StringUtil.ReplaceCaseInsensitive(exeFolder, handlerData.BinariesFolder.ToLower(), "");
            }
            if (!string.IsNullOrEmpty(handlerData.WorkingFolder))
            {
                workingFolder = Path.Combine(exeFolder, handlerData.WorkingFolder.ToLower());
            }

            bool first    = true;
            bool keyboard = false;

            //if (handlerData.SupportsKeyboard)
            //{
            //    // make sure the keyboard player is the last to be started,
            //    // so it will get the focus by default
            //    KeyboardPlayer player = (KeyboardPlayer)profile.Options["KeyboardPlayer"];
            //    if (player.Value != -1)
            //    {
            //        keyboard = true;
            //        List<PlayerInfo> newPlayers = new List<PlayerInfo>();

            //        for (int i = 0; i < players.Count; i++)
            //        {
            //            PlayerInfo p = players[i];
            //            if (i == player.Value)
            //            {
            //                continue;
            //            }

            //            newPlayers.Add(p);
            //        }
            //        newPlayers.Add(players[player.Value]);
            //        players = newPlayers;
            //    }
            //}

            for (int i = 0; i < players.Count; i++)
            {
                PlayerInfo  player    = players[i];
                ProcessInfo procData  = player.ProcessData;
                bool        hasSetted = procData != null && procData.Setted;

                if (i > 0 && (handlerData.KillMutex?.Length > 0 || !hasSetted))
                {
                    PlayerInfo before = players[i - 1];
                    for (; ;)
                    {
                        if (exited > 0)
                        {
                            return("");
                        }
                        Thread.Sleep(1000);

                        if (handlerData.KillMutex != null)
                        {
                            if (handlerData.KillMutex.Length > 0 && !before.ProcessData.KilledMutexes)
                            {
                                // check for the existence of the mutexes
                                // before invoking our StartGame app to kill them
                                ProcessInfo pdata = before.ProcessData;

                                if (StartGameUtil.MutexExists(pdata.Process, handlerData.KillMutex))
                                {
                                    // mutexes still exist, must kill
                                    StartGameUtil.KillMutex(pdata.Process, handlerData.KillMutex);
                                    pdata.KilledMutexes = true;
                                    break;
                                }
                                else
                                {
                                    // mutexes dont exist anymore
                                    break;
                                }
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                Rectangle  playerBounds = player.MonitorBounds;
                UserScreen owner        = player.Owner;

                int  width        = playerBounds.Width;
                int  height       = playerBounds.Height;
                bool isFullscreen = owner.Type == UserScreenType.FullScreen;

                string exePath;
                string linkFolder;
                string linkBinFolder;

                if (handlerData.SymlinkGame || handlerData.HardcopyGame)
                {
                    List <string> dirExclusions  = new List <string>();
                    List <string> fileExclusions = new List <string>();
                    List <string> fileCopies     = new List <string>();

                    // symlink the game folder (and not the bin folder, if we have one)
                    linkFolder = Path.Combine(tempDir, "Instance" + i);
                    Directory.CreateDirectory(linkFolder);

                    linkBinFolder = linkFolder;
                    if (!string.IsNullOrEmpty(handlerData.BinariesFolder))
                    {
                        linkBinFolder = Path.Combine(linkFolder, handlerData.BinariesFolder);
                        dirExclusions.Add(handlerData.BinariesFolder);
                    }
                    exePath = Path.Combine(linkBinFolder, Path.GetFileName(this.userGame.ExePath));

                    if (!string.IsNullOrEmpty(handlerData.WorkingFolder))
                    {
                        linkBinFolder = Path.Combine(linkFolder, handlerData.WorkingFolder);
                        dirExclusions.Add(handlerData.WorkingFolder);
                    }

                    // some games have save files inside their game folder, so we need to access them inside the loop
                    jsData[Folder.InstancedGameFolder.ToString()] = linkFolder;

                    if (handlerData.Hook.CustomDllEnabled)
                    {
                        fileExclusions.Add("xinput1_3.dll");
                        fileExclusions.Add("ncoop.ini");
                    }
                    if (!handlerData.SymlinkExe)
                    {
                        fileCopies.Add(handlerData.ExecutableName.ToLower());
                    }

                    // additional ignored files by the generic info
                    if (handlerData.FileSymlinkExclusions != null)
                    {
                        string[] symlinkExclusions = handlerData.FileSymlinkExclusions;
                        for (int k = 0; k < symlinkExclusions.Length; k++)
                        {
                            string s = symlinkExclusions[k];
                            // make sure it's lower case
                            fileExclusions.Add(s.ToLower());
                        }
                    }
                    if (handlerData.FileSymlinkCopyInstead != null)
                    {
                        string[] fileSymlinkCopyInstead = handlerData.FileSymlinkCopyInstead;
                        for (int k = 0; k < fileSymlinkCopyInstead.Length; k++)
                        {
                            string s = fileSymlinkCopyInstead[k];
                            // make sure it's lower case
                            fileCopies.Add(s.ToLower());
                        }
                    }
                    if (handlerData.DirSymlinkExclusions != null)
                    {
                        string[] symlinkExclusions = handlerData.DirSymlinkExclusions;
                        for (int k = 0; k < symlinkExclusions.Length; k++)
                        {
                            string s = symlinkExclusions[k];
                            // make sure it's lower case
                            dirExclusions.Add(s.ToLower());
                        }
                    }

                    string[] fileExclusionsArr = fileExclusions.ToArray();
                    string[] fileCopiesArr     = fileCopies.ToArray();

                    if (handlerData.HardcopyGame)
                    {
                        // copy the directory
                        //int exitCode;
                        //FileUtil.CopyDirectory(rootFolder, new DirectoryInfo(rootFolder), linkFolder, out exitCode, dirExclusions.ToArray(), fileExclusionsArr, true);
                    }
                    else
                    {
                        int exitCode;
                        CmdUtil.LinkDirectory(rootFolder, new DirectoryInfo(rootFolder), linkFolder, out exitCode, dirExclusions.ToArray(), fileExclusionsArr, fileCopiesArr, true);

                        if (!handlerData.SymlinkExe)
                        {
                            //File.Copy(userGame.ExePath, exePath, true);
                        }
                    }
                }
                else
                {
                    exePath       = userGame.ExePath;
                    linkBinFolder = rootFolder;
                    linkFolder    = workingFolder;
                }

                HandlerContext context = handlerData.CreateContext(profile, player);
                context.PlayerID     = player.PlayerID;
                context.IsFullscreen = isFullscreen;

                context.ExePath           = exePath;
                context.RootInstallFolder = exeFolder;
                context.RootFolder        = linkFolder;

                handlerData.PrePlay(context, player);

                string startArgs = context.StartArguments;

                if (context.Hook.CustomDllEnabled)
                {
                    byte[] xdata = Properties.Resources.xinput1_3;
                    if (context.Hook.XInputNames == null)
                    {
                        using (Stream str = File.OpenWrite(Path.Combine(linkBinFolder, "xinput1_3.dll")))
                        {
                            str.Write(xdata, 0, xdata.Length);
                        }
                    }
                    else
                    {
                        string[] xinputs = context.Hook.XInputNames;
                        for (int z = 0; z < xinputs.Length; z++)
                        {
                            string xinputName = xinputs[z];
                            using (Stream str = File.OpenWrite(Path.Combine(linkBinFolder, xinputName)))
                            {
                                str.Write(xdata, 0, xdata.Length);
                            }
                        }
                    }

                    string ncoopIni = Path.Combine(linkBinFolder, "ncoop.ini");
                    using (Stream str = File.OpenWrite(ncoopIni))
                    {
                        byte[] ini = Properties.Resources.ncoop;
                        str.Write(ini, 0, ini.Length);
                    }

                    IniFile x360 = new IniFile(ncoopIni);
                    x360.IniWriteValue("Options", "ForceFocus", handlerData.Hook.ForceFocus.ToString(CultureInfo.InvariantCulture));
                    x360.IniWriteValue("Options", "ForceFocusWindowName", handlerData.Hook.ForceFocusWindowName.ToString(CultureInfo.InvariantCulture));

                    x360.IniWriteValue("Options", "WindowX", playerBounds.X.ToString(CultureInfo.InvariantCulture));
                    x360.IniWriteValue("Options", "WindowY", playerBounds.Y.ToString(CultureInfo.InvariantCulture));

                    if (context.Hook.SetWindowSize)
                    {
                        x360.IniWriteValue("Options", "ResWidth", context.Width.ToString(CultureInfo.InvariantCulture));
                        x360.IniWriteValue("Options", "ResHeight", context.Height.ToString(CultureInfo.InvariantCulture));
                    }
                    else
                    {
                        x360.IniWriteValue("Options", "ResWidth", "0");
                        x360.IniWriteValue("Options", "ResHeight", "0");
                    }

                    x360.IniWriteValue("Options", "RerouteInput", context.Hook.XInputReroute.ToString(CultureInfo.InvariantCulture));
                    x360.IniWriteValue("Options", "RerouteJoystickTemplate", JoystickDatabase.GetID(player.GamepadProductGuid.ToString()).ToString(CultureInfo.InvariantCulture));

                    x360.IniWriteValue("Options", "EnableMKBInput", player.IsKeyboardPlayer.ToString(CultureInfo.InvariantCulture));

                    // windows events
                    x360.IniWriteValue("Options", "BlockInputEvents", context.Hook.BlockInputEvents.ToString(CultureInfo.InvariantCulture));
                    x360.IniWriteValue("Options", "BlockMouseEvents", context.Hook.BlockMouseEvents.ToString(CultureInfo.InvariantCulture));
                    x360.IniWriteValue("Options", "BlockKeyboardEvents", context.Hook.BlockKeyboardEvents.ToString(CultureInfo.InvariantCulture));

                    // xinput
                    x360.IniWriteValue("Options", "XInputEnabled", context.Hook.XInputEnabled.ToString(CultureInfo.InvariantCulture));
                    x360.IniWriteValue("Options", "XInputPlayerID", player.GamepadId.ToString(CultureInfo.InvariantCulture));

                    // dinput
                    x360.IniWriteValue("Options", "DInputEnabled", context.Hook.DInputEnabled.ToString(CultureInfo.InvariantCulture));
                    x360.IniWriteValue("Options", "DInputGuid", player.GamepadGuid.ToString().ToUpper());
                    x360.IniWriteValue("Options", "DInputForceDisable", context.Hook.DInputForceDisable.ToString());
                }

                Process proc;
                if (context.NeedsSteamEmulation)
                {
                    string steamEmu = GameManager.Instance.ExtractSteamEmu(Path.Combine(linkFolder, "SmartSteamLoader"));
                    //string steamEmu = GameManager.Instance.ExtractSteamEmu();
                    if (string.IsNullOrEmpty(steamEmu))
                    {
                        return("Extraction of SmartSteamEmu failed!");
                    }

                    string  emuExe = Path.Combine(steamEmu, "SmartSteamLoader.exe");
                    string  emuIni = Path.Combine(steamEmu, "SmartSteamEmu.ini");
                    IniFile emu    = new IniFile(emuIni);

                    emu.IniWriteValue("Launcher", "Target", exePath);
                    emu.IniWriteValue("Launcher", "StartIn", Path.GetDirectoryName(exePath));
                    emu.IniWriteValue("Launcher", "CommandLine", startArgs);
                    emu.IniWriteValue("Launcher", "SteamClientPath", Path.Combine(steamEmu, "SmartSteamEmu.dll"));
                    emu.IniWriteValue("Launcher", "SteamClientPath64", Path.Combine(steamEmu, "SmartSteamEmu64.dll"));
                    emu.IniWriteValue("Launcher", "InjectDll", "1");

                    emu.IniWriteValue("SmartSteamEmu", "AppId", context.SteamID);
                    //emu.IniWriteValue("SmartSteamEmu", "SteamIdGeneration", "Static");

                    //string userName = $"Player { context.PlayerID }";

                    //emu.IniWriteValue("SmartSteamEmu", "PersonaName", userName);
                    //emu.IniWriteValue("SmartSteamEmu", "ManualSteamId", userName);

                    //emu.IniWriteValue("SmartSteamEmu", "Offline", "False");
                    //emu.IniWriteValue("SmartSteamEmu", "MasterServer", "");
                    //emu.IniWriteValue("SmartSteamEmu", "MasterServerGoldSrc", "");

                    handlerData.SetupSse?.Invoke();

                    if (context.KillMutex?.Length > 0)
                    {
                        // to kill the mutexes we need to orphanize the process
                        proc = ProcessUtil.RunOrphanProcess(emuExe);
                    }
                    else
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo();
                        startInfo.FileName = emuExe;
                        proc = Process.Start(startInfo);
                    }

                    player.SteamEmu = true;
                }
                else
                {
                    if (context.KillMutex?.Length > 0)
                    {
                        proc = Process.GetProcessById(StartGameUtil.StartGame(
                                                          new DirectoryInfo(exePath).GetRelativePath(nucleusRootFolder), startArgs,
                                                          new DirectoryInfo(linkFolder).GetRelativePath(nucleusRootFolder)));
                    }
                    else
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo();
                        startInfo.FileName = exePath;
                        //startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        startInfo.Arguments        = startArgs;
                        startInfo.UseShellExecute  = true;
                        startInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
                        proc = Process.Start(startInfo);
                    }

                    if (proc == null)
                    {
                        for (int times = 0; times < 200; times++)
                        {
                            Thread.Sleep(50);

                            Process[] procs        = Process.GetProcesses();
                            string    proceName    = Path.GetFileNameWithoutExtension(context.ExecutableName).ToLower();
                            string    launcherName = Path.GetFileNameWithoutExtension(context.LauncherExe).ToLower();

                            for (int j = 0; j < procs.Length; j++)
                            {
                                Process p      = procs[j];
                                string  lowerP = p.ProcessName.ToLower();
                                if (((lowerP == proceName) || lowerP == launcherName) &&
                                    !attached.Contains(p))
                                {
                                    attached.Add(p);
                                    proc = p;
                                    break;
                                }
                            }

                            if (proc != null)
                            {
                                break;
                            }
                        }
                    }
                    else
                    {
                        attached.Add(proc);
                    }
                }

                ProcessInfo data = new ProcessInfo(proc);

                data.Position      = new Point(playerBounds.X, playerBounds.Y);
                data.Size          = new Size(playerBounds.Width, playerBounds.Height);
                data.KilledMutexes = context.KillMutex?.Length == 0;
                player.ProcessData = data;

                first = false;

                Thread.Sleep(TimeSpan.FromSeconds(handlerData.PauseBetweenStarts));
            }

            return(string.Empty);
        }
Esempio n. 32
0
        private static Expression HandleContains(HandlerContext handlerContext)
        {
            var filteringVisitor = handlerContext.CreateSqlTranslatingVisitor();

            var itemResultOperator = (ContainsResultOperator)handlerContext.ResultOperator;

            var item = filteringVisitor.Visit(itemResultOperator.Item);

            if (item != null)
            {
                if (item is SelectExpression itemSelectExpression)
                {
                    var queryCompilationContext = handlerContext.QueryModelVisitor.QueryCompilationContext;
                    var entityType = queryCompilationContext.FindEntityType(handlerContext.QueryModel.MainFromClause)
                                     ?? handlerContext.Model.FindEntityType(handlerContext.QueryModel.MainFromClause.ItemType);

                    if (entityType != null)
                    {
                        var outerSelectExpression = handlerContext.SelectExpressionFactory.Create(queryCompilationContext);

                        var collectionSelectExpression
                            = handlerContext.SelectExpression.Clone(queryCompilationContext.CreateUniqueTableAlias());
                        outerSelectExpression.AddTable(collectionSelectExpression);

                        itemSelectExpression.Alias = queryCompilationContext.CreateUniqueTableAlias();
                        var joinExpression = outerSelectExpression.AddInnerJoin(itemSelectExpression);

                        foreach (var property in entityType.FindPrimaryKey().Properties)
                        {
                            var itemProperty = itemSelectExpression.BindProperty(
                                property,
                                itemSelectExpression.ProjectStarTable.QuerySource);

                            itemSelectExpression.AddToProjection(itemProperty);

                            var collectionProperty = collectionSelectExpression.BindProperty(
                                property,
                                collectionSelectExpression.ProjectStarTable.QuerySource);

                            collectionSelectExpression.AddToProjection(collectionProperty);

                            var predicate = Expression.Equal(
                                collectionProperty.LiftExpressionFromSubquery(collectionSelectExpression),
                                itemProperty.LiftExpressionFromSubquery(itemSelectExpression));

                            joinExpression.Predicate
                                = joinExpression.Predicate == null
                                    ? predicate
                                    : Expression.AndAlso(
                                      joinExpression.Predicate,
                                      predicate);
                        }

                        SetConditionAsProjection(
                            handlerContext,
                            new ExistsExpression(outerSelectExpression));

                        return(TransformClientExpression <bool>(handlerContext));
                    }
                }

                SetConditionAsProjection(
                    handlerContext,
                    new InExpression(
                        item,
                        handlerContext.SelectExpression.Clone("")));

                return(TransformClientExpression <bool>(handlerContext));
            }

            return(handlerContext.EvalOnClient());
        }
 public GetFilesCategoriesHandler(HandlerContext <GetFilesCategoriesHandler> context) : base(context)
 {
 }