public bool FindUserEmailID(int userEmailID) { string sql = string.Format("SELECT * FROM UserEmails WHERE UserEmailID = '{0}' ", userEmailID); using(Connection cn = new Connection()) { using (SqlCommand cmd = new SqlCommand()) { try { cmd.Connection = cn.SqlConnection; cmd.CommandText = sql; int recordsAffected = cmd.ExecuteNonQuery(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { //UserID = (int)reader["UserID"]; //loginName = reader["LoginName"].ToString(); } return true; } else return false; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return false; } } } //return true; }
//delete public int Delete(Entities.KhoHang kh1) { int tra = 0; try { kh = new Constants.KhoHang(); Entities.KhoHang khohang = new Entities.KhoHang(); Sql = new Constants.Sql(); string sql = Sql.DeleteKhoHang; Connection conn = new Connection(); SqlConnection cn = conn.openConnection(); SqlCommand cmd = new SqlCommand(sql, cn); cmd.Parameters.Add(kh.HanhDong, SqlDbType.NVarChar, 20).Value = kh1.HanhDong; cmd.Parameters.Add(kh.KhoHangID, SqlDbType.Int).Value = kh1.KhoHangID; tra = cmd.ExecuteNonQuery(); cmd.Connection.Dispose(); cn.Close(); conn.closeConnection(); cn = null; conn = null; } catch (Exception ex) { string s = ex.Message; tra = 0; } return tra; }
public override string SendQuery(string query) { var data = encode.GetBytes(query); if (Connections.Count > 300) { throw new Exception("TcpClientPool连接已超过500"); } Connection connection; lock (lockObj) { connection = Connections.Find(b => b.Used == false); if (connection == null) { connectionIndex += 1; connection = new Connection() { Socket = new CoreHelper.SocketUtil.TcpClient(server, port, 3, true), Index = connectionIndex }; Connections.Add(connection); } connection.Used = true; } var result = connection.Socket.SendAndReceive(data); lock (lockObj) { connection.Used = false; connection.LastUseTime = DateTime.Now; } if (result == null) { //connection.Socket.Dispose(); //Connections.Remove(connection); throw new Exception("连接到缓存服务器时发生错误:" + connection.Socket.LastException.Message); } var response = encode.GetString(result); return response; }
//insert update public Entities.KhoHang InsertUpdate(Entities.KhoHang kh1) { Entities.KhoHang k = new Entities.KhoHang(); try { kh = new Constants.KhoHang(); Sql = new Constants.Sql(); string sql = Sql.InsertUpdateKhoHang; Connection conn = new Connection(); SqlConnection cn = conn.openConnection(); SqlCommand cmd = new SqlCommand(sql, cn); cmd.Parameters.Add(kh.HanhDong, SqlDbType.NVarChar, 20).Value = kh1.HanhDong; cmd.Parameters.Add(kh.KhoHangID, SqlDbType.Int).Value = kh1.KhoHangID; cmd.Parameters.Add(kh.MaKho, SqlDbType.VarChar, 20).Value = kh1.MaKho; cmd.Parameters.Add(kh.TenKho, SqlDbType.NVarChar, 200).Value = kh1.TenKho; cmd.Parameters.Add(kh.DiaChi, SqlDbType.NVarChar, 200).Value = kh1.DiaChi; cmd.Parameters.Add(kh.DienThoai, SqlDbType.NVarChar, 200).Value = kh1.DienThoai; cmd.Parameters.Add(kh.MaNhanVien, SqlDbType.NVarChar, 200).Value = kh1.MaNhanVien; cmd.Parameters.Add(kh.GhiChu, SqlDbType.NVarChar, 100).Value = kh1.GhiChu; cmd.Parameters.Add(kh.Deleted, SqlDbType.Bit).Value = kh1.Deleted; dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); while (dr.Read()) { k.GhiChu = dr[0].ToString(); } } catch (Exception ex) { string s = ex.Message.ToString(); k.GhiChu = null; } return k; }
public Recordset GetDataByID(Connection cn, int id) { string sql = "ad_GetCategoryByID " + id; Recordset rs = conn.Execute(sql, cn); return rs; }
public Recordset GetDataByUsername(Connection cn, string username) { string sql = "GetUserByUsername " + username; Recordset rs = conn.Execute(sql, cn); return rs; }
internal DCC(ServerConnection creatorsServerConnection, Connection Parent) : base(creatorsServerConnection) { chat = new DCCChatContainer(creatorsServerConnection); transfer = new DCCTransferContainer(creatorsServerConnection); parent = Parent; }
public void SelectNode(Node node) { GameObject connection = Instantiate(Resources.Load("Connection")) as GameObject; Connection connection_component = connection.GetComponent<Connection>(); connection_component.InitializeWithStartNode(node); m_connection = connection_component; }
public BinaryDecoder(Connection conn) { Connection = conn; // some messages have multiple blank lines between the header & message body while(conn.PeekLine() == string.Empty) conn.ReadLine(); }
public override Connection CreateClientConnection(Connection connection) { if (this.HasCertificate) this.LoadCertificate(); return new HttpSslConnection(this, connection); }
public override void SetUp() { this.connection = (Connection) CreateConnection(); this.connection.RedeliveryPolicy = GetRedeliveryPolicy(); this.counter = 0; }
/// <summary> /// Initializes a new instance of the <see cref="CollectionMetadata"/> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="databaseName">Name of the database.</param> /// <param name="collectionName">The name.</param> /// <param name="connection">The connection.</param> internal CollectionMetadata(MongoConfiguration configuration, string databaseName, string collectionName, Connection connection) { //Todo: Add public constrcutors for users to call _fullName = databaseName + "." + collectionName; _name = collectionName; _database = new MongoDatabase(configuration, connection, databaseName); }
public override void Handle(Connection connection) { var account = connection.Session.Account; var notification = new Notification(); notification.UserId = account.Id; notification.Regex = new Regex(RegexPattern); notification.DeviceToken = DeviceToken; if (Program.NotificationManager.Exists(DeviceToken)) { notification.Save(); } else { if (Program.NotificationManager.FindWithId(account.Id).Count() < 5) { notification.Insert(); } else { connection.SendSysMessage("You may only have 5 devices registered for push notifications."); return; } } Program.NotificationsDirty = true; var notificationSubscription = new NotificationSubscription(); notificationSubscription.DeviceToken = DeviceToken; notificationSubscription.RegexPattern = RegexPattern; notificationSubscription.Registered = true; connection.Send(notificationSubscription); }
public static void Add( Connection connection, NetworkMessage outMessage, Location fromLocation, Location toLocation ) { if (fromLocation.Y > toLocation.Y) { // north, for old x outMessage.AddByte((byte)ServerPacketType.MapSliceNorth); AddMapDescription(connection, outMessage, fromLocation.X - 8, toLocation.Y - 6, toLocation.Z, 18, 1); } else if (fromLocation.Y < toLocation.Y) { // south, for old x outMessage.AddByte((byte)ServerPacketType.MapSliceSouth); AddMapDescription(connection, outMessage, fromLocation.X - 8, toLocation.Y + 7, toLocation.Z, 18, 1); } if (fromLocation.X < toLocation.X) { // east, [with new y] outMessage.AddByte((byte)ServerPacketType.MapSliceEast); AddMapDescription(connection, outMessage, toLocation.X + 9, toLocation.Y - 6, toLocation.Z, 1, 14); } else if (fromLocation.X > toLocation.X) { // west, [with new y] outMessage.AddByte((byte)ServerPacketType.MapSliceWest); AddMapDescription(connection, outMessage, toLocation.X - 8, toLocation.Y - 6, toLocation.Z, 1, 14); } }
public NodePingInfo(IConnection con, string nodeName = null) { Connection = new Connection(con); NextPingDate = DateTime.Now; IsPinged = false; NodeName = nodeName; }
protected void grdUsuarios_ItemUpdated(object source, GridUpdatedEventArgs e) { try { GridEditableItem item = e.Item as GridEditableItem; string userId = item.GetDataKeyValue("USER_ID").ToString(); Connection conexion = new Connection(); conexion.Actualizar(String.Format("UPDATE USUARIOS SET P_EXPIRATION = '{0}' WHERE USER_ID = '{1}'", DateTime.Now.AddMonths(1).ToString("yyyMMdd"), userId)); if (e.Exception != null) { e.KeepInEditMode = true; e.ExceptionHandled = true; RadAjaxManager1.ResponseScripts.Add(String.Format("errorEdicion('{0}');", e.Exception.Message.ToString())); } else { RadAjaxManager1.ResponseScripts.Add(String.Format("alert('Usuario actualizado.');")); } } catch (Exception error) { RadAjaxManager1.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message)); } }
protected void Page_Load(object sender, EventArgs e) { try { Menu menu = Master.FindControl("NavigationMenu") as Menu; menu.Items[2].ChildItems[0].ChildItems.RemoveAt(1); if (Session.Contents["rol"].ToString().Equals("DSTADM")) Response.Redirect("../Default.aspx"); Connection conexion = new Connection(); string query = String.Empty; SqlDataSource1.ConnectionString = conexion.getConnectionString(); if (Session.Contents["rol"].ToString().Equals("KCPADM")) query = String.Format("SELECT USER_ID, USER_NAME, STATUS, E_MAIL FROM USUARIOS AS U WHERE USER_ID <> '{0}' AND ID_COUNTRY = '{1}' AND 0 = (SELECT count(Kam.KAM_NAME) from Kam where Kam.KAM_ID = U.USER_ID AND Kam.KAM_ACTIVE = 1)", Session.Contents["userid"].ToString(), conexion.getUserCountry(Session.Contents["userid"].ToString())); else if (Session.Contents["rol"].ToString().Equals("KCPCCR")) query = String.Format("SELECT USER_ID, USER_NAME, STATUS, E_MAIL FROM USUARIOS WHERE USER_ID <> '{0}' AND ID_COUNTRY = '{1}' AND (ID_ROL <> 'KCPADM' AND ID_ROL <> 'KCPCCR')", Session.Contents["userid"].ToString(), conexion.getUserCountry(Session.Contents["userid"].ToString())); SqlDataSource1.SelectCommand = query; SqlDataSource1.ConflictDetection = ConflictOptions.CompareAllValues; } catch (Exception error) { RadAjaxManager1.ResponseScripts.Add(String.Format("errorEnvio('{0}');", error.Message)); } }
public int InsertUpdate(Entities.TKNganHang tk1) { TKNH = new Constants.TKNganHang(); Sql = new Constants.Sql(); string sql = Sql.InsertUpdateTKNganHang; Connection conn = new Connection(); SqlConnection cn = conn.openConnection(); SqlCommand cmd = new SqlCommand(sql, cn); cmd.Parameters.Add(TKNH.HanhDong, SqlDbType.NVarChar, 20).Value = tk1.HanhDong; cmd.Parameters.Add(TKNH.TKNganHangID, SqlDbType.Int).Value = tk1.TKNganHangID; cmd.Parameters.Add(TKNH.MaTKNganHang, SqlDbType.NVarChar, 20).Value = tk1.MaTKNganHang; cmd.Parameters.Add(TKNH.SoTK, SqlDbType.NVarChar, 20).Value = tk1.SoTK; cmd.Parameters.Add(TKNH.MaTienTe, SqlDbType.NVarChar, 200).Value = tk1.MaTienTe; cmd.Parameters.Add(TKNH.SoDu, SqlDbType.Int).Value = tk1.SoDu; cmd.Parameters.Add(TKNH.SoSecKeTiep, SqlDbType.NVarChar, 20).Value = tk1.SoSecKeTiep; cmd.Parameters.Add(TKNH.NguoiLienHe, SqlDbType.NVarChar, 200).Value = tk1.NguoiLienHe; cmd.Parameters.Add(TKNH.DiaChi, SqlDbType.NVarChar, 200).Value = tk1.DiaChi; cmd.Parameters.Add(TKNH.DienThoai, SqlDbType.NVarChar, 20).Value = tk1.DienThoai; cmd.Parameters.Add(TKNH.Email, SqlDbType.NVarChar, 20).Value = tk1.Email; cmd.Parameters.Add(TKNH.Website, SqlDbType.NVarChar, 20).Value = tk1.Website; cmd.Parameters.Add(TKNH.GhiChu, SqlDbType.NVarChar, 200).Value = tk1.Ghichu; cmd.Parameters.Add(TKNH.Laisuat, SqlDbType.Float).Value = tk1.Laisuat; cmd.Parameters.Add(TKNH.Deleted, SqlDbType.Bit).Value = tk1.Deleted; int i = cmd.ExecuteNonQuery(); cmd.Connection.Dispose(); cn.Close(); conn.closeConnection(); cn = null; conn = null; return i; }
public Instance(AppSettings settings, string instanceName, ConnectionType type) { //is this necessary to store? _connectionType = type; _settings = settings; if (!_settings.WorkingPath.Exists) { _settings.WorkingPath.Create(); } if (!_settings.TransferPath.Exists) { _settings.TransferPath.Create(); } Connection = new Connection(type, settings, instanceName); Connection.Service.Instance = this; Connection.LostConnection += new EventHandler<ExceptionEventArgs>(Connection_LostConnection); Connection.MessageReceived += new EventHandler<MessageEventArgs>(Connection_MessageReceived); Connection.MessageSending += new EventHandler<MessageEventArgs>(Connection_MessageSending); Connection.ConnectionMade += new EventHandler(Connection_ConnectionMade); Connection.ConnectionTermainated += new EventHandler(Connection_ConnectionTermainated); }
public void TestConnectionSerialization() { var obj = new Connection { Id = Guid.NewGuid(), Type = ExpressionNodeType.Connection, Sink = new ConnectorIn(null) {Id = Guid.NewGuid()}, Source = new ConnectorOut(null) {Id = Guid.NewGuid()} }; var tw = new StringWriter(); using (var xw = XmlWriter.Create(tw)) { xw.WriteStartElement("Node"); obj.Serialize(xw); xw.WriteEndElement(); } var sr = new StringReader(tw.ToString()); using (var wr = XmlReader.Create(sr)) { wr.ReadToFollowing("Node"); var result = new Connection(); result.Deserialize(wr); Assert.AreEqual(obj.Id, result.Id); Assert.AreEqual(obj.Type, result.Type); Assert.AreEqual(obj.Sink.Id, result.Sink.Id); Assert.AreEqual(obj.Source.Id, result.Source.Id); } }
public void Delete(Entities.TKNganHang tk1) { try { TKNH = new Constants.TKNganHang(); Entities.TKNganHang TKNganHang = new Entities.TKNganHang(); Sql = new Constants.Sql(); string sql = Sql.DeleteTKNganHang; Connection conn = new Connection(); SqlConnection cn = conn.openConnection(); SqlCommand cmd = new SqlCommand(sql, cn); cmd.Parameters.Add(TKNH.HanhDong, SqlDbType.NVarChar, 20).Value = tk1.HanhDong; cmd.Parameters.Add(TKNH.TKNganHangID, SqlDbType.Int).Value = tk1.TKNganHangID; cmd.ExecuteNonQuery(); cmd.Connection.Dispose(); cn.Close(); conn.closeConnection(); cn = null; conn = null; } catch (Exception ex) { string s = ex.Message; } }
public override async Task<bool> Connect(Connection newConnection) { var deviceInfo = newConnection.Source as DeviceInformation; if (deviceInfo != null) { this.service = await SerialDevice.FromIdAsync(deviceInfo.Id); if (this.service == null) { return false; } this.service.BaudRate = 115200; this.service.StopBits = SerialStopBitCount.One; this.service.Handshake = SerialHandshake.None; this.service.DataBits = 8; this.service.ReadTimeout = TimeSpan.FromSeconds(5); this.service.WriteTimeout = TimeSpan.FromSeconds(5); this.service.IsDataTerminalReadyEnabled = false; return this.InstrumentSocket(this.service.InputStream, this.service.OutputStream); } return false; }
/// <summary> /// lay bang cong ty /// </summary> /// <param name="ct"></param> /// <returns></returns> public Entities.ThongTinCongTy sp_ThongTinCongTy(Entities.TruyenGiaTri ct) { Entities.ThongTinCongTy banghi = new Entities.ThongTinCongTy(); try { string sql = "exec sp_ThongTinCongTy @MaCongTy"; conn = new Connection(); cn = conn.openConnection(); cmd = new SqlCommand(sql, cn); cmd.Parameters.Add("MaCongTy", SqlDbType.VarChar, 20).Value = ct.Giatritruyen; dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); ArrayList arr = new ArrayList(); while (dr.Read()) { banghi.MaCongTy = dr[0].ToString(); banghi.TenCongTy = dr[1].ToString(); banghi.DiaChi = dr[2].ToString(); banghi.SoDienThoai = dr[3].ToString(); banghi.Email = dr[4].ToString(); banghi.Website = dr[5].ToString(); banghi.Fax = dr[6].ToString(); } } catch (Exception ex) { string s = ex.Message.ToString(); banghi = null; } finally { cmd.Connection.Dispose(); cn.Close(); conn.closeConnection(); } return banghi; }
public void SendingCommandObjectSetsCommandOnBus() { var messageBus = new Mock<IMessageBus>(); var counters = new Mock<IPerformanceCounterWriter>(); Message message = null; messageBus.Setup(m => m.Publish(It.IsAny<Message>())).Returns<Message>(m => { message = m; return TaskAsyncHelper.Empty; }); var serializer = new JsonNetSerializer(); var traceManager = new Mock<ITraceManager>(); var connection = new Connection(messageBus.Object, serializer, "signal", "connectonid", new[] { "a", "signal", "connectionid" }, new string[] { }, traceManager.Object, counters.Object); connection.Send("a", new Command { Type = CommandType.AddToGroup, Value = "foo" }); Assert.NotNull(message); Assert.True(message.IsCommand); var command = serializer.Parse<Command>(message.Value); Assert.Equal(CommandType.AddToGroup, command.Type); Assert.Equal("foo", command.Value); }
public static Dictionary<string, Category> GetTarget_CategoriesToTransfer(Connection connection) { var transferCategories = connection.ThisSideCategories .Where( tCat => tCat.NativeCategoryDomainName == "AaltoGlobalImpact.OIP" && tCat.NativeCategoryObjectName == "Category") .ToArray(); CategoryCollection categoryCollection = CategoryCollection.RetrieveFromOwnerContent( InformationContext.CurrentOwner, "MasterCollection"); var sourceCategoryDict = categoryCollection.CollectionContent.ToDictionary(cat => cat.ID); var sourceCategoryList = categoryCollection.CollectionContent; var childrenInclusiveSourceIDs = connection.CategoryLinks.Where(catLink => catLink.LinkingType == TheBall.Interface.Category.LINKINGTYPE_INCLUDECHILDREN).Select(catLink => catLink.SourceCategoryID).ToArray(); var childrenInclusiveIDs = transferCategories .Where(tCat => childrenInclusiveSourceIDs.Contains(tCat.ID)) .Select(tCat => tCat.NativeCategoryID).OrderBy(str => str) .ToList(); var exactMatchSourceIDs = connection.CategoryLinks.Where(catLink => catLink.LinkingType == TheBall.Interface.Category.LINKINGTYPE_ONE).Select(catLink => catLink.SourceCategoryID).ToArray(); var exactMatchIDs = transferCategories .Where(tCat => exactMatchSourceIDs.Contains(tCat.ID)) .Select(tCat => tCat.NativeCategoryID).OrderBy(str => str) .ToList(); var result = sourceCategoryList .Where(cat => matchesOrParentMatches(cat, exactMatchIDs, childrenInclusiveIDs, sourceCategoryDict)) .ToArray(); return result.ToDictionary(cat => cat.ID); }
public Mensalista getMensalistabyId_cliente(int id_cliente) { Mensalista returnMensalista = null; Connection con = new Connection(); con.openConnection(); SqlCommand command = new SqlCommand(); SqlDataReader reader; string sql = "select * from Mensalistas m inner join Clientes c on m.Id_cliente = c.Id_Cliente where m.Id_cliente = " + id_cliente + " "; command.CommandText = sql; command.CommandType = CommandType.Text; command.Connection = con.getConnection(); reader = command.ExecuteReader(); if (reader.Read()) { while (reader.Read()) { returnMensalista.id_mensalista = Int32.Parse(string.Format("{0}", reader[0])); returnMensalista.id_cliente = Int32.Parse(string.Format("{0}", reader[1])); returnMensalista.nome_cliente = string.Format("{0}", reader[4]); returnMensalista.data_termino = string.Format("{0}", reader[2]); } } return returnMensalista; }
public JDBCCategoryDataset(string url, string driverName, string user, string passwd) { JDBCCategoryDataset jdbcCategoryDataset = this; this.transpose = true; Class.forName(driverName, JDBCCategoryDataset.__\u003CGetCallerID\u003E()); this.connection = DriverManager.getConnection(url, user, passwd, JDBCCategoryDataset.__\u003CGetCallerID\u003E()); }
public SeekerData(SeekerData original, Connection connection, float gScore, float hScore) { m_Path = new List<Connection> (original.Path); m_Path.Add (connection); m_GScore = original.GScore + gScore; m_HScore = original.HScore + hScore; }
public List<Mensalista> buscar(String nomeCliente) { Connection con = new Connection(); con.openConnection(); SqlCommand command = new SqlCommand(); SqlDataReader reader; string sql = "SELECT * FROM Mensalistas m INNER JOIN Clientes c ON m.Id_cliente = c.Id_Cliente WHERE c.Nome like '%"+ nomeCliente +"%'"; command.CommandText = sql; command.CommandType = CommandType.Text; command.Connection = con.getConnection(); reader = command.ExecuteReader(); List<Mensalista> listaMensalistas = new List<Mensalista>(); while (reader.Read()) { Mensalista mensalista = new Mensalista(); mensalista.id_mensalista = Int32.Parse(string.Format("{0}", reader[0])); mensalista.id_cliente = Int32.Parse(string.Format("{0}", reader[1])); Cliente cliente = new Cliente(); cliente.nome = string.Format("{0}", reader[4]); mensalista.nome_cliente = cliente.nome; mensalista.data_termino = string.Format("{0}", reader[2]); listaMensalistas.Add(mensalista); } con.closeConnection(); return listaMensalistas; }
public void CheckIn(Connection value) { lock (_ConnectionQueue) { _ConnectionQueue.Enqueue(value); } }
public void LoadStaticDnsWillNotFail() { var dnsConfiguration = Connection.LoadSingle <DnsStatic>(); Assert.IsNotNull(dnsConfiguration); }
/// <summary> /// Runs any postprocessing that is needed after server loads new areas. /// </summary> /// <param name="loadRequest">Load request instance</param> /// <param name="areas">New areas</param> /// <param name="segments">New segments</param> protected override void OnAreasLoaded(LoadRequest loadRequest, List<ServerArea> areas, List<ServerSegment> segments) { if (loadRequest.MessageId < 0 || loadRequest.Entity == null) { return; } // the newly loaded areas/segments aren't usable as they could have been // covered by other players' terrain areas.Clear(); segments.Clear(); // construct player's area keys List<int> areaKeys = new List<int>(); foreach (Tuple<int, int> column in GetEntityColumns(loadRequest.ColumnX, loadRequest.ColumnZ)) { for (int y = 0; y < 256; y += 64) { areaKeys.Add(Area.GenerateKey(column.Item1, y, column.Item2)); } } // retrieve player connection Connection connection = ServerManager.Instance.GetPlayerConnection(loadRequest.Entity.ID); if (connection == null) { // no longer online return; } // process terrain response in a synced and handled task HandledTask task = new HandledTask(() => { // compare the new keys with current ones List<int> currentKeys = new List<int>(); lock (_ClientLock) { currentKeys = _ClientAreas[loadRequest.Entity.ID]; } lock (CollectionsLock) { foreach (int key in areaKeys.Where(a => !currentKeys.Contains(a))) { areas.Add(Areas[key]); } } lock (_ClientLock) { _ClientAreas[loadRequest.Entity.ID] = areaKeys; } if (areas.Count == 0) { // there is actually nothing to send ServerManager.Instance.ServerToClientProvider.TerrainDataResponse(connection, loadRequest.MessageId, new List<ServerArea>(), (byte)0, (byte)0); } else { // send the terrain data to the requesting client int batchSize = Configuration.Network.MaxTerrainBatchSize; byte current = 1; byte total = (byte)Math.Ceiling((float)areas.Count / (float)batchSize); for (int i = 0; i < areas.Count; i += batchSize) { List<ServerArea> partial = areas.Skip(i).Take(batchSize).ToList(); ServerManager.Instance.ServerToClientProvider.TerrainDataResponse(connection, loadRequest.MessageId, partial, current, total); current++; } } }); task.Start(); }
private void CheckHoveringAndSelection() { if (_isLayoutEvent) { return; } ResetHover(); bool isDraggingGrid = _currentActivity == Activity.DraggingGrid; Rect selectionRect = _selectionRect; Vector2 mousePosition = _mousePosition; List <Object> boxSelected = new List <Object>(); //TODO Investigate reverse recognition not working!? //Never mind it works, it's just my architecture works bottom-top, //instead of top-bottom-or-stop //Why? Cause hovering //TODO Investigate alternatives for conversion for (int i = 0; i < Graph.NodeCount; i++) { Node node = Graph.GetNode(i); NodeEditor nodeEditor = NodeEditor.GetEditor(node); Vector2 size; if (_nodeSizes.TryGetValue(node, out size)) { Rect nodeRect = new Rect(node.Position, size); nodeRect = GridToWindowRect(nodeRect); if (nodeRect.Contains(mousePosition)) { _hoveredNode = node; } if (isDraggingGrid && nodeRect.Overlaps(selectionRect)) { boxSelected.Add(node); } } //Check hovering over ports var inputNode = node as IInput; if (inputNode != null) { InputPort input = inputNode.InputPort; Rect inputRect = nodeEditor.GetPortRect(input); //inputRect.position += node.Position; inputRect = GridToWindowRect(inputRect); if (inputRect.Contains(mousePosition)) { HoveredPort = input; } } IOutput sOutputNode = node as IOutput; if (sOutputNode != null) { OutputPort output = sOutputNode.OutputPort; Rect outputRect = nodeEditor.GetPortRect(output); //outputRect.position += node.Position; outputRect = GridToWindowRect(outputRect); if (outputRect.Contains(mousePosition)) { HoveredPort = output; } } IMultipleOutput mOutputNode = node as IMultipleOutput; if (mOutputNode != null) { var outputs = mOutputNode.GetOutputs(); foreach (OutputPort output in outputs) { Rect outputRect = nodeEditor.GetPortRect(output); //outputRect.position += node.Position; outputRect = GridToWindowRect(outputRect); if (outputRect.Contains(mousePosition)) { HoveredPort = output; } } } } for (int i = 0; i < Graph.ConnectionCount; i++) { Connection connection = Graph.GetConnection(i); if (connection == null) { Debug.Log("Null connection at index " + i); OnNull(Graph); continue; } Vector2 start = NodeEditor.FindPortRect(connection.Start).center; Vector2 end = NodeEditor.FindPortRect(connection.End).center; start = GridToWindowPosition(start); end = GridToWindowPosition(end); //if (OtherUtilities.PointOverlapBezier(mousePosition, start, end, NodePreferences.CONNECTION_WIDTH)) if (LineSegment.WideLineSegmentPointCheck(mousePosition, start, end, NodePreferences.CONNECTION_WIDTH * 2 / Zoom)) { _hoveredConnection = connection; } //DONE: Add range percentage overlap check, as just overlapping might be too annoying. if (isDraggingGrid && LineSegment.LineRectOverlapPercentageCheck(selectionRect, start, end) > 0.3f) { boxSelected.Add(connection); } Rect[] modifierRects; if (!_connectionModifierRects.TryGetValue(connection, out modifierRects)) { continue; } for (int j = 0; j < connection.InstructionCount; j++) { Instruction mod = connection.GetInstruction(j); Rect rect = GridToWindowRect(modifierRects[j]); if (rect.Contains(mousePosition)) { _hoveredInstruction = mod; } if (isDraggingGrid && rect.Overlaps(selectionRect)) { boxSelected.Add(mod); } } } //return; if (isDraggingGrid) { if (_cachedEvent.control || _cachedEvent.shift) { boxSelected.AddRange(_cachedSelectedObjects); } Selection.objects = boxSelected.ToArray(); } else { _selectionRect = Rect.zero; } }
public virtual void Dispose() { Connection?.Close(); }
public void Dispose() { Connection.Dispose(); }
/// <summary> /// (re)initialize all controls and data<br /> /// this is needed if the configuration has changed /// </summary> private void init() { //if (m_parent.InvokeRequired) //{ // try // { // m_parent.Invoke(new UtilsHelper.Action(init)); // } // catch (ObjectDisposedException) // { // } // return; //} m_vpn = null; m_menu.DropDownItems.Clear(); m_status.Hide(); try { if (!m_isService) { m_vpn = new UserSpaceConnection(m_bin, m_file, new EventHandler <LogEventArgs>(addLog), m_dbglevel, m_smartCard); } else { m_vpn = new ServiceConnection(m_file, new EventHandler <LogEventArgs>(addLog), m_dbglevel, m_smartCard); } } catch (ApplicationException e) { m_error_message = e.Message; } Name = VPNConfig.GetDescriptiveName(m_file); if (m_isService) { Name += " (" + ProgramVPN.res.GetString("DIALOG_Service") + ")"; } m_menu.Text = Name; m_infobox.Init(); if (m_error_message != null) { m_menu_error = new ToolStripMenuItem(ProgramVPN.res.GetString("TRAY_Error_Information")); m_menu_error.Click += new EventHandler(m_menu_error_Click); m_menu.DropDownItems.Add(m_menu_error); return; } m_vpn.Logs.DebugLevel = m_dbglevel; m_vpn.State.StateChanged += new EventHandler <StateChangedEventArgs>(State_StateChanged); m_vpn.NeedCardId += new EventHandler <NeedCardIdEventArgs>(m_vpn_needCardID); m_vpn.NeedPassword += new EventHandler <NeedPasswordEventArgs>(m_vpn_needPassword); m_vpn.NeedLoginAndPassword += new EventHandler <NeedLoginAndPasswordEventArgs>(m_vpn_needLoginAndPassword); m_status.Init(); m_menu_connect = new ToolStripMenuItem(ProgramVPN.res.GetString("TRAY_Connect")); m_menu_connect.Image = Properties.Resources.BUTTON_Connect; m_menu_connect.Click += new EventHandler(m_menu_connect_Click); m_menu.DropDownItems.Add(m_menu_connect); m_menu_disconnect = new ToolStripMenuItem(ProgramVPN.res.GetString("TRAY_Disconnect")); m_menu_disconnect.Image = Properties.Resources.BUTTON_Disconnect; m_menu_disconnect.Click += new EventHandler(m_menu_disconnect_Click); m_menu_disconnect.Visible = false; m_menu.DropDownItems.Add(m_menu_disconnect); m_menu_show = new ToolStripMenuItem(ProgramVPN.res.GetString("TRAY_Show")); m_menu_show.Image = Properties.Resources.BUTTON_Details; m_menu_show.Click += new EventHandler(m_menu_show_Click); m_menu.DropDownItems.Add(m_menu_show); m_menu_edit = new ToolStripMenuItem(ProgramVPN.res.GetString("TRAY_Edit")); m_menu_edit.Enabled = !m_isService; m_menu_edit.Image = Properties.Resources.BUTTON_Edit; m_menu_edit.Click += new EventHandler(m_menu_edit_Click); m_menu.DropDownItems.Add(m_menu_edit); m_menu.Image = Properties.Resources.STATE_Stopped; }
public void Initialize() { connection = new Connection(); }
public void LoadIpDnsSettingsWillNotFail() { var list = Connection.LoadAll <IpDns>(); Assert.IsNotNull(list); }
/// <summary> /// Initializes a new instance of the <see cref="LogicSwapCharacterCommand"/> class. /// </summary> public LogicSwapCharacterCommand(Connection connection, ByteStream stream) : base(connection, stream) { // LogicSwapCharacterCommand. }
public void LoadIpDnsSettings2WillNotFail() { var dnsConfiguration = Connection.LoadSingle <IpDns>(); Assert.IsNotNull(dnsConfiguration); }
public static bool RuleActive(Connection row, Connection column) { return(GlobalReferences.RuleMatrix[row.MatrixId, column.MatrixId]); }
public void Dispose() { connection.Stop(); connection.Dispose(); connection = null; }
public override async ValueTask HandleMessageAsync(IMessageReader reader, MessageType messageType) { var flag = reader.Tag; _logger.LogTrace("[{0}] Server got {1}.", Id, flag); switch (flag) { case MessageFlags.HostGame: { // Read game settings. var gameInfo = Message00HostGameC2S.Deserialize(reader); // Create game. var game = await _gameManager.CreateAsync(gameInfo); // Code in the packet below will be used in JoinGame. using (var writer = MessageWriter.Get(MessageType.Reliable)) { Message00HostGameS2C.Serialize(writer, game.Code); await Connection.SendAsync(writer); } break; } case MessageFlags.JoinGame: { Message01JoinGameC2S.Deserialize( reader, out var gameCode, out _); var game = _gameManager.Find(gameCode); if (game == null) { await DisconnectAsync(DisconnectReason.GameMissing); return; } var result = await game.AddClientAsync(this); switch (result.Error) { case GameJoinError.None: break; case GameJoinError.InvalidClient: await DisconnectAsync(DisconnectReason.Custom, "Client is in an invalid state."); break; case GameJoinError.Banned: await DisconnectAsync(DisconnectReason.Banned); break; case GameJoinError.GameFull: await DisconnectAsync(DisconnectReason.GameFull); break; case GameJoinError.InvalidLimbo: await DisconnectAsync(DisconnectReason.Custom, "Invalid limbo state while joining."); break; case GameJoinError.GameStarted: await DisconnectAsync(DisconnectReason.GameStarted); break; case GameJoinError.GameDestroyed: await DisconnectAsync(DisconnectReason.Custom, DisconnectMessages.Destroyed); break; case GameJoinError.Custom: await DisconnectAsync(DisconnectReason.Custom, result.Message); break; default: await DisconnectAsync(DisconnectReason.Custom, "Unknown error."); break; } break; } case MessageFlags.StartGame: { if (!IsPacketAllowed(reader, true)) { return; } await Player.Game.HandleStartGame(reader); break; } // No idea how this flag is triggered. case MessageFlags.RemoveGame: break; case MessageFlags.RemovePlayer: { if (!IsPacketAllowed(reader, true)) { return; } Message04RemovePlayerC2S.Deserialize( reader, out var playerId, out var reason); await Player.Game.HandleRemovePlayer(playerId, (DisconnectReason)reason); break; } case MessageFlags.GameData: case MessageFlags.GameDataTo: { if (!IsPacketAllowed(reader, false)) { return; } var toPlayer = flag == MessageFlags.GameDataTo; // Handle packet. using var readerCopy = reader.Copy(); var verified = await Player.Game.HandleGameDataAsync(readerCopy, Player, toPlayer); if (verified) { // Broadcast packet to all other players. using (var writer = MessageWriter.Get(messageType)) { if (toPlayer) { var target = reader.ReadPackedInt32(); reader.CopyTo(writer); await Player.Game.SendToAsync(writer, target); } else { reader.CopyTo(writer); await Player.Game.SendToAllExceptAsync(writer, Id); } } } break; } case MessageFlags.EndGame: { if (!IsPacketAllowed(reader, true)) { return; } Message08EndGameC2S.Deserialize( reader, out var gameOverReason); await Player.Game.HandleEndGame(reader, gameOverReason); break; } case MessageFlags.AlterGame: { if (!IsPacketAllowed(reader, true)) { return; } Message10AlterGameC2S.Deserialize( reader, out var gameTag, out var value); if (gameTag != AlterGameTags.ChangePrivacy) { return; } await Player.Game.HandleAlterGame(reader, Player, value); break; } case MessageFlags.KickPlayer: { if (!IsPacketAllowed(reader, true)) { return; } Message11KickPlayerC2S.Deserialize( reader, out var playerId, out var isBan); await Player.Game.HandleKickPlayer(playerId, isBan); break; } case MessageFlags.GetGameListV2: { Message16GetGameListC2S.Deserialize(reader, out var options); await OnRequestGameListAsync(options); break; } default: _logger.LogWarning("Server received unknown flag {0}.", flag); break; } #if DEBUG if (flag != MessageFlags.GameData && flag != MessageFlags.GameDataTo && flag != MessageFlags.EndGame && reader.Position < reader.Length) { _logger.LogWarning( "Server did not consume all bytes from {0} ({1} < {2}).", flag, reader.Position, reader.Length); } #endif }
/// <summary> /// Initializes a new instance of the <see cref="LogicSwapCharacterCommand"/> class. /// </summary> public LogicSwapCharacterCommand(Connection connection) : base(connection) { this.Type = Command.SwapCharacter; }
/// Public constructor (overrides base constructor) public DORule(Connection connection) : base(connection) { this.tableName = "rules"; this.idField = "i_RuleId"; }
public void RemoveConnection(Connection connection) { this.context.Connections.Remove(connection); }
/// <summary> /// Close /// </summary> public void Close() { Connection.Close(); }
public static async Task InitializeAsync() { Accounts = Connection.GetCollection <Account>("Accounts"); }
public virtual void UpdateRange(params TEntity[] entities) => Connection.Update(entities, Transaction, CommandTimeout);
/// <summary> /// Begin a transaction. /// </summary> public void BeginTransaction() { SqlTransaction = Connection.BeginTransaction(IsolationLevel.Serializable); }
public IQueryable<TEntity> ReadRange() => Connection.GetAll<TEntity>(Transaction, CommandTimeout).AsQueryable();
public SubscriptionTypeModel(Connection connection) { this.connection = connection; }
public void Remove(TEntity entity) => Connection.Delete(entity, Transaction, CommandTimeout);
public virtual void Update(TEntity entity) => Connection.Update(entity, Transaction, CommandTimeout);
public virtual void Add(TEntity entity) => Connection.Insert(entity, Transaction, CommandTimeout);
public void RemoveRange(params TEntity[] entities) => Connection.Delete(entities, Transaction, CommandTimeout);
public void InsertBrokenFileIDsIntoTable(long filesetid, string tablename, string IDfieldname, System.Data.IDbTransaction transaction) { using (var cmd = Connection.CreateCommand(transaction)) cmd.ExecuteNonQuery(string.Format(INSERT_BROKEN_IDS, FOLDER_BLOCKSET_ID, SYMLINK_BLOCKSET_ID, RemoteVolumeType.Blocks.ToString(), tablename, IDfieldname), filesetid); }
public virtual void AddRange(params TEntity[] entities) => Connection.Insert(entities, Transaction, CommandTimeout);
public void Execute(string cmd, Action <int, DataNode, bool> callback) { var args = cmd.Split(','); DataNode answer; int id = 0; if (!int.TryParse(args[0], out id)) { answer = APIUtils.FromAPIResult(new Error() { message = "Invalid request id" }); callback(id, answer, false); return; } if (args.Length != 2) { answer = APIUtils.FromAPIResult(new Error() { message = "Malformed request" }); callback(id, answer, false); return; } cmd = args[1]; args = cmd.Split('/'); bool success = false; var requestType = args[0]; if (requestType != "authorize") { var status = this.Status; if (status != WalletStatus.Ready) { answer = APIUtils.FromAPIResult(new Error() { message = $"Wallet is {status}" }); callback(id, answer, false); return; } } if (_isPendingRequest) { answer = APIUtils.FromAPIResult(new Error() { message = $"A previous request is still pending" }); callback(id, answer, false); return; } _isPendingRequest = true; Connection connection = null; if (requestType != "authorize") { connection = ValidateRequest(args); if (connection == null) { answer = APIUtils.FromAPIResult(new Error() { message = "Invalid or missing API token" }); callback(id, answer, false); return; } // exclude dapp/token args args = args.Take(args.Length - 2).ToArray(); } args = args.Skip(1).ToArray(); switch (requestType) { case "authorize": { if (args.Length == 1 || args.Length == 2) { string token; var dapp = args[0]; int version; if (args.Length == 2) { var str = args[1]; if (!int.TryParse(str, out version)) { answer = APIUtils.FromAPIResult(new Error() { message = $"authorize: Invalid version: {str}" }); callback(id, answer, false); _isPendingRequest = false; return; } } else { version = 1; } if (_connections.ContainsKey(dapp)) { connection = _connections[dapp]; success = true; answer = APIUtils.FromAPIResult(new Authorization() { wallet = this.Name, nexus = this.Nexus, dapp = dapp, token = connection.Token, version = connection.Version }); } else { var bytes = new byte[32]; rnd.NextBytes(bytes); token = Base16.Encode(bytes); this.Authorize(dapp, token, version, (authorized, error) => { if (authorized) { _connections[dapp] = new Connection(token, version); success = true; answer = APIUtils.FromAPIResult(new Authorization() { wallet = this.Name, nexus = this.Nexus, dapp = dapp, token = token }); } else { answer = APIUtils.FromAPIResult(new Error() { message = error }); } callback(id, answer, success); _isPendingRequest = false; }); return; } } else { answer = APIUtils.FromAPIResult(new Error() { message = $"authorize: Invalid amount of arguments: {args.Length}" }); } break; } case "getAccount": { int expectedLength; switch (connection.Version) { case 1: expectedLength = 0; break; default: expectedLength = 1; break; } if (args.Length == expectedLength) { string platform; if (connection.Version >= 2) { platform = args[0].ToLower(); } else { platform = "phantasma"; } GetAccount(platform, (account, error) => { if (error == null) { success = true; answer = APIUtils.FromAPIResult(account); } else { answer = APIUtils.FromAPIResult(new Error() { message = error }); } callback(id, answer, success); _isPendingRequest = false; }); return; } else { answer = APIUtils.FromAPIResult(new Error() { message = $"getAccount: Invalid amount of arguments: {args.Length}" }); } break; } case "signData": { int expectedLength; switch (connection.Version) { case 1: expectedLength = 2; break; default: expectedLength = 3; break; } if (args.Length == expectedLength) { var data = Base16.Decode(args[0], false); if (data == null) { answer = APIUtils.FromAPIResult(new Error() { message = $"signTx: Invalid input received" }); } else { SignatureKind signatureKind; if (!Enum.TryParse <SignatureKind>(args[1], out signatureKind)) { answer = APIUtils.FromAPIResult(new Error() { message = $"signData: Invalid signature: " + args[1] }); callback(id, answer, false); _isPendingRequest = false; return; } var platform = connection.Version >= 2 ? args[2].ToLower() : "phantasma"; SignData(platform, signatureKind, data, id, (signature, random, txError) => { if (signature != null) { success = true; answer = APIUtils.FromAPIResult(new Signature() { signature = signature, random = random }); } else { answer = APIUtils.FromAPIResult(new Error() { message = txError }); } callback(id, answer, success); _isPendingRequest = false; }); } return; } else { answer = APIUtils.FromAPIResult(new Error() { message = $"signTx: Invalid amount of arguments: {args.Length}" }); } break; } case "signTx": { int expectedLength; switch (connection.Version) { case 1: expectedLength = 4; break; default: expectedLength = 5; break; } if (args.Length == expectedLength) { int index = 0; if (connection.Version == 1) { var txNexus = args[index]; index++; if (txNexus != this.Nexus) { answer = APIUtils.FromAPIResult(new Error() { message = $"signTx: Expected nexus {this.Nexus}, instead got {txNexus}" }); callback(id, answer, false); _isPendingRequest = false; return; } } var chain = args[index]; index++; var script = Base16.Decode(args[index], false); index++; if (script == null) { answer = APIUtils.FromAPIResult(new Error() { message = $"signTx: Invalid script data" }); } else { byte[] payload = args[index].Length > 0 ? Base16.Decode(args[index], false) : null; index++; string platform; SignatureKind signatureKind; if (connection.Version >= 2) { if (!Enum.TryParse <SignatureKind>(args[index], out signatureKind)) { answer = APIUtils.FromAPIResult(new Error() { message = $"signTx: Invalid signature: " + args[index] }); callback(id, answer, false); _isPendingRequest = false; return; } index++; platform = args[index].ToLower(); index++; } else { platform = "phantasma"; signatureKind = SignatureKind.Ed25519; } SignTransaction(platform, signatureKind, chain, script, payload, id, (hash, txError) => { if (hash != Hash.Null) { success = true; answer = APIUtils.FromAPIResult(new Transaction() { hash = hash.ToString() }); } else { answer = APIUtils.FromAPIResult(new Error() { message = txError }); } callback(id, answer, success); _isPendingRequest = false; }); } return; } else { answer = APIUtils.FromAPIResult(new Error() { message = $"signTx: Invalid amount of arguments: {args.Length}" }); } break; } case "invokeScript": { if (args.Length == 2) { var chain = args[0]; var script = Base16.Decode(args[1], false); if (script == null) { answer = APIUtils.FromAPIResult(new Error() { message = $"signTx: Invalid script data" }); } else { InvokeScript(chain, script, id, (invokeResult, invokeError) => { if (invokeResult != null) { success = true; answer = APIUtils.FromAPIResult(new Invocation() { result = Base16.Encode(invokeResult) }); } else { answer = APIUtils.FromAPIResult(new Error() { message = invokeError }); } callback(id, answer, success); _isPendingRequest = false; }); return; } } else { answer = APIUtils.FromAPIResult(new Error() { message = $"invokeScript: Invalid amount of arguments: {args.Length}" }); } break; } case "writeArchive": { if (args.Length == 3) { var archiveHash = Hash.Parse(args[0]); var blockIndex = int.Parse(args[1]); var bytes = Base16.Decode(args[2], false); if (bytes == null) { answer = APIUtils.FromAPIResult(new Error() { message = $"invokeScript: Invalid archive data" }); } else { WriteArchive(archiveHash, blockIndex, bytes, (result, error) => { if (result) { success = true; answer = APIUtils.FromAPIResult(new Transaction() { hash = archiveHash.ToString() }); } else { answer = APIUtils.FromAPIResult(new Error() { message = error }); } callback(id, answer, success); _isPendingRequest = false; }); } return; } else { answer = APIUtils.FromAPIResult(new Error() { message = $"writeArchive: Invalid amount of arguments: {args.Length}" }); } break; } default: answer = APIUtils.FromAPIResult(new Error() { message = "Invalid request type" }); break; } callback(id, answer, success); _isPendingRequest = false; }
public QuiescingSession(Connection connection, ushort channelNumber, ShutdownEventArgs reason) : base(connection, channelNumber) { _reason = reason; }