/// <summary> /// Default constructor. /// Initializes a new instance of the <see cref="ErrorResponseBody"/> class /// </summary> /// <param name="code">The error code</param> /// <param name="message">The message</param> public ErrorResponse(short code, string message) { // Create the body Response = new ErrorResponseBody { Code = code, Message = message }; }
public ErrorBody(ErrorResponseBody errorBody) : this() { if (errorBody == null) { throw new ArgumentNullException("errorBody"); } Code = errorBody.Code; Message = errorBody.Message; Details = errorBody .Details .Where(errorDetail => errorDetail != null) .Select(errorDetail => new ErrorField(errorDetail)) .ToArray(); }
/// <summary> /// Accept subscription ownership. /// </summary> /// <param name='subscriptionId'> /// Subscription Id. /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseBodyException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationHeaderResponse <SubscriptionAcceptOwnershipHeaders> > BeginAcceptOwnershipWithHttpMessagesAsync(string subscriptionId, AcceptOwnershipRequest body, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (subscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } if (body != null) { body.Validate(); } string apiVersion = "2021-10-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("subscriptionId", subscriptionId); tracingParameters.Add("body", body); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginAcceptOwnership", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Subscription/subscriptions/{subscriptionId}/acceptOwnership").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(subscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 202) { var ex = new ErrorResponseBodyException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponseBody _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponseBody>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationHeaderResponse <SubscriptionAcceptOwnershipHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject <SubscriptionAcceptOwnershipHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public override void Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ResponseBody responseBody = null; //Check for Flex2 messages and skip if (amfBody.IsEmptyTarget) { continue; } if (amfBody.IsDebug) { continue; } if (amfBody.IsDescribeService) { responseBody = new ResponseBody(); responseBody.IgnoreResults = amfBody.IgnoreResults; responseBody.Target = amfBody.Response + AMFBody.OnResult; responseBody.Response = null; DescribeService describeService = new DescribeService(amfBody); responseBody.Content = describeService.GetDescription(); messageOutput.AddBody(responseBody); continue; } //Check if response exists. responseBody = messageOutput.GetResponse(amfBody); if (responseBody != null) { continue; } try { MessageBroker messageBroker = _endpoint.GetMessageBroker(); RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService; if (remotingService == null) { string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId); responseBody = new ErrorResponseBody(amfBody, new FluorineException(serviceNotFound)); messageOutput.AddBody(responseBody); if (log.IsErrorEnabled) { log.Error(serviceNotFound); } continue; } Destination destination = null; if (destination == null) { destination = remotingService.GetDestinationWithSource(amfBody.TypeName); } if (destination == null) { destination = remotingService.DefaultDestination; } //At this moment we got a destination with the exact source or we have a default destination with the "*" source. if (destination == null) { string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName); responseBody = new ErrorResponseBody(amfBody, new FluorineException(destinationNotFound)); messageOutput.AddBody(responseBody); if (log.IsErrorEnabled) { log.Error(destinationNotFound); } continue; } try { remotingService.CheckSecurity(destination); } catch (UnauthorizedAccessException exception) { responseBody = new ErrorResponseBody(amfBody, exception); if (log.IsDebugEnabled) { log.Debug(exception.Message); } continue; } //Cache check string source = amfBody.TypeName + "." + amfBody.Method; IList parameterList = amfBody.GetParameterList(); string key = FluorineFx.Configuration.CacheMap.GenerateCacheKey(source, parameterList); if (FluorineConfiguration.Instance.CacheMap.ContainsValue(key)) { object result = FluorineFx.Configuration.FluorineConfiguration.Instance.CacheMap.Get(key); if (result != null) { if (log != null && log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.Cache_HitKey, source, key)); } responseBody = new ResponseBody(amfBody, result); messageOutput.AddBody(responseBody); continue; } } object instance; FactoryInstance factoryInstance = destination.GetFactoryInstance(); lock (factoryInstance) { factoryInstance.Source = amfBody.TypeName; if (FluorineContext.Current.ActivationMode != null)//query string can override the activation mode { factoryInstance.Scope = FluorineContext.Current.ActivationMode; } instance = factoryInstance.Lookup(); } if (instance != null) { try { bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType()); if (!isAccessible) { string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName); if (log.IsErrorEnabled) { log.Error(msg); } responseBody = new ErrorResponseBody(amfBody, new FluorineException(msg)); messageOutput.AddBody(responseBody); continue; } MethodInfo mi = null; if (!amfBody.IsRecordsetDelivery) { mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, parameterList); } else { //will receive recordsetid only (ignore) mi = instance.GetType().GetMethod(amfBody.Method); } if (mi != null) { object[] roleAttributes = mi.GetCustomAttributes(typeof(RoleAttribute), true); if (roleAttributes != null && roleAttributes.Length == 1) { RoleAttribute roleAttribute = roleAttributes[0] as RoleAttribute; string[] roles = roleAttribute.Roles.Split(','); bool authorized = messageBroker.LoginManager.DoAuthorization(roles); if (!authorized) { throw new UnauthorizedAccessException(__Res.GetString(__Res.Security_AccessNotAllowed)); } } #region Invocation handling PageSizeAttribute pageSizeAttribute = null; MethodInfo miCounter = null; object[] pageSizeAttributes = mi.GetCustomAttributes(typeof(PageSizeAttribute), true); if (pageSizeAttributes != null && pageSizeAttributes.Length == 1) { pageSizeAttribute = pageSizeAttributes[0] as PageSizeAttribute; miCounter = instance.GetType().GetMethod(amfBody.Method + "Count"); if (miCounter != null && miCounter.ReturnType != typeof(System.Int32)) { miCounter = null; //check signature } } ParameterInfo[] parameterInfos = mi.GetParameters(); //Try to handle missing/optional parameters. object[] args = new object[parameterInfos.Length]; if (!amfBody.IsRecordsetDelivery) { if (args.Length != parameterList.Count) { string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length); if (log != null && log.IsErrorEnabled) { log.Error(msg); } responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg)); messageOutput.AddBody(responseBody); continue; } parameterList.CopyTo(args, 0); if (pageSizeAttribute != null) { PagingContext pagingContext = new PagingContext(pageSizeAttribute.Offset, pageSizeAttribute.Limit); PagingContext.SetPagingContext(pagingContext); } } else { if (amfBody.Target.EndsWith(".release")) { responseBody = new ResponseBody(amfBody, null); messageOutput.AddBody(responseBody); continue; } string recordsetId = parameterList[0] as string; string recordetDeliveryParameters = amfBody.GetRecordsetArgs(); byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters); recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer); if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty) { string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' }); for (int j = 0; j < stringParameters.Length; j++) { if (stringParameters[j] == string.Empty) { args[j] = null; } else { args[j] = stringParameters[j]; } } //TypeHelper.NarrowValues(argsStore, parameterInfos); } PagingContext pagingContext = new PagingContext(System.Convert.ToInt32(parameterList[1]), System.Convert.ToInt32(parameterList[2])); PagingContext.SetPagingContext(pagingContext); } TypeHelper.NarrowValues(args, parameterInfos); try { InvocationHandler invocationHandler = new InvocationHandler(mi); object result = invocationHandler.Invoke(instance, args); if (FluorineConfiguration.Instance.CacheMap != null && FluorineConfiguration.Instance.CacheMap.ContainsCacheDescriptor(source)) { //The result should be cached CacheableObject cacheableObject = new CacheableObject(source, key, result); FluorineConfiguration.Instance.CacheMap.Add(cacheableObject.Source, cacheableObject.CacheKey, cacheableObject); result = cacheableObject; } responseBody = new ResponseBody(amfBody, result); if (pageSizeAttribute != null) { int totalCount = 0; string recordsetId = null; IList list = amfBody.GetParameterList(); string recordetDeliveryParameters = null; if (!amfBody.IsRecordsetDelivery) { //fist call paging object[] argsStore = new object[list.Count]; list.CopyTo(argsStore, 0); recordsetId = System.Guid.NewGuid().ToString(); if (miCounter != null) { //object[] counterArgs = new object[0]; totalCount = (int)miCounter.Invoke(instance, args); } string[] stringParameters = new string[argsStore.Length]; for (int j = 0; j < argsStore.Length; j++) { if (argsStore[j] != null) { stringParameters[j] = argsStore[j].ToString(); } else { stringParameters[j] = string.Empty; } } recordetDeliveryParameters = string.Join(",", stringParameters); byte[] buffer = System.Text.Encoding.UTF8.GetBytes(recordetDeliveryParameters); recordetDeliveryParameters = System.Convert.ToBase64String(buffer); } else { recordsetId = amfBody.GetParameterList()[0] as string; } if (result is DataTable) { DataTable dataTable = result as DataTable; dataTable.ExtendedProperties["TotalCount"] = totalCount; dataTable.ExtendedProperties["Service"] = recordetDeliveryParameters + "/" + amfBody.Target; dataTable.ExtendedProperties["RecordsetId"] = recordsetId; if (amfBody.IsRecordsetDelivery) { dataTable.ExtendedProperties["Cursor"] = Convert.ToInt32(list[list.Count - 2]); dataTable.ExtendedProperties["DynamicPage"] = true; } } } } catch (UnauthorizedAccessException exception) { responseBody = new ErrorResponseBody(amfBody, exception); if (log.IsDebugEnabled) { log.Debug(exception.Message); } } catch (Exception exception) { if (exception is TargetInvocationException && exception.InnerException != null) { responseBody = new ErrorResponseBody(amfBody, exception.InnerException); } else { responseBody = new ErrorResponseBody(amfBody, exception); } if (log.IsDebugEnabled) { log.Debug(__Res.GetString(__Res.Invocation_Failed, mi.Name, exception.Message)); } } #endregion Invocation handling } else { responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method)); } } finally { factoryInstance.OnOperationComplete(instance); } } else { responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null)); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(exception.Message + String.Format(" (Type: {0}, Method: {1})", amfBody.TypeName, amfBody.Method), exception); } responseBody = new ErrorResponseBody(amfBody, exception); } messageOutput.AddBody(responseBody); } }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { Type typeForWebService; Exception exception; ErrorResponseBody body2; AMFBody bodyAt = context.AMFMessage.GetBodyAt(i); if (!bodyAt.IsEmptyTarget) { if (bodyAt.IsWebService) { try { typeForWebService = this.GetTypeForWebService(bodyAt.TypeName); if (typeForWebService != null) { bodyAt.Target = typeForWebService.FullName + "." + bodyAt.Method; } else { exception = new TypeInitializationException(bodyAt.TypeName, null); if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Type_InitError", new object[] { bodyAt.Target }), exception); } body2 = new ErrorResponseBody(bodyAt, exception); context.MessageOutput.AddBody(body2); } } catch (Exception exception1) { exception = exception1; if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { bodyAt.Target }), exception); } body2 = new ErrorResponseBody(bodyAt, exception); context.MessageOutput.AddBody(body2); } } } else { object content = bodyAt.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if ((message != null) && (message is RemotingMessage)) { RemotingMessage message2 = message as RemotingMessage; string source = message2.source; if ((source != null) && source.ToLower().EndsWith(".asmx")) { try { typeForWebService = this.GetTypeForWebService(source); if (typeForWebService != null) { message2.source = typeForWebService.FullName; } else { exception = new TypeInitializationException(source, null); if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Type_InitError", new object[] { source }), exception); } body2 = new ErrorResponseBody(bodyAt, message, exception); context.MessageOutput.AddBody(body2); } } catch (Exception exception2) { exception = exception2; if ((log != null) && log.get_IsErrorEnabled()) { log.Error(__Res.GetString("Wsdl_ProxyGen", new object[] { source }), exception); } body2 = new ErrorResponseBody(bodyAt, message, exception); context.MessageOutput.AddBody(body2); } } } } } }
public override void Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); if (!amfBody.IsEmptyTarget) { continue; } object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; //Check for Flex2 messages and handle if (message != null) { if (Context.AMFContext.Current.Client == null) { Context.AMFContext.Current.SetCurrentClient(_endpoint.GetMessageBroker().ClientRegistry.GetClient(message)); } if (message.clientId == null) { message.clientId = Guid.NewGuid().ToString("D"); } //Check if response exists. ResponseBody responseBody = messageOutput.GetResponse(amfBody); if (responseBody != null) { continue; } try { if (context.AMFMessage.BodyCount > 1) { CommandMessage commandMessage = message as CommandMessage; //Suppress poll wait if there are more messages to process if (commandMessage != null && commandMessage.operation == CommandMessage.PollOperation) { commandMessage.SetHeader(CommandMessage.AMFSuppressPollWaitHeader, null); } } IMessage resultMessage = _endpoint.ServiceMessage(message); if (resultMessage is ErrorMessage) { ErrorMessage errorMessage = resultMessage as ErrorMessage; responseBody = new ErrorResponseBody(amfBody, message, resultMessage as ErrorMessage); if (errorMessage.faultCode == ErrorMessage.ClientAuthenticationError) { messageOutput.AddBody(responseBody); for (int j = i + 1; j < context.AMFMessage.BodyCount; j++) { amfBody = context.AMFMessage.GetBodyAt(j); if (!amfBody.IsEmptyTarget) { continue; } content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } message = content as IMessage; //Check for Flex2 messages and handle if (message != null) { responseBody = new ErrorResponseBody(amfBody, message, new SecurityException(errorMessage.faultString)); messageOutput.AddBody(responseBody); } } //Leave further processing return; } } else { responseBody = new ResponseBody(amfBody, resultMessage); } } catch (Exception exception) { responseBody = new ErrorResponseBody(amfBody, message, exception); } messageOutput.AddBody(responseBody); } } }
public override Task Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ResponseBody responseBody = null; //Check for Flex2 messages and skip if (amfBody.IsEmptyTarget) { continue; } //Check if response exists. responseBody = messageOutput.GetResponse(amfBody); if (responseBody != null) { continue; } try { MessageBroker messageBroker = _endpoint.GetMessageBroker(); RemotingService remotingService = messageBroker.GetService(RemotingService.RemotingServiceId) as RemotingService; if (remotingService == null) { string serviceNotFound = __Res.GetString(__Res.Service_NotFound, RemotingService.RemotingServiceId); responseBody = new ErrorResponseBody(amfBody, new AMFException(serviceNotFound)); messageOutput.AddBody(responseBody); continue; } Destination destination = null; if (destination == null) { destination = remotingService.GetDestinationWithSource(amfBody.TypeName); } if (destination == null) { destination = remotingService.DefaultDestination; } //At this moment we got a destination with the exact source or we have a default destination with the "*" source. if (destination == null) { string destinationNotFound = __Res.GetString(__Res.Destination_NotFound, amfBody.TypeName); responseBody = new ErrorResponseBody(amfBody, new AMFException(destinationNotFound)); messageOutput.AddBody(responseBody); continue; } //Cache check string source = amfBody.TypeName + "." + amfBody.Method; IList parameterList = amfBody.GetParameterList(); FactoryInstance factoryInstance = destination.GetFactoryInstance(); factoryInstance.Source = amfBody.TypeName; object instance = factoryInstance.Lookup(); if (instance != null) { bool isAccessible = TypeHelper.GetTypeIsAccessible(instance.GetType()); if (!isAccessible) { string msg = __Res.GetString(__Res.Type_InitError, amfBody.TypeName); responseBody = new ErrorResponseBody(amfBody, new AMFException(msg)); messageOutput.AddBody(responseBody); continue; } MethodInfo mi = null; if (!amfBody.IsRecordsetDelivery) { mi = MethodHandler.GetMethod(instance.GetType(), amfBody.Method, amfBody.GetParameterList()); } else { //will receive recordsetid only (ignore) mi = instance.GetType().GetMethod(amfBody.Method); } if (mi != null) { #region Invocation handling ParameterInfo[] parameterInfos = mi.GetParameters(); //Try to handle missing/optional parameters. object[] args = new object[parameterInfos.Length]; if (!amfBody.IsRecordsetDelivery) { if (args.Length != parameterList.Count) { string msg = __Res.GetString(__Res.Arg_Mismatch, parameterList.Count, mi.Name, args.Length); responseBody = new ErrorResponseBody(amfBody, new ArgumentException(msg)); messageOutput.AddBody(responseBody); continue; } parameterList.CopyTo(args, 0); } else { if (amfBody.Target.EndsWith(".release")) { responseBody = new ResponseBody(amfBody, null); messageOutput.AddBody(responseBody); continue; } string recordsetId = parameterList[0] as string; string recordetDeliveryParameters = amfBody.GetRecordsetArgs(); byte[] buffer = System.Convert.FromBase64String(recordetDeliveryParameters); recordetDeliveryParameters = System.Text.Encoding.UTF8.GetString(buffer); if (recordetDeliveryParameters != null && recordetDeliveryParameters != string.Empty) { string[] stringParameters = recordetDeliveryParameters.Split(new char[] { ',' }); for (int j = 0; j < stringParameters.Length; j++) { if (stringParameters[j] == string.Empty) { args[j] = null; } else { args[j] = stringParameters[j]; } } //TypeHelper.NarrowValues(argsStore, parameterInfos); } } TypeHelper.NarrowValues(args, parameterInfos); try { InvocationHandler invocationHandler = new InvocationHandler(mi); object result = invocationHandler.Invoke(instance, args); responseBody = new ResponseBody(amfBody, result); } catch (UnauthorizedAccessException exception) { responseBody = new ErrorResponseBody(amfBody, exception); } catch (Exception exception) { if (exception is TargetInvocationException && exception.InnerException != null) { responseBody = new ErrorResponseBody(amfBody, exception.InnerException); } else { responseBody = new ErrorResponseBody(amfBody, exception); } } #endregion Invocation handling } else { responseBody = new ErrorResponseBody(amfBody, new MissingMethodException(amfBody.TypeName, amfBody.Method)); } } else { responseBody = new ErrorResponseBody(amfBody, new TypeInitializationException(amfBody.TypeName, null)); } } catch (Exception exception) { responseBody = new ErrorResponseBody(amfBody, exception); } messageOutput.AddBody(responseBody); } return(Task.FromResult <object>(null)); }
public override void Invoke(AMFContext context) { IPrincipal principal = null; int num; ErrorResponseBody body2; MessageBroker messageBroker = this._endpoint.GetMessageBroker(); try { string str3; AMFHeader header = context.AMFMessage.GetHeader("Credentials"); if ((header != null) && (header.Content != null)) { string username = ((ASObject)header.Content)["userid"] as string; string password = ((ASObject)header.Content)["password"] as string; ASObject content = new ASObject(); content["name"] = "Credentials"; content["mustUnderstand"] = false; content["data"] = null; AMFHeader header2 = new AMFHeader("RequestPersistentHeader", true, content); context.MessageOutput.AddHeader(header2); ILoginCommand loginCommand = this._endpoint.GetMessageBroker().LoginCommand; if (loginCommand == null) { throw new UnauthorizedAccessException(__Res.GetString("Security_LoginMissing")); } Hashtable credentials = new Hashtable(1); credentials["password"] = password; principal = loginCommand.DoAuthentication(username, credentials); if (principal == null) { throw new UnauthorizedAccessException(__Res.GetString("Security_AccessNotAllowed")); } FluorineContext.Current.StorePrincipal(principal, username, password); str3 = FluorineContext.Current.EncryptCredentials(this._endpoint, principal, username, password); FluorineContext.Current.StorePrincipal(principal, str3); ASObject obj3 = new ASObject(); obj3["name"] = "CredentialsId"; obj3["mustUnderstand"] = false; obj3["data"] = str3; AMFHeader header3 = new AMFHeader("RequestPersistentHeader", true, obj3); context.MessageOutput.AddHeader(header3); } else { header = context.AMFMessage.GetHeader("CredentialsId"); if (header != null) { str3 = header.Content as string; if (str3 != null) { FluorineContext.Current.RestorePrincipal(messageBroker.LoginCommand, str3); } } else { principal = FluorineContext.Current.RestorePrincipal(messageBroker.LoginCommand); } } } catch (UnauthorizedAccessException exception) { for (num = 0; num < context.AMFMessage.BodyCount; num++) { body2 = new ErrorResponseBody(context.AMFMessage.GetBodyAt(num), exception); context.MessageOutput.AddBody(body2); } } catch (Exception exception2) { if ((log != null) && log.get_IsErrorEnabled()) { log.Error(exception2.Message, exception2); } for (num = 0; num < context.AMFMessage.BodyCount; num++) { body2 = new ErrorResponseBody(context.AMFMessage.GetBodyAt(num), exception2); context.MessageOutput.AddBody(body2); } } FluorineContext.Current.User = principal; Thread.CurrentPrincipal = principal; }
internal ErrorResponse(ErrorResponseBody error) { Error = error; }
public override void Invoke(AMFContext context) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); if (!amfBody.IsEmptyTarget) { if (amfBody.IsWebService) { try { Type type = GetTypeForWebService(amfBody.TypeName); if (type != null) { //We can handle it with a LibraryAdapter now amfBody.Target = type.FullName + "." + amfBody.Method; } else { Exception exception = new TypeInitializationException(amfBody.TypeName, null); if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Type_InitError, amfBody.Target), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Wsdl_ProxyGen, amfBody.Target), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } } else { //Flex message object content = amfBody.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if (message != null && message is RemotingMessage) { RemotingMessage remotingMessage = message as RemotingMessage; //Only RemotingMessages for now string source = remotingMessage.source; if (source != null && source.ToLower().EndsWith(".asmx")) { try { Type type = GetTypeForWebService(source); if (type != null) { //We can handle it with a LibraryAdapter now remotingMessage.source = type.FullName; } else { Exception exception = new TypeInitializationException(source, null); if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Type_InitError, source), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, message, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(__Res.GetString(__Res.Wsdl_ProxyGen, source), exception); } ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, message, exception); context.MessageOutput.AddBody(errorResponseBody); } } } } } }
public override void Invoke(AMFContext context) { MessageBroker messageBroker = _endpoint.GetMessageBroker(); try { AMFHeader amfHeader = context.AMFMessage.GetHeader(AMFHeader.CredentialsHeader); if (amfHeader != null && amfHeader.Content != null) { string userId = ((ASObject)amfHeader.Content)["userid"] as string; string password = ((ASObject)amfHeader.Content)["password"] as string; //Clear credentials header, further requests will not send the credentials ASObject asoObject = new ASObject(); asoObject["name"] = AMFHeader.CredentialsHeader; asoObject["mustUnderstand"] = false; asoObject["data"] = null;//clear AMFHeader header = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObject); context.MessageOutput.AddHeader(header); IPrincipal principal = _endpoint.GetMessageBroker().LoginManager.Login(userId, amfHeader.Content as IDictionary); string key = EncryptCredentials(_endpoint, principal, userId, password); ASObject asoObjectCredentialsId = new ASObject(); asoObjectCredentialsId["name"] = AMFHeader.CredentialsIdHeader; asoObjectCredentialsId["mustUnderstand"] = false; asoObjectCredentialsId["data"] = key;//set AMFHeader headerCredentialsId = new AMFHeader(AMFHeader.RequestPersistentHeader, true, asoObjectCredentialsId); context.MessageOutput.AddHeader(headerCredentialsId); } else { amfHeader = context.AMFMessage.GetHeader(AMFHeader.CredentialsIdHeader); if (amfHeader != null) { string key = amfHeader.Content as string; if (key != null) { _endpoint.GetMessageBroker().LoginManager.RestorePrincipal(key); } } else { _endpoint.GetMessageBroker().LoginManager.RestorePrincipal(); } } } catch (UnauthorizedAccessException exception) { for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } catch (Exception exception) { if (log != null && log.IsErrorEnabled) { log.Error(exception.Message, exception); } for (int i = 0; i < context.AMFMessage.BodyCount; i++) { AMFBody amfBody = context.AMFMessage.GetBodyAt(i); ErrorResponseBody errorResponseBody = new ErrorResponseBody(amfBody, exception); context.MessageOutput.AddBody(errorResponseBody); } } }
public override void Invoke(AMFContext context) { MessageOutput messageOutput = context.MessageOutput; for (int i = 0; i < context.AMFMessage.BodyCount; i++) { ResponseBody body2; AMFBody bodyAt = context.AMFMessage.GetBodyAt(i); if (!bodyAt.IsEmptyTarget) { continue; } object content = bodyAt.Content; if (content is IList) { content = (content as IList)[0]; } IMessage message = content as IMessage; if (message == null) { continue; } if (FluorineContext.Current.Client == null) { FluorineContext.Current.SetCurrentClient(this._endpoint.GetMessageBroker().ClientRegistry.GetClient(message)); } if (message.clientId == null) { message.clientId = Guid.NewGuid().ToString("D"); } if (messageOutput.GetResponse(bodyAt) != null) { continue; } try { if (context.AMFMessage.BodyCount > 1) { CommandMessage message2 = message as CommandMessage; if ((message2 != null) && (message2.operation == 2)) { message2.SetHeader(CommandMessage.FluorineSuppressPollWaitHeader, null); } } IMessage message3 = this._endpoint.ServiceMessage(message); if (message3 is ErrorMessage) { ErrorMessage message4 = message3 as ErrorMessage; body2 = new ErrorResponseBody(bodyAt, message, message3 as ErrorMessage); if (!(message4.faultCode == "Client.Authentication")) { goto Label_0291; } messageOutput.AddBody(body2); for (int j = i + 1; j < context.AMFMessage.BodyCount; j++) { bodyAt = context.AMFMessage.GetBodyAt(j); if (bodyAt.IsEmptyTarget) { content = bodyAt.Content; if (content is IList) { content = (content as IList)[0]; } message = content as IMessage; if (message != null) { body2 = new ErrorResponseBody(bodyAt, message, new SecurityException(message4.faultString)); messageOutput.AddBody(body2); } } } break; } body2 = new ResponseBody(bodyAt, message3); } catch (Exception exception) { if ((log != null) && log.get_IsErrorEnabled()) { log.Error(exception.Message, exception); } body2 = new ErrorResponseBody(bodyAt, message, exception); } Label_0291: messageOutput.AddBody(body2); } }
/// <summary> /// Lists all of the available Microsoft.Subscription API operations. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseBodyException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IPage <Operation> > > ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseBodyException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponseBody _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorResponseBody>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <Operation> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page1 <Operation> >(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }