protected virtual TimeSpan GetResponseTimeout(ClientActionContext context, TimeSpan defaultTimeout) { var currentScope = RequestScope.Current; if (currentScope != null && currentScope.Timeout > TimeSpan.Zero) { return(currentScope.Timeout); } TimeSpan timeout = defaultTimeout; ActionMetadata metadata = context.GetActionOrThrow(); if (metadata.Timeout > TimeSpan.Zero) { timeout = metadata.Timeout; } var timeoutProvider = TimeoutProvider; if (timeoutProvider != null) { var timeoutOverride = timeoutProvider.GetActionTimeout(context.Contract, context.Action); if (timeoutOverride > TimeSpan.Zero) { timeout = timeoutOverride; } } return(timeout); }
public virtual Uri GetEndpoint(Uri server, ContractMetadata contract, ActionMetadata action) { StringBuilder sb = new StringBuilder(); if (server != null) { sb.Append(server); } if (action != null) { if (sb.Length > 0 && sb[sb.Length - 1] == '/') { if (!string.IsNullOrEmpty(_options.Prefix)) { sb.Append(_options.Prefix + "/"); } sb.Append(contract.NormalizedName); } else { if (!string.IsNullOrEmpty(_options.Prefix)) { sb.Append("/" + _options.Prefix); } sb.Append("/" + contract.NormalizedName); } sb.Append("/" + action.NormalizedName); } return(new Uri(sb.ToString(), server != null ? UriKind.Absolute : UriKind.Relative)); }
public Task WriteParametersAsync(Stream stream, IReadOnlyList <ParameterMetadata> parameters, object[] values, Action <long> onContentLength) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (parameters == null || parameters.Count == 0) { return(Task.CompletedTask); } ActionMetadata.ValidateParameters(parameters, values); for (int i = 0; i < parameters.Count; i++) { var parameterMetadata = parameters[i]; if (!parameterMetadata.IsSerializable) { values[i] = null; } } return(DoWriteParametersAsync(stream, parameters, values, onContentLength)); }
public async Task <object[]> ReadParametersAsync(Stream stream, IReadOnlyList <ParameterMetadata> parameters, long contentLength) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (parameters == null || parameters.Count == 0) { throw new ArgumentNullException(nameof(parameters)); } object[] values = await DoReadParametersAsync(stream, parameters, contentLength); for (int i = 0; i < values.Length; i++) { var rawValue = values[i]; if (rawValue != null) { if (Convert.GetTypeCode(rawValue) != TypeCode.Object) { rawValue = Convert.ChangeType(rawValue, parameters[i].Type, CultureInfo.InvariantCulture); } } values[i] = rawValue; } ActionMetadata.ValidateParameters(parameters, values); return(values); }
protected virtual HttpContent BuildRequestContent(ClientActionContext context) { ActionMetadata metadata = context.GetActionOrThrow(); if (metadata.HasSerializableParameters) { try { metadata.ValidateParameters(context.Parameters); } catch (Exception e) { throw new BoltClientException( $"Parameter validation failed for action '{context.Action.Name}'.", ClientErrorCode.SerializeParameters, context.Action.Name, e); } } if (context.Action.HasSerializableParameters) { return(new SerializeParametersContent(Serializer, context)); } return(null); }
public HttpMethod From(ActionMetadata evidence) { return StartsWith(evidence.Action, HttpMethod.Get) ?? StartsWith(evidence.Action, HttpMethod.Post) ?? StartsWith(evidence.Action, HttpMethod.Put) ?? StartsWith(evidence.Action, HttpMethod.Delete) ?? HttpMethod.Get; }
public HttpMethod From(ActionMetadata evidence) { return(StartsWith(evidence.Action, HttpMethod.Get) ?? StartsWith(evidence.Action, HttpMethod.Post) ?? StartsWith(evidence.Action, HttpMethod.Put) ?? StartsWith(evidence.Action, HttpMethod.Delete) ?? HttpMethod.Get); }
public ActionDescriptor(ActionMetadata metadata) { Parameters = metadata.Action.GetParameters().ToList(); ParametersTypes = Parameters.Select(p => p.ParameterType).ToArray(); _compiledLambda = MethodInvokerBuilder.Build(metadata.Action.DeclaringType, metadata.Action); _isTaskResult = typeof(Task).IsAssignableFrom(metadata.Action.ReturnType); if (_isTaskResult && metadata.Action.ReturnType.GetTypeInfo().IsGenericType) { _taskResultProvider = MethodInvokerBuilder.BuildTaskResultProvider(metadata.ResultType); } }
public async void CreateNewAction(string action_id, IActionProvider actionProvider, string newName = null) { try { ActionMetadata actionMetadata = actionProvider.GetActionMetadata(action_id); List <IParameter> actionParameters = await Base.Parameter.InitActionParameters(actionProvider.GetProviderId(), actionMetadata.ParametersMetadata.Values.ToList(), HiddenPlace, OnChangeParameterHandler, HiddenPlaceLayout, HiddenPlace, currentActionPoint, false, CanvasGroup); string newActionName; if (string.IsNullOrEmpty(newName)) { newActionName = Base.ProjectManager.Instance.GetFreeActionName(actionMetadata.Name); } else { newActionName = Base.ProjectManager.Instance.GetFreeActionName(newName); } if (Base.Parameter.CheckIfAllValuesValid(actionParameters)) { List <IO.Swagger.Model.ActionParameter> parameters = new List <IO.Swagger.Model.ActionParameter>(); foreach (IParameter actionParameter in actionParameters) { if (!actionMetadata.ParametersMetadata.TryGetValue(actionParameter.GetName(), out Base.ParameterMetadata actionParameterMetadata)) { Base.Notifications.Instance.ShowNotification("Failed to create new action", "Failed to get metadata for action parameter: " + actionParameter.GetName()); return; } IO.Swagger.Model.ActionParameter ap = new IO.Swagger.Model.ActionParameter(name: actionParameter.GetName(), value: JsonConvert.SerializeObject(actionParameter.GetValue()), type: actionParameter.GetCurrentType()); parameters.Add(ap); } try { addedActionName = newActionName; Hide(); AREditorResources.Instance.LeftMenuProject.SetActiveSubmenu(AREditorResources.Instance.LeftMenuProject.CurrentSubmenuOpened); await Base.WebsocketManager.Instance.AddAction(currentActionPoint.GetId(), parameters, Base.Action.BuildActionType( actionProvider.GetProviderId(), actionMetadata.Name), newActionName, actionMetadata.GetFlows(newActionName)); foreach (Transform t in HiddenPlace.transform) { if (!t.CompareTag("Persistent")) { Destroy(t.gameObject); } } } catch (Base.RequestFailedException e) { Base.Notifications.Instance.ShowNotification("Failed to add action", e.Message); addedActionName = null; } } } catch (Base.RequestFailedException e) { Base.Notifications.Instance.ShowNotification("Failed to add action", e.Message); } }
static AdminPage() { var logoMetadata = new PropertyMetadata(() => { return(string.Empty); }, OnLogoChanged); LogoProperty = DependencyProperty.Register <string, AdminPage>("Logo", logoMetadata); var principalPhotoMetadata = new PropertyMetadata(() => { return(string.Empty); }, OnPrincipalPhotoChanged); PrincipalPhotoProperty = DependencyProperty.Register <string, AdminPage>("PrincipalPhoto", principalPhotoMetadata); var principalNameMetadata = new PropertyMetadata(() => { return(string.Empty); }); PrincipalNameProperty = DependencyProperty.Register <string, AdminPage>("PrincipalName", principalNameMetadata); var assetsPathMetadata = new PropertyMetadata(() => { return(string.Empty); }); AssetsPathProperty = DependencyProperty.Register <string, AdminPage>("AssetsPath", assetsPathMetadata); var rootMenuMetadata = new PropertyMetadata(() => { return(string.Empty); }); RootMenuProperty = DependencyProperty.Register <string, AdminPage>("RootMenu", rootMenuMetadata); var isLocalMenuMetadata = new PropertyMetadata(() => { return(false); }); IsLocalMenuProperty = DependencyProperty.Register <bool, AdminPage>("IsLocalMenu", isLocalMenuMetadata); var getMenuCodeMetadata = new ActionMetadata(GetMenuCodeActionProduce); GetMenuCodeAction = DependencyAction.Register <AdminPage>("GetMenuCode", false, getMenuCodeMetadata); var workTitleMetadata = new PropertyMetadata(() => { return(string.Empty); }); WorkTitleProperty = DependencyProperty.Register <string, AdminPage>("WorkTitle", workTitleMetadata); var workDescriptionMetadata = new PropertyMetadata(() => { return(string.Empty); }); WorkDescriptionProperty = DependencyProperty.Register <string, AdminPage>("WorkDescription", workDescriptionMetadata); var showWorkHeaderMetadata = new PropertyMetadata(() => { return(true); }, OnShowWorkHeaderChanged); ShowWorkHeaderProperty = DependencyProperty.Register <bool, AdminPage>("ShowWorkHeader", showWorkHeaderMetadata); var menuRedirectMetadata = new PropertyMetadata(() => { return(string.Empty); }); MenuRedirectProperty = DependencyProperty.Register <string, AdminPage>("MenuRedirect", menuRedirectMetadata); var themeMetadata = new PropertyMetadata(() => { return("darkblue"); }); ThemeProperty = DependencyProperty.Register <string, AdminPage>("Theme", themeMetadata); var logoStyleMetadata = new PropertyMetadata(() => { return(string.Empty); }); LogoProperty = DependencyProperty.Register <string, AdminPage>("LogoStyle", logoStyleMetadata); }
private ClientActionContext CreateContext(ActionMetadata action, params object[] parameters) { ClientActionContext context; if (!_contexts.TryDequeue(out context)) { context = new ClientActionContext(); } context.Init(this, Contract, action, parameters); return(context); }
protected override MethodMetadata Create(MethodInfo key, object context) { ActionMetadata metadata = BoltFramework.ActionMetadata.Resolve(key); Func <Task <object>, Task> provider = null; if (metadata.IsAsynchronous && metadata.HasResult) { provider = MethodInvokerBuilder.Build(metadata.ResultType); } MethodInfo method = _proxyBase.GetRuntimeMethod(key.Name, key.GetParameters().Select(p => p.ParameterType).ToArray()); return(new MethodMetadata(metadata, provider, method)); }
public virtual async Task HandleContractMetadataAsync(ServerActionContext context) { try { string result; string actionName = context.HttpContext.Request.Query["action"]; Bolt.Metadata.ActionMetadata action = null; if (!string.IsNullOrEmpty(actionName)) { action = _actionResolver.Resolve(context.Contract, actionName.AsReadOnlySpan()); } if (action == null) { var contractMetadata = CrateContractMetadata(context); result = JsonConvert.SerializeObject(contractMetadata, Formatting.Indented, CreateSettings()); } else { context.Action = action; ActionMetadata actionMetadata = new ActionMetadata(); if (context.Action.HasSerializableParameters) { actionMetadata.Parameters = context.Action.Parameters.Where(p => p.IsSerializable).Select(p => p.Name).ToArray(); } if (context.Action.HasResult) { actionMetadata.Response = context.Action.ResultType.Name; } result = JsonConvert.SerializeObject(actionMetadata, Formatting.Indented, CreateSettings()); } context.HttpContext.Response.ContentType = "application/json"; context.HttpContext.Response.StatusCode = 200; await context.HttpContext.Response.WriteAsync(result); } catch (Exception e) { Logger.LogWarning( BoltLogId.HandleContractMetadataError, "Failed to generate Bolt metadata for contract '{0}'. Error: {1}", context.Contract.Name, e); } }
public void Init(IProxy proxy, ContractMetadata contract, ActionMetadata action, object[] parameters) { Contract = contract; Action = action; Parameters = parameters; Proxy = proxy; Request = new HttpRequestMessage(); if (Action.CancellationTokenIndex >= 0 && parameters != null) { var cancellation = parameters[Action.CancellationTokenIndex]; if (cancellation is CancellationToken) { RequestAborted = (CancellationToken)cancellation; } } }
// No dependency on HttpActionDescriptor - Easier Testing public static ActionMetadata GetDocs(string controllerName, string actionName, Type returnType, string parentControllerName, string relativePath, HttpMethod httpMethod, XPathNavigator actionNode) { var alternatePath = GetAlternatePath(controllerName, parentControllerName, relativePath).ToLower(); var returnTypeMeta = returnType==null ? null : returnType.GetDocs(); var actionMeta = new ActionMetadata() { Name = actionName, HttpMethod = httpMethod.ToString(), RelativePath = relativePath.ToLower(), AlternatePath = alternatePath, Summary = Utils.GetNodeValue(actionNode, "summary"), Remarks = Utils.GetNodeValue(actionNode, "remarks"), ReturnType = returnTypeMeta, ReturnsComment = Utils.GetNodeValue(actionNode, "returns"), ErrorResponses = null }; return actionMeta; }
// No dependency on HttpActionDescriptor - Easier Testing public static ActionMetadata GetDocs(string controllerName, string actionName, Type returnType, string parentControllerName, string relativePath, HttpMethod httpMethod, XPathNavigator actionNode) { var alternatePath = GetAlternatePath(controllerName, parentControllerName, relativePath).ToLower(); var returnTypeMeta = returnType == null ? null : returnType.GetDocs(); var actionMeta = new ActionMetadata() { Name = actionName, HttpMethod = httpMethod.ToString(), RelativePath = relativePath.ToLower(), AlternatePath = alternatePath, Summary = Utils.GetNodeValue(actionNode, "summary"), Remarks = Utils.GetNodeValue(actionNode, "remarks"), ReturnType = returnTypeMeta, ReturnsComment = Utils.GetNodeValue(actionNode, "returns"), ErrorResponses = null }; return(actionMeta); }
public MethodMetadata(ActionMetadata actionMetadata, Func <Task <object>, Task> asyncValueProvider, MethodInfo invocationTarget) { ActionMetadata = actionMetadata; AsyncValueProvider = asyncValueProvider; InvocationTarget = invocationTarget; }
public override IEnumerable <ServerEventResourceInfromation> ResourceInformation(ActionMetadata actionMetadata) { var resource = base.ReadPayloadFromResponce.Invoke(actionMetadata); //Если в результате выполнгения произошла ошибка и вернулся OperationOutcome то попытаемся взять информацию из реквеста if (resource is OperationOutcome) { resource = base.ReadPayloadFromRequest.Invoke(actionMetadata); } return(BuildersFuctory.GetBuilder(resource).Build(resource, actionMetadata)); }
public virtual IEnumerable <ServerEventMessage> ConvertToServerEvent(ActionMetadata actionMetadata) { var resourceinfoBuilder = _actionReaders.FirstOrDefault(a => a.CanRead(actionMetadata.ActionRequest.HttpMethod)); if (resourceinfoBuilder == null) { throw new Exception($"Не зарегистрировано обработчиков для метода {actionMetadata.ActionRequest.HttpMethod}"); } var serverEventMessageRegistered = actionMetadata.ExecutionDateTime.ToUniversalTime().ToString("u"); var serverEventMessageActionCode = actionMetadata.ActionRequest.HttpMethod; var outcome = OutcomeBuilder(actionMetadata.ActionResponce.StatusCode); var clientIp = ClientIP.ClientIpFromRequest(actionMetadata.ActionRequest.Header, false); var source = actionMetadata.ActionRequest.Header .FirstOrDefault(h => h.Key.Equals("Host", StringComparison.CurrentCultureIgnoreCase)).Value; var resourceInfo = resourceinfoBuilder.ResourceInformation(actionMetadata); JwtSecurityToken tokenS = null; var token = actionMetadata.ActionRequest.Header.FirstOrDefault(h => h.Key.Equals("Authorization")) .Value?.Split(' ')[1]; if (!string.IsNullOrEmpty(token)) { var handler = new JwtSecurityTokenHandler(); tokenS = handler.ReadToken(token) as JwtSecurityToken; } foreach (var serverEventResourceInfromation in resourceInfo) { yield return(new ServerEventMessage { ResourceType = serverEventResourceInfromation.ResourceType, ResourceVersionId = serverEventResourceInfromation.ResourceVersion, ResourceId = serverEventResourceInfromation.ResourceId, PatientId = serverEventResourceInfromation.PatientId, PatientVersionId = serverEventResourceInfromation.PatientVersion, EncounterId = serverEventResourceInfromation.EncounterId, EncounterVersionId = serverEventResourceInfromation.EncounterVersionId, ActionScope = serverEventResourceInfromation.Scope, Registered = serverEventMessageRegistered, ActionCode = serverEventMessageActionCode, Outcome = outcome.Key, OutcomeDesc = outcome.Value, AccessPoint = clientIp, Source = source, ClientId = tokenS == null?null: string.Join(" ", tokenS.Audiences), Claims = tokenS?.Claims.Select(c => new KeyValuePair <string, string>(c.Type, c.Value)).ToList(), UserId = tokenS?.Subject, Resource = serverEventResourceInfromation.ResourceJson }); } }
protected virtual async Task <object[]> DeserializeParametersAsync(ServerActionContext context, ActionMetadata metadata) { object[] parameters = null; if (metadata.HasSerializableParameters) { ISerializer serializer = context.GetSerializerOrThrow(); try { // TODO: copy body to another stream to prevent blocking in json deserialization parameters = await serializer.ReadParametersAsync(context.HttpContext.Request.Body, metadata.Parameters, context.HttpContext.Request.ContentLength ?? -1); } catch (OperationCanceledException) { throw; } catch (Exception e) { throw new BoltServerException( $"Failed to deserialize parameters for action '{context.Action.Name}'.", ServerErrorCode.DeserializeParameters, context.Action.Name, context.RequestUrl, e); } } else if (context.Action.Parameters.Count > 0) { parameters = new object[context.Action.Parameters.Count]; } if (metadata.CancellationTokenIndex >= 0) { parameters[metadata.CancellationTokenIndex] = context.RequestAborted; } return(parameters); }
public IEnumerable <ServerEventResourceInfromation> Build(Resource resource, ActionMetadata actionMetadata) { return(BuildCore((T)resource, actionMetadata)); }
public TimeSpan GetActionTimeout(ContractMetadata contract, ActionMetadata actionMetadata) { throw new NotImplementedException(); }
public string From(ActionMetadata evidence) { return(evidence.Action); }
public virtual IEnumerable <ServerEventResourceInfromation> ResourceInformation(ActionMetadata actionMetadata) { var resource = ReadPayloadFromResponce(actionMetadata); return(BuildersFuctory.GetBuilder(resource).Build(resource, actionMetadata)); }
protected static Metadata Validate(Type contract, MethodInfo method) { if (contract == null) { throw new ArgumentNullException(nameof(contract)); } if (method == null) { throw new ArgumentNullException(nameof(method)); } ActionMetadata actionMetadata = BoltFramework.ActionMetadata.Resolve(method); var parameters = actionMetadata.Parameters; if (parameters.Count > 2) { throw new ContractViolationException( $"Action '{method.Name}' has invalid declaration. Only single parameter of HttpContent type is supported with optional CancellationToken parameter.", contract, method); } if (typeof(HttpResponseMessage).CanAssign(actionMetadata.ResultType)) { throw new ContractViolationException( $"Action '{method.Name}' has invalid declaration. The HttpResponseMessage return type is not supported.", contract, method); } bool hasContentResult = typeof(HttpContent).CanAssign(actionMetadata.ResultType); if (hasContentResult && actionMetadata.ResultType != typeof(HttpContent)) { throw new ContractViolationException( $"Action '{method.Name}' has invalid declaration. Only HttpContent return type is supported.", contract, method); } Metadata metadata = new Metadata { Action = actionMetadata }; if (hasContentResult) { metadata.ContentResultType = actionMetadata.ResultType; } for (int i = 0; i < parameters.Count; i++) { ParameterMetadata info = parameters[i]; if (typeof(HttpContent).CanAssign(info.Type)) { if (info.Type != typeof(HttpContent)) { throw new ContractViolationException( $"Action '{method.Name}' has invalid declaration. Only HttpContent parameter type is supported.", contract, method); } if (metadata.HttpContentIndex >= 0) { throw new ContractViolationException( $"Action '{method.Name}' contains duplicate parameter '{info.Name}' of HttpContent type.", contract, method); } metadata.ContentRequestType = info.Type; metadata.HttpContentIndex = i; } } if (metadata.HttpContentIndex >= 0 && parameters.Count > 1 && actionMetadata.CancellationTokenIndex < 0) { throw new ContractViolationException( $"Action '{method.Name}' has invalid declaration. Only HttpContent parameter type witj optional cancellation token is supported.", contract, method); } if (metadata.HttpContentIndex >= 0 || metadata.ContentResultType != null) { return(metadata); } return(null); }
public string From(ActionMetadata evidence) { return evidence.Action; }
protected override IEnumerable <ServerEventResourceInfromation> BuildCore(OperationOutcome resource, ActionMetadata actionMetadata) { object type = ""; actionMetadata.ActionRequest.RouteData.TryGetValue("type", out type); object id = ""; actionMetadata.ActionRequest.RouteData.TryGetValue("id", out id); yield return(new ServerEventResourceInfromation() { ResourceId = id?.ToString(), ResourceType = type?.ToString() }); }
protected virtual IEnumerable <ServerEventResourceInfromation> BuildCore(T resource, ActionMetadata actionMetadata) { var resourceinfo = GetResource(resource); var patientinfo = GetRelatedPatientInformation(resource); var encounterinfo = GetRelatedEncounter(resource); var scope = GetScope(resource); var resourceJsonString = FhirSerializer.SerializeResourceToJson(resource); yield return(new ServerEventResourceInfromation() { ResourceType = resource.TypeName, ResourceId = resourceinfo.ResourceId, ResourceVersion = resourceinfo.ResourceVersionId, EncounterId = encounterinfo.ResourceId, EncounterVersionId = encounterinfo.ResourceVersionId, PatientId = patientinfo.ResourceId, PatientVersion = patientinfo.ResourceVersionId, Scope = scope, ResourceJson = resourceJsonString }); }
protected override IEnumerable <ServerEventResourceInfromation> BuildCore(Bundle resource, ActionMetadata actionMetadata) { foreach (var bundleEntryComponent in resource.Entry) { var builder = BuildersFuctory.GetBuilder(bundleEntryComponent.Resource); var result = builder.Build(bundleEntryComponent.Resource, actionMetadata); foreach (var serverEventResourceInfromation in result) { yield return(serverEventResourceInfromation); } } }