Esempio n. 1
0
        /// <summary>
        /// 还书通知
        /// </summary>
        private void ResponseGiveBackBookNoticeMsg(string toReaders, string first, string name, string date, string remark)
        {
            string    tempID                = ConfigurationManager.AppSettings["GiveBackBookNoticeID"];//模板ID
            string    access_tocken         = Com.IsExistAccess_Token(ConfigurationManager.AppSettings["AppID"], ConfigurationManager.AppSettings["AppSecret"]);
            SendTools tools                 = new SendTools();
            GiveBackBookNoticeTempData data = new GiveBackBookNoticeTempData();

            data.first  = new TempItem(first);
            data.name   = new TempItem(name);
            data.date   = new TempItem(date);
            data.remark = new TempItem(remark);
            TempModel model = new TempModel();

            model.objGiveBackBookNoticeTempData = data;
            model.template_id = tempID;
            model.url         = ConfigurationManager.AppSettings["GiveBackBookNotice_URL"];
            model.topcolor    = "#FF0000";
            //处理学号toReaders,逗号隔开
            string[] readers = toReaders.Split(',');
            foreach (var item in readers)
            {
                string OPENID = SqlTools.GetOpenId(item);
                if (OPENID != "")
                {
                    model.touser = OPENID;
                    OpenApiResult result = tools.SendTempMessage(access_tocken, model);
                }
            }
        }
Esempio n. 2
0
        public async Task <OpenApiResult> ListPets(int limit = 10, string?continuationToken = null)
        {
            int skip = ParseContinuationToken(continuationToken);

            PetResource[] pets = this.pets.Skip(skip).Take(limit).ToArray();

            string?     nextContinuationToken = (skip + limit < this.pets.Count) ? BuildContinuationToken(limit + skip) : null;
            HalDocument response = await this.petListMapper.MapAsync(
                new PetListResource(pets)
            {
                TotalCount = this.pets.Count,
                PageSize   = limit,
                CurrentContinuationToken = continuationToken,
                NextContinuationToken    = nextContinuationToken,
            }).ConfigureAwait(false);

            OpenApiResult result = this.OkResult(response, "application/hal+json");

            // We also add the next page link to the header, just to demonstrate that it's possible
            // to use WebLink items in this way.
            WebLink nextLink = response.GetLinksForRelation("next").FirstOrDefault();

            if (nextLink != default)
            {
                result.Results.Add("x-next", nextLink.Href);
            }

            result.AddAuditData(("skip", skip), ("limit", limit));

            return(result);
        }
Esempio n. 3
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, ClaimPermissions Result)> CreateClaimPermissionsAsync(ClaimPermissions newClaimPermissions)
        {
            OpenApiResult result = await this.claimsService.CreateClaimPermissionsAsync(this.MakeOpenApiContext(), newClaimPermissions);

            result.Results.TryGetValue("application/json", out object claimPermissions);
            return(result.StatusCode, claimPermissions as ClaimPermissions);
        }
Esempio n. 4
0
        private static OpenApiResult GetOpenApiResultForPoco(object result, OpenApiOperation operation, ILogger logger)
        {
            logger.LogDebug(
                "Attempting to get OpenAPI result for with POCO with [{operation}]",
                operation.GetOperationId());
#pragma warning disable IDE0007 // Use implicit type - see https://github.com/dotnet/roslyn/issues/30450
            List <KeyValuePair <string, OpenApiResponse> > successResponses = operation
#pragma warning restore IDE0007 // Use implicit type
                                                                              .Responses
                                                                              .Where(r => r.Key == "default" || (r.Key.Length == 3 && r.Key[0] == '2'))
                                                                              .ToList();
            if (successResponses.Count != 1)
            {
                throw new OpenApiServiceMismatchException($"An OpenApi service can only return a plain old CLR object (POCO) for operations that define exactly one success response (including the default response, if present), but '{operation.OperationId}' defines '{successResponses.Count}'. Return an {nameof(OpenApiResult)} instead, or modify the service definition to define a single successful response.");
            }

            KeyValuePair <string, OpenApiResponse> response = successResponses.Single();
            var openApiResult = new OpenApiResult
            {
                // Use the status code for the first response
                StatusCode = int.Parse(response.Key),
            };

            foreach (KeyValuePair <string, OpenApiMediaType> mediaType in response.Value.Content)
            {
                // Add all our candidate media types in
                openApiResult.Results.Add(mediaType.Key, result);
            }

            logger.LogDebug(
                "Got openAPIResult [{apiResult}] for poco with [{operation}]",
                openApiResult.Results.Keys,
                operation.GetOperationId());
            return(openApiResult);
        }
