public void Excute() { OnPreExecute(); //会调用重写的方法 SerialPortController mSerialPortController = SerialPortController.GetInstance(); //这个类只会new一次 mSerialPortController.PortName = Param.PortName; mSerialPortController.BaudRate = Param.BaudRate; mSerialPortController.Initialization((object sender, EventArgs e) => { SerialPortEventArgs mSerialPortEventArgs = e as SerialPortEventArgs; //通知异常 OnPostExecute(default(T), new Exception(mSerialPortEventArgs.ErrorMessage)); }, (object sender, EventArgs e) => { SerialPortEventArgs mSerialPortEventArgs = e as SerialPortEventArgs; recvByteArray = mSerialPortEventArgs.Data; if (null != MyProtocol && null != mSerialPortEventArgs) { //会调用重写的方法 OnPostExecute(MyProtocol.Decode(mSerialPortEventArgs.Data) as T, null); } else { //通知异常 OnPostExecute(default(T), new Exception("返回数据为空")); } }, MyProtocol); if (RequestProtocol != null && RequestProtocol.GetCommand() != SerialPortConst.COMMAND_EMPTY_VIRTUAL) { mSerialPortController.SendCommand(RequestProtocol.Encode()); Console.WriteLine("-----------------send value-----------------\n" + Util.ToHexString(RequestProtocol.Encode())); } }
public RequestUriBuilder BuildBaseUrl(RequestProtocol protocol) { if (string.IsNullOrEmpty(Body) || string.IsNullOrWhiteSpace(Body)) { throw new ArgumentNullException(nameof(Body)); } Body = Body.AppendProtocol(protocol); return(this); }
public static string AppendProtocol(this string url, RequestProtocol requestProtocol) { return(StringBuilder .Clear() .Append(requestProtocol .ToString() .ToLower()) .Append("://") .Append(url) .ToString()); }
public InvokeResult Invoke(Type returnType, string typeName, string methodName, params Parameter[] paras) { logger.Debug("current thread count:" + ThreadCount); if (ThreadCount > config.MaxThreadCount) { logger.Error("server is too busy(" + ThreadCount + ").Service:" + _ServiceName); throw new Exception("server is too busy.(" + _ServiceName + ")"); } try { System.Threading.Interlocked.Increment(ref ThreadCount); Stopwatch watcher = new Stopwatch(); watcher.Start(); List <RpParameter> listPara = new List <RpParameter>(); IList <Type> outParaTypes = new List <Type>(); Array.ForEach(paras, delegate(Parameter p) { listPara.Add(new RpParameter(TypeMapping.ParseType(p.DataType.ToString()), p.Para)); if (p.ParaType == Com.Bj58.Spat.Gaea.Client.Proxy.Enum.ParaType.Out) { outParaTypes.Add(p.DataType); } }); RequestProtocol requestProtocol = new RequestProtocol(typeName, methodName, listPara.ToArray()); byte[] userData = config.Protocol.Serializer.Serialize(requestProtocol); Protocol sendP = new Protocol(config.Protocol, CreateSessionId(), UserDataType.Request, userData); var server = dispatcher.GetServer(); if (server == null) { logger.Error("can't get server"); throw new Exception("can't get server"); } Protocol receiveP = server.Request(sendP);//request server if (receiveP.UserDataType == UserDataType.Response) { var rpGtype = returnType; if (returnType == typeof(void)) { rpGtype = typeof(VOID); } var rpType = typeof(ResponseProtocol <>).MakeGenericType(rpGtype); var rp = config.Protocol.Serializer.Deserialize(receiveP.UserData, rpType); object result = rpType.GetProperty("Result").GetValue(rp, null); object[] outPara = (object[])rpType.GetProperty("Outpara").GetValue(rp, null); logger.Debug("invoke time:" + watcher.ElapsedMilliseconds + "ms"); return(new InvokeResult(result, outPara)); } else if (receiveP.UserDataType == UserDataType.Exception) { var ep = config.Protocol.Serializer.Deserialize <ExceptionProtocol>(receiveP.UserData); throw ExceptionProvider.ThrowServiceError(ep.ErrorCode, ep.ErrorMsg); } else { logger.Error("userdatatype error!"); throw new Exception("userdatatype error!"); } } finally { System.Threading.Interlocked.Decrement(ref ThreadCount); } }
private static ResponseImage GetDanbooruImage(string[] tags, RequestProtocol protocol, long channelId) { List <DanbooruBlockList> blockList = Database.GetMany <DanbooruBlockList>(); string[] blockedTags = new string[blockList.Count]; int i = 0; foreach (DanbooruBlockList entry in blockList) { blockedTags[i] = entry.Tag; i++; } if (tags.Any(tag => blockedTags.Contains(tag))) { return(new ResponseImage()); } string requestTags = string.Join("+", tags); byte[] authToken = Encoding.ASCII.GetBytes($"{Config.DanbooruUser}:{Config.DanbooruApiKey}"); int page = 1; const int limit = 50; DanbooruResults result = null; WherePredicate whereChannel = new WherePredicate() { Source = "channel_id", Comparitor = "=", Target = channelId }; WherePredicate whereProtocol = new WherePredicate() { Source = "protocol", Comparitor = "=", Target = protocol }; string[] cache = { }; if (channelId != 0) { WherePredicate whereExpires = new WherePredicate() { Source = "expires", Comparitor = ">", Target = DateTime.UtcNow }; List <DanbooruCache> danCache = Database.GetMany <DanbooruCache>(new[] { whereExpires, whereProtocol, whereChannel }); i = 0; cache = new string[danCache.Count]; foreach (DanbooruCache item in danCache) { cache[i] = item.FileUrl; i++; } } using HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken)); while (true) { string requestUrl = $"https://danbooru.donmai.us/posts.json?limit={limit}&page={page}&tags={requestTags}"; HttpResponseMessage request = client.GetAsync(requestUrl).Result; string content = request.Content.ReadAsStringAsync().Result; List <DanbooruResults> results = JsonConvert.DeserializeObject <List <DanbooruResults> >(content); if (results.Count == 0) { break; } result = Rng.PickRandom(results); results.Remove(result); bool badImage = false; while (results.Count > 0) { if (badImage) { result = Rng.PickRandom(results); results.Remove(result); badImage = false; } if (cache.Contains(result.FileUrl)) { badImage = true; continue; } string[] resultTags = result.TagString.Split(" "); if (blockedTags.Any(tag => resultTags.Contains(tag))) { badImage = true; } if (!badImage) { break; } } if (!badImage) { break; } result = null; page++; } if (result != null) { TextInfo ti = new CultureInfo("en-US", false).TextInfo; bool isValidUri = Uri.TryCreate(result.FileUrl, UriKind.RelativeOrAbsolute, out Uri uriResult); bool isValidUriScheme = uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps; string fileUrl = (isValidUri && isValidUriScheme) ? result.FileUrl : $"http://danbooru.donmai.us{result.FileUrl}"; string[] characterTags = result.TagStringCharacter.Split(" "); string characterString = ""; if (characterTags.Length > 0) { characterString = ti.ToTitleCase(characterTags[0].Split("(")[0].Replace("_", " ")); if (characterTags.Length == 2) { string secondCharacter = ti.ToTitleCase(characterTags[1].Split("(")[0].Replace("_", " ")); characterString = $"{characterString} and {secondCharacter}"; } else if (characterTags.Length > 2) { characterString = "Multiple"; } } string[] copyrightTags = result.TagStringCopyright.Split(" "); string copyrightString = ""; if (copyrightTags.Length > 0) { copyrightString = ti.ToTitleCase(copyrightTags[0].Replace("_", " ")); } string[] artist = result.TagStringArtist.Split("_"); string artistString = string.Join(" ", artist); string descriptionString; if (characterString != "" && copyrightString != "") { descriptionString = $"{characterString} - {copyrightString}"; } else if (copyrightString != "") { descriptionString = $"Unknown - {copyrightString}"; } else { descriptionString = $"Original"; } descriptionString += $"\nDrawn by {artistString}"; if (channelId != 0) { WherePredicate whereFileUrl = new WherePredicate { Source = "file_url", Comparitor = "=", Target = result.FileUrl }; List <DanbooruCache> cachedItems = Database.GetMany <DanbooruCache>(new[] { whereFileUrl, whereProtocol, whereChannel }); if (cachedItems.Count > 1) { throw new Exception("Multiple entries for file in Danbooru cache."); } else if (cachedItems.Count == 1) { cachedItems[0].Expires = DateTime.UtcNow.AddDays(1); cachedItems[0].Update(); } else { DanbooruCache cacheItem = new DanbooruCache() { FileUrl = result.FileUrl, Expires = DateTime.UtcNow.AddDays(1), Protocol = protocol, ChannelId = channelId }; cacheItem.Insert(); } } return(new ResponseImage() { Url = fileUrl, Source = $"https://danbooru.donmai.us/posts/{result.Id}", Description = descriptionString, Referrer = "danbooru.donmai.us", }); } return(new ResponseImage()); }
/// <summary> /// 设置请求上下文的协议 /// </summary> /// <param name="protocol"></param> /// <returns></returns> public RequestConfigManager SetGlobalRequestProtocol(RequestProtocol protocol) { RequestConfigContext.configContext.Protocol = protocol; return(this); }