private async ValueTask <(IConnection?, string?)> InternalAcceptAsync(ICap cap, CancellationToken cancellationToken) { using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); linkedTokenSource.CancelAfter(TimeSpan.FromSeconds(20)); var baseConnectionOptions = new BaseConnectionOptions() { MaxSendByteCount = 4 * 1024 * 1024, MaxReceiveByteCount = 4 * 1024 * 1024, BytesPool = _bytesPool, }; var baseConnection = new BaseConnection(cap, _baseConnectionDispatcher, baseConnectionOptions); var omniSecureConnectionOptions = new OmniSecureConnectionOptions() { Type = OmniSecureConnectionType.Accepted, BufferPool = _bytesPool, }; var omniSecureConnection = new OmniSecureConnection(baseConnection, omniSecureConnectionOptions); await omniSecureConnection.HandshakeAsync(linkedTokenSource.Token); ConnectionHelloMessage?helloMessage = null; await omniSecureConnection.DequeueAsync((sequence) => helloMessage = ConnectionHelloMessage.Import(sequence, _bytesPool), linkedTokenSource.Token); return(omniSecureConnection, helloMessage?.ServiceType); }
/// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { #if DEBUG this.Window.Title = "Asteroids-dev-debug"; #else this.Window.Title = "Asteroids-dev-release"; #endif this.Window.Title += " - Version: " + this.GetVersionString(); System.Diagnostics.Trace.WriteLine(DateTime.Now + " " + this.Window.Title); UserConfig.Instance = UserConfig.Load(); WindowSettings.Initialize(this, this.graphics); WindowSettings.SetWindowResolution(new Point(UserConfig.Instance.ScreenWidth, UserConfig.Instance.ScreenHeight)); WindowSettings.SetBorderless(UserConfig.Instance.Borderless); WindowSettings.MinWindowResolution = GameConfig.MinWindowSize; WindowSettings.UnitsVisible = new Vector2(1280, 720); this.renderTarget = new RenderTarget2D(this.GraphicsDevice, WindowSettings.RenderArea.Width, WindowSettings.RenderArea.Height); this.sceneManager = new GUISceneManager(this); this.Components.Add(new Kadro.Input.KeyboardInput(this)); this.Components.Add(new MouseInput(this)); this.Components.Add(new GamepadInput(this)); this.Components.Add(new TouchpanelInput(this)); this.performanceCounter = new PerformanceMetrics(); Assets.Initialize(Content); this.networkManager = new NetworkManager(UserConfig.Instance.NetworkName); this.connectionInfo = new BaseConnection(); base.Initialize(); }
private async ValueTask <IConnection?> InternalConnectAsync(ICap cap, string serviceType, CancellationToken cancellationToken) { using var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); linkedTokenSource.CancelAfter(TimeSpan.FromSeconds(20)); var baseConnectionOptions = new BaseConnectionOptions() { MaxSendByteCount = 4 * 1024 * 1024, MaxReceiveByteCount = 4 * 1024 * 1024, BytesPool = _bytesPool, }; var baseConnection = new BaseConnection(cap, _baseConnectionDispatcher, baseConnectionOptions); var omniSecureConnectionOptions = new OmniSecureConnectionOptions() { Type = OmniSecureConnectionType.Connected, BufferPool = _bytesPool, }; var omniSecureConnection = new OmniSecureConnection(baseConnection, omniSecureConnectionOptions); await omniSecureConnection.HandshakeAsync(linkedTokenSource.Token); var helloMessage = new ConnectionHelloMessage(serviceType); await omniSecureConnection.EnqueueAsync((bufferWriter) => helloMessage.Export(bufferWriter, _bytesPool), linkedTokenSource.Token); return(omniSecureConnection); }
private void SendResponse(BaseConnection c, StatusCodes statusCode, string json) { using (var writer = httpServer.GetHttpMessageWriter()) { int length = (json == null) ? 0 : Encoding.UTF8.GetByteCount(json); writer.WriteStatusLine(statusCode); writer.WriteCacheControlNoCache(); if (json != null) { writer.WriteContentType(ContentType.ApplicationJson); } writer.WriteContentLength(length); writer.WriteCRLF(); if (json != null) { writer.ValidateCapacity(length); Encoding.UTF8.GetBytes(json, 0, json.Length, writer.Buffer, writer.End); writer.AddCount(length); } httpServer.SendResponse(c, writer); } }
protected CommConnection getSQLConnection(DataBases DBName, String ServerIP, String Account, String Password) { try { BaseConnection BConn = new BaseConnection(); if (ServerIP != null) { BConn.Server = ServerIP; BConn.Account = Account; BConn.Password = Password; } else { BConn.Path = Server.MapPath(Url.Content("~")); } return(BConn.GetConnection(DBName)); } catch (Exception ex) { Log.Write(new Log.LogPlamInfo() { }, this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex); return(null); } }
/// <summary> /// Removes the given node from our list, but in a way that allows it to be undone. /// Registers all changes into the UnityEditor.Undo system. /// </summary> /// <param name="node">The node to remove.</param> public void RemoveNode_Editor(BaseNode node) { if (mNodes == null) { mNodes = new List <BaseNode>(); } // Remove all this node's connections for (int i = 0; i < mConnections.Count; ++i) { BaseConnection c = mConnections[i]; if (c.inNode != node && c.outNode != node) { continue; } RemoveConnection_Editor(c); --i; } // Delete the asset, but in a way that allows it to be undone. UnityEditor.Undo.RegisterCompleteObjectUndo(this, "Delete Node"); UnityEditor.Undo.DestroyObjectImmediate(node); mNodes.Remove(node); OnValidate(); // Flag our asset as dirty so that Unity updates it. UnityEditor.EditorUtility.SetDirty(this); }
public bool UpdateComments(HistoriaMedica objHmEnt) { bool flag = false; try { DbTransaction transaction = BaseConnection.GetTransaction(); try { MuestraLaboratorioDao muestraLaboratorioDao = new MuestraLaboratorioDao(); HistoriaMedicaDao historiaMedicaDao = new HistoriaMedicaDao(); if (!historiaMedicaDao.Update(objHmEnt, transaction)) { throw new Exception(historiaMedicaDao.Error); } if (!muestraLaboratorioDao.UpdateStatus(objHmEnt, transaction)) { throw new Exception(muestraLaboratorioDao.Error); } transaction.Commit(); flag = true; } catch (Exception ex) { this.error = ex.InnerException != null ? ex.InnerException.Message : ex.Message; transaction.Rollback(); } } catch (Exception ex) { this.error = ex.InnerException != null ? ex.InnerException.Message : ex.Message; } return(flag); }
private void ExecuteInternal(BaseConnection c, HttpMessageReader httpReader, ArraySegment <byte> content) { var method = GetRestMethod(GetHttpMethod(httpReader.Method)); if (method.Method == RestMethods.None) { SendResponse(c, StatusCodes.NotImplemented); } else { var domainName = (parser.DomainName.IsValid) ? parser.DomainName : parser.Authname; var account = accounts.GetAccount(domainName); if (IsAuthorized(httpReader.RequestUri, method.Auth, account) == false) { SendResponse(c, StatusCodes.Forbidden); } else { try { var result = CallMethod(content, method, account, (method.UsersIndex < 0) ? null : userz[method.UsersIndex]); SendResponse(c, StatusCodes.OK, result.Result); } catch (Exception ex) { SendResponse(c, StatusCodes.NotAcceptable, "{ \"message\": \"" + ex.Message.ToString().Replace("\"", "\\\"") + "\" }"); } } } }
private void Register() { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Task.Run(async() => { var stream = BaseConnection.StreamAsync <EventArgs>(IMetaReporterHub.ReportLogMethodename); await foreach (var item in stream) { ReceiveLog?.Invoke(this, item); } }); Task.Run(async() => { var stream = BaseConnection.StreamAsync <Quaternion>(IMetaReporterHub.ReportImuMethodename); await foreach (var item in stream) { ReceiveImu?.Invoke(this, item); } }); Task.Run(async() => { var stream = BaseConnection.StreamAsync <byte[]>(IMetaReporterHub.ReportMotorsMethodename); await foreach (var item in stream) { ReceiveMotors?.Invoke(this, item); } }); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed }
/// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">True if managed resources should be disposed; otherwise, false.</param> protected virtual void Dispose(bool disposing) { if (disposing) { BaseConnection.Dispose(); } }
public AuthenticationService(DatabaseSettings databaseSettings, string facility) { _base = BaseConnection.Instance; _base.DatabaseSettings = databaseSettings; _facility = facility; }
public MultiplayerGameScene(Game game, NetworkManager networkManager, BaseConnection connectionInfo) : base(game, networkManager, connectionInfo) { this.scene = new GUIScene(); this.background = new Background(Assets.Get <Texture2D>(GameConfig.Folders.Particles, "circle"), new Rectangle(Point.Zero, GameConfig.WorldSize)); this.intentManager = new IntentManager(); this.clientInputManager = new ClientInputManager(this.connectionInfo, this.intentManager); List <Texture2D> list = new List <Texture2D> { Assets.Get <Texture2D>(GameConfig.Folders.Particles, "circle") }; this.particleEngine = new ParticleEngine(list, Vector2.Zero, 0, 50, false); this.entityWorld = new EntityWorld(); this.entityFactory = new ClientEntityFactory(this.entityWorld); this.scoreboardUI = new Scoreboard(GameConfig.Fonts.Medium, true); this.scoreboardUI.Hide(); this.scene.AddChild(this.scoreboardUI); this.entityWorld.SystemManager.AddSystem(new MotionSystem(this.entityWorld)); //dead reckoning (for client side prediction) this.entityWorld.SystemManager.AddSystem(new RespawnTimeoutSystem(this.entityWorld)); this.entityWorld.SystemManager.AddSystem(new TextureRenderSystem(this.entityWorld)); this.entityWorld.SystemManager.AddSystem(new ScoreboardSystem(this.entityWorld, this.scoreboardUI)); this.entityWorld.SystemManager.AddSystem(new ParticleSystem(this.entityWorld, this.particleEngine)); this.CreateScene(); this.CreateEscMenu(); }
public DashboardService(DatabaseSettings databaseSettings, string facility) { _base = BaseConnection.Instance; _base.DatabaseSettings = databaseSettings; _facility = facility; }
public void Handle(BaseConnection connection, BinaryReader packet) { GameConnection game = connection as GameConnection; if (game != null && game.LoggedIn) { Dictionary <int, int> powerups = new Dictionary <int, int>(); if (game.User.Missiles > 0) { powerups.Add(UserPowerupsOutgoingPacket.Missile, game.User.Missiles); } if (game.User.Parachutes > 0) { powerups.Add(UserPowerupsOutgoingPacket.Parachute, game.User.Parachutes); } if (game.User.Shields > 0) { powerups.Add(UserPowerupsOutgoingPacket.Shield, game.User.Shields); } connection.SendPacket(new UserPowerupsOutgoingPacket(powerups)); } }
public bool Delete(int idHistToDel, int idUserProcess, string pathFilesToDelete) { bool flag = false; DbTransaction parentTrans = (DbTransaction)null; try { HistoriaMedicaDao historiaMedicaDao = new HistoriaMedicaDao(); parentTrans = BaseConnection.GetTransaction(); if (!historiaMedicaDao.Delete(idHistToDel, idUserProcess, parentTrans)) { throw new Exception(historiaMedicaDao.Error); } parentTrans.Commit(); flag = true; } catch (Exception ex) { this.error = ex.InnerException != null ? ex.InnerException.Message : ex.Message; } finally { parentTrans?.Dispose(); } return(flag); }
public void Handle(BaseConnection connection, BinaryReader packet) { APIConnection api = connection as APIConnection; if (api != null) { if (api.PrivateAPIUsable) { uint userId = packet.ReadUInt32(); string username = packet.ReadString(); string figure = packet.ReadString(); string gender = packet.ReadString(); byte badgesCount = packet.ReadByte(); List <string> badges = new List <string>(badgesCount); for (byte i = 0; i < badgesCount; i++) { badges.Add(packet.ReadString()); } int missiles = packet.ReadInt32(); int parachutes = packet.ReadInt32(); int shilds = packet.ReadInt32(); int credits = packet.ReadInt32(); connection.SendPacket(new AuthenicateUserResponseOutgoingPacket(true, api.Hotel.AuthenicateUser(new FastFoodUser(api.Hotel, userId, username, figure, gender, badges, missiles, parachutes, shilds, credits)))); } else { connection.SendPacket(new AuthenicateUserResponseOutgoingPacket(false, null)); } } }
public void BaseConnection_ProperInit_ConnectionIsNotNull() { BaseConnection.openConnection(); Assert.IsNotNull(BaseConnection.connection); Assert.IsNotNull(BaseConnection.connectionString); BaseConnection.closeConnection(); }
public async Task SimpleFunctionTest() { var(senderSocket, receiverSocket) = SocketHelper.GetSocketPair(); await using var dispacher = new BaseConnectionDispatcher(new BaseConnectionDispatcherOptions()); using var senderConnection = new BaseConnection(new SocketCap(senderSocket), dispacher, new BaseConnectionOptions()); using var receiverConnection = new BaseConnection(new SocketCap(receiverSocket), dispacher, new BaseConnectionOptions()); var mockTestService = new Mock <ITestService>(); mockTestService.Setup(n => n.Unary1Async(It.IsAny <TestParam>(), It.IsAny <CancellationToken>())).Returns(new ValueTask <TestResult>(new TestResult(1))); var client = new TestService.Client(senderConnection, BytesPool.Shared); var server = new TestService.Server(mockTestService.Object, receiverConnection, BytesPool.Shared); var eventLoop = server.EventLoopAsync(); var testResult1 = await client.Unary1Async(new TestParam(1), default); mockTestService.Verify(n => n.Unary1Async(new TestParam(1), default), Times.AtMostOnce()); await client.DisposeAsync(); await Assert.ThrowsAsync <ChannelClosedException>(() => eventLoop); }
protected void SendResponse(BaseConnection c, ArraySegment <byte> data, int agentIndex) { int offset = data.Offset, left = data.Count; while (left > 0) { var r = EventArgsManager.Get(); r.CopyAddressesFrom(c); r.OffsetOffset = r.MinimumRequredOffsetOffset; r.AllocateBuffer(); r.SetMaxCount(); if (r.Count > left) { r.Count = left; } r.BlockCopyFrom(new ArraySegment <byte>(data.Array, offset, r.Count)); offset += r.Count; left -= r.Count; SendAsync(r, agentIndex); } }
public void Handle(BaseConnection connection, BinaryReader packet) { APIConnection api = connection as APIConnection; if (api != null && api.PrivateAPIUsable) { Dictionary <string, string> texts = new Dictionary <string, string>(); byte textsCount = packet.ReadByte(); for (byte i = 0; i < textsCount; i++) { texts.Add(packet.ReadString(), packet.ReadString()); } List <GamePowerup> gamePowerups = new List <GamePowerup>(); byte gamePowerupsCount = packet.ReadByte(); for (byte i = 0; i < gamePowerupsCount; i++) { string packageName = packet.ReadString(); GamePowerupType type = (GamePowerupType)packet.ReadByte(); int amount = packet.ReadInt32(); int cost = packet.ReadInt32(); gamePowerups.Add(new GamePowerup(packageName, type, amount, cost)); } api.Hotel.Settings = new HotelSettings(texts, gamePowerups); } }
public void Handle(BaseConnection connection, BinaryReader packet) { connection.SendPacket(new GameLoadDetailsOutgoingPacket(Server.Config["game.swf.url"], Server.Config["game.swf.quality"], Server.Config["game.swf.scale"], int.Parse(Server.Config["game.swf.fps"]), int.Parse(Server.Config["game.swf.flash.major"]), int.Parse(Server.Config["game.swf.flash.minor"]), new Dictionary <string, string>() { { "assetUrl", Server.Config["game.swf.asset.url"] }, { "gameServerHost", Server.Config["game.tcp.ip"] }, { "gameServerPort", Server.Config["game.tcp.port"] }, { "socketPolicyPort", Server.Config["game.policy.port"] } })); }
public void ExecCommand_SelectQuery_NoUpdate() { BaseConnection.openConnection(); var result = BaseConnection.execCommand("SELECT * FROM Products;"); BaseConnection.closeConnection(); Assert.IsTrue(result == -1, "Number should be minus one"); }
void OnConnected(BaseConnection connection) { var from = NodeViews[connection.FromNodeGUID]; var to = NodeViews[connection.ToNodeGUID]; ConnectView(from, to, connection); SetDirty(); }
public void SetConnectionsIsShadowed(BaseConnection context, bool value) { var otherNodeConnections = this.Connections.Cast <BaseConnection>() .Where(x => x != context) .ToList(); otherNodeConnections.ForEach(x => x.IsShadowed = value); }
public void Handle(BaseConnection connection, BinaryReader packet) { //GameConnection game = connection as GameConnection; //if (game?.LoggedIn ?? false) //{ // game.User.Hotel.APIConnection?.SendPacket(new UserLeftGameOutgoingPacket(game.User.UserID)); //} }
public void ExecScalar_CorrectQuery_One() { BaseConnection.openConnection(); var result = (int)BaseConnection.execScalar("SELECT Id FROM Contractors WHERE Id = 1;"); BaseConnection.closeConnection(); Assert.IsTrue(result == 1, "Result should be number one"); }
/// <summary> /// Opens a database connection with the settings specified by the ConnectionString property of the provider-specific Connection object. /// </summary> public void Open() { try { BaseConnection.Open(); } catch { throw; } }
public NodeRecord(T node, BaseConnection <T> connection, float costSoFar, float estTotalCost, NodeCategory category) { this.node = node; this.connection = connection; this.costSoFar = costSoFar; this.estimatedTotalCost = estTotalCost; this.category = category; }
/// <summary> /// 上传文件 /// 将返回路径存储到d0字段中 /// </summary> /// <param name="value"></param> public void SetA1(object value) { ControlDetailForPage obj = (this.Tag as ControlDetailForPage); //上传文件 var values = new[] { new KeyValuePair <string, string>("api_type", "upload"), new KeyValuePair <string, string>("sql", /*obj.d5*/ string.Empty), //other values }; OpenFileDialog opf = new OpenFileDialog(); string filter = this.GetFilterType(); if (!string.IsNullOrEmpty(filter)) { opf.Filter = filter; } if (opf.ShowDialog() == DialogResult.OK) { if (IsValidImage(opf.FileName)) { long length = new System.IO.FileInfo(opf.FileName).Length; float lef = length / (1024 * 1024); if (lef > 2.0) { MessageBox.Show("图片大小超过2m!"); return; } } try { bool resultbol = false; //if (CommonFunction.IsFinishLoading) //{ // resultbol = true; // CommonFunction.IsFinishLoading = false; // CommonFunction.ShowWaitingForm(); //} BaseConnection bcc = new BaseConnection(); var result = bcc.PostFile(opf.FileName, values); BaseReturn brj = JsonController.DeSerializeToClass <BaseReturn>(result.Result); FileUploadReturn returnResult = JsonController.DeSerializeToClass <FileUploadReturn>(brj.data.ToString()); obj.d0 = returnResult.data.path; this.Tag = obj; this.SetP9(obj.p9); //if (resultbol) //{ // CommonFunction.IsFinishLoading = true; //} } catch { //调用失败后走这里 this.SetP12(obj.p12); } } }
public void Handle(BaseConnection connection, BinaryReader packet) { GameConnection game = connection as GameConnection; if (game != null && game.LoggedIn) { connection.SendPacket(new GamePowerupsOutgoingPacket(game.User.Hotel.Settings.GamePowerups)); } }
protected CommConnection getSQLConnection() { BaseConnection BConn = new BaseConnection(); String DataConnectionCode = System.Configuration.ConfigurationManager.AppSettings["DB00"]; String[] DataConnectionInfo = DataConnectionCode.Split(','); BConn.Server = DataConnectionInfo[0]; BConn.Account = DataConnectionInfo[1]; BConn.Password = DataConnectionInfo[2]; return BConn.GetConnection(); }
public static BaseConnection GetConection() { if (_BaseConnection != null) return _BaseConnection; _BaseConnection = new BaseConnection(); _BaseConnection.BaseOnLine+=new IBaseConnectionEvents_BaseOnLineEventHandler(_BaseConnection_BaseOnLine); IsTryingConnect = true; IsConected = false; _BaseConnection.Open(1, "1-8"); return _BaseConnection; }
private void InitSunVoteDll() { try { this.baseConn = new BaseConnection(); this.signIn = new SignIn(); this.number = new Number(); this.choices = new Choices(); signIn.BaseConnection = baseConn; number.BaseConnection = baseConn; choices.BaseConnection = baseConn; this.baseConn.BaseOnLine += new IBaseConnectionEvents_BaseOnLineEventHandler(this.baseConn_BaseOnLine); this.signIn.KeyStatus += new ISignInEvents_KeyStatusEventHandler(this.signIn_KeyStatus); this.number.KeyStatus += new INumberEvents_KeyStatusEventHandler(this.number_KeyStatus); this.choices.KeyStatus += new IChoicesEvents_KeyStatusEventHandler(this.choices_KeyStatus); } catch (System.Runtime.InteropServices.COMException ex) { MessageBox.Show(ex.Message); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
private void TryBaseConnect(BaseConnection baseConn, int baseId) { baseConn.Open(1, baseId.ToString()); //baseConn.Open(1, "1-8"); }