Esempio n. 5
0
        public async Task <OpenApiResult> GetContentHistory(string tenantId, string slug, int?limit, string continuationToken, string ifNoneMatch)
        {
            IContentStore contentStore = await this.contentStoreFactory.GetContentStoreForTenantAsync(tenantId).ConfigureAwait(false);

            ContentSummaries result = await contentStore.GetContentSummariesAsync(slug, limit ?? 20, continuationToken).ConfigureAwait(false);

            string resultEtag = EtagHelper.BuildEtag(nameof(ContentSummary), result.Summaries.Select(x => x.ETag).ToArray());

            // If the etag in the result matches ifNoneMatch then we return 304 Not Modified
            if (EtagHelper.IsMatch(ifNoneMatch, resultEtag))
            {
                return(this.NotModifiedResult());
            }

            var mappingContext = new ContentSummariesResponseMappingContext
            {
                ContinuationToken = continuationToken,
                Limit             = limit,
                Slug     = slug,
                TenantId = tenantId,
            };

            HalDocument resultDocument = this.contentSummariesMapper.Map(result, mappingContext);

            OpenApiResult response = this.OkResult(resultDocument);

            response.Results.Add(HeaderNames.ETag, resultEtag);

            return(response);
        }
Esempio n. 6
0
        public async Task <OpenApiResult> GetContentSummary(IOpenApiContext context, string slug, string contentId, string ifNoneMatch)
        {
            IContentStore contentStore = await this.contentStoreFactory.GetContentStoreForTenantAsync(context.CurrentTenantId).ConfigureAwait(false);

            ContentSummary result = await contentStore.GetContentSummaryAsync(contentId, slug).ConfigureAwait(false);

            string etag = EtagHelper.BuildEtag(nameof(ContentSummary), result.ETag);

            // If the etag in the result matches ifNoneMatch then we return 304 Not Modified
            if (EtagHelper.IsMatch(ifNoneMatch, etag))
            {
                return(this.NotModifiedResult());
            }

            HalDocument resultDocument = this.contentSummaryMapper.Map(result, new ResponseMappingContext {
                TenantId = context.CurrentTenantId
            });

            OpenApiResult response = this.OkResult(resultDocument);

            response.Results.Add(HeaderNames.ETag, etag);

            // Since content is immutable we can allow clients to cache it indefinitely.
            response.Results.Add(HeaderNames.CacheControl, Constants.CacheControlHeaderOptions.NeverExpire);

            return(response);
        }
        /// <inheritdoc/>
        public async Task <List <ResourceAccessEvaluation> > EvaluateAsync(string tenantId, IEnumerable <ResourceAccessSubmission> submissions)
        {
            var context = new Context
            {
                CurrentTenantId = tenantId,
            };

            OpenApiResult result = await this.service.GetClaimPermissionsPermissionBatchAsync(context, ToInternalModel(submissions)).ConfigureAwait(false);

            var results = (IList <ClaimPermissionsBatchResponseItem>)result.Results["application/json"];

            // If any of the requests didn't return an OK result, we need to log a warning, as this is most likely due to
            // misconfiguration of the claims service (e.g. a missing ClaimPermissionsId). The caller may still be able to carry
            // on and evaluate the remaining results.
            foreach (ClaimPermissionsBatchResponseItem r in results.Where(x => x.ResponseCode != (int)HttpStatusCode.OK))
            {
                this.logger.LogWarning(
                    "Claims service returned [{statusCode}] permission evaluation for claim permission ID [{claimPermissionID}] accessing resource [{resourceUri}], [{httpMethod}]",
                    r.ResponseCode,
                    r.ClaimPermissionsId,
                    r.ResourceUri,
                    r.ResourceAccessType);
            }

            return(results
                   .Where(x => x.ResponseCode == (int)HttpStatusCode.OK)
                   .Select(x => new ResourceAccessEvaluation
            {
                Result = new PermissionResult
                {
                    Permission = Enum.TryParse(x.Permission, true, out Permission permission) ? permission : throw new FormatException(),
                },
Esempio n. 8
0
        /// <summary>
        /// 图书馆借书成功通知
        /// </summary>
        private void ResponseBorrowBooksSucceedNoticeMsg(string toReaders, string first, string keyword1, string keyword2, string keyword3, string keyword4, string remark)
        {
            string    tempID        = ConfigurationManager.AppSettings["BorrowBooksSucceedID"];//模板ID
            string    access_tocken = Com.IsExistAccess_Token(ConfigurationManager.AppSettings["AppID"], ConfigurationManager.AppSettings["AppSecret"]);
            SendTools tools         = new SendTools();
            ActivityToBeginningNoticeTempData data = new ActivityToBeginningNoticeTempData();

            data.first    = new TempItem(first);
            data.keyword1 = new TempItem(keyword1);
            data.keyword2 = new TempItem(keyword2);
            data.keyword3 = new TempItem(keyword3);
            data.keyword4 = new TempItem(keyword4);
            data.remark   = new TempItem(remark);

            TempModel model = new TempModel();

            model.objActivityToBeginningNoticeTempData = data;
            model.template_id = tempID;
            model.url         = ConfigurationManager.AppSettings["BorrowBooksSucceed_URL"];
            model.topcolor    = "#FF0000";
            //处理学号toReaders,逗号隔开
            string[] readers = toReaders.Split(',');
            foreach (var item in readers)
            {
                string OPENID = SqlTools.GetOpenId(item);
                if (OPENID != "")
                {
                    model.touser = OPENID;
                    OpenApiResult result = tools.SendTempMessage(access_tocken, model);
                }
            }
        }
Esempio n. 9
0
        public async Task WhenICallOperationsControlOpenApiService_CreateOperationWithId(Guid operationId)
        {
            OpenApiResult result = await this.service.CreateOperation(
                this.transientTenantManager.PrimaryTransientClient.Id,
                operationId).ConfigureAwait(false);

            this.scenarioContext.Set(result);
        }
Esempio n. 10
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, ResourceAccessRuleSet Result)> CreateResourceAccessRuleSetAsync(ResourceAccessRuleSet newClaimPermissions)
        {
            OpenApiResult result = await this.ruleSetService.CreateResourceAccessRuleSetAsync(
                this.testTenants.TransientClientTenantId, newClaimPermissions);

            result.Results.TryGetValue("application/json", out object claimPermissions);
            return(result.StatusCode, claimPermissions as ResourceAccessRuleSet);
        }
Esempio n. 11
0
        public async Task WhenICallOperationsStatusOpenApiService_SetOperationSucceededWithIdAsync(Guid operationId)
        {
            OpenApiResult result = await this.service.SetOperationSucceeded(
                this.transientTenantManager.PrimaryTransientClient.Id,
                operationId).ConfigureAwait(false);

            this.scenarioContext.Set(result);
        }
Esempio n. 12
0
        public async Task WhenICallOperationsStatusOpenApiService_GetOperationByIdWithId(Guid operationId)
        {
            OperationsStatusOpenApiService service = this.serviceProvider.GetRequiredService <OperationsStatusOpenApiService>();

            OpenApiResult result = await service.GetOperationById(this.transientTenantManager.PrimaryTransientClient.Id, operationId).ConfigureAwait(false);

            this.scenarioContext.Set(result);
        }
Esempio n. 13
0
        public async Task WhenICallOperationsStatusOpenApiService_SetOperationRunningWithIdAndPercentCompleteOf(
            Guid operationId, int percentComplete)
        {
            OpenApiResult result = await this.service.SetOperationRunning(
                this.transientTenantManager.PrimaryTransientClient.Id,
                operationId,
                percentComplete).ConfigureAwait(false);

            this.scenarioContext.Set(result);
        }
Esempio n. 14
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, IList <ResourceAccessRule> Result)> GetEffectiveRulesForClaimPermissionsAsync(
            string claimPermissionsId)
        {
            OpenApiResult result = await this.claimsService.GetClaimPermissionResourceAccessRulesAsync(
                this.MakeOpenApiContext(),
                claimPermissionsId);

            result.Results.TryGetValue("application/json", out object rules);
            return(result.StatusCode, rules as IList <ResourceAccessRule>);
        }
Esempio n. 15
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, IList <ClaimPermissionsBatchResponseItem> Result)> BatchEvaluatePermissionsForClaimPermissionsAsync(
            IEnumerable <ClaimPermissionsBatchRequestItem> items)
        {
            OpenApiResult result = await this.claimsService.GetClaimPermissionsPermissionBatchAsync(
                this.MakeOpenApiContext(),
                items.ToArray());

            result.Results.TryGetValue("application/json", out object rules);
            return(result.StatusCode, rules as IList <ClaimPermissionsBatchResponseItem>);
        }
        private Task <OpenApiResult> ServiceMethodImplementation()
        {
            var result = new OpenApiResult {
                StatusCode = 200
            };

            this.scenarioContext.Set(result, OperationInvokedScenarioContextKey);

            return(Task.FromResult(result));
        }
Esempio n. 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OpenApiActionResult"/> class.
 /// </summary>
 /// <param name="openApiResult">The <see cref="OpenApiResult"/>.</param>
 /// <param name="operation">The OpenAPI operation definition.</param>
 /// <param name="converters">The OpenAPI converters to use.</param>
 /// <param name="logger">A logger for the operation.</param>
 private OpenApiActionResult(
     OpenApiResult openApiResult,
     OpenApiOperation operation,
     IEnumerable <IOpenApiConverter> converters,
     ILogger logger)
 {
     this.openApiResult = openApiResult;
     this.operation     = operation;
     this.converters    = converters;
     this.logger        = logger;
 }
Esempio n. 18
0
        private OpenApiResult AcceptedResultWithHeader(Operation operation)
        {
            WebLink link = this.linkResolver.ResolveByOperationIdAndRelationType(
                nameof(this.GetOperationById),
                "self",
                ("tenantId", operation.TenantId),
                ("operationId", operation.Id));
            OpenApiResult result = this.AcceptedResult(link.Href);

            result.Results.Add("application/json", operation);
            return(result);
        }
Esempio n. 19
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, JObject Result)> SetRuleSetsForClaimPermissionsAsync(
            string claimId,
            List <ResourceAccessRuleSet> resourceAccessRuleSets)
        {
            OpenApiResult result = await this.claimsService.SetClaimPermissionsResourceAccessRuleSetsAsync(
                this.MakeOpenApiContext(),
                claimId,
                resourceAccessRuleSets);

            result.Results.TryGetValue("application/json", out object claimPermissions);
            return(result.StatusCode, claimPermissions as JObject);
        }
