public static void Contains(IEnumerable<HttpParameter> collection, HttpParameter single, string errorMessage) { Assert.IsNotNull(errorMessage, "Test error: errorMessage is required."); Assert.IsNotNull(collection, "Test error: collection cannot be null."); Assert.IsNotNull(single, "Test error: single cannot be null."); bool isContained = collection.Any((hpd) => string.Equals(hpd.Name, single.Name, StringComparison.OrdinalIgnoreCase) && hpd.Type == single.Type); Assert.IsTrue(isContained, errorMessage); }
/// <summary> /// Initializes a new instance of a <see cref="ResponseContentHandler"/> with the /// given <paramref name="responseContentParameter"/> and <paramref name="formatters"/>. /// </summary> /// <param name="responseContentParameter">The <see cref="HttpParameter"/> for the content of the response.</param> /// <param name="formatters">The collection of <see cref="MediaTypeFormatter"/> instances to use for deserializing the response content.</param> public ResponseContentHandler(HttpParameter responseContentParameter, IEnumerable <MediaTypeFormatter> formatters) { if (formatters == null) { throw Fx.Exception.ArgumentNull("formatters"); } Type paramType = responseContentParameter == null ? TypeHelper.VoidType : responseContentParameter.Type; if (paramType == TypeHelper.VoidType) { this.responseMessageConverter = voidHttpResponseMessageConverter; this.outputParameter = HttpParameter.ResponseMessage; } else { paramType = HttpTypeHelper.GetHttpResponseOrContentInnerTypeOrNull(paramType) ?? paramType; if (HttpTypeHelper.IsHttpRequest(paramType)) { throw Fx.Exception.AsError( new InvalidOperationException( SR.InvalidParameterForContentHandler( HttpParameter.HttpParameterType.Name, responseContentParameter.Name, responseContentParameter.Type.Name, responseContentHandlerType.Name))); } Type outputParameterType = HttpTypeHelper.IsHttp(paramType) ? paramType : HttpTypeHelper.MakeHttpResponseMessageOf(paramType); this.outputParameter = new HttpParameter(responseContentParameter.Name, outputParameterType); this.inputParameter = responseContentParameter; if (HttpTypeHelper.IsHttpResponse(paramType)) { this.responseMessageConverter = simpleHttpResponseMessageConverter; } else if (HttpTypeHelper.IsHttpContent(paramType)) { this.responseMessageConverter = httpContentMessageConverter; } else { Type closedConverterType = httpResponseMessageConverterGenericType.MakeGenericType(new Type[] { paramType }); ConstructorInfo constructor = closedConverterType.GetConstructor(Type.EmptyTypes); this.responseMessageConverter = constructor.Invoke(null) as HttpResponseMessageConverter; } } this.Formatters = new MediaTypeFormatterCollection(formatters); }
/// <summary> /// Initializes a new instance of a <see cref="ResponseContentHandler"/> with the /// given <paramref name="responseContentParameter"/> and <paramref name="formatters"/>. /// </summary> /// <param name="responseContentParameter">The <see cref="HttpParameter"/> for the content of the response.</param> /// <param name="formatters">The collection of <see cref="MediaTypeFormatter"/> instances to use for deserializing the response content.</param> public ResponseContentHandler(HttpParameter responseContentParameter, IEnumerable<MediaTypeFormatter> formatters) { if (formatters == null) { throw Fx.Exception.ArgumentNull("formatters"); } Type paramType = responseContentParameter == null ? TypeHelper.VoidType : responseContentParameter.Type; if (paramType == TypeHelper.VoidType) { this.responseMessageConverter = voidHttpResponseMessageConverter; this.outputParameter = HttpParameter.ResponseMessage; } else { paramType = HttpTypeHelper.GetHttpResponseOrContentInnerTypeOrNull(paramType) ?? paramType; if (HttpTypeHelper.IsHttpRequest(paramType)) { throw Fx.Exception.AsError( new InvalidOperationException( SR.InvalidParameterForContentHandler( HttpParameter.HttpParameterType.Name, responseContentParameter.Name, responseContentParameter.Type.Name, responseContentHandlerType.Name))); } Type outputParameterType = HttpTypeHelper.IsHttp(paramType) ? paramType : HttpTypeHelper.MakeHttpResponseMessageOf(paramType); this.outputParameter = new HttpParameter(responseContentParameter.Name, outputParameterType); this.inputParameter = responseContentParameter; if (HttpTypeHelper.IsHttpResponse(paramType)) { this.responseMessageConverter = simpleHttpResponseMessageConverter; } else if (HttpTypeHelper.IsHttpContent(paramType)) { this.responseMessageConverter = httpContentMessageConverter; } else { Type closedConverterType = httpResponseMessageConverterGenericType.MakeGenericType(new Type[] { paramType }); ConstructorInfo constructor = closedConverterType.GetConstructor(Type.EmptyTypes); this.responseMessageConverter = constructor.Invoke(null) as HttpResponseMessageConverter; } } this.Formatters = new MediaTypeFormatterCollection(formatters); }
/// <summary> /// Implementation of <see cref="HttpOperationHandler.OnGetOutputParameters"/> that always returns /// the output <see cref="HttpParameter"/> instances of the service operation. /// </summary> /// <returns>The output <see cref="HttpParameter"/> instances of the service operation.</returns> protected override IEnumerable <HttpParameter> OnGetOutputParameters() { List <HttpParameter> outputParameters = new List <HttpParameter>(this.httpOperationDescription.OutputParameters); HttpParameter returnValue = this.httpOperationDescription.ReturnValue; if (returnValue != null) { outputParameters.Insert(0, returnValue); } return(outputParameters); }
public void InputParametersReturnsReadOnlyCollection() { SHttpOperationHandler handler = new SHttpOperationHandler(); handler.OnGetInputParameters01 = () => new HttpParameter[] { new HttpParameter("arg1", typeof(string)) }; ReadOnlyCollection <HttpParameter> arguments = handler.InputParameters; Assert.IsNotNull(arguments, "InputParameters should never be null."); Assert.AreEqual(1, arguments.Count, "InputParameters.Count should have been 1."); HttpParameter hpd = arguments[0]; Assert.AreEqual("arg1", hpd.Name, "Did not set inputParameters[0] corectly."); }
//private static string FormatPropertyValue(PropertyInfo pi, object sample) //{ // var val = pi.GetValue(sample, null); // if (val == null) return "null"; // if (pi.PropertyType == typeof (DateTime) || // Nullable.GetUnderlyingType(pi.PropertyType) == typeof (DateTime)) // return "'\\/Date(" + (long)((DateTime)val - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds + "+" // + TimeZoneInfo.Local.BaseUtcOffset.Hours.ToString("D2") // + TimeZoneInfo.Local.BaseUtcOffset.Minutes.ToString("D2") + ")\\/'".Replace("+-", "-"); // var omitQuotes = IsNumericType(pi.PropertyType); // return omitQuotes // ? Converter.GetStringFromObject(val) // : "'" + Converter.GetStringFromObject(val) + "'"; //} //private static readonly HashSet<Type> numericTypes = new HashSet<Type> //{ // typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal) //}; //internal static bool IsNumericType(Type type) //{ // return numericTypes.Contains(type) || // numericTypes.Contains(Nullable.GetUnderlyingType(type)); //} /// <summary> /// вернуть true если дальнейшая обработка запроса не требуется /// </summary> private static bool ProcessQueryString(NameValueCollection query, out string resp) { resp = string.Empty; if (query.AllKeys.Contains("reset")) { ResetServiceState(); return(false); } // вернуть сессии пользователей if (query.AllKeys.Contains("current_session")) { var sessions = UserSessionStorage.Instance.GetSessions(); var userInfos = sessions.Select(s => new TerminalUser { IP = s.ip, Login = s.login, Account = s.accountId }).Cast <HttpParameter>().ToList(); resp = HttpParameter.SerializeInJSon(userInfos); return(true); } if (query.AllKeys.Contains("sendMessage") && query.AllKeys.Contains("terminal")) { var msg = query["sendMessage"]; var terminal = query["terminal"].ToLongSafe() ?? 0; Logger.InfoFormat("Command send message (\"{0}\" to {1})", msg, terminal); SendMessageToTerminal(msg, terminal); return(true); } if (query.AllKeys.Contains("logoutUser")) { var terminal = query["logoutUser"].ToLongSafe() ?? 0; Logger.InfoFormat("Logout user {0}", terminal); UserSessionStorage.Instance.ExcludeStaleSessions(new List <long> { terminal }); return(true); } return(false); }
public static void AreEqual(HttpParameter expected, HttpParameter actual, string errorMessage) { Assert.IsNotNull(errorMessage, "Test error: errorMessage is required."); if (expected == null) { Assert.IsNull(actual, string.Format("{0} were expecting null but found non-null.", errorMessage)); } Assert.IsNotNull(actual, string.Format("{0} were expecting non-null but found null.", errorMessage)); Assert.AreEqual(expected.Name, actual.Name, string.Format("{0} Name mismatch.", errorMessage)); Assert.AreEqual(expected.Type, actual.Type, string.Format("{0} Type mismatch.", errorMessage)); }
public void OutputParametersPreservesOrderFromOnGetOutputParameters() { HttpParameter[] parameters = new HttpParameter[] { new HttpParameter("arg1", typeof(string)), new HttpParameter("arg2", typeof(int)) }; SHttpOperationHandler handler = new SHttpOperationHandler(); handler.OnGetOutputParameters01 = () => parameters; ReadOnlyCollection <HttpParameter> arguments = handler.OutputParameters; HttpParameterAssert.AreEqual(parameters, arguments, "Order was not preserved."); }
public Task HandleRequest(HttpParameter parameter, HttpRequest request) { try { //Get all attributed headers var headerList = Headers.GetOrAdd(parameter.GetType(), HandleType); headerList.ForEach(header => request.AddHeader(header.Key, header.Value)); return(Task.FromResult(true)); } catch (Exception e) { Error(e); return(Task.FromResult(false)); } }
public void Serialization() { var time = DateTime.Now; var objects = new List <HttpParameter> { new TradeSharpServiceProcess { FileName = "TradeSharp.SiteBridge", Name = "SiteBridge", Title = "Мост Web-сервиса" }, new TradeSharpServiceProcess { FileName = "TradeSharp.Quote", Name = "Quote", Title = "Котировки" }, new TradeSharpServiceStartStop { ShouldStart = true, SrvName = "TradeSharp.SiteBridge" }, new ExecutionReport { Comment = "not OK", IsOk = false }, new TerminalUser { Account = 100, IP = "198.15.12.45", Login = "******" }, new ChangeAccountBalanceQuery { AccountId = 3, ChangeType = BalanceChangeType.Deposit, Amount = 0.15M, ValueDate = time } }; var str = HttpParameter.SerializeInJSon(objects); var objs = HttpParameter.DeserializeFromJSon(str); Assert.IsNotNull(objs); Assert.AreEqual(objs.Count, objects.Count); Assert.IsFalse(objects.Select(o => o.ToString()).Except(objs.Select(o => o.ToString())).Any()); }
public void Constructor() { HttpParameter hpd = new HttpParameter("x", typeof(int)); HttpParameter expectedContentParameter = new HttpParameter("x", typeof(HttpRequestMessage <int>)); SMediaTypeFormatter formatter = new SMediaTypeFormatter() { CallBase = true }; MediaTypeFormatter[] formatters = new MediaTypeFormatter[] { formatter }; RequestContentHandler handler = new RequestContentHandler(hpd, formatters); HttpParameterAssert.ContainsOnly(handler.InputParameters, HttpParameter.RequestMessage, "Failed to initialize input parameters to HttpRequestMessage."); HttpParameterAssert.ContainsOnly(handler.OutputParameters, expectedContentParameter, "Failed to initialize content parameter."); CollectionAssert.Contains(handler.Formatters, formatter, "Failed to accept mediaTypeFormatter."); }
public void OutputParameterAreCreatedAllValueAndReferenceTypes() { TestDataAssert.Execute( HttpTestData.RepresentativeValueAndRefTypeTestDataCollection, TestDataVariations.All, "OutputParameters all types failed.", (type, obj) => { Type convertType = obj == null ? type : obj.GetType(); HttpParameter hpd = new HttpParameter("x", convertType); Type expectedType = typeof(HttpRequestMessage <>).MakeGenericType(convertType); HttpParameter expectedContentParameter = new HttpParameter("x", expectedType); RequestContentHandler handler = new RequestContentHandler(hpd, Enumerable.Empty <MediaTypeFormatter>()); HttpParameterAssert.ContainsOnly(handler.OutputParameters, expectedContentParameter, string.Format("Failed to initialize content parameter for {0}.", convertType.Name)); }); }
public void HandleCallsOnHandle() { HttpParameter[] parameters = new HttpParameter[] { new HttpParameter("arg1", typeof(string)), }; SHttpOperationHandler handler = new SHttpOperationHandler(); bool called = false; handler.OnGetInputParameters01 = () => parameters; handler.OnGetOutputParameters01 = () => parameters; handler.OnHandleObjectArray = (oArray) => { called = true; return(oArray); }; handler.Handle(new object[] { "fred" }); Assert.IsTrue(called, "Handle did not call OnHandle."); }
public void HandleThrowsWithNullInput() { HttpParameter[] parameters = new HttpParameter[] { new HttpParameter("arg1", typeof(string)), }; SHttpOperationHandler handler = new SHttpOperationHandler() { CallBase = true }; handler.OnGetInputParameters01 = () => parameters; handler.OnGetOutputParameters01 = () => parameters; ExceptionAssert.ThrowsArgumentNull("input", () => handler.Handle(null)); }
public void HandleReturnsEmptyArrayIfOnHandleReturnsNull() { HttpParameter[] parameters = new HttpParameter[] { new HttpParameter("arg1", typeof(string)), }; SHttpOperationHandler handler = new SHttpOperationHandler(); handler.OnGetInputParameters01 = () => parameters; handler.OnGetOutputParameters01 = () => parameters; handler.OnHandleObjectArray = (oArray) => null; object[] result = handler.Handle(new object[] { "fred" }); Assert.IsNotNull(result, "Handle returned null."); Assert.AreEqual(1, result.Length, "Handle returned wrong length array."); Assert.IsNull(result[0], "Handle did not return empty array."); }
/// <summary> /// 獲得一個webrequest的實例 /// </summary> /// <returns></returns> protected HttpWebRequest GetRequestInstance(HttpParameter hp, ResponseObject hd) { var handler = new HttpClientHandler(); HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(new Uri(hp.ToUrl)); string cookieheader = ""; if (hr.CookieContainer != null) { cookieheader = hr.CookieContainer.GetCookieHeader(new Uri(hp.ToUrl)); } CookieContainer cookieCon = new CookieContainer(); hr.CookieContainer = cookieCon; hr.CookieContainer.SetCookies(new Uri(hp.ToUrl), cookieheader); hr.Method = hp.RequestMethod; hr.Proxy = hp.HttpWebProxy; //if (_cert != null) //{ // hr.ClientCertificates.Add(_cert); //} //添加header foreach (var k in hp.Header.Keys) { if (k.ToLower() == "date") { hr.Headers["Date"] = DateTimeStd.IsDateTime(hp.Header.GetValue(k)) ? DateTimeStd.ParseStd(ComFunc.nvl(hp.Header.GetValue(k))).Value.ToUniversalTime().ToString("r") : DateTime.Now.ToString("r"); } else if (k.ToLower() == "content-length") { hr.Headers["Content-Length"] = ComFunc.nvl(hp.Header.GetValue(k)); } else if (k.ToLower() == "user-agent") { hr.Headers["User-Agent"] = ComFunc.nvl(hp.Header.GetValue(k)); } else { hr.Headers[k] = ComFunc.nvl(hp.Header.GetValue(k)); } } return(hr); }
public void HandlePropagatesExceptionFromOnHandle() { HttpParameter hpd = new HttpParameter("arg1", typeof(int)); HttpParameter[] parameters = new HttpParameter[] { hpd }; SHttpOperationHandler handler = new SHttpOperationHandler(); handler.OnGetInputParameters01 = () => parameters; handler.OnGetOutputParameters01 = () => parameters; handler.OnHandleObjectArray = (oArray) => { throw new NotSupportedException("myMessage"); }; ExceptionAssert.Throws <NotSupportedException>( "myMessage", () => handler.Handle(new object[] { 5 }) ); }
public void OutputParametersClonesParametersFromOnGetInputParameters() { HttpParameter[] parameters = new HttpParameter[] { new HttpParameter("arg1", typeof(string)), }; SHttpOperationHandler handler = new SHttpOperationHandler(); handler.OnGetOutputParameters01 = () => parameters; ReadOnlyCollection <HttpParameter> arguments = handler.OutputParameters; bool isContentParameterOriginal = parameters[0].IsContentParameter; bool isContentParameterCloned = arguments[0].IsContentParameter; Assert.AreEqual(isContentParameterOriginal, isContentParameterCloned, "IsContentParameter property was not properly cloned."); parameters[0].IsContentParameter = !isContentParameterOriginal; Assert.AreEqual(isContentParameterOriginal, isContentParameterCloned, "IsContentParameter property on original should not have affected clone."); }
/// <summary> /// Add Authorization header to the <see cref="HttpRequest" /> /// </summary> /// <param name="parameter">The parameter for the request</param> /// <param name="request">The http request</param> public async Task HandleRequest(HttpParameter parameter, HttpRequest request) { try { var requireAuth = AuthTypes.GetOrAdd(parameter.GetType(), HandleType); if (requireAuth) { var accessToken = await AuthorizationService.GetAccessToken(); request.AddHeader("Authorization", $"Bearer {accessToken}"); } } catch (Exception e) { Error(e); } }
private static string ProcessFormattedRequestRegister(List <HttpParameter> ptrs) { if (ptrs.Count != 1 || ptrs[0] is RegisterAccountQuery == false) { return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = false, Comment = "Список параметров (JSON) - ожидается один параметр типа RegisterAccountQuery" } })); } var queryPtr = (RegisterAccountQuery)ptrs[0]; var status = ManagerAccount.Instance.RegisterAccount( new PlatformUser { Login = queryPtr.UserLogin, Password = queryPtr.UserPassword, Name = queryPtr.UserName, Surname = queryPtr.UserSurname, Patronym = queryPtr.UserPatronym, Description = queryPtr.UserDescription, Title = queryPtr.UserLogin, Email = queryPtr.UserEmail, Phone1 = queryPtr.UserPhone1, Phone2 = queryPtr.UserPhone2, RegistrationDate = DateTime.Now, RightsMask = queryPtr.UserRightsMask, RoleMask = queryPtr.UserRoleMask }, queryPtr.Currency, (int)queryPtr.Balance, (decimal)queryPtr.MaxLeverage, queryPtr.UserPassword, // пароль задан заранее, автоматом не сочиняем false); // не подписывать автоматом на торговые сигналы лучших в мире трейдеров return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = status == AccountRegistrationStatus.OK, Comment = EnumFriendlyName <AccountRegistrationStatus> .GetString(status) } })); }
public void InputParameterAreCreatedAllValueAndReferenceTypes() { TestDataAssert.Execute( HttpTestData.RepresentativeValueAndRefTypeTestDataCollection, TestDataVariations.All, "InputParameters for all types failed.", (type, obj) => { Type convertType = obj == null ? type : obj.GetType(); HttpParameter hpd = new HttpParameter("x", convertType); Type expectedType = typeof(HttpResponseMessage <>).MakeGenericType(convertType); HttpParameter expectedContentParameter = new HttpParameter("x", expectedType); ResponseContentHandler handler = new ResponseContentHandler(hpd, Enumerable.Empty <MediaTypeFormatter>()); HttpParameterAssert.Contains(handler.InputParameters, HttpParameter.RequestMessage, "Failed to initialize input parameters for RequestMessage."); HttpParameterAssert.Contains(handler.InputParameters, hpd, "Failed to initialize input parameter."); }); }
/// <summary> /// Normalizes the request parameters according to the spec /// </summary> /// <param name="parameters">The list of parameters already sorted</param> /// <returns>a string representing the normalized parameters</returns> private string NormalizeRequestParameters(IList <HttpParameter> parameters) { StringBuilder sb = new StringBuilder(); HttpParameter p = null; for (int i = 0; i < parameters.Count; i++) { p = parameters[i]; sb.AppendFormat("{0}={1}", p.Name, UrlEncode(p.Value)); if (i < parameters.Count - 1) { sb.Append("&"); } } return(sb.ToString()); }
public ActionResult StartStopServiceAjax(string name, bool start) { var shouldStart = start; if (string.IsNullOrEmpty(name)) { return(Json(new { result = Resource.ErrorMessage }, JsonRequestBehavior.AllowGet)); } // отправить запрос на останов сервиса var result = Resource.ErrorMessageServer; var request = new TradeSharpServiceStartStop { ShouldStart = shouldStart, SrvName = HttpUtility.UrlDecode(name.Trim()) }; try { string rawData; var procList = HttpParameter.DeserializeServerResponse(urlWatchSrv + QueryPtr, new List <HttpParameter> { request }, out rawData, userName, userPwrd).Cast <ExecutionReport>().ToList(); result = procList.Count > 0 ? (procList[0].IsOk ? "OK" : Resource.ErrorMessage + ": " + procList[0].Comment) : rawData; if (string.IsNullOrEmpty(result)) { result = Resource.ErrorMessageCommon; } } catch (Exception ex) { Logger.Error("StartStopServiceAjax", ex); } return(Json(new { result = result }, JsonRequestBehavior.AllowGet)); }
internal IEnumerable <HttpParameter> BuildInputParameterCollection() { MethodInfo executeMethod = this.HandleMethod; if (executeMethod == null) { return(Enumerable.Empty <HttpParameter>()); } ParameterInfo[] parameterInfos = executeMethod.GetParameters(); HttpParameter[] arguments = new HttpParameter[parameterInfos.Length]; for (int i = 0; i < parameterInfos.Length; ++i) { ParameterInfo parameter = parameterInfos[i]; HttpParameter pad = new HttpParameter(parameter.Name, parameter.ParameterType); arguments[i] = pad; } return(arguments); }
/// <summary> /// параметры запроса переданы в формате JSON /// /// возвращает ответ, сериализованный в JSON /// если параметры запроса не прочитаны - вернуть состояние всех сервисов /// иначе - выполнить действие /// </summary> private string ProcessFormattedHttpRequest(HttpListenerContext context) { using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) { var text = reader.ReadToEnd(); if (string.IsNullOrEmpty(text)) { return(GetServiceStateJSon()); } var ptrs = HttpParameter.DeserializeFromJSon(text); if (ptrs.Count == 0) { return(GetServiceStateJSon()); } // остановить / запустить сервис if (ptrs[0] is TradeSharpServiceStartStop) { var cmd = (TradeSharpServiceStartStop)ptrs[0]; var report = new ExecutionReport(); if (cmd.ShouldStart) { var status = ServiceProcessManager.StartProcess(cmd.SrvName); report.IsOk = status == ServiceProcessManager.StartProcessStatus.OK; report.Comment = status.ToString(); } else { var status = ServiceProcessManager.KillProcess(cmd.SrvName); report.IsOk = status == ServiceProcessManager.KillProcessStatus.OK; report.Comment = status.ToString(); } return(HttpParameter.SerializeInJSon(new List <HttpParameter> { report })); } } return(GetServiceStateJSon()); }
/// <summary> /// Retrieves the collection of <see cref="HttpParameter"/> instances describing the /// output values of this <see cref="UriTemplateHandler"/>. /// </summary> /// <remarks> /// The <see cref="UriTemplateHandler"/> always returns output <see cref="HttpParameter"/> /// instances in which the <see cref="HttpParameter.Name"/> is the <see cref="UriTemplateHandler.UriTemplate"/> /// variable and the <see cref="HttpParameter.Type"/> is of type <see cref="String"/>. /// </remarks> /// <returns>The collection of <see cref="HttpParameter"/> instances.</returns> protected override sealed IEnumerable <HttpParameter> OnGetOutputParameters() { int numberOfVariables = this.UriTemplate.PathSegmentVariableNames.Count + this.UriTemplate.QueryValueVariableNames.Count; HttpParameter[] parameters = new HttpParameter[numberOfVariables]; int i = 0; foreach (string name in this.UriTemplate.PathSegmentVariableNames) { parameters[i] = new HttpParameter(name, TypeHelper.StringType); i++; } foreach (string name in this.UriTemplate.QueryValueVariableNames) { parameters[i] = new HttpParameter(name, TypeHelper.StringType); i++; } return(parameters); }
private string ProcessFormattedHttpRequest(HttpListenerContext context) { using (var reader = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding)) { var text = reader.ReadToEnd(); if (string.IsNullOrEmpty(text)) { return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = false, Comment = "Список параметров (JSON) пуст" } })); } var ptrs = HttpParameter.DeserializeFromJSon(text); if (ptrs.Count == 0) { return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = false, Comment = "Список параметров (JSON) - ошибка десериализации" } })); } if (context.Request.QueryString.AllKeys.Contains("register")) { return(ProcessFormattedRequestRegister(ptrs)); } if (context.Request.QueryString.AllKeys.Contains("balance")) { return(ProcessFormattedRequestBalance(ptrs)); } } return(HttpParameter.SerializeInJSon(new List <HttpParameter> { new ExecutionReport { IsOk = false, Comment = "Запрос не поддерживается" } })); }
public void InputParametersReturnsReflectedHttpParameters() { List <Type> types = new List <Type>(); TestDataAssert.Execute( TestData.RepresentativeValueAndRefTypeTestDataCollection, (type, obj) => { if (!types.Contains(type)) { types.Add(type); for (int i = 2; i <= 17; i++) { if (types.Count - i < 0) { break; } Type[] typeArray = types.Skip(types.Count - i).ToArray(); HttpOperationHandler genericHandler = GetGenericHandlerForTypes(typeArray); for (int j = 0; j < genericHandler.InputParameters.Count; j++) { HttpParameter parameter = genericHandler.InputParameters[j]; Assert.AreEqual(typeArray[j], parameter.Type, "The HttpParameter.Type should have been the same type as from the array."); if (i == 2) { Assert.AreEqual("input", parameter.Name, "The HttpParameter.Name should have been 'input'."); } else { string expectedName = "input" + (j + 1).ToString(); Assert.AreEqual(expectedName, parameter.Name, string.Format("The HttpParameter.Name should have been '{0}'.", expectedName)); } } } } }); }
public void HandleThrowsWithTooLargeInput() { HttpParameter[] parameters = new HttpParameter[] { new HttpParameter("arg1", typeof(string)), }; SHttpOperationHandler handler = new SHttpOperationHandler() { CallBase = true }; handler.OnGetInputParameters01 = () => parameters; handler.OnGetOutputParameters01 = () => parameters; string errorMessage = SR.HttpOperationHandlerReceivedWrongNumberOfValues( typeof(HttpOperationHandler).Name, handler.ToString(), handler.OperationName, parameters.Length, 2); ExceptionAssert.Throws <InvalidOperationException>(errorMessage, () => handler.Handle(new object[2])); }
public static string VerifyEthAddress(string addr) { HttpParameter param = new HttpParameter(); param.Url = "https://etherscan.io/address/" + addr; var result = HttpClient.GetPage(param); Regex rx = new Regex(@"\d+(<b>.</b>\d+)?\sEther"); Regex rxInvalid = new Regex(@"Ethereum\sAccount\s\(Invalid\sAddress\)"); if (rxInvalid.IsMatch(result.RawData)) { return(null); } if (rx.IsMatch(result.RawData)) { return(rx.Match(result.RawData).Value.Replace("<b>", "").Replace("</b>", "").Replace("Ether", "").Trim()); } return(null); }
public ActionResult ListSystemServicesAjax() { List <TradeSharpServiceProcess> procList = null; // получить данные от сервиса WatchService try { string rawData; procList = HttpParameter.DeserializeServerResponse(urlWatchSrv + QueryPtr, null, out rawData, userName, userPwrd) .Cast <TradeSharpServiceProcess>() .ToList(); } catch (Exception ex) { Logger.Error("ListSystemServicesAjax", ex); procList = new List <TradeSharpServiceProcess>(); } return(Json(new { Records = procList }, JsonRequestBehavior.AllowGet)); }
private static RequestParameterSerializationStyle GetSerializationStyle(HttpParameter httpParameter, Schema valueSchema) { Debug.Assert(httpParameter.In == ParameterLocation.Query || httpParameter.In == ParameterLocation.Header); switch (httpParameter.Style) { case null: case SerializationStyle.Form: case SerializationStyle.Simple: return(valueSchema is ArraySchema ? RequestParameterSerializationStyle.CommaDelimited : RequestParameterSerializationStyle.Simple); case SerializationStyle.PipeDelimited: return(RequestParameterSerializationStyle.PipeDelimited); case SerializationStyle.SpaceDelimited: return(RequestParameterSerializationStyle.SpaceDelimited); case SerializationStyle.TabDelimited: return(RequestParameterSerializationStyle.TabDelimited); default: throw new ArgumentOutOfRangeException(); } }
private static void ThrowForUnboundServiceOperation(HttpParameter parameter, string operationName) { Fx.Assert(parameter != null, "The 'parameter' parameter should not be null."); Fx.Assert(operationName != null, "The 'operationName' parameter should not be null."); string exceptionMessage = null; if (parameter.ValueConverter.CanConvertFromString) { exceptionMessage = SR.ServiceOperationWithNoPossibleBindingForStringConvertableType( operationName, parameter.Name, parameter.Type.Name, HttpOperationHandler.HttpOperationHandlerType.Name); } else { exceptionMessage = SR.ServiceOperationWithNoPossibleBindingForNonStringConvertableType( operationName, parameter.Name, parameter.Type.Name, HttpOperationHandler.HttpOperationHandlerType.Name); } Fx.Assert(exceptionMessage != null, "The 'exceptionMessage' variable should have been set."); throw Fx.Exception.AsError(new InvalidOperationException(exceptionMessage)); }
public static OperationDescription GetEquivalentOperationDescription(OperationDescription operation) { Fx.Assert(operation != null, "OperationDescription cannnot be null"); OperationDescription copy = CreateEmptyOperationDescription(operation); HttpOperationDescription httpDescription = copy.ToHttpOperationDescription(); HttpOperationDescription originalHttpDescription = operation.ToHttpOperationDescription(); UriTemplate template = originalHttpDescription.GetUriTemplate(); List<string> templateVariables = new List<string>(template.PathSegmentVariableNames.Concat(template.QueryValueVariableNames)); IEnumerable<HttpParameter> originalRequestBodyParameters = originalHttpDescription.InputParameters.Where(param => param.IsContentParameter); IEnumerable<HttpParameter> originalResponseBodyParameters = originalHttpDescription.OutputParameters.Where(param => param.IsContentParameter); IEnumerable<HttpParameter> originalUriTemplateParameters = originalHttpDescription.InputParameters.Where( (param) => { foreach (string templateVariable in templateVariables) { if (string.Equals(templateVariable, param.Name, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; }); httpDescription.ReturnValue = originalHttpDescription.ReturnValue; // add UriTemplate parameters foreach (HttpParameter parameter in originalUriTemplateParameters) { httpDescription.InputParameters.Add(parameter); } // add body parameters foreach (HttpParameter parameter in originalRequestBodyParameters) { httpDescription.InputParameters.Add(parameter); } int index = httpDescription.InputParameters.Count; int requestBodyParametersCount = originalRequestBodyParameters.Count<HttpParameter>(); int responseBodyParametersCount = originalResponseBodyParameters.Count<HttpParameter>(); if (requestBodyParametersCount == 0 || responseBodyParametersCount == 0) { // Special case if any input parameter is HttpRequestMessage or HttpResponseMessage foreach (HttpParameter inputParameter in originalHttpDescription.InputParameters) { if (requestBodyParametersCount == 0 && originalHttpDescription.GetHttpMethod() != HttpMethod.Get && httpRequestMessageType.IsAssignableFrom(inputParameter.Type)) { // add the HttpRequestmessage as a body parameter of type Message HttpParameter parameter = new HttpParameter(new MessagePartDescription(inputParameter.Name, string.Empty) { Type = typeof(Message), Index = index++ }); httpDescription.InputParameters.Add(parameter); } if (!operation.IsOneWay && responseBodyParametersCount == 0 && httpResponseMessageType.IsAssignableFrom(inputParameter.Type)) { // add the HttpResponsemessage as a return value of type Message httpDescription.ReturnValue = new HttpParameter(new MessagePartDescription(inputParameter.Name, string.Empty) { Type = typeof(Message) }); } } } foreach (HttpParameter parameter in originalResponseBodyParameters) { // cannot do a byRef comparison here if (parameter.Type != originalHttpDescription.ReturnValue.Type || !string.Equals(parameter.Name, originalHttpDescription.ReturnValue.Name, StringComparison.OrdinalIgnoreCase)) { httpDescription.OutputParameters.Add(parameter); } } if (responseBodyParametersCount == 0) { foreach (HttpParameter outputParameter in originalHttpDescription.OutputParameters) { // special case HttpResponseMessage when it is set as an out parameter if (httpResponseMessageType.IsAssignableFrom(outputParameter.Type)) { httpDescription.ReturnValue = new HttpParameter(new MessagePartDescription(outputParameter.Name, string.Empty) { Type = typeof(Message) }); } } } if (templateVariables.Count > originalUriTemplateParameters.Count<HttpParameter>()) { // this means that we have some UriTemplate variables that are not explicitly bound to an input parameter foreach (HttpParameter parameter in originalUriTemplateParameters) { templateVariables.Remove(parameter.Name); } foreach (string variable in templateVariables) { HttpParameter parameter = new HttpParameter(new MessagePartDescription(variable, operation.DeclaringContract.Namespace) { Type = typeof(string), Index = index++ }); httpDescription.InputParameters.Add(parameter); } } return httpDescription.ToOperationDescription(); }
public static void ContainsOnly(IEnumerable<HttpParameter> collection, HttpParameter single, string errorMessage) { Assert.IsNotNull(errorMessage, "Test error: errorMessage is required."); Assert.IsNotNull(collection, "Test error: collection cannot be null."); Assert.IsNotNull(single, "Test error: single cannot be null."); int count = collection.Where((hpd) => string.Equals(hpd.Name, single.Name, StringComparison.OrdinalIgnoreCase) && hpd.Type == single.Type).Count(); Assert.AreEqual(1, count, errorMessage); }
private static void ThrowForUnboundParameter(HttpOperationHandler handler, HttpParameter parameter, HandlerType handlerType, string operationName) { Fx.Assert(handler != null, "The 'handler' parameter should not be null."); Fx.Assert(parameter != null, "The 'parameter' parameter should not be null."); Fx.Assert(operationName != null, "The 'operationName' parameter should not be null."); if (handler == responseMessageSinkHandler) { throw Fx.Exception.AsError( new InvalidOperationException( SR.ResponseSinkHandlerWithNoHttpResponseMessageSource( HttpOperationHandler.HttpOperationHandlerType.Name, HttpTypeHelper.HttpResponseMessageType.Name, operationName))); } switch (handlerType) { case HandlerType.Request: ThrowForUnboundRequestHandler(handler, parameter, operationName); break; case HandlerType.ServiceOperation: ThrowForUnboundServiceOperation(parameter, operationName); break; case HandlerType.Response: ThrowForUnboundResponseHandler(handler, parameter, operationName); break; default: Fx.Assert("The handlerType should have been one of the above cases."); break; } }
private static void ValidateResponseContentParameter(HttpParameter responseContentParameter, bool isReturnValue, string operationName) { Fx.Assert(responseContentParameter != null, "The 'responseContentParameter' parameter should not be null."); Fx.Assert(operationName != null, "The 'operationName' parameter should not be null."); if (!IsValidContentType(responseContentParameter) || HttpTypeHelper.HttpRequestMessageType.IsAssignableFrom(responseContentParameter.Type)) { if (isReturnValue) { throw Fx.Exception.AsError( new InvalidOperationException( SR.InvalidReturnValueContentParameter( operationName, responseContentParameter.Type.Name, httpOperationHandlerFactoryType.Name))); } throw Fx.Exception.AsError( new InvalidOperationException( SR.InvalidResponseContentParameter( operationName, responseContentParameter.Type.Name, httpOperationHandlerFactoryType.Name))); } }
internal IEnumerable<HttpParameter> BuildInputParameterCollection() { MethodInfo executeMethod = this.HandleMethod; if (executeMethod == null) { return Enumerable.Empty<HttpParameter>(); } ParameterInfo[] parameterInfos = executeMethod.GetParameters(); HttpParameter[] arguments = new HttpParameter[parameterInfos.Length]; for (int i = 0; i < parameterInfos.Length; ++i) { ParameterInfo parameter = parameterInfos[i]; HttpParameter pad = new HttpParameter(parameter.Name, parameter.ParameterType); arguments[i] = pad; } return arguments; }
private static void ThrowExceptionForMulitpleResponseContentParameters(List<HttpParameter> possibleContentParameters, HttpParameter returnValue, string operationName) { Fx.Assert(possibleContentParameters != null, "The 'possibleContentParameters' parameter should not be null."); Fx.Assert(returnValue != null, "The 'returnValue' parameter should not be null."); Fx.Assert(operationName != null, "The 'operationName' parameter should not be null."); string errorMessage = SR.MultipleResponseContentParameters( httpOperationHandlerFactoryType.Name, operationName, possibleContentParameters.Count); StringBuilder stringBuilder = new StringBuilder(errorMessage); foreach (HttpParameter parameter in possibleContentParameters) { string parameterMessage = null; if (parameter.IsContentParameter) { if (parameter == returnValue) { parameterMessage = SR.ReturnValueWithIsContentParameterSet( HttpParameter.IsContentParameterPropertyName, bool.TrueString); } else { parameterMessage = SR.ResponseParameterWithIsContentParameterSet( parameter.Name, HttpParameter.IsContentParameterPropertyName, bool.TrueString); } } else { if (parameter == returnValue) { parameterMessage = SR.ReturnValueWithContentType( parameter.Type.Name); } else { parameterMessage = SR.ResponseParameterWithContentType( parameter.Name, parameter.Type.Name); } } stringBuilder.Append(Environment.NewLine); stringBuilder.Append(parameterMessage); } throw Fx.Exception.AsError(new InvalidOperationException(stringBuilder.ToString())); }
private static void SetXmlAndJsonSerializers(HttpOperationDescription operation, HttpParameter httpParameter, MediaTypeFormatterCollection formatters) { Fx.Assert(operation != null, "The 'operation' parameter should not be null."); Fx.Assert(httpParameter != null, "The 'httpParameter' parameter should not be null."); Fx.Assert(formatters != null, "The 'formatters' parameter should not be null."); Type contentType = HttpTypeHelper.GetHttpInnerTypeOrNull(httpParameter.Type) ?? httpParameter.Type; if (contentType != typeof(JsonValue) && !HttpTypeHelper.IsHttp(contentType)) { SetSerializerForXmlFormatter(operation, contentType, formatters); SetSerializerForJsonFormatter(operation, contentType, httpParameter.Name, formatters); } }
private static bool IsValidContentType(HttpParameter requestContentParameter) { Fx.Assert(requestContentParameter != null, "The 'requestContentParameter' parameter should not be null."); foreach (Type invalidType in invalidContentTypes) { if (invalidType.IsAssignableFrom(requestContentParameter.Type)) { return false; } } return true; }
private static bool IsPossibleResponseContentParameter(HttpParameter parameter) { Fx.Assert(parameter != null, "The 'parameter' parameter should not be null."); if (parameter.IsContentParameter || HttpTypeHelper.GetHttpResponseOrContentInnerTypeOrNull(parameter.Type) != null) { return true; } return false; }
internal IEnumerable<HttpParameter> BuildOutputParameterCollection(string outputParameterName) { HttpParameter parameter = new HttpParameter(outputParameterName, this.OutputParameterType); return new HttpParameter[] { parameter }; }