public static IApplicationBuilder UseInDirectLineCore(this IApplicationBuilder app) { var sp = app.ApplicationServices; var env = sp.GetRequiredService <IWebHostEnvironment>(); var directLineSettings = sp.GetRequiredService <IOptions <InDirectLineSettings> >()?.Value; if (directLineSettings == null) { throw new Exception("InDirectLineOptions cannot be null!"); } var webSocketOptions = new WebSocketOptions() { KeepAliveInterval = TimeSpan.FromSeconds(120), ReceiveBufferSize = 4 * 1024 }; var botEndPoint = directLineSettings.BotEndpoint; var botOrigin = UtilsEx.GetOrigin(botEndPoint); webSocketOptions.AllowedOrigins.Add(botOrigin); webSocketOptions.AllowedOrigins.Add("*"); app.UseWebSockets(webSocketOptions); app.UseMiddleware <WebSocketConnectionMiddleware>(); return(app); }
private DirectLineConversation GetDirectLineConversation(string userId, string conversationId) { var claims = new List <Claim>(); claims.Add(new Claim(TokenBuilder.ClaimTypeConversationID, conversationId)); var expiresIn = this._inDirectlineSettings.TokenExpiresIn; var token = this._tokenBuilder.BuildToken(userId, claims, expiresIn); var mustBeConnectedIn = this._inDirectlineSettings.StreamUrlMustBeConnectedIn; var streamUrlToken = this._tokenBuilder.BuildToken(userId, claims, mustBeConnectedIn); // we should not use ServiceUrl here because // - Service URL is exposed to Bot Message Endpont only, // - it might be different from the one exposed to client // so we should get the StreamURL from current URL var origin = $"{this.HttpContext.Request.Scheme}://{HttpContext.Request.Host}"; // note the Host has already included the PORT origin = UtilsEx.GetWebSocketOrigin(origin); this._logger.LogInformation($"the origin for streamUrl is {origin}"); return(new DirectLineConversation { ConversationId = conversationId, ExpiresIn = expiresIn, Token = token, StreamUrl = $"{origin}/v3/directline/conversations/{conversationId}/stream?t={streamUrlToken}" }); }
public static void UploadDeleteFile(String oldUrl, String newUrl) { String oldFile = ""; try { oldFile = HttpContext.Current.Server.MapPath(oldUrl); } catch { } String newFile = (!String.IsNullOrWhiteSpace(newUrl) ? HttpContext.Current.Server.MapPath(newUrl) : ""); if (newFile == oldFile) { return; } if (!File.Exists(oldFile)) { return; } // Eliminar o ficheiro antigo try { File.Delete(oldFile); } catch (Exception ex) { UtilsEx.Log(ex); } }
public async Task <IActionResult> Conversations() { var userId = HttpContext.User?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value; if (string.IsNullOrEmpty(userId)) { return(BadRequest("userId cannot be null!")); } var conversationId = HttpContext.User?.Claims.FirstOrDefault(c => c.Type == TokenBuilder.ClaimTypeConversationID)?.Value; var result = await this._helper.CreateNewConversationWithId(userId, conversationId); // make sure the conversationId is created if null or empty conversationId = result.Activity.Conversation.Id; var claims = new List <Claim>(); claims.Add(new Claim(TokenBuilder.ClaimTypeConversationID, conversationId)); var expiresIn = this._inDirectlineSettings.TokenExpiresIn; var token = this._tokenBuilder.BuildToken(userId, claims, expiresIn); var mustBeConnectedIn = this._inDirectlineSettings.StreamUrlMustBeConnectedIn; var streamUrlToken = this._tokenBuilder.BuildToken(userId, claims, mustBeConnectedIn); var origin = UtilsEx.GetWebSocketOrigin(this._inDirectlineSettings.ServiceUrl); return(new OkObjectResult(new DirectLineConversation { ConversationId = conversationId, ExpiresIn = expiresIn, Token = token, StreamUrl = $"{origin}/v3/directline/conversations/{conversationId}/stream?t={streamUrlToken}" })); }
public Object SynLoadAsset(string prefab) { if (string.IsNullOrEmpty(prefab)) { LoggerHelper.Error("null prefab name."); return(null); } ResourceInfo resourceInfo; var flag = m_resourcesDic.TryGetValue(prefab, out resourceInfo); if (!flag) { resourceInfo = new ResourceInfo(); if (m_filesDic.ContainsKey(prefab)) { resourceInfo.Path = m_filesDic[prefab]; resourceInfo.ResType = UtilsEx.GetTypeByExtension(Path.GetExtension(prefab)); } else { LoggerHelper.Error("prefab not exist: " + prefab); return(null); } m_resourcesDic.Add(prefab, resourceInfo); } resourceInfo.ReferenceCount++; return(resourceInfo.GameObject); }
public void SynLoadAsset(string prefab, Action <Object> loaded) { ResourceInfo resourceInfo; var flag = m_resourcesDic.TryGetValue(prefab, out resourceInfo); if (!flag) { resourceInfo = new ResourceInfo(); if (m_filesDic.ContainsKey(prefab)) { resourceInfo.Path = m_filesDic[prefab]; resourceInfo.ResType = UtilsEx.GetTypeByExtension(Path.GetExtension(prefab)); } else { LoggerHelper.Error("prefab not exist: " + prefab); if (loaded != null) { loaded(null); } return; } m_resourcesDic.Add(prefab, resourceInfo); } resourceInfo.ReferenceCount++; if (loaded != null) { loaded(resourceInfo.GameObject); } }
public static String CallWebService(String url, Dictionary <String, String> parms, String method) { Boolean isGet = (method.ToLowerInvariant() == "get"); // Se for via POST, enviar dados if (!isGet) { NameValueCollection webParms = new NameValueCollection(); if (parms != null) { foreach (KeyValuePair <String, String> pair in parms) { webParms.Add(pair.Key, pair.Value); } } try { using (WebClient webClient = new WebClient()) { byte[] bytes = webClient.UploadValues(url, method, webParms); return(Encoding.UTF8.GetString(bytes)); } } catch (Exception ex) { UtilsEx.Log(ex); throw; } } // Se for GET, adicionar ao Url if (parms != null) { foreach (KeyValuePair <String, String> pair in parms) { url += (url.IndexOf('?') > 0 ? "&" : "?") + pair.Key + "=" + Uri.EscapeDataString(pair.Value); } } try { using (WebClient webClient = new WebClient()) { byte[] bytes = webClient.DownloadData(url); return(Encoding.UTF8.GetString(bytes)); } } catch (Exception ex) { UtilsEx.Log(ex); throw; } }
public string Start() { InitData(); var ip = UtilsEx.GetIP(); LoggerHelper.Debug(ip); ipAddress = ip; portNum = 43998; /*创建一个服务器线程并启动*/ newt = new Thread(new ThreadStart(StartListening)); newt.IsBackground = true; newt.Start(); return(ip.ToString()); }
public void LoadAsset(string prefab, Action <Object> loaded, Action <float> progress) { if (string.IsNullOrEmpty(prefab)) { LoggerHelper.Error("null prefab name."); if (loaded != null) { loaded(null); } return; } ResourceInfo resourceInfo; var flag = m_resourcesDic.TryGetValue(prefab, out resourceInfo); if (!flag) { resourceInfo = new ResourceInfo(); if (m_filesDic.ContainsKey(prefab)) { resourceInfo.Path = m_filesDic[prefab]; resourceInfo.ResType = UtilsEx.GetTypeByExtension(Path.GetExtension(prefab)); } else { LoggerHelper.Error("prefab not exist: " + prefab); if (loaded != null) { loaded(null); } return; } m_resourcesDic.Add(prefab, resourceInfo); } resourceInfo.ReferenceCount++; //if (loaded != null) // loaded(resourceInfo.GameObject); //if (prefab.EndsWith(".exr")) //{ // if (loaded != null) // loaded(resourceInfo.GameObject); //} //else //{ StartCoroutine(resourceInfo.GetGameObject(loaded)); //} }
protected override void OnResourceLoaded() { var parent = MogoWorld.m_uiManager.MogoMainUIPanel; SyncCreateUIInstanceWithRootTransform(Resources[0], parent); m_myTransform.localPosition = new Vector3(0f, -30f, 0f); var btnCreate = FindComponent <MogoUIBtn>("BtnCreateServer"); btnCreate.SetText(LanguageData.GetContent(1)); btnCreate.ClickAction = OnBtnCreate; var btnFind = FindComponent <MogoUIBtn>("BtnFindServer"); btnFind.SetText(LanguageData.GetContent(2)); btnFind.ClickAction = OnBtnFind; var btnJoin = FindComponent <MogoUIBtn>("BtnJoin"); btnJoin.SetText(LanguageData.GetContent(11)); btnJoin.ClickAction = OnBtnJoin; var btnScanJoin = FindComponent <MogoUIBtn>("BtnScanJoin"); btnScanJoin.SetText(LanguageData.GetContent(12)); btnScanJoin.ClickAction = OnBtnScanJoin; m_inputPlayerName = FindComponent <UIInput>("PlayerName"); m_inputPlayerName.text = UtilsEx.GetRandomName(); m_inputPlayerName.maxChars = NAME_MAX_LENGTH; m_inputPlayerName.onSubmit = OnSubmitName; m_inputPlayerName.lostFocusAction = OnLostFocusInputName; m_inputPlayerName.functionName = "OnSubmitName"; FindComponent <UILabel>("LblPlayerName").text = LanguageData.GetContent(10); m_inputServerIP = FindComponent <UIInput>("ServerIP"); m_inputServerIP.text = SystemConfig.GetCfgInfoUrl("serverlist"); m_inputServerIP.onSubmit = OnSubmitName; FindComponent <UILabel>("LblIP").text = LanguageData.GetContent(9); var btnGuide = FindComponent <MogoUIBtn>("BtnWenHao"); btnGuide.ClickAction = OnBtnGuide; }
// 根据配置的参数来设置策略截止期限 private void setupDeadline() { DateTime preDay = TradingDayHelper.GetPreTradingDay(TradingDate); _deadlineWatching = UtilsEx.CalcDeadline(TradingDate, preDay, _tradeSlices, UtilsEx.DeadlineDir.ByBegin, DurationWatchChangeInHours * 60); _deadlineStopRunningIfPositionEmpty = UtilsEx.CalcDeadline(TradingDate, preDay, _tradeSlices, UtilsEx.DeadlineDir.ByEnd, DurationTerminalRunningIfPositionEmptyInHours * 60); _deadlineUnconditionLiquidate = UtilsEx.CalcDeadline(TradingDate, preDay, _tradeSlices, UtilsEx.DeadlineDir.ByEnd, DurationUnconditionLiquidateInMinutes); _deadlineTryLiquidate = UtilsEx.CalcDeadline(TradingDate, preDay, _tradeSlices, UtilsEx.DeadlineDir.ByEnd, DurationTryLiquidateInHours * 60); _timerWatching = new DeadlineTimer(_deadlineWatching, onDeadlineWatchingTicking, onDeadlineWatchingHit); _timerStopRunning = new DeadlineTimer(_deadlineStopRunningIfPositionEmpty, null, onDeadlineStopRunningHit); _timerTryLiquidate = new DeadlineTimer(_deadlineTryLiquidate, null, onDeadlineTryLiquidateHit); _timerUnconditionLiquidate = new DeadlineTimer(_deadlineUnconditionLiquidate, null, onDeadlineUnconditionLiquidateHit); Print("截止时间->观察: " + _deadlineWatching); Print("截止时间->平仓停止策略运行如果距离收盘时间小于" + DurationTerminalRunningIfPositionEmptyInHours + ": " + _deadlineStopRunningIfPositionEmpty); Print("截止时间->无条件平仓如果距离收盘时间小于" + DurationUnconditionLiquidateInMinutes + ": " + _deadlineUnconditionLiquidate); Print("截止时间->尝试平仓如果距离收盘时间小于" + DurationTryLiquidateInHours + ": " + _deadlineTryLiquidate); }
public static IServiceCollection AddInDirectLine(this IServiceCollection services, InDirectLineSettings directlineOpts) { services.Configure <InDirectLineSettings>(opt => { foreach (var pi in opt.GetType().GetProperties()) { var propValue = pi.GetValue(directlineOpts); pi.SetValue(opt, propValue); } }); services.AddHttpClient(); services.AddHttpContextAccessor(); services.AddSingleton <IConversationHistoryStore, InMemoryConversationHistoryStore>(); services.AddSingleton <IDirectLineConnection, WebSocketDirectLineConnection>(); services.AddSingleton <IDirectLineConnectionManager, DirectLineConnectionManager>(); services.AddSingleton <TokenBuilder>(); services.AddScoped <ChannelServiceHandler, InDirectLineConversationHandler>(); services.AddAuthorization(opt => { opt.AddPolicy("MatchConversation", pb => pb.Requirements.Add(new MatchConversationAuthzRequirement())); }); services.AddHttpClient <InDirectLineClient>(); var botEndPointUri = UtilsEx.GetOrigin(directlineOpts.BotEndpoint); services.AddSingleton <IAuthorizationHandler, MatchConversationAuthzHandler>(); services.AddCors(options => { options.AddPolicy( InDirectLineDefaults.CorsPolicyNames, builder => { builder.WithOrigins(botEndPointUri); builder.AllowAnyOrigin(); builder.AllowAnyHeader(); builder.AllowAnyMethod(); } ); }); services.AddScoped <WebSocketConnectionMiddleware>(); return(services.AddScoped <DirectLineHelper>()); }
void OnGUI() { if (GUI.Button(new Rect(0, 0, 10, 10), "")) { m_switch = !m_switch; } if (!m_switch) { return; } if (GUI.Button(new Rect(10, 0, 90, 100), "touch")) { foreach (var item in MogoWorld.m_dataMapManager.ReachStarList) { foreach (var soliders in item.SoldierDic.Values) { foreach (var solider in soliders.Values) { solider.OnHit(); } } } //MogoWorld.thePlayer.controllerInput.SetStickType(StickType.Touch); } serverIp = GUI.TextArea(new Rect(0, 100, 150, 50), serverIp); if (GUI.Button(new Rect(100, 0, 100, 100), "CreateServer")) { serverIp = MogoWorld.CreateServer(); } if (GUI.Button(new Rect(200, 0, 100, 100), "login")) { MogoWorld.ServerIP = serverIp; MogoWorld.ConnectServer(serverIp, 43998); MogoWorld.TmpPlayerName = UtilsEx.GetRandomName(); MogoWorld.Login(); } if (GUI.Button(new Rect(300, 0, 100, 100), "createAvatar")) { MogoWorld.thePlayer.RpcCall("CreateAvatarReq"); } if (GUI.Button(new Rect(400, 0, 100, 100), "vrWidth+")) { MogoWorld.MainCamera.SetVRWidth(true); } if (GUI.Button(new Rect(500, 0, 100, 100), "vrWidth-")) { MogoWorld.MainCamera.SetVRWidth(false); } if (GUI.Button(new Rect(600, 0, 100, 100), "vrRot+")) { MogoWorld.MainCamera.SetVRRotation(true); } if (GUI.Button(new Rect(700, 0, 100, 100), "vrRot-")) { MogoWorld.MainCamera.SetVRRotation(false); } if (GUI.Button(new Rect(800, 0, 100, 100), "vr")) { MogoWorld.MainCamera.SwitchVR(); } if (GUI.Button(new Rect(0, 100, 100, 100), "into main")) { MogoWorld.EnterMainEufloria(1); } if (GUI.Button(new Rect(100, 100, 100, 100), "init map")) { UIManager.I.GetUILogic <MapUIMgr>().InitStarMap(1); } if (GUI.Button(new Rect(200, 100, 100, 100), "remove soldier")) { MogoWorld.thePlayer.RpcCall("RemoveSoldier", MogoWorld.thePlayer.ID, 0, 1, 100, 1); } if (GUI.Button(new Rect(300, 100, 100, 100), "ShowSoldierIntrusionStar")) { //MogoWorld.m_dataMapManager.addSoldierToStar(MogoWorld.thePlayer.ID, 1, 1); //MogoWorld.thePlayer.RpcCall("ArrayedSoldier", 1, 1); // MogoWorld.m_dataMapManager.ShowSoldierIntrusionStar(MogoWorld.thePlayer.ID, 1, 1, 150); } if (GUI.Button(new Rect(400, 100, 100, 100), "stop game")) { //MogoWorld.m_dataMapManager.addSoldierToStar(MogoWorld.thePlayer.ID, 1, 1); //MogoWorld.thePlayer.RpcCall("ArrayedSoldier",1, 2); //UIManager.I.GetUILogic<MapUIMgr>().EraserTexture(); //MogoWorld.IsInGame = false; MogoWorld.thePlayer.RpcCall("GameOver", 1); } if (GUI.Button(new Rect(500, 100, 100, 100), "OpenRangleCheck")) { //MogoWorld.m_dataMapManager.addSoldierToStar(MogoWorld.thePlayer.ID, 1, 1); //MogoWorld.thePlayer.RpcCall("ArrayedSoldier",1, 2); //UIManager.I.GetUILogic<MapUIMgr>().EraserTexture(); UIManager.I.GetUILogic <StarInfoUIMgr>().IsOpenRangleCheck = !UIManager.I.GetUILogic <StarInfoUIMgr>().IsOpenRangleCheck; } }
public static void AtualizarBD() { try { if (String.IsNullOrEmpty(PathBackups)) { throw new ApplicationException("Caminho da pasta de backups em falta!"); } if (String.IsNullOrEmpty(PathBackups)) { throw new ApplicationException("Caminho da pasta dos scripts em falta!"); } if (!BackupBaseDados()) { throw new ApplicationException("Backup da base de dados nao foi feita!"); } if (!HasAtualizacaoInDB()) { throw new ApplicationException("Não existe ou nao esta configurada a tabela de atualizacoes!"); } BaseDados bd = new BaseDados(); int VersaoRelease = -1; if (HasUpdates(out VersaoRelease)) { for (int i = VersaoRelease; i < (VersaoUpdate - VersaoRelease); i++) { UtilsEx.Log("Entrou no ciclo for. script n " + i); string script = "\\" + string.Format(ScriptName, i); string path = PathScripts + script; if (!File.Exists(path)) { throw new ApplicationException("Script" + i + " não existe!"); } try { string content = File.ReadAllText(path); bd.ExecNonQuery(path); UtilsEx.Log("Executou script n " + i); }catch (Exception e) { UtilsEx.Log(e, "Erro ao executar: script" + i); break; } } } }catch (Exception e) { UtilsEx.Log(e, "Erro ao fazer update da base de dados!"); } }
/// <summary> /// Validar um ficheiro carregado e transformar em definitivo se necessário /// </summary> /// <returns>Devolve o URL para a localização definitiva do ficheiro</returns> public static String UploadCheckFile(String fileUrl, String savePath) { fileUrl = fileUrl.TrimStart('~', '/'); fileUrl = "~/" + fileUrl; // Verificar se o ficheiro existe String filePath = HttpContext.Current.Server.MapPath(fileUrl); if (!File.Exists(filePath)) { return(""); } // Se já é um ficheiro definitivo, não altera String fileName = Path.GetFileName(filePath); if (!fileName.ToLowerInvariant().StartsWith("tmp_")) { return(fileUrl.TrimStart('~')); } // Se for um ficheiro temporário, transforma em definitivo String newPath = savePath.Trim('~', '/'); newPath = "~/" + newPath + "/"; newPath += fileName.Substring(4); String newUrl = VirtualPathUtility.ToAbsolute(newPath); // Mover o ficheiro temporário para definitivo newPath = HttpContext.Current.Server.MapPath(newUrl); String fileDir = Path.GetDirectoryName(newPath); if (!Directory.Exists(fileDir)) { try { Directory.CreateDirectory(fileDir); } catch (Exception ex) { UtilsEx.Log(ex); return(""); } } try { File.Move(filePath, newPath); } catch (Exception ex) { UtilsEx.Log(ex); return(""); } newUrl = VirtualPathUtility.ToAppRelative(newUrl); newUrl = newUrl.TrimStart('~'); return(newUrl); }