Esempio n. 20
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, PermissionResult Result)> EvaluateSinglePermissionForClaimPermissionsAsync(
            string claimPermissionsId, string resourceUri, string accessType)
        {
            OpenApiResult result = await this.claimsService.GetClaimPermissionsPermissionAsync(
                this.MakeOpenApiContext(),
                claimPermissionsId,
                resourceUri,
                accessType);

            result.Results.TryGetValue("application/json", out object rules);
            return(result.StatusCode, rules as PermissionResult);
        }
        public Task <TenancyResponse> GetSwaggerAsync()
        {
            OpenApiResult result = this.tenancyService.NotFoundResult();

            // TODO: Fix if statement to check for swagger endpoint
            if (this.openApiContext != null)
            {
                result = this.tenancyService.OkResult();
            }

            return(Task.FromResult(MakeResponse(result)));
        }
Esempio n. 22
0
        /// <inheritdoc/>
        public async Task <(int HttpStatusCode, JObject Result)> AddRulesToResourceAccessRuleSetAsync(
            string ruleSetId,
            IList <ResourceAccessRule> newRules)
        {
            OpenApiResult result = await this.ruleSetService.UpdateResourceAccessRuleSetResourceAccessRulesAsync(
                this.testTenants.TransientClientTenantId,
                ruleSetId,
                UpdateOperation.Add,
                newRules);

            result.Results.TryGetValue("application/json", out object claimPermissions);
            return(result.StatusCode, claimPermissions as JObject);
        }
        public async Task <OpenApiResult> GetTenantAsync(
            string tenantId,
            [OpenApiParameter("If-None-Match")]
            string?etag,
            IOpenApiContext context)
        {
            if (string.IsNullOrEmpty(tenantId))
            {
                throw new OpenApiBadRequestException("Bad request");
            }

            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            try
            {
                ITenant result = tenantId == RootTenant.RootTenantId
                    ? this.GetRedactedRootTenant()
                    : result = await this.tenantStore.GetTenantAsync(tenantId, etag).ConfigureAwait(false);

                OpenApiResult okResult = this.OkResult(await this.tenantMapper.MapAsync(result).ConfigureAwait(false), "application/json");

                if (!string.IsNullOrEmpty(result.ETag))
                {
                    okResult.Results.Add("ETag", result.ETag !);
                }

                if (!string.IsNullOrEmpty(this.cacheConfiguration.GetTenantResponseCacheControlHeaderValue))
                {
                    okResult.Results.Add("Cache-Control", this.cacheConfiguration.GetTenantResponseCacheControlHeaderValue !);
                }
                else
                {
                    this.logger.LogWarning("Tenancy cache configuration does not contain a GetTenantResponseCacheControlHeaderValue so no cache header will be sent on the returned tenant.");
                }

                return(okResult);
            }
            catch (TenantNotModifiedException)
            {
                return(this.NotModifiedResult());
            }
            catch (TenantNotFoundException)
            {
                return(this.NotFoundResult());
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Determines if the action result can be constructed from the provided result and operation definition.
        /// </summary>
        /// <param name="openApiResult">The <see cref="OpenApiResult"/>.</param>
        /// <param name="operation">The OpenAPI operation definition.</param>
        /// <returns>True if an action result can be constructed from this operation result.</returns>
        public static bool CanConstructFrom(OpenApiResult openApiResult, OpenApiOperation operation)
        {
            if (!operation.Responses.TryGetResponseForStatusCode(openApiResult.StatusCode, out OpenApiResponse response))
            {
                return(false);
            }

            // Validate the required headers
            if (!response.Headers.Where(h => h.Value.Required).All(h => openApiResult.Results.ContainsKey(h.Key)))
            {
                return(false);
            }

            // Validate the response body
            return(response.Content == null || response.Content.Count == 0 || response.Content.Any(c => openApiResult.Results.ContainsKey(c.Key)));
        }
Esempio n. 25
0
        public async Task <OpenApiResult> GetWorkflow(string tenantId, string workflowId)
        {
            ITenant tenant = await this.marainServicesTenancy.GetRequestingTenantAsync(tenantId).ConfigureAwait(false);

            IWorkflowStore workflowStore = await this.workflowStoreFactory.GetWorkflowStoreForTenantAsync(tenant).ConfigureAwait(false);

            Workflow workflow = await workflowStore.GetWorkflowAsync(workflowId).ConfigureAwait(false);

            OpenApiResult result = this.OkResult(workflow, "application/json");

            if (!string.IsNullOrEmpty(workflow.ETag))
            {
                result.Results.Add("ETag", workflow.ETag);
            }

            return(result);
        }
        public void ThenThePropertyInTheResultShouldBe(string propertyName, string propertyValue)
        {
            propertyValue = propertyValue.Replace("{transientTenantId}", this.transientTenantManager.PrimaryTransientClient.Id);

            OpenApiResult result = this.scenarioContext.Get <OpenApiResult>();

            Assert.IsTrue(
                result.Results.TryGetValue(propertyName, out object?value),
                $"Property '{propertyName}' not found in result");
            if (value is string stringValue)
            {
                Assert.AreEqual(propertyValue, stringValue);
            }
            else
            {
                Assert.Fail($"Property '{propertyName}' should be a string, but is of type {value!.GetType().FullName}");
            }
        }
        private void Push(string OPENID, TemplateModel m)
        {
            try
            {
                SeatManage.SeatManageComm.WriteLog.Write(OPENID);
                string      tempID        = "WY4Z5Z0rigwhaSBl3onTma-VZC2sdTlHNviIXHV1n2s"; //座位状态变更通知模板ID
                CommonTools tools         = new CommonTools();
                string      access_tocken = tool.IsExistAccess_TokenV2();                  //tools.IsExistAccess_Token("wx2b5a801cd0aa12c7", "42ac52963fadb13b2abff3a4c374888e");

                m.touser      = OPENID;
                m.template_id = tempID;
                m.url         = "http://wechat.gxchuwei.com/NewUser/MySeat";
                m.topcolor    = "#FF0000";
                OpenApiResult result = tools.SendTemplateMessage(access_tocken, m);
                SeatManage.SeatManageComm.WriteLog.Write("msg_id" + result.msg_id + "error_code" + result.error_code + "error_msg" + result.error_msg);
            }
            catch (Exception ex)
            {
                SeatManage.SeatManageComm.WriteLog.Write(ex.ToString());
            }
        }
Esempio n. 28
0
        /// <summary>
        /// 获取服务端的Token
        /// </summary>
        /// <param name="tokenData">Token数据</param>
        /// <returns>授权对象</returns>
        public static OpenApiResult <AccessGrant> GetToken(SimpleTokenData tokenData)
        {
            UpdateClient();
            var url = UriPathBuilder.Combine(OAuthService.OAuthServicePath, "token");

            var data = new NameValueCollection();

            tokenData.UpdateDatas(data);
            var innerResult = client.HttpPostForResult <AccessGrant.InnerAccessGrant>(url, data);

            var result = new OpenApiResult <AccessGrant>()
            {
                Code = innerResult.Code, Message = innerResult.Message
            };

            if (innerResult.Data != null)
            {
                result.Data = innerResult.Data.Convert();
            }
            return(result);
        }
Esempio n. 29
0
        //发送内部消息
        private void ResponseMsg(string OPENID, string first, string keyword1, string keyword2, string keyword3, string remark)
        {
            try
            {
                //  SeatManage.SeatManageComm.WriteLog.Write("4:ResponseMsg");
                string tempID        = "oLdL1fEDKZsPdc9njn7V2yioHhFWpQQy1JyfxKV_NsM";//座位状态变更通知模板ID
                string access_tocken = Com.IsExistAccess_Token("wx5c27898c83a612dc", "51fed2e73dddd6e6eabbb528c973074d");

                SendTools     tools = new SendTools();
                TemplateModel m     = new TemplateModel(first, keyword1, keyword2, keyword3, remark);
                m.touser      = OPENID;
                m.template_id = tempID;
                m.url         = "https://lib.xmu.edu.cn/seatwx/NewUser/MySeat";
                m.topcolor    = "#FF0000";
                OpenApiResult result = tools.SendTemplateMessage(access_tocken, m);
                // SeatManage.SeatManageComm.WriteLog.Write("msg_id" + result.msg_id + "error_code" + result.error_code + "error_msg" + result.error_msg);
            }
            catch (Exception ex)
            {
                SeatManage.SeatManageComm.WriteLog.Write(ex.ToString());
            }
        }
        public async Task <OpenApiResult> CreateContent(string tenantId, string slug, CreateContentRequest body)
        {
            IContentStore contentStore = await this.contentStoreFactory.GetContentStoreForTenantAsync(tenantId).ConfigureAwait(false);

            Content request = body.AsContent(slug);

            Content result = await contentStore.StoreContentAsync(request).ConfigureAwait(false);

            string etag = EtagHelper.BuildEtag(nameof(Content), result.ETag);

            HalDocument resultDocument = this.contentMapper.Map(result, new ResponseMappingContext {
                TenantId = tenantId
            });

            WebLink location = resultDocument.GetLinksForRelation("self").First();

            OpenApiResult response = this.CreatedResult(location.Href, resultDocument);

            response.Results.Add(HeaderNames.ETag, etag);

            return(response);
        }