/// <summary> /// 其他页面 /// </summary> public ActionResult Other(string routerMainLinkDiscription, string linkUrl, string linkId, string noLinkId, int linkKind) { ViewBag.linkId = linkId; ViewBag.noLinkId = noLinkId; ViewBag.linkKind = linkKind; CreateTree(); var routerManager = new RouterManager(); if (linkUrl == "") { return(View(routerManager.GetParameterList(routerMainLinkDiscription, linkKind))); } var value = routerManager.GetParameterForOther(routerMainLinkDiscription, linkUrl, linkKind); var list1 = value as List <string>; if (list1 != null) { try { var list = list1; ViewBag.state = list[0]; ViewBag.value = list[1]; } catch (Exception) { // ignored } return(View(routerManager.GetParameterList(routerMainLinkDiscription, linkKind))); } return(View(value)); }
static void Main(string[] args) { var mgr = new RouterManager(); mgr.Progress += new ProgressEventHandler(UpdateProgress); bool result = mgr.RunUserLoad(Settings.Default.UserLoadDaysInterval); try { mgr.SendEmailToAllRouterContacts(Settings.Default.MaxEmailsSent, Settings.Default.SafetyHours); } catch (Exception e) { string errorFilename = $"error-main-{DateTime.Now:yyyy-MM-dd_hh-mm-ss-tt}.txt"; string msg = $"Current Email: {mgr.CurrentEmail}{Environment.NewLine}{e.Message}"; Exception inner = e.InnerException; while (inner != null) { msg += $"{Environment.NewLine}{inner.Message}"; inner = inner.InnerException; } msg += $"{Environment.NewLine}{e.StackTrace}"; File.AppendAllText(@"Logs\" + errorFilename, msg); throw; } }
private static async Task <int> Main(string[] args) { try { if (args.Length > 0) { LoadConfigIntoEnvironment(args[0]); } var BOT_ACCESS_TOKEN = ReadEnvVarOnce("BOT_ACCESS_TOKEN"); var BOT_AUTHORIZED_USERS = ReadEnvVarOnce("BOT_AUTHORIZED_USERS"); var BOT_ROUTER_HOSTNAME = ReadEnvVarOnce("BOT_ROUTER_HOSTNAME"); var BOT_ROUTER_SSH_USERNAME = ReadEnvVarOnce("BOT_ROUTER_SSH_USERNAME"); var BOT_ROUTER_SSH_PASSWORD = ReadEnvVarOnce("BOT_ROUTER_SSH_PASSWORD"); var botClient = new TelegramBotClient(BOT_ACCESS_TOKEN); var authenticator = SimpleAuthenticator.Parse(BOT_AUTHORIZED_USERS); var routerCredentials = new RouterCredentials(BOT_ROUTER_HOSTNAME, BOT_ROUTER_SSH_USERNAME, BOT_ROUTER_SSH_PASSWORD); var sshSessionFactory = new RenciSshNetSessionFactory(); var routerManager = new RouterManager(sshSessionFactory, routerCredentials); var server = new TelegramBotServer(botClient, authenticator, routerManager); await server.RunAsync().ConfigureAwait(false); return(0); } catch (Exception e) { Console.Error.WriteLine(e); return(-1); } }
public IHttpActionResult SendSurveyEmail([FromUri] string emailAddress) { var manager = new RouterManager(); var result = manager.SendSurveyEmail(emailAddress, Utility.GetClientIpAddress()); return(Ok(result)); }
List <CheckPoint> validCheckPoints = new List <CheckPoint>(); //checkpoint validated they will be used for last result private void DeltaQualityCheck() { for (int i = 0; i < bucketCheckPoints.Count - 1; i++) { //if is not the same if (!UMath.nearEqualByDistance(bucketCheckPoints[i].Point, bucketCheckPoints[i + 1].Point, 0.1f)) { if (!RouterManager.IsWaterOrMountainBtw(bucketCheckPoints[i].Point, bucketCheckPoints[i + 1].Point)) { validCheckPoints.Add(bucketCheckPoints[i]); } //if is in water wont add the current one else { RestartDeltaRouter(bucketCheckPoints[i].Point); Init(); deltaRouted = false; return; } } } //add the last one validCheckPoints.Add(bucketCheckPoints[bucketCheckPoints.Count - 1]); DoneDelta(); }
void TryDirect(Vector3 fromP, Vector3 toP) { if (!RouterManager.IsWaterOrMountainBtw(fromP, toP)) { ConformValidResult(fromP, toP); } else { _currentTo = toP; TryDeltaRoute(_from, _currentTo); } }
/// <summary> /// Defines the last good position from the origin to that prime /// in this case the prime is not seeing or use directly bz 'positionsToCheck' was created /// using the prime position already /// </summary> private void ThrowRays() { int lastI = -1; for (int i = 0; i < positionsToCheck.Count; i++) { if (!RouterManager.IsWaterOrMountainBtw(currentOrigin, positionsToCheck[i])) { lastI = i; break; } } DefineLastCurrent(lastI); }
public IHttpActionResult SurveyAction([FromUri] int routerContactId, [FromUri] int hostId, [FromUri] int projectId, [FromUri] string surveyURL) { //1. save record in RouterAction table //2. the transactionid needs to be appended to the url //3. the varible name that the transId gets assigned to varies by host //return Ok(new Uri(Request.RequestUri, RequestContext.VirtualPathRoot)); //returns //http://devmapi.cashbackresearch.com/ try { //var compare = Utility.HashHmacMD5("unique_user_id=b1e269bc-99a5-4b96-a095-06a9cd56d446", ConfigurationManager.AppSettings["YourSurveysSecretKey"]); var _manager = new RouterManager(); var routerAction = _manager.SetSurveyAction(routerContactId, hostId, projectId, surveyURL, Utility.GetClientIpAddress()); //TODO append TransactionID. Maybe only on Your Surveys. //TODO For precision sample, waiting to see if the transid comes back or we just have to use survey and userguid string newUrl = null; if (hostId == (int)RouterHost.YourSurvey) { //surveyURL = $"{surveyURL}&supplier_sub_id={transationID}&supplier_sub_id2={routerContactId}"; surveyURL = $"{surveyURL}&ssi2={routerAction.TransactionId}&ssi3={routerContactId}"; //newUrl = CreateUrlForYourSurveys(surveyURL); } if (hostId == (int)RouterHost.PrecisionSample) { surveyURL = $"{surveyURL}&sub_id={routerAction.TransactionId}"; } routerAction.PostedUrl = surveyURL; _manager.SetRouterActionUrl(routerAction); return(Redirect(surveyURL)); //return Redirect(newUrl); } catch (Exception e) { return(InternalServerError(e)); } //var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect); //response.Headers.Location = new Uri("https://www.stackoverflow.com"); //actionContext.Response = response; }
/// <summary> /// 美容页面 /// </summary> public ActionResult Beauty(string routerMainLinkDiscription, string linkUrl, string linkId, string noLinkId, int linkKind) { ViewBag.linkId = linkId; ViewBag.noLinkId = noLinkId; ViewBag.linkKind = linkKind; var valid = false; //标志用于验证 是否应该解析 string latter = null; var routerManager = new RouterManager(); var content = routerManager.GetMainLink(routerMainLinkDiscription, linkKind).Content; if (linkUrl != "" && linkKind == 1) { //解析APP链接 参数拼接格式:/webView?url=xxx try { var array = linkUrl.Split('?'); var cont = array[0]; var url = array[1].Split('='); if (linkUrl.Length > linkUrl.IndexOf("=", StringComparison.Ordinal) + 1) { latter = linkUrl.Substring(linkUrl.IndexOf("=", StringComparison.Ordinal) + 1); } if (url[0] == "url" && cont == content) { valid = true; } } catch (Exception) { // ignored } } if (linkUrl != "" && linkKind == 2) //解析小程序链接 参数拼接格式:/pages /... { var cont = "/" + linkUrl.Split('/')[1]; if (linkKind == 2 && cont == content) { latter = linkUrl.Substring(6); valid = true; } } if (valid) { return(View(routerManager.GetParameterState(routerMainLinkDiscription, latter, linkKind))); //进入解析结果页面 } return(View(routerManager.GetParameterList(routerMainLinkDiscription, linkKind))); //进入空白页面 }
private ModuleResolver AddModule(byte[] dllBytes, bool ignoreDependencyIndexUpdate = true) { var resolver = new ModuleResolver(dllBytes); var manifest = resolver.GetModuleManifest(); if (ignoreDependencyIndexUpdate) { UpdateDependencyIndex(manifest); } GetTheme(resolver); ModuleManager.AddModule(manifest, resolver.Assembly); RouterManager.ResolveRouteInformation(resolver.Assembly); AuthenticationManager.Upload(dllBytes); return(resolver); }
//Redirect for Your Surveys public IHttpActionResult RedirectYourSurveys([FromUri] int ssi3) { try { var m = new RouterManager(); var uniqueId = m.GetRouterContactUnqueId(ssi3); var url = $"{ConfigurationManager.AppSettings["BaseWebUrl"]}mysurveys?ug={uniqueId}"; return(Redirect(url)); } catch (Exception e) { var msg = e; return(InternalServerError()); } }
private void TryDirectBoth() { if (!RouterManager.IsWaterOrMountainBtw(_from, _endABot)) { ConformValidResult(_from, _endABot); } else if (!RouterManager.IsWaterOrMountainBtw(_from, _endBBot)) { ConformValidResult(_from, _endBBot); } else { _currentTo = _endABot; TryDeltaRoute(_from, _currentTo); } }
/// <summary> /// Created so the player doesnt pass thru river terrain tht is unenven /// </summary> /// <param name="lastI">Last index was good</param> private void DefineLastCurrent(int lastI) { if (lastI != -1) { currentLast = positionsToCheck[lastI]; if (lastI + 1 < positionsToCheck.Count) { //IMPORTANT here am checking if the one before is visible if (!RouterManager.IsWaterOrMountainBtw(positionsToCheck[lastI + 1], currentOrigin)) { //the middle btw the last good and the one before currentLast = (positionsToCheck[lastI] + positionsToCheck[lastI + 1]) / 2; } } } }
public IHttpActionResult UpdateMinimumInfo([FromBody] MinimumSurveyInfo minimumSurveyInfo) { //second half of RouterEmailPush. //if all info not present then it gets sent in. //then set up for surveys try { var _manager = new RouterManager(); _manager.UpdateMinimumSurveyInfo(minimumSurveyInfo); RouterContact user = _manager.RouterContactFullSetup(minimumSurveyInfo.EmailAddress); return(Ok(user.UniqueId)); } catch (Exception e) { return(Ok(e.Message)); } }
/// <summary> /// 发现文章页面 /// </summary> public ActionResult Find(string routerMainLinkDiscription, string linkUrl, string linkId, string noLinkId, int linkKind) { ViewBag.linkId = linkId; ViewBag.noLinkId = noLinkId; ViewBag.linkKind = linkKind; var valid = false; //标志是否解析 var routerManager = new RouterManager(); var content = routerManager.GetMainLink(routerMainLinkDiscription, linkKind).Content; var articleId = ""; if (linkUrl != "") { try { var array = linkUrl.Split('?'); var url = array[1].Split('='); var manager = new ArticleManager(); if (url[0] == "url" && array[0] == content && linkKind == 1) { valid = true; var articleModel = manager.GetByUrl(linkUrl.Substring(linkUrl.IndexOf("=", StringComparison.Ordinal) + 1)); if (articleModel != null) { articleId = articleModel.PKID.ToString(); } } if (array[1].Split('&')[0].Split('=')[0] == "id" && array[0] == content && linkKind == 2) { valid = true; articleId = array[1].Split('&')[0].Split('=')[1]; } } catch (Exception) { // ignored } } if (valid) { return(View(routerManager.GetParameterState(routerMainLinkDiscription, articleId, linkKind))); //进入解析页面 } return(View(routerManager.GetParameterList(routerMainLinkDiscription, linkKind))); //进入空白页面 }
public IHttpActionResult RouterEmailPush([FromUri] string emailAddress) { //this method takes an email address. Checks if minimum data exists. Then //if it doesn't it returns a flag to collect more data. //if minumum data does exist it creates a new router user and redirects them ot //the daily surveys page var _manager = new RouterManager(); MinimumInfoExistsResult minimumInfoExistsResult = _manager.CheckIfMinimumInfoExistsForEmail(emailAddress); if (minimumInfoExistsResult.HasMinimumInfo && !minimumInfoExistsResult.HasRounterContact) { RouterContact user = _manager.RouterContactFullSetup(emailAddress); minimumInfoExistsResult.HasRounterContact = true; minimumInfoExistsResult.RouterContactUniqueId = user.UniqueId; } return(Ok(minimumInfoExistsResult)); }
public IHttpActionResult Get([FromUri] string userId) { //return Ok(new Uri(Request.RequestUri, RequestContext.VirtualPathRoot)); //returns //http://devmapi.cashbackresearch.com/ try { var manager = new RouterManager(); RouterReturnContainer r = manager.GetUserSurveys(Guid.Parse(userId), Utility.GetClientIpAddress()); return(Ok(r.RouterReturnList)); } catch (Exception e) { return(Ok(e.Message)); return(InternalServerError(e)); } }
/// <summary> /// 初始化音乐控制线程 /// </summary> /// <returns>是否初始化成功</returns> public static bool Init() { if (MusicianRouterHandler.IsInitialized) { LogUtils.LogLine("Duplicated init musician thread", "MusicianThreadHandler", LogLevel.Warning); return(false); } var musicianRouter = new YuriRouter() { Name = MusicianRouterHandler.MusicianRouterName }; RouterManager.SetRouter(musicianRouter); Thread mt = new Thread(new ThreadStart(MusicianRouterHandler.MusicianHandler)) { IsBackground = true }; mt.Start(); return(true); }
private static void MonitorHealth(RouterManager rm, bool isInitialized, ILogger logger) { string connectionType = rm.GetConnectionType(); if (!isInitialized) { logger.Info("Current connection type is {0}. Monitoring...", RouterManager.ConnectionStatusType.Parse(connectionType)); } if (!string.IsNullOrEmpty(connectionType) && connectionType != RouterManager.ConnectionStatusType.LTE) { Console.WriteLine(); logger.Info("Connection dropped to {0}. Switching.", RouterManager.ConnectionStatusType.Parse(connectionType)); // Switch to LTE if (rm.Login()) { rm.SwitchConnectionType(RouterManager.ConnectionSwitchType.LTE); rm.SwitchConnectionType(RouterManager.ConnectionSwitchType.Auto); } logger.Info("Switching... Done!"); } }
public IHttpActionResult UpdateRegistration([FromUri] Guid userId, [FromBody] UserRegistrationRequest userRegistrationRequest) { if (!string.IsNullOrWhiteSpace(userRegistrationRequest.Zip)) { XVerifyManager x = new XVerifyManager(); var zipinfo = x.GetZipcodeLookup(userRegistrationRequest.Zip); if (!zipinfo.IsValid) { return(Ok(new UserRegistrationResponse() { ZipIsValid = false, Success = false, Message = "Zipcode is invalid." })); } userRegistrationRequest.State = zipinfo.zipdata.state; userRegistrationRequest.City = zipinfo.zipdata.primary_city; } var m = new MobileUserManager(); int?routerContactId = m.Register(userId, userRegistrationRequest); if (!routerContactId.HasValue) { var rm = new RouterManager(); var routerContact = rm.RouterContactFullSetup(userRegistrationRequest.EmailAddress); routerContactId = routerContact.RouterContactId; m.SetRouterContact(routerContactId, userId); } return(Ok(new UserRegistrationResponse() { ZipIsValid = true, Success = true, Message = "Success." })); }
//Redirect for Precision Samples public IHttpActionResult RedirectPrecisionSample([FromUri] string ug, string sub_id, decimal gross, decimal reward, string status, DateTime date, int surveyid) { try { //test url //http://devmapi.cashbackresearch.com/api/surveys/postback/2?ug=F1CA2526-4995-47A1-89BE-474A223505D9 var m = new RouterManager(); var p = new PostbackManager(); p.PostbackPrecisionSample(ug, sub_id, reward, status, date, surveyid, gross); var uniqueId = m.GetRouterUserFromPrecisionSampleId(ug); var url = $"{ConfigurationManager.AppSettings["BaseWebUrl"]}mysurveys?ug={uniqueId}"; return(Redirect(url)); } catch (Exception e) { var msg = e; return(InternalServerError()); } }
/// <summary> /// Move each point towards is target and throw Ray agaisnt the other to see if can /// see it already /// </summary> private void MoveEachOneAloneAndThrowRayAndConformRoute() { Vector3 aMove = _deltaRoute.AnyA; Vector3 bMove = _deltaRoute.AnyB; //will keep mpving them towards target until they can see eachother without water on midle while (RouterManager.IsWaterOrMountainBtw(aMove, bMove)) { aMove = Vector3.MoveTowards(aMove, _deltaRoute.TargetA, step / 2); bMove = Vector3.MoveTowards(bMove, _deltaRoute.TargetB, step / 2); loopCounts++; //this address probblem of inifitnie loop //for some reason in void DefineDeltaRoute() somehting is not working fine. //if a river is on middle should never have 2 points with good on the same side if (loopCounts > 100) { loopCounts = 0; _isDeltaRoutable = false; Stop(); break; } } //push away a bit towards target. To avoid infinite recursion on certain spots aMove = Vector3.MoveTowards(aMove, _deltaRoute.TargetA, step); bMove = Vector3.MoveTowards(bMove, _deltaRoute.TargetB, step); _deltaRoute.BestA = AssignIniPositionIfNotInBuild(aMove, _deltaRoute.TargetA); _deltaRoute.BestB = AssignIniPositionIfNotInBuild(bMove, _deltaRoute.TargetB); _deltaRoute.ConformRoute(); // _person.DebugList.Add( UVisHelp.CreateHelpers(_deltaRoute.BestA, Root.redSphereHelp)); // _person.DebugList.Add(UVisHelp.CreateHelpers(_deltaRoute.BestB, Root.redSphereHelp)); }
//Called when router is placed void Awake() { manager = GameObject.Find("RouterManager").GetComponent <RouterManager>(); }
static void Main(string[] args) { DisableInputMode(); var logger = NLog.LogManager.GetCurrentClassLogger(); var configuration = new Config(); logger.Info("Starting"); logger.Debug("Seeking interval is {0} seconds in config", configuration.MonitorIntervalSeconds); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); CancellationToken ct = cancellationTokenSource.Token; // Start watching periodically Task.Factory.StartNew(() => { RouterManager rm = new RouterManager(); var isInitialized = false; Stopwatch sw = new Stopwatch(); sw.Start(); while (true) { try { if (ct.IsCancellationRequested) { logger.Info("Requested cancellation. Exiting..."); break; } Thread.Sleep(500); if ((sw.Elapsed.Seconds > configuration.MonitorIntervalSeconds || !isInitialized) && rm.IsInitialized) { if (isInitialized) { Console.Write("\r> Monitoring health. Latest update at "); Console.ForegroundColor = ConsoleColor.Yellow; Console.Write("{0} {1}", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()); Console.ResetColor(); } MonitorHealth(rm, isInitialized, logger); // Reset and start timer for next cycle sw.Reset(); sw.Start(); isInitialized = true; } } catch (Exception e) { logger.Error("Unexpected error inside execution: " + e); } } }, ct, TaskCreationOptions.LongRunning, TaskScheduler.Current); logger.Info("Started"); // User can press any key to exit now Console.ReadLine(); cancellationTokenSource.Cancel(); logger.Info("Exit completed."); }
/// <summary> /// 获取所有主链接,设置下拉框 /// </summary> public ActionResult GetMainLinkList(int linkKind) { var routerManager = new RouterManager(); return(Json(routerManager.GetMainLinkList(linkKind))); }
/// <summary> /// 客户端Rpc调用 /// </summary> /// <typeparam name="R">R</typeparam> /// <typeparam name="A">A</typeparam> /// <param name="server">server</param> /// <param name="m">m</param> /// <param name="args">args</param> /// <param name="code">code</param> /// <returns>RR</returns> public static R Send <A, R>(string server, string m, A args, RpcContext context, out StatusCode code) { Args <A> a = new Args <A>() { ct = ClientType.InnerRpc.ToString(), // 只有内部的rpc请求才能如此标记 cv = string.Empty, m = m, v = args, rid = Guid.NewGuid().ToString("N"), Headers = new Dictionary <string, HeaderValue>(), }; EventId eventId = new EventId(0, a.rid); try { #region 构造路由 // 添加自己的头信息 string sk = $"{ServerSetting.AppName}(idx:{ServerSetting.Pool})_{ServiceEnvironment.ComputerName}_{ServiceEnvironment.ComputerAddress}"; string key = $"{ServerSetting.AppName}_{HeaderValue.INNERIP}"; // 强制在一个请求链上一个微服务只能被调用一次,防止出现来回循环调用的情况出现 a.Headers.TryAdd(key, new HeaderValue(sk, HeaderValue.INNERIP, ServiceEnvironment.ComputerAddress)); // 原样透传rpcContext if (context != null) { a.ct = string.IsNullOrEmpty(context.Args.ct) ? a.ct : context.Args.ct; a.cv = string.IsNullOrEmpty(context.Args.cv) ? a.cv : context.Args.cv; a.rid = string.IsNullOrEmpty(context.Args.rid) ? a.rid : context.Args.rid; a.lg = string.IsNullOrEmpty(context.Args.lg) ? a.lg : context.Args.lg; a.tk = string.IsNullOrEmpty(context.Args.tk) ? a.tk : context.Args.tk; a.uri = string.IsNullOrEmpty(context.Args.uri) ? a.uri : context.Args.uri; if (context.Headers != null && context.Headers.Any()) { foreach (var item in context.Headers) { a.Headers.TryAdd(item.Key, item.Value); } } } int error = 0; gotoHere: ClientServer cServer = null; ClientItem cItem = null; Result <R> rr = new Result <R>(); try { readerWriterLock.AcquireReaderLock(80); string s = server.ToLower(); if (cls.ContainsKey(s)) { cServer = cls[s]; var clients = cServer.Client; int idx = 0; switch (cServer.RouterType) { case RouterType.Hash: idx = RouterManager.GetPool(a.uri); break; case RouterType.Polling: idx = RouterManager.GetPolling(0, clients.Length); break; default: case RouterType.Random: idx = RouterManager.GetRandom(0, clients.Length); break; } cItem = clients[idx]; } else { StatusCode cc = new StatusCode(402, $"server :{server} not found rid = {a.rid}"); rr.c = cc.code; rr.msg = cc.msg; rr.v = default(R); logger.LogError(eventId, new LogInfo() { ServiceName = server, ApiName = a.m, CreatedBy = "FrameWork", TransactionId = a.rid, UseChain = JsonConvert.SerializeObject(a.Headers), CodeMsg = rr.msg, Code = rr.c, Desc = $"server :{server} not found rid = {a.rid}", }.ToString()); } } catch (Exception e) { string msg = $"获取路由信息异常{server}{e.Message} rid={a.rid}"; StatusCode cc = new StatusCode(502, msg); rr.c = cc.code; rr.msg = cc.msg; rr.v = default(R); logger.LogCritical(eventId, new LogInfo() { ServiceName = server, ApiName = a.m, CreatedBy = "FrameWork", TransactionId = a.rid, UseChain = JsonConvert.SerializeObject(a.Headers), CodeMsg = rr.msg, Code = rr.c, Desc = $"获取路由信息异常{server}{e.Message} rid={a.rid}", }.ToString()); // GrantLogTextWriter.Write(new Exception(msg, e)); } finally { if (readerWriterLock.IsReaderLockHeld) { readerWriterLock.ReleaseReaderLock(); } } #endregion 构造路由 #region 发送请求 var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; jSetting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; jSetting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; var sendValue = JsonConvert.SerializeObject(a, jSetting); if (cItem == null) { code = new StatusCode(403, $"{server}的路由信息无法找到 rid={a.rid}"); rr.v = default(R); } else { logger.LogInformation(eventId, $"Client发送请求\r\n\tserver={cServer.ServerName},ip={cItem.Ip},port={cItem.Port}\r\n\targs={sendValue}"); bool isOk = false; using (IGrantRpcClient rpcClient = ClientConnectionManager.GetClient(cItem)) { string result = null; if (rpcClient.Send(sendValue, m, out result)) { rr = JsonConvert.DeserializeObject <Result <R> >(result); code = new StatusCode(rr.c, rr.msg); isOk = true; } } if (!isOk) { error += 1; System.Threading.Thread.Sleep(100); // 重试3次 if (error < 3) { goto gotoHere; // 失败了就重新去找一个连接重试,如果是单台短时间内重试就没有意义了 } rr = new Result <R> { v = default(R) }; code = new StatusCode(501, "client_error无法访问远程服务器 rid=" + a.rid); } else { code = new StatusCode(rr.c, rr.msg); } } logger.LogInformation(eventId, $"Client返回结果\r\n\tServiceName:{server},ApiName:{a.m},Code:{code.code},CodeMsg:{code.msg},\r\n\tUseChain{JsonConvert.SerializeObject(a.Headers)}\r\n\tResult:{JsonConvert.SerializeObject(rr)}"); return(rr.v); #endregion 发送请求 } catch (Exception e) { code = new StatusCode(504, $"未知异常:{e.Message}"); logger.LogError(eventId, e, $"未知异常"); return(default(R)); } }
void Start() { //Finds cursor object in hierarchy cursor = Instantiate(gridCursor, new Vector3(0, -1, 0), Quaternion.Euler(-90, 0, 0)); routerManager = GameObject.Find("RouterManager").GetComponent <RouterManager>(); }
private void Awake() { inst = this; }
/// <summary> /// 代理层使用 /// </summary> /// <param name="args">参数</param> /// <param name="url">前端要求将M值体现在路径上,接入层自己来做个转换处理</param> /// <returns>string,参数</returns> internal static (string c, Result <object> r) Send(Args <object> args, string url) { var serverName = ""; ClientServer cServer = null; Result <object> rr = new Result <object>(); EventId eventId = new EventId(0, args.rid); try { // 这里需要重构,统一做成一个Fliter ClientType ct = ClientTypeParser.Parser(args.ct); switch (ct) { case ClientType.InnerRpc: // 需要拦截 throw new Exception("你想干什么?"); case ClientType.QtApp: case ClientType.QtWeb: // 需要要做来源ip和reffer网站,都来着grant的域名 case ClientType.Unkunwn: // 未知的和第三方都必须验证appkey case ClientType.ThirdPart: break; } string[] motheds = url.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (motheds == null || motheds.Length < 2) { rr.msg = "HttpProxy.Error:Request args Error,Server name Could not found rid=" + args.rid; rr.c = 503; rr.v = default(object); } else { #region 重构,获取路由配置 string server = motheds[motheds.Length - 2]; serverName = server; args.m = motheds[motheds.Length - 1]; int error = 0; gotoHere: readerWriterLock.AcquireReaderLock(80); ClientItem cItem = null; try { string s = server.ToLower(); if (cls.ContainsKey(s)) { cServer = cls[s]; var clients = cServer.Client; int idx = 0; switch (cServer.RouterType) { case RouterType.Hash: idx = RouterManager.GetPool(args.uri); break; case RouterType.Polling: idx = RouterManager.GetPolling(0, clients.Length); break; default: case RouterType.Random: idx = RouterManager.GetRandom(0, clients.Length); break; } cItem = clients[idx]; } else { StatusCode cc = new StatusCode(402, $"HttpProxy.Error:server :{server} not found rid={args.rid}"); rr.c = cc.code; rr.msg = cc.msg; rr.v = default(object); logger.LogError(eventId, new LogInfo() { ServiceName = serverName, ApiName = args.m, CreatedBy = "httpProxy", TransactionId = args.rid, UseChain = JsonConvert.SerializeObject(args.Headers), CodeMsg = rr.msg, Code = rr.c, Desc = $"HttpProxy.Error:server :{server} not found rid={args.rid}", }.ToString()); } } catch (Exception e) { string msg = $"获取路由信息异常{server}{e.Message} rid = {args.rid}"; StatusCode cc = new StatusCode(502, msg); rr.c = cc.code; rr.msg = cc.msg; rr.v = default(object); logger.LogError(eventId, e, $"获取Server:{server}路由信息异常"); } finally { if (readerWriterLock.IsReaderLockHeld) { readerWriterLock.ReleaseReaderLock(); } } #endregion 重构,获取路由配置 #region 发送请求 if (cItem == null) { string msg = $"HttpProxy.Error:无法获取路由信息:{server} rid = {args.rid}"; StatusCode cc = new StatusCode(503, msg); rr.c = cc.code; rr.msg = cc.msg; rr.v = default(object); logger.LogError(eventId, new LogInfo { ServiceName = server, ApiName = args.m, CreatedBy = "httpProxy", TransactionId = args.rid, Desc = msg, Code = rr.c, CodeMsg = rr.msg, UseChain = JsonConvert.SerializeObject(args.Headers), }.ToString()); } else { cItem.Url = args.m; var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; jSetting.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; jSetting.DateFormatString = "yyyy-MM-dd HH:mm:ss"; var msg = JsonConvert.SerializeObject(args, jSetting); logger.LogTrace(eventId, new LogInfo { ServiceName = server, ApiName = args.m, CreatedBy = "httpProxy", TransactionId = args.rid, Desc = string.Format("开始访问服务器:server={0},ip={1},port={2},args={3},rid={4}", cServer.ServerName, cItem.Ip, cItem.Port, msg, args.rid), Code = StatusCode.OK.code, CodeMsg = StatusCode.OK.msg, UseChain = JsonConvert.SerializeObject(args.Headers), }.ToString()); using (IGrantRpcClient rpcClient = ClientConnectionManager.GetClient(cItem)) { string result = null; if (rpcClient.Send(msg, args.m, out result)) { var resultObj = JsonConvert.DeserializeObject <Result <object> >(result); logger.LogTrace(eventId, new LogInfo { ServiceName = server, ApiName = args.m, CreatedBy = "httpProxy", TransactionId = args.rid, Desc = string.Format( "服务器返回:server={0},ip={1},port={2},result={3},rid={4}", cServer.ServerName, cItem.Ip, cItem.Port, result, args.rid), Code = resultObj.c, CodeMsg = resultObj.msg, UseChain = JsonConvert.SerializeObject(args.Headers), }.ToString()); return(result, resultObj); // 直接返回结果 } } // 走到这里就说明失败了 error += 1; System.Threading.Thread.Sleep(100); // 重试3次 if (error < 3) { goto gotoHere; // 失败了就重新去找一个连接重试 } // rr = new Result<R> { v = default(R) }; // 要知道请求的rid这里只能反解出来 StatusCode ccc = new StatusCode(502, "HttpProxy.Error:无法访问远程服务器 rid=" + args.rid); rr = new Result <object>() { c = ccc.code, msg = ccc.msg, rid = args.rid, uri = args.uri, v = null, }; } #endregion 发送请求 } } catch (Exception ex) { StatusCode cc = new StatusCode(501, "HttpProxy.Error:" + ex.Message); rr.c = cc.code; rr.msg = cc.msg; rr.v = default(object); logger.LogError(eventId, ex, new LogInfo() { ServiceName = serverName, ApiName = args.m, CreatedBy = "httpProxy", TransactionId = args.rid, UseChain = JsonConvert.SerializeObject(args.Headers), CodeMsg = rr.msg, Code = rr.c, Desc = "GrantRpcClientManager.Send<R, A>.error", }.ToString()); } var js = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }; js.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat; js.DateFormatString = "yyyy-MM-dd HH:mm:ss"; var rst = JsonConvert.SerializeObject(rr, js); logger.LogInformation(eventId, new LogInfo() { ServiceName = serverName, ApiName = args.m, CreatedBy = "httpProxy", TransactionId = args.rid, UseChain = JsonConvert.SerializeObject(args.Headers), CodeMsg = rr.msg, Code = rr.c, Desc = string.Format("返回结果是:{0}", rst), }.ToString()); return(rst, rr); }
/// <summary> /// 保养页面 /// </summary> public ActionResult Maintenance(string routerMainLinkDiscription, string linkUrl, string linkId, string noLinkId, int linkKind) { ViewBag.linkId = linkId; ViewBag.noLinkId = noLinkId; ViewBag.linkKind = linkKind; var valid = false; //标志是否解析 var routerManager = new RouterManager(); var content = routerManager.GetMainLink(routerMainLinkDiscription, linkKind).Content; var list = new List <string>(); var type = ""; string[] aid; var aId = ""; if (linkKind == 1) { type = "type"; aId = "aid"; } if (linkKind == 2) { type = "baoyangtypes"; aId = "actid"; } if (linkUrl != "") { //解析格式APP/maintenance? type=xxx;xxx;xxx&aid=xxx&produceIds=xx,xx&productActivityId=xx&IsTuhuRecommend=x //小程序 /pages/keep_list2/keep_list2?baoyangtypes=xxx&actid=xxxx try { var array = linkUrl.Split('?'); var arrayLatter = array[1].Split('&'); ViewBag.paraArray = array[1]; //paraArray 是参数以&分隔的字符串 var typeString = arrayLatter[0].Split('='); ViewBag.typeArray = typeString[1]; //typeArray 是种类以;分隔的字符串 if (typeString[0] == type && array[0] == content) { valid = true; } if (arrayLatter.Length >= 2) { aid = arrayLatter[1].Split('='); if (aid[0] == aId) { ViewBag.aid = aid[1]; for (var i = 2; i < arrayLatter.Length; i++) { list.Add(arrayLatter[i]); } } else { for (var i = 1; i < arrayLatter.Length; i++) { list.Add(arrayLatter[i]); } } } } catch (Exception) { // ignored } } if (valid) { return(View(routerManager.GetParameterStateList(routerMainLinkDiscription, list, linkKind))); //进入解析页面 } return(View(routerManager.GetParameterList(routerMainLinkDiscription, linkKind))); //进入空白页面 }