public DeckCloudFileResponse(DataSet dset, RequestType requestType) { // Get the only row in the cloud_file table. DataRow deckCloudFile = dset.Tables["cloud_file"].AsEnumerable().Single(); // Get the file data ID. FileDataId = deckCloudFile.Field<long>("id"); if (requestType != RequestType.FinishChunking) { // Get the only row in the multipart_upload table. DataRow deckMultipartUpload = dset.Tables["multipart_upload"].AsEnumerable().Single(); // Get the multipart upload ID. UploadId = deckMultipartUpload.Field<string>("id"); } if (requestType == RequestType.RequestChunk) { // Get the only row in the parameters table. DataRow deckParameters = dset.Tables["parameters"].AsEnumerable().Single(); // Get the upload parameters. DeckCloudUploadInfo = new DeckCloudUploadInformation(deckParameters); } }
/// <summary> /// Excute request async method operator [httpclient version] /// </summary> /// <param name="requestUrl">Request Url</param> /// <param name="requestType">Request Type</param> /// <param name="postArguemntList">Post Argument List</param> public void ExcuteAsyncRequest(string requestUrl, RequestType requestType,List<KeyValuePair<string,object>> postArguemntList=null) { HttpClient requestClient = new HttpClient(); if (requestType == RequestType.GET) requestClient.GetAsync(requestUrl).ContinueWith((postback) => { postback.Result.EnsureSuccessStatusCode(); if (AsyncResponseComplated != null) AsyncResponseComplated(postback.Result.Content.ReadAsStringAsync().Result, null); }); else if (requestType == RequestType.POST) { HttpContent content=null; if (postArguemntList != null) { List<KeyValuePair<string, string>> argumentList = null; postArguemntList.ForEach(queryArgument => { argumentList.Add(new KeyValuePair<string,string>(queryArgument.Key,queryArgument.Value.ToString())); }); content = new FormUrlEncodedContent(argumentList); } requestClient.PostAsync(requestUrl, content).ContinueWith((postback) => { postback.Result.EnsureSuccessStatusCode(); if (AsyncResponseComplated != null) AsyncResponseComplated(postback.Result.Content.ReadAsStringAsync().Result, null); }); } }
public Task<Response> SendAsync(object data, RequestType type) { Request req = new Request() { Data = data, RequestType = type }; return Task.Run(() => { try { this.Formatter.Serialize(this.SocketStream, req); var response = this.Formatter.Deserialize(this.SocketStream) as Response; return response; } catch { return new Response() { ResponseType = ResponseType.Error, Message = "Server not responding. Try later." }; } }); }
public RequestInXML(XmlNode xnRequestNode) { switch (xnRequestNode.Attributes["type"].Value) { case "GET": this.type = RequestType.GET; break; case "POST": this.type = RequestType.POST; break; case "PUT": this.type = RequestType.PUT; break; case "DELETE": this.type = RequestType.DELETE; break; default: this.type = RequestType.DEFAULT; break; } foreach (XmlNode xnRequestParam in xnRequestNode.SelectNodes("param")) { requestParams.Add(new RequestParam(xnRequestParam)); } }
public _0x34GetPlayerStatus(int Serial,RequestType reqtype) : base(0x34) { Data.WriteUInt(0xedededed); Data.WriteBit((byte)reqtype); Data.WriteInt(Serial); }
public static WebRequest createRequest(RequestType type, Authentication authentication, int? id, Notification model) { HttpRequestAttr requestAttrs = (HttpRequestAttr) type.GetAttr(); WebRequest request; string url = requestAttrs.URL; if (id.HasValue) { url += ("/" + id); } url += "?username="******"&secretKey=" + authentication.SecretKey; request = WebRequest.Create(url); request.Method = requestAttrs.Method; if (model != null) { request.ContentType = "application/json"; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { string json = model.GenerateJsonString(); streamWriter.Write(json); } } else { request.ContentLength = 0; } request.Timeout = CONNECTION_TIMEOUT; return request; }
/// <summary> /// Creates the request of the specified type. /// </summary> /// <param name="requestType">Type of the request.</param> /// <param name="args">The args needed to create the request.</param> /// <returns>the request instance</returns> public IRequest CreateRequest(RequestType requestType, object[] args) { string requestName = GetRequestClassNameFromType(requestType); Type type = Type.GetType(requestName); IRequest request = (IRequest) Activator.CreateInstance(type, args); return request; }
private Command C(string path, RequestType requestType = RequestType.Get) { return Cmd(path, requestType) .WithParameter(@"login", _login) .WithParameter(@"apiKey", _apiKey) .WithParameter(@"format", @"json"); }
public object Execute(string serviceName, string methodName, object param, RequestType requestType) { serviceName = serviceName.ToUpper(); methodName = methodName.ToUpper(); var svType = YAssembly.FindServiceType(serviceName); if (svType == null) { throw new UserFriendlyException("'{0}' Service 不存在".Fill(serviceName.ToLower())); } var interfaceType = YAssembly.ServiceDic[svType]; var methodForCheck = YAssembly.GetMethodByType(svType, methodName); var method = YAssembly.GetMethodByType(interfaceType, methodName); //权限安全检查 var authorizeAttrList = ReflectionHelper.GetAttributesOfMemberAndDeclaringType<MabpAuthorizeAttribute>(methodForCheck ); if (authorizeAttrList.Count > 0) { using (var authorizationAttributeHelper = IocManager.Instance.ResolveAsDisposable<IAuthorizeAttributeHelper>()) { authorizationAttributeHelper.Object.Authorize(authorizeAttrList); } } object result = null; var instance = IocManager.Instance.Resolve(interfaceType); result = Invoke(method, instance, param); return result; }
public ChangeRequest(string path, string target, RequestType requestType, ItemType itemType) { this.item = new ItemSpec(path, RecursionType.None); this.target = target; this.requestType = requestType; this.itemType = itemType; }
//REQUEST public NetCommand(RequestType request, int session) { Type = CommandType.REQUEST; Session = session; Timestamp = Helper.Now; Request = request; }
public RequestBuilder(RequestType requestType, string action) { this.RequestType = requestType; this.Action = action; this._urlSegments = new List<string>(); this._queryStringParameters = new Dictionary<string, string>(); }
public RequestResourceContext(IAdapter adapter, IAdaptee adaptee, RequestType resource) { Adaptee = adaptee; Adapter = adapter; ReqType = resource; }
private static ApiResponse GetApiResponse(string response, RequestType requestType, HttpStatusCode statusCode) { var apiResponse = new ApiResponse(); // If result doesn't come back as an array, let's make it an array for JArray if (response.StartsWith("{")) response = String.Format("[{0}]", response); if (response != string.Empty) { switch (requestType) { case RequestType.JsonObject: JArray jsonResponse = JArray.Parse(response); apiResponse.ResponseObject = jsonResponse; break; case RequestType.Json: case RequestType.Xml: apiResponse.ResponseString = response; break; } } apiResponse.StatusCode = statusCode; return apiResponse; }
public static void ConflictRequest(RequestType firstRequest, RequestType secondRequest) { // For RequestType.Lease, only containg one request (Create with Lease context) // for the second client, so DeleteAfter is not applicable. Condition.IfThen(firstRequest == RequestType.UncommitedDelete, secondRequest != RequestType.Lease); // DeleteAfter is the same as Delete for second request Condition.IsTrue(secondRequest != RequestType.UncommitedDelete); switch (firstRequest) { case RequestType.ExclusiveLock: State = FileState.Locked; break; case RequestType.Lease: State = FileState.LeaseGranted; break; case RequestType.UncommitedDelete: State = FileState.ToBeDeleted; break; case RequestType.Delete: State = FileState.Deleted; break; // No state changed case RequestType.Write: case RequestType.Read: default: break; } SecondRequest = secondRequest; }
protected async Task<string> ExecuteRequestAsync(string url, RequestType type, Dictionary<string, string> @params) { string result; using (var client = new HttpClient()) { if (type == RequestType.POST) { var content = new FormUrlEncodedContent(@params); var response = await client.PostAsync(url, content); result = await response.Content.ReadAsStringAsync(); } else { // append guid to prevent http requests caching StringBuilder args = new StringBuilder("?nocache=" + Guid.NewGuid() + "&"); // build params string foreach (var pair in @params) { args.AppendFormat("{0}={1}&", pair.Key, pair.Value); } // append params to url url = url + args; // remove last '&' symbol and execute request result = await client.GetStringAsync(url.Remove(url.Length - 1)); } } return result; }
public OutputWindow(RequestType request, string uri) : this() { // Will do this here to make it easier to write to the output window _canceller = new CancellationTokenSource(1000 * 10/* timeout = 10s */); _canceller.Token.Register(() => { Output.AddLine(Resolved ? "Request stopped." : "Request timed out."); Resolved = true; }); Task.Run(() => ProcessRequest(uri, Output), _canceller.Token); }
public Request(string clientAddress, RequestType type, string path, double version, Dictionary<string, string> headers) { ClientAddress = clientAddress; Type = type; Path = path; Version = version; Headers = headers; string lengthString; if (Headers.TryGetValue("Content-Length", out lengthString)) { try { ContentLength = Convert.ToInt32(lengthString); } catch (FormatException) { throw new ClientException("Invalid content length specified"); } } else ContentLength = null; Headers.TryGetValue("X-Real-IP", out ClientAddress); Content = new Dictionary<string, string>(); //Arguments are null until set by a non-default Handler Arguments = null; RequestHandler = null; }
public static object Service(this Uri url, RequestType requestType, ResponseType responseType, out int resultCode, string outputFilename, IDictionary<string, string> formData) { object result = null; resultCode = -1; var webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Proxy = GetProxy(); webRequest.CookieContainer = Cookies.GetCookieContainer(); switch (requestType) { case RequestType.POST: webRequest.Method = "POST"; webRequest.ContentType = "application/x-www-form-urlencoded"; var encodedFormData = Encoding.UTF8.GetBytes(GetFormData(formData).ToString()); using (var requestStream = webRequest.GetRequestStream()) { requestStream.Write(encodedFormData, 0, encodedFormData.Length); } break; case RequestType.GET: webRequest.Method = "GET"; if (formData != null) { var ub = new UriBuilder(url) { Query = GetFormData(formData).ToString() }; url = ub.Uri; } break; } try { if (credentialCache != null) { webRequest.Credentials = credentialCache; webRequest.PreAuthenticate = true; } var webResponse = webRequest.GetResponse(); if (!KeepCookiesClean) { Cookies.AddCookies(webRequest.CookieContainer.GetCookies(webResponse.ResponseUri)); } switch (responseType) { case ResponseType.String: result = GetStringResponse(webResponse); resultCode = 200; break; case ResponseType.Binary: result = GetBinaryResponse(webResponse); resultCode = 200; break; case ResponseType.File: result = GetBinaryFileResponse(webResponse, outputFilename); resultCode = 200; break; } } catch { resultCode = 0; } return result; }
public TransactionBase(RequestType transactionType, bool useUI, string amount = "", string transactionID = "", string orderNumber = "") { this.TransactionID = transactionID; this.OrderNumber = orderNumber; this.Amount = amount; this.TransactionType = getTransactionType(transactionType, useUI); }
public static WebRequest createGetRequest(RequestType requestType, Authentication authentication, int? id, int? type, bool? unread, int? fromId) { HttpRequestAttr requestAttrs = (HttpRequestAttr)requestType.GetAttr(); WebRequest request; string url = requestAttrs.URL; if (id.HasValue) { url += ("/" + id); } url += "?username="******"&secretKey=" + authentication.SecretKey; if (type.HasValue) { url += "&type=" + type.Value; } if (unread.HasValue) { url += "&unread=" + unread.Value; } if (fromId.HasValue) { url += "&fromId=" + fromId.Value; } request = WebRequest.Create(url); request.Method = requestAttrs.Method; request.Timeout = CONNECTION_TIMEOUT; return request; }
public VersionNameRequest (RequestType request_type, Photo photo, Gtk.Window parent_window) : base ("version_name_dialog") { this.request_type = request_type; this.photo = photo; switch (request_type) { case RequestType.Create: this.Dialog.Title = Catalog.GetString ("Create New Version"); prompt_label.Text = Catalog.GetString ("Name:"); break; case RequestType.Rename: this.Dialog.Title = Catalog.GetString ("Rename Version"); prompt_label.Text = Catalog.GetString ("New name:"); version_name_entry.Text = photo.GetVersion (photo.DefaultVersionId).Name; version_name_entry.SelectRegion (0, -1); break; } version_name_entry.ActivatesDefault = true; this.Dialog.TransientFor = parent_window; this.Dialog.DefaultResponse = ResponseType.Ok; Update (); }
public static RequestReply Request(RequestType type, string title, string message, List<string> choices, string default_choice) { RequestReply request = new RequestReply(); if(type== RequestType.Choice&&choices==null) throw new MException("NeedInfo Error","A choice was requested, but no options provided",true); RequestEventArgs e = new RequestEventArgs(type,title,message,choices,default_choice,request); ICommunicationReceiver receiver = getReceiver(); if(receiver==null) { request.cancelled =true; return request; } if(receiver.context!=null) { receiver.context.Post(new SendOrPostCallback(delegate(object state) { RequestEventHandler handler = receiver.requestInformation; if(handler!=null) { handler(e); } }),null); } else { receiver.requestInformation(e); } waitForResponse(e); if(e.response== ResponseType.Cancel||e.response== ResponseType.No) e.result.cancelled = true; return e.result; }
private InstrumentationToken(RequestType type, ExecutionFlags executionFlags, string cql) { Id = Guid.NewGuid(); Type = type; ExecutionFlags = executionFlags; Cql = cql; }
private void send(RequestType type) { client.RequestType = type; clientThread = new Thread(new ThreadStart(client.Send)); clientThread.IsBackground = true; clientThread.Start(); }
protected ResponseHandler(RequestType type, Player requested, Player causedBy) { this.type = type; this.requested = requested; this.causedBy = causedBy; current = new Stack<ResponseHandler>(); active = false; }
public Request(string user, string password, string token, RequestType req, string Signature) { m_Username = user; m_Password = password; m_Token = token; m_RequestType = req; m_Signature = Signature; }
public ChangeRequest(string path, RequestType requestType, ItemType itemType, RecursionType recursion, LockLevel lockLevel) { this.item = new ItemSpec(path, recursion); this.requestType = requestType; this.itemType = itemType; this.lockLevel = lockLevel; }
public UVRequest(RequestType type) { var size = UVInterop.uv_req_size(type); _handle = Marshal.AllocHGlobal(size); _requestPointer = (uv_req_t*)_handle; GCHandle = GCHandle.Alloc(this, GCHandleType.Normal); }
//********************************************************** //* Добавление нового запроса //********************************************************** public static void AddRequest(Int32 researchId, RequestType requestType) { using (SandBoxDataContext db = new SandBoxDataContext()) { Request request = new Request() {ResearchId = researchId, Type = (Int32)requestType, State = (Int32)RequestState.EXECUTING}; db.Requests.InsertOnSubmit(request); db.SubmitChanges(); } }
public MarketDataRequest(RequestType requestType) { this.RequestType = requestType; this.enabled = true; }
public ResponseData DoRang(RequestType type, string key, double begin = 0, double end = -1) { return(DoRangAsync(type, key, begin, end, TimeSpan.FromSeconds(_actionTimeout)).Result); }
public ResponseChangedLanguages(ResponseStatus status, RequestType type, List <string> parameters) { Status = status; Type = RequestType.CHANGED_LANGUAGES; ChangedLanguages = parameters; }
/// <summary> /// Others Scan /// </summary> /// <param name="type"></param> /// <param name="key"></param> /// <param name="offset"></param> /// <param name="pattern"></param> /// <param name="count"></param> /// <returns></returns> public ScanResponse DoScanKey(RequestType type, string key, int offset = 0, string pattern = "*", int count = -1) { return(DoScanKeyAsync(TimeSpan.FromSeconds(_actionTimeout), type, key, offset, pattern, count).Result); }
public ResponseData DoClusterSetSlot(RequestType type, string action, int slot, string nodeID) { return(DoClusterSetSlotAsync(type, action, slot, nodeID, TimeSpan.FromSeconds(_actionTimeout)).Result); }
protected Analyzer(RequestType type) { AnalyzerType = type; Status = AnalyzeResult.WaitingForUrl; }
public MvcForm BeginForm <TController>(string action, RequestType formType) where TController : BaseController { return(BeginForm <TController>(action, formType, null)); }
static void Main() { try { VoidService voidService = new VoidService(); VoidShipmentRequest voidRequest = new VoidShipmentRequest(); RequestType request = new RequestType(); String[] requestOption = { "1" }; request.RequestOption = requestOption; voidRequest.Request = request; VoidShipmentRequestVoidShipment voidShipment = new VoidShipmentRequestVoidShipment(); voidShipment.ShipmentIdentificationNumber = "1ZISDE016691676846"; voidRequest.VoidShipment = voidShipment; UPSSecurity upss = new UPSSecurity(); UPSSecurityServiceAccessToken upssSvcAccessToken = new UPSSecurityServiceAccessToken(); upssSvcAccessToken.AccessLicenseNumber = "4CF6E9703C30E4B6"; upss.ServiceAccessToken = upssSvcAccessToken; UPSSecurityUsernameToken upssUsrNameToken = new UPSSecurityUsernameToken(); upssUsrNameToken.Username = "******"; upssUsrNameToken.Password = "******"; upss.UsernameToken = upssUsrNameToken; voidService.UPSSecurityValue = upss; System.Net.ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy(); Console.WriteLine(voidRequest); VoidShipmentResponse voidResponse = voidService.ProcessVoid(voidRequest); Console.WriteLine("The transaction was a " + voidResponse.Response.ResponseStatus.Description); Console.WriteLine("The shipment has been : " + voidResponse.SummaryResult.Status.Description); Console.ReadKey(); } catch (System.Web.Services.Protocols.SoapException ex) { Console.WriteLine(""); Console.WriteLine("---------Void Web Service returns error----------------"); Console.WriteLine("---------\"Hard\" is user error \"Transient\" is system error----------------"); Console.WriteLine("SoapException Message= " + ex.Message); Console.WriteLine(""); Console.WriteLine("SoapException Category:Code:Message= " + ex.Detail.LastChild.InnerText); Console.WriteLine(""); Console.WriteLine("SoapException XML String for all= " + ex.Detail.LastChild.OuterXml); Console.WriteLine(""); Console.WriteLine("SoapException StackTrace= " + ex.StackTrace); Console.WriteLine("-------------------------"); Console.WriteLine(""); } catch (System.ServiceModel.CommunicationException ex) { Console.WriteLine(""); Console.WriteLine("--------------------"); Console.WriteLine("CommunicationException= " + ex.Message); Console.WriteLine("CommunicationException-StackTrace= " + ex.StackTrace); Console.WriteLine("-------------------------"); Console.WriteLine(""); } catch (Exception ex) { Console.WriteLine(""); Console.WriteLine("-------------------------"); Console.WriteLine(" Generaal Exception= " + ex.Message); Console.WriteLine(" Generaal Exception-StackTrace= " + ex.StackTrace); Console.WriteLine("-------------------------"); } finally { Console.ReadKey(); } }
private Command(RequestType type, string path, RestApiProvider executor) { _type = type; _path = path; _executor = executor; }
/// <summary> /// Add Path /// </summary> /// <param name="Path"></param> /// <param name="Type"></param> /// <param name="UseCache"></param> /// <param name="Weight"></param> /// <returns></returns> public INode AddNode(string Path, RequestType Type = RequestType.GET, bool UseCache = false, int Weight = 50) { return(HttpMultiClientWare.Nodes.AddNode(Path, Type, UseCache, Weight)); }
/// <summary> /// Add Path /// </summary> /// <typeparam name="T"></typeparam> /// <param name="Path"></param> /// <param name="Param"></param> /// <param name="MapFied"></param> /// <param name="Type"></param> /// <param name="UseCache"></param> /// <param name="Weight"></param> /// <returns></returns> public INode AddNode <T>(string Path, T Param, IDictionary <string, string> MapFied = null, RequestType Type = RequestType.GET, bool UseCache = false, int Weight = 50) where T : class, new() { return(HttpMultiClientWare.Nodes.AddNode(Path, Param, MapFied, Type, UseCache, Weight)); }
/// <summary> /// Add Path /// </summary> /// <param name="Path"></param> /// <param name="Param"></param> /// <param name="Type"></param> /// <param name="UseCache"></param> /// <param name="Weight"></param> /// <returns></returns> public INode AddNode(string Path, List <KeyValuePair <String, String> > Param, RequestType Type = RequestType.GET, bool UseCache = false, int Weight = 50) { return(HttpMultiClientWare.Nodes.AddNode(Path, Param, Type, UseCache, Weight)); }
private void ResponseMsg(string weixin)// 服务器响应微信请求 { XmlDocument doc = new XmlDocument(); doc.LoadXml(weixin);//读取xml字符串 XmlElement root = doc.DocumentElement; ExmlMsg xmlMsg = ExmlMsg.GetExmlMsg(root); if (!string.IsNullOrEmpty(xmlMsg.EventName) && xmlMsg.EventName.ToLower() == "location") { Latitude = xmlMsg.Latitude; Longitude = xmlMsg.Longitude; string myxy = RequestType.HttpGet("http://api.map.baidu.com/geoconv/v1/?coords=" + Longitude + "," + Latitude + "&from=1&to=5&ak=EuF8VnvpoIxvLKdmyQOuMPSpbE9ErZe4"); Location locadata = JsonConvert.DeserializeObject<Location>(myxy); x = locadata.result[0].y; y = locadata.result[0].x; } //string messageType = MsgType.InnerText; string messageType = xmlMsg.MsgType;//获取收到的消息类型。文本(text),图片(image),语音等。 try { switch (messageType) { //当消息为文本时 case "text": textCase(xmlMsg); break; //当消息为事件时 case "event": if (!string.IsNullOrEmpty(xmlMsg.EventName)) { string resxml = ""; int nowtime = ConvertDateTimeInt(DateTime.Now); switch (xmlMsg.EventName.Trim()) { case "subscribe": //刚关注时的时间,用于欢迎词 string title = "欢迎关注微信demo\n"; resxml = "<xml><ToUserName><![CDATA[" + xmlMsg.FromUserName + "]]></ToUserName><FromUserName><![CDATA[" + xmlMsg.ToUserName + "]]></FromUserName><CreateTime>" + nowtime + "</CreateTime><MsgType><![CDATA[news]]></MsgType><ArticleCount>1</ArticleCount><Articles><item><Title><![CDATA[" + title + "]]></Title><Description><![CDATA[微信接口测试demo]]></Description><PicUrl><![CDATA[]]></PicUrl><Url><![CDATA[http://ljx.pqpqpq.cn]]></Url></item></Articles></xml>"; break; case "CLICK": resxml = GetContent(xmlMsg.EventKey, xmlMsg); break; case "MASSSENDJOBFINISH": StringBuilder sb = new StringBuilder(); sb.Append("公众号的微信号:" + xmlMsg.ToUserName + "<br/>"); sb.Append("公众号群发助手的微信号:" + xmlMsg.FromUserName + "<br/>"); sb.Append("创建时间的时间戳:" + Utility.WxHelper.GetTime(xmlMsg.CreateTime).ToString("yyyy-MM-dd HH:mm:ss") + "<br/>"); sb.Append("消息类型:" + xmlMsg.MsgType + "<br/>"); sb.Append("事件信息:" + xmlMsg.EventName + "<br/>"); sb.Append("群发的消息ID:" + xmlMsg.MsgID + "<br/>"); sb.Append("群发的结构:" + xmlMsg.Status + "<br/>"); sb.Append("group_id下粉丝数:" + xmlMsg.TotalCount + "<br/>"); sb.Append("准备发送的粉丝数:" + xmlMsg.FilterCount + "<br/>"); sb.Append("发送成功的粉丝数:" + xmlMsg.SentCount + "<br/>"); sb.Append("发送失败的粉丝数:" + xmlMsg.ErrorCount + "<br/>"); msgresult = sb.ToString(); break; default: break; } Response.Write(resxml); } break; case "image": textOtherCase(xmlMsg, "图片"); break; case "voice": textOtherCase(xmlMsg, "声音,识别结果:" + xmlMsg.Recognition); break; case "shortvideo": textOtherCase(xmlMsg, "视频"); break; case "location": textOtherCase(xmlMsg, "位置"); break; case "link": textOtherCase(xmlMsg, "链接"); break; default: break; } Response.End(); } catch (Exception) { } }
public async Task LogAsync(RequestType type, string path, string method, int?code, DateTime datetime) { var log = new RequestLog(type, path, method, code, datetime); await _loggingRepository.SaveLogAsync(log); }
/// <summary> /// CTOR /// </summary> /// <param name="type"></param> /// <param name="assetUUID"></param> public ClientRequestMsg(RequestType type, string assetUUID) { this.SetupHeader(type, assetUUID, 0); }
public object CreateRequest(string pathInfo, Dictionary <string, string> queryStringAndFormData, object fromInstance) { var requestComponents = pathInfo.Split(PathSeperatorChar) .Where(x => !string.IsNullOrEmpty(x)).ToArray(); ExplodeComponents(ref requestComponents); if (requestComponents.Length != this.TotalComponentsCount) { var isValidWildCardPath = this.IsWildCardPath && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount; if (!isValidWildCardPath) { throw new ArgumentException($"Path Mismatch: Request Path '{pathInfo}' has invalid number of components compared to: '{this.Path}'"); } } var requestKeyValuesMap = new Dictionary <string, string>(); var pathIx = 0; for (var i = 0; i < this.TotalComponentsCount; i++) { var variableName = this.variablesNames[i]; if (variableName == null) { pathIx++; continue; } string propertyNameOnRequest; if (!this.propertyNamesMap.TryGetValue(variableName.ToLower(), out propertyNameOnRequest)) { if (Keywords.Ignore.EqualsIgnoreCase(variableName)) { pathIx++; continue; } throw new ArgumentException("Could not find property " + variableName + " on " + RequestType.GetOperationName()); } var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; //wildcard has arg mismatch if (value != null && this.isWildcard[i]) { if (i == this.TotalComponentsCount - 1) { // Wildcard at end of path definition consumes all the rest var sb = StringBuilderCache.Allocate(); sb.Append(value); for (var j = pathIx + 1; j < requestComponents.Length; j++) { sb.Append(PathSeperatorChar + requestComponents[j]); } value = StringBuilderCache.ReturnAndFree(sb); } else { // Wildcard in middle of path definition consumes up until it // hits a match for the next element in the definition (which must be a literal) // It may consume 0 or more path parts var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1]; if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) { var sb = StringBuilderCache.Allocate(); sb.Append(value); pathIx++; while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) { sb.Append(PathSeperatorChar + requestComponents[pathIx++]); } value = StringBuilderCache.ReturnAndFree(sb); } else { value = null; } } } else { // Variable consumes single path item pathIx++; } requestKeyValuesMap[propertyNameOnRequest] = value; } if (queryStringAndFormData != null) { //Query String and form data can override variable path matches //path variables < query string < form data foreach (var name in queryStringAndFormData) { requestKeyValuesMap[name.Key] = name.Value; } } return(this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap, HostContext.Config.IgnoreWarningsOnPropertyNames)); }
private byte[] GetRequestTypeBytes(RequestType requestType) { return(BitConverter.GetBytes((int)requestType)); }
public object CreateRequest(string pathInfo, Dictionary<string, string> queryStringAndFormData, object fromInstance) { var requestComponents = pathInfo.Split(new[] { PathSeperatorChar }, StringSplitOptions.RemoveEmptyEntries); ExplodeComponents(ref requestComponents); if (requestComponents.Length != this.TotalComponentsCount) { var isValidWildCardPath = this.IsWildCardPath && requestComponents.Length >= this.TotalComponentsCount - this.wildcardCount; if (!isValidWildCardPath) { throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "Path Mismatch: Request Path '{0}' has invalid number of components compared to: '{1}'", pathInfo, this.restPath)); } } var requestKeyValuesMap = new Dictionary<string, string>(); var pathIx = 0; for (var i = 0; i < this.TotalComponentsCount; i++) { var variableName = this.variablesNames[i]; if (variableName == null) { pathIx++; continue; } if (!this._propertyNamesMap.Contains(variableName)) { if (string.Equals("ignore", variableName, StringComparison.OrdinalIgnoreCase)) { pathIx++; continue; } throw new ArgumentException("Could not find property " + variableName + " on " + RequestType.GetMethodName()); } var value = requestComponents.Length > pathIx ? requestComponents[pathIx] : null; // wildcard has arg mismatch if (value != null && this.isWildcard[i]) { if (i == this.TotalComponentsCount - 1) { // Wildcard at end of path definition consumes all the rest var sb = new StringBuilder(); sb.Append(value); for (var j = pathIx + 1; j < requestComponents.Length; j++) { sb.Append(PathSeperatorChar) .Append(requestComponents[j]); } value = sb.ToString(); } else { // Wildcard in middle of path definition consumes up until it // hits a match for the next element in the definition (which must be a literal) // It may consume 0 or more path parts var stopLiteral = i == this.TotalComponentsCount - 1 ? null : this.literalsToMatch[i + 1]; if (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) { var sb = new StringBuilder(value); pathIx++; while (!string.Equals(requestComponents[pathIx], stopLiteral, StringComparison.OrdinalIgnoreCase)) { sb.Append(PathSeperatorChar) .Append(requestComponents[pathIx++]); } value = sb.ToString(); } else { value = null; } } } else { // Variable consumes single path item pathIx++; } requestKeyValuesMap[variableName] = value; } if (queryStringAndFormData != null) { // Query String and form data can override variable path matches // path variables < query string < form data foreach (var name in queryStringAndFormData) { requestKeyValuesMap[name.Key] = name.Value; } } return this.typeDeserializer.PopulateFromMap(fromInstance, requestKeyValuesMap); }
protected Analyzer(String url, RequestType type) { AnalyzerType = type; SiteUrl = url; Status = AnalyzeResult.WaitingForAnalyze; }
public ResponseData DoBatchWithIDDic(RequestType type, string id, Dictionary <string, string> dic) { return(DoBatchWithIDDicAsync(type, id, dic, TimeSpan.FromSeconds(_actionTimeout)).Result); }
public ResponseData DoMutiCmd(RequestType type, params object[] @params) { return(DoMutiCmdAsync(TimeSpan.FromSeconds(_actionTimeout), type, @params).Result); }
public ResponseData DoBatchWithList(RequestType type, string id, List <string> list) { return(DoBatchWithListAsync(type, id, list, TimeSpan.FromSeconds(_actionTimeout)).Result); }
public int req_size(RequestType reqType) { return(_uv_req_size(reqType)); }
/// <summary> /// 构造函数 设置请求类型 /// </summary> /// <param name="requestType">请求类型</param> public WebMethodAttr(RequestType requestType) { CurRequestType = requestType; CurContentType = ContentType.JSON; base.PriorityLevel = 9999; }
public ResponseData DoBatchWithIDKeys(RequestType type, string id, params string[] keys) { return(DoBatchWithIDKeysAsync(TimeSpan.FromSeconds(_actionTimeout), type, id, keys).Result); }
/// <summary> /// Sends an action request (delete, insert, or update) to the /// data source and returns a boolean indicating whether the /// request was successful. /// </summary> /// <param name="Command">A command string. This be either /// a request instruction (such as a sql string) or a procedure /// name. The implementation of this interface determines the /// meaning of this parameter.</param> /// <param name="Args">The parameter array. The type of this /// array is determined by the implementation.</param> /// <returns>True if the request was successful. Otherwise false.</returns> public abstract bool SendActionRequest(RecordType Record, RequestType Request, IDataParameter[] Args);
public ResponseData DoRangByScore(RequestType type, string key, double min = double.MinValue, double max = double.MaxValue, RangType rangType = RangType.None, long offset = -1, int count = 20, bool withScore = false) { return(DoRangByScoreAsync(TimeSpan.FromSeconds(_actionTimeout), type, key, min, max, rangType, offset, count, withScore).Result); }
/// <summary> /// CTOR /// </summary> /// <param name="type"></param> /// <param name="assetUUID"></param> /// <param name="data"></param> public ClientRequestMsg(RequestType type, string assetUUID, byte[] data) { this.SetupHeader(type, assetUUID, data.Length); _data.Append(data); }
/// <summary> /// 构造函数 设置请求类型 设置输出文本类型 /// </summary> /// <param name="requestType">请求类型</param> /// <param name="contentType">输出文本类型 可使用ContentType常量</param> public WebMethodAttr(RequestType requestType, string contentType) { CurRequestType = requestType; CurContentType = contentType; base.PriorityLevel = 9999; }
public void CreateRequestTypeThrowsError() { var client = CommonMethods.GetClientByRoute(TargetProcessRoutes.Route.RequestTypes); var requestType = new RequestType(); }