Inheritance: MonoBehaviour
Example #1
0
 public void AddFriend(Friend f, bool program = false)
 {
     if (!friends.Contains(f, (new FriendsComparer())))
     {
         friends.Add(f);
         TabItem t = new TabItem();
         t.Header = f.NickName;
         MyTabItem m = new MyTabItem(ref f, nickname,program);
         t.Content = m;
         tabControl1.Items.Add(t);
         
         if (!program || tabControl1.Items.Count == 1)
         {
             ((TabItem)tabControl1.Items[tabControl1.Items.Count - 1]).Focus();
             tabControl1.SelectedIndex = tabControl1.Items.Count - 1;
         }
     }
     else
     {
         bool find = false;
         for (int i = 0; i < friends.Count && !find; i++)
         {
             if (friends[i].Thread_Id == f.Thread_Id)
             {
                 find = true;
                 ((TabItem)tabControl1.Items[i]).Focus();                     
             }
         }
     }
     Show();
 }
 public void ReadPacket(PacketReader reader)
 {
     Unknown1 = reader.ReadInt32();
     var count = reader.ReadInt32();
     Friends = new List<Friend>();
     for (int i = 0; i < count; i++)
     {
         Friend friend = new Friend();
         friend.UserID1 = reader.ReadInt64();
         friend.UserID2 = reader.ReadInt64();
         friend.Username = reader.ReadString();
         friend.FacebookID = reader.ReadString();
         friend.Unknown3 = reader.ReadString();
         friend.Unknown4 = reader.ReadInt32();
         friend.Level = reader.ReadInt32();
         friend.Unknown6 = reader.ReadInt32();
         friend.Trophies = reader.ReadInt32();
         friend.HasClan = reader.ReadBoolean();
         if (friend.HasClan)
         {
             friend.ClanID = reader.ReadInt64();
             friend.ClanUnknown1 = reader.ReadInt32();
             friend.ClanName = reader.ReadString();
             friend.ClanRole = reader.ReadInt32();
             friend.ClanLevel = reader.ReadInt32();
         }
         Friends.Add(friend);
     }
 }
Example #3
0
 public ICollection<Friend> GetAllAccount(Friend acc)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         return session.CreateCriteria(typeof(Friend)).List<Friend>();
     }
 }
    void OnClick()
    {
        var friendContentUIManager = (FriendContentUIManager)FindObjectOfType<FriendContentUIManager>();
        if (friendContentUIManager)
        {
            friendContentUIManager.hideFriendContentWindow();
        }
        string friendName = Title.text;
        long uid = 0;
        Friend f = new Friend();
        List<Friend> applyLsit = MonoInstancePool.getInstance<FriendManager>().applyLsit;
        foreach (Friend friend in applyLsit)
        {
            if (friend.friendName == friendName)
            {
                uid = friend.fiendId;
                f = friend;
            }
        }
        MonoInstancePool.getInstance<FriendManager>().applyLsit.Remove(f);
		MonoInstancePool.getInstance<SendFriendSystemHander>().SendAgreeOrDisagree(uid, false);
		var inviteListUIManager = (InviteListUIManager)FindObjectOfType<InviteListUIManager> ();
		inviteListUIManager.deleteInviteFriendObject (uid);
        //MonoInstancePool.getInstance<FriendManager>().inviteObject.Remove(transform.parent.gameObject);
        //Destroy(transform.parent.gameObject);
    }
Example #5
0
    public void StartByInvitation(Friend friend, OperationCompleteEvent opCompleteEvent, object tag)
    {
        object[] objs = (object[])tag;
        string sbIP = (string)objs[0];
        int sbPort = (int)objs[1];
        string hash = (string)objs[2];
        string sessionID = (string)objs[3];

        try
        {
            Proxy.IConnection conn = this.control.CreateConnection();
            conn.Connect("", 0, sbIP, sbPort, Proxy.ConnectionType.Tcp);
            sbRouter = new MessageRouter(this.protocol, conn, null, null);

            RegisterCodeEvents();

            sbRouter.SendMessage(Message.ConstructMessage("ANS",
                this.settings.Username + " " + hash + " " + sessionID),
                new ResponseReceivedHandler(OnAnswerResponse), opCompleteEvent);
        }
        catch
        {
            opCompleteEvent.Execute(new OperationCompleteArgs("Could not connect", true));
        }
    }
    void OnClick()
    {
        var friendContentUIManager = (FriendContentUIManager)FindObjectOfType<FriendContentUIManager>();
        if (friendContentUIManager)
        {
            friendContentUIManager.hideFriendContentWindow();
        }
        string friendName = Title.text;
        long uid = 0;
        Friend f = new Friend();
        List<Friend> applyLsit = MonoInstancePool.getInstance<FriendManager>().applyLsit;
        foreach (Friend friend in applyLsit)
        {
            if (friend.friendName == friendName)
            {
                uid = friend.fiendId;
                f = friend;

            }
        }
		MonoInstancePool.getInstance<FriendManager>().applyLsit.Remove(f);
		MonoInstancePool.getInstance<SendFriendSystemHander>().SendAgreeOrDisagree(uid, true);
		var inviteListUIManager = (InviteListUIManager)FindObjectOfType<InviteListUIManager> ();
		inviteListUIManager.deleteInviteFriendObject (uid);
        //MonoInstancePool.getInstance<FriendManager>().inviteObject.Remove(transform.parent.gameObject);
        //Destroy(transform.parent.gameObject);
        //for(int i =0; i < MonoInstancePool.getInstance<FriendManager>().inviteObject.Count; i++)
        //{
       //     MonoInstancePool.getInstance<FriendManager>().inviteObject[i].transform.localPosition = new Vector3(-370, 90 - (i * 108), 0);
        //}
    }
 public void SaveFriend(Friend friend)
 {
     using (var dataService = _dataServiceCreator())
     {
         dataService.SaveFriend(friend);
     }
 }
Example #8
0
    // No duplicate entries
    public void HashSetTest()
    {
        Friend chris = new Friend("Chris",10,1230,1);
        Friend john = new Friend("John",5,234,3);
        Friend annie = new Friend("Annie",7,902,2);
        Friend rosy = new Friend("Rosy",1,10,4);

        HashSet<Friend> friend_list = new HashSet<Friend>();
        friend_list.Add(chris);
        friend_list.Add(john);
        friend_list.Add(annie);
        friend_list.Add(rosy);

        StringBuilder str = new StringBuilder();

        foreach(Friend friend in friend_list)
        {
            str.Append("Name: ");str.Append(friend.name);
            str.Append(" / ");
            str.Append("Level: ");str.Append(friend.level);
            str.Append(" / ");
            str.Append("Point: ");str.Append(friend.point);
            str.Append(" / ");
            str.Append("Rank: ");str.Append(friend.rank);
            str.Append("\n");
        }
        textResult.text = str.ToString();
    }
    //获取好友列表
    public void onGetFriendList(SocketModel module)
    {
		FriendMessage.MsgFriendListRep msg = MsgSerializer.Deserialize<FriendMessage.MsgFriendListRep>(module);

        MonoInstancePool.getInstance<FriendManager>().friendList.Clear();
        MonoInstancePool.getInstance<FriendManager>().applyLsit.Clear();
        for (int i = 0; i < msg.FriendAry.Count; i++)
        {
            Friend friend = new Friend();
            friend.fiendId = msg.FriendAry[i].uid;
            friend.friendName = msg.FriendAry[i].name;
            friend.friendLevel = msg.FriendAry[i].level;
            friend.imageID = msg.FriendAry[i].headid;
            friend.vipLevel = msg.FriendAry[i].vip;
            if (msg.type == (int)GlobalDef.FriendType.FriendList)
            {
                MonoInstancePool.getInstance<FriendManager>().friendList.Add(friend);
            }
            else if (msg.type == (int)GlobalDef.FriendType.InviteList)
            {
                MonoInstancePool.getInstance<FriendManager>().applyLsit.Add(friend);
            }
        }
        if (msg.type == (int)GlobalDef.FriendType.FriendList)       //显示好友列表
        {
            MonoInstancePool.getInstance<FriendManager>().IsDirty = true;
        }
        else if (msg.type == (int)GlobalDef.FriendType.InviteList)  //显示邀请好友列表
        {
            MonoInstancePool.getInstance<FriendManager>().IsDirty = true;
        }
    }
Example #10
0
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			string friendName;
			NavigationContext.QueryString.TryGetValue("friend-name", out friendName);
			if (friendName == null)
			{
				NavigationService.GoBack();
				return;
			}

			Friend friend = App.IsolatedStorage.UserAccount.Friends.First(f => f.Name == friendName);
			if (friend == null || App.IsolatedStorage.FriendsBests == null)
			{
				NavigationService.GoBack();
				return;
			}
			_friend = friend;

			LabelUserName.DataContext = App.IsolatedStorage.UserAccount.Friends.First(f => f.Name == friendName);
			LabelDisplayName.DataContext = App.IsolatedStorage.UserAccount.Friends.First(f => f.Name == friendName);

			Best usersBests;
			App.IsolatedStorage.FriendsBests.TryGetValue(friend.Name, out usersBests);
			if (usersBests == null)
			{
				usersBests = new Best
				{
					BestFriends = new string[] {},
					Score = 0
				};
			}
			DataContext = usersBests;

			base.OnNavigatedTo(e);
		}
Example #11
0
        public Color GetStatusColor(Friend steamid)
        {
            Color inGame = this.settings.Color.StatusIngameFore;
            Color online = this.settings.Color.StatusOnlineFore;
            Color offline = this.settings.Color.StatusOfflineFore;
            Color blocked = this.settings.Color.StatusBlockedFore;
            Color invited = this.settings.Color.StatusInvitedFore;
            Color requesting = this.settings.Color.StatusInvitedBack;

            if (steamid.IsAcceptingFriendship())
            {
                return invited;
            }
            else if (steamid.IsRequestingFriendship())
            {
                return requesting;
            }
            else if (steamid.IsBlocked())
            {
                return blocked;
            }
            else if (steamid.IsInGame())
            {
                return inGame;
            }
            else if (!steamid.IsOnline())
            {
                return offline;
            }
            
            return online;
        }
Example #12
0
        protected void Page_Load(object sender, EventArgs e)
        {

            m_FriendUserID = _Request.Get<int>("uid", Method.Get, 0);

            if (_Request.IsClick("shieldfriend"))
            {
                Shield();
                return;
            }

            using (ErrorScope es = new ErrorScope())
            {
                m_FriendToShield = FriendBO.Instance.GetFriend(MyUserID, m_FriendUserID);
                WaitForFillSimpleUser<Friend>(m_FriendToShield);

                if (es.HasUnCatchedError)
                {
                    es.CatchError<ErrorInfo>(delegate(ErrorInfo error)
                    {
                        ShowError(error);
                        return;
                    });
                }
            }

        }
Example #13
0
 public FriendshipBaseEvent(Friend f)
 {
     this.mFriendRelationId = f.FriendRelationID;
     this.mUser1 = f.User1;
     this.mUser2 = f.User2;
     this.mEventTime = f.FriendsSince;
 }
Example #14
0
	public void AddFriend(string name)
	{
		Friend friend = new Friend();
		friend.Name = name;
		friends.Add(friend);

	}
        public ActionResult SaveData(Friend friend)
        {
            FriendDB db = new FriendDB();
            db.Friends.Add(friend);
            db.SaveChanges();

            return Json("Data saved and name was " + friend.Name);
        }
Example #16
0
 public void RefreshDynamicElements(Player player, Friend friend)
 {
     this.DynamicElements["playerBeerBelly"].Text = player.BeerBelly.ToString();
     this.DynamicElements["playerLife"].Text = player.Life.ToString();
     this.DynamicElements["playerHealth"].Text = player.Health.ToString(CultureInfo.CurrentUICulture);
     this.DynamicElements["friendLife"].Text = friend.Life.ToString();
     this.DynamicElements["friendHealth"].Text = friend.Health.ToString(CultureInfo.CurrentUICulture);
 }
 private void InsertFriend(Friend friend)
 {
     var friends = ReadFromFile();
     var maxFriendId = friends.Max(f => f.Id);
     friend.Id = maxFriendId + 1;
     friends.Add(friend);
     SaveToFile(friends);
 }
Example #18
0
        public ChatAdapter(Friend friend, Context context)
        {
            this.context = context;
            messages = new List<ChatMessage>();
            inflater = LayoutInflater.FromContext(context);
            this.friend = friend;

            SteamService.GetClient().AddHandler(this);
        }
Example #19
0
    public void StartByInvitation(Friend friend, OperationCompleteEvent opCompleteEvent, object tag)
    {
        this.friend = friend;
        opCompleteEvent.Execute(new OperationCompleteArgs());
        Message message = (Message)tag;
        this.control.FriendSay(friend, message.GetArgumentString(14));

        this.protocol.conversationTable.Add(friend.Username, this);
    }
 public void SaveFriend(Friend friend)
 {
     if (friend.Id <= 0) {
         InsertFriend(friend);
     }
     else {
         UpdateFriend(friend);
     }
 }
        public static FriendViewModel GetViewModel(Friend friend)
        {
            if (Cache.ContainsKey(friend))
                return Cache[friend];

            var viewModel = new FriendViewModel(friend);
            Cache.Add(friend, viewModel);
            return viewModel;
        }
	//设置当前操作的好友(针对好友列表内的好友)
	public void setCurrentFriend2(string name){
		foreach (Friend friend in friendList)
		{
			if (friend.friendName == name)
			{
				this.currentFriend = friend;
			}
		}
	}
Example #23
0
 void AddFacebookFriend(string id, string username)
 {
     ids.Add(id);
     Friend friend = new Friend();
     friend.id = id;
     friend.username = username;
     all.Add(friend);
     StartCoroutine(GetPicture(id));
 }
 //设置当前操作的好友(针对邀请列表内的好友)
 public void setCurrentFriend(string name)
 {
     foreach (Friend friend in applyLsit)
     {
         if (friend.friendName == name)
         {
             this.currentFriend = friend;
         }
     }
 }
Example #25
0
        private void PopulateDynamicElements(Player player, Friend friend)
        {
            this.DynamicElements.Add("playerBeerBelly", new TextBlock()
            {
                Name = "playerBeerBelly",
                Text = player.BeerBelly.ToString(),
                HorizontalAlignment = HorizontalAlignment.Left,
                TextWrapping = TextWrapping.Wrap,
                VerticalAlignment = VerticalAlignment.Top,
                Width = 39,
                Margin = new Thickness(677, 30, 0, 0)
            });

            this.DynamicElements.Add("playerLife", new TextBlock()
            {
                Name = "playerLife",
                Text = player.Life.ToString(),
                Margin = new Thickness(373, 30, 0, 0),
                Width = 18,
                HorizontalAlignment = HorizontalAlignment.Left,
                TextWrapping = TextWrapping.Wrap,
                VerticalAlignment = VerticalAlignment.Top,
            });
            this.DynamicElements.Add("friendLife", new TextBlock()
            {
                Name = "friendLife",
                Text = friend.Life.ToString(),
                Margin = new Thickness(373, 80, 0, 0),
                Width = 18,
                HorizontalAlignment = HorizontalAlignment.Left,
                TextWrapping = TextWrapping.Wrap,
                VerticalAlignment = VerticalAlignment.Top,
            });
            this.DynamicElements.Add("playerHealth", new TextBlock()
            {
                Name = "plyerHealth",
                Text = player.Health.ToString(CultureInfo.CurrentUICulture),
                Margin = new Thickness(459, 30, 0, 0),
                Width = 28,
                HorizontalAlignment = HorizontalAlignment.Left,
                TextWrapping = TextWrapping.Wrap,
                VerticalAlignment = VerticalAlignment.Top,
            });

            this.DynamicElements.Add("friendHealth", new TextBlock()
            {
                Name = "friendHealth",
                Text = friend.Health.ToString(CultureInfo.CurrentUICulture),
                Margin = new Thickness(459, 80, 0, 0),
                Width = 28,
                HorizontalAlignment = HorizontalAlignment.Left,
                TextWrapping = TextWrapping.Wrap,
                VerticalAlignment = VerticalAlignment.Top,
            });
        }
Example #26
0
 public void Delete(Friend acc)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             //session.Delete(acc.UserName);
             transaction.Commit();
         }
     }
 }
Example #27
0
 public void Update(Friend acc)
 {
     using (NHibernate.ISession session = SessionFactory.GetNewSession())
     {
         using (NHibernate.ITransaction transaction = session.BeginTransaction())
         {
             //session.Update(acc.Password, acc);
             transaction.Commit();
         }
     }
 }
    public void SetFriend(Friend friend)
    {
        this.friend = friend;
        nameField.text = friend.name;

        photo.sprite = friend.GetPhoto();
        if (!friend.PhotoLoaded() && !friend.PhotoLoading())
        {
            StartCoroutine(friend.DownloadPhotoCoroutine(photo));
        }
    }
Example #29
0
 public void OnClick1()
 {
     Friend f1 = new Friend ("Pham Tan Long", 12);
     string s1 = MiniJSON.Json.Serialize (f1);
     Debug.Log (s1);
     Friend f2 = MiniJSON.Json.Deserialize <Friend> (s1);
     if (f2 != null) {
         Debug.Log (MiniJSON.Json.Serialize (f2));
     } else {
         Debug.LogError ("Can not parse");
     }
 }
Example #30
0
        public void Insert(Friend acc)
        {
            using (NHibernate.ISession session = SessionFactory.GetNewSession())
            {
                using (NHibernate.ITransaction transaction = session.BeginTransaction())
                {
                    session.Save(acc);

                    transaction.Commit();
                }
            }
        }
Example #31
0
        public Holder <Friend> AddFriend([FromBody] Friend friend)
        {
            Holder <Friend> retVal = _userBusiness.AddFriend(friend);

            return(retVal);
        }
Example #32
0
 public virtual TypePrinterResult VisitFriend(Friend friend)
 {
     throw new NotImplementedException();
 }
Example #33
0
        public async Task <int> CreateFriend([FromBody] Friend friend)
        {
            var result = _HostRepository.CreateFriend(friend).Result;

            return(result);
        }
 public void getFriendlyAccounts(FriendSystem system, bool isOnline)
 {
     if (system == null || system._friends.Count == 0)
     {
         return;
     }
     try
     {
         using (NpgsqlConnection connection = SQLjec.getInstance().conn())
         {
             NpgsqlCommand command    = connection.CreateCommand();
             string        loaded     = "";
             List <string> parameters = new List <string>();
             for (int idx = 0; idx < system._friends.Count; idx++)
             {
                 Friend friend = system._friends[idx];
                 if (friend.state > 0)
                 {
                     return;
                 }
                 string param = "@valor" + idx;
                 command.Parameters.AddWithValue(param, friend.player_id);
                 parameters.Add(param);
             }
             loaded = string.Join(",", parameters.ToArray());
             if (loaded == "")
             {
                 return;
             }
             connection.Open();
             command.Parameters.AddWithValue("@on", isOnline);
             command.CommandText = "SELECT player_name,player_id,rank,status FROM contas WHERE player_id in (" + loaded + ") AND online=@on ORDER BY player_id";
             NpgsqlDataReader data = command.ExecuteReader();
             while (data.Read())
             {
                 Friend friend = system.GetFriend(data.GetInt64(1));
                 if (friend != null)
                 {
                     friend.player.player_name = data.GetString(0);
                     friend.player._rank       = data.GetInt32(2);
                     friend.player._isOnline   = isOnline;
                     friend.player._status.SetData((uint)data.GetInt64(3), friend.player_id);
                     if (isOnline && !_contas.ContainsKey(friend.player_id))
                     {
                         friend.player.setOnlineStatus(false);
                         friend.player._status.ResetData(friend.player_id);
                     }
                 }
             }
             command.Dispose();
             data.Dispose();
             data.Close();
             connection.Dispose();
             connection.Close();
         }
     }
     catch (Exception ex)
     {
         SaveLog.fatal(ex.ToString());
         Printf.b_danger("[AccountManager.FriendAccounts2] Erro fatal!");
     }
 }
Example #35
0
 /// <summary>
 /// This constructor is used for passing in a single friend for and add, remove, or update status.  It also allows you to override the online status so the WorldManager isn't checked.
 /// </summary>
 /// <param name="session"></param>
 /// <param name="updateType"></param>
 /// <param name="friend"></param>
 /// <param name="overrideOnlineStatus">Set to true if you want to force a value for the online status of the friend.  Useful if you know the status and don't want to have the WorldManager check</param>
 /// <param name="onlineStatusVal">If overrideOnlineStatus is true, then this is the online status value that you want to force in the packet</param>
 public GameEventFriendsListUpdate(Session session, FriendsUpdateTypeFlag updateType, Friend friend, bool overrideOnlineStatus = false, bool onlineStatusVal = false)
     : base(GameEventType.FriendsListUpdate, session)
 {
     this.updateType           = updateType;
     this.friend               = friend;
     this.overrideOnlineStatus = overrideOnlineStatus;
     this.onlineStatusVal      = onlineStatusVal;
     WriteEventBody();
 }
Example #36
0
 /// <summary>
 /// Gets per-user metadata for someone in this lobby
 /// </summary>
 public string GetMemberData(Friend member, string key)
 {
     return(SteamMatchmaking.Internal.GetLobbyMemberData(Id, member.Id, key));
 }
Example #37
0
 private async Task MakeRequestToRetrieveLeftBehindMessagesFromChatHub()
 {
     string recepientPhoneNumber = Preferences.Get(ApplicationConstants.YOUR_PHONE_NUM_PREF, ApplicationConstants.NO_PHONE_NUMBER);
     Friend friendChattingWith   = (Friend)BindingContext;
     await hubConnectionManager.GetHubConnection().InvokeAsync("GetChatMessagesLeftForUserFromAnotherUser", recepientPhoneNumber, friendChattingWith.ID);
 }
 public FriendPackage(Friend friend, string keyword) : base(InformationType.FRIEND, keyword)
 {
     SendList = new FriendList();
     SendList.AddNewFriend(friend);
 }
Example #39
0
        private void ProcessLogInPacket(Client client, Friend friend)
        {
            //
            // Sign out anyone who is using the same user name.
            //

            var clientManager   = ClientManager.GetInstance();
            var duplicateClient = clientManager.GetClientList()
                                  .FirstOrDefault(c => c.UserInfo.EmailAddress == friend.EmailAddress);

            if (duplicateClient != null)
            {
                duplicateClient.Disconnect();
            }

            client.UserInfo = friend;

            clientManager.AddClient(client);

            //
            // Look for the user in the database.  If the user does not exist, add
            // 'em to the DB
            //

            var db   = Database.GetInstance();
            var user = db.GetUserByEmail(client.UserInfo.EmailAddress);

            if (user == null)
            {
                db.AddNewUser(client.UserInfo.EmailAddress, client.UserInfo.Alias);
            }

            user = db.GetUserByEmail(client.UserInfo.EmailAddress);

            var userAsFriend = MessageReceiver.GetFriendFromUser(user);


            //
            // Send the user a copy of his/her stats.
            //

            MessageSender.SendMessage(
                client,
                PacketType.s_UserStats,
                userAsFriend);


            //
            // Send both the online list and the complete list of friends to the user.
            //

            MessageReceiver.SendOnlineAndCompleteFriendList(client);


            //
            // Send pending friend requests to user.
            //

            var pendingRequests = db.GetPendingFriendRequests(client.UserInfo.EmailAddress);

            if (null != pendingRequests)
            {
                var pendingFriendRequests = MessageReceiver.CreateFriendListFromUserList(pendingRequests);

                MessageSender.SendMessage(
                    client,
                    PacketType.s_FriendRequests,
                    pendingFriendRequests);
            }
        }
Example #40
0
 /// <summary>
 /// 加入新的建议项
 /// </summary>
 /// <param name="friend">需要新加入的用户</param>
 public void insert(Friend friend)
 {
     suggestItems.Add(friend);
 }
Example #41
0
        private Border CreateNewFriendStackPannel(Friend friend)
        {
            Border border = new Border();

            border.CornerRadius = new CornerRadius(15);
            border.Margin       = new Thickness(5);

            LinearGradientBrush linearGradientBrush = new LinearGradientBrush();

            GradientStop gradientStop1 = new GradientStop();

            gradientStop1.Color  = (Color)ColorConverter.ConvertFromString("#40567a");
            gradientStop1.Offset = 0.2;

            GradientStop gradientStop2 = new GradientStop();

            gradientStop2.Color  = (Color)ColorConverter.ConvertFromString("#3a5f9c");
            gradientStop2.Offset = 0.5;

            linearGradientBrush.GradientStops.Add(gradientStop1);
            linearGradientBrush.GradientStops.Add(gradientStop2);

            border.Background = linearGradientBrush;

            StackPanel stackPanel = new StackPanel();

            stackPanel.Orientation         = Orientation.Vertical;
            stackPanel.Opacity             = 0.5;
            stackPanel.HorizontalAlignment = HorizontalAlignment.Center;
            stackPanel.VerticalAlignment   = VerticalAlignment.Center;

            StackPanel name = new StackPanel();

            name.Margin = new Thickness(5);

            Label label = new Label();

            label.Foreground          = Brushes.White;
            label.FontFamily          = new FontFamily("Arial");
            label.HorizontalAlignment = HorizontalAlignment.Center;
            label.VerticalAlignment   = VerticalAlignment.Center;
            label.FontSize            = 22;
            label.FontWeight          = FontWeights.Light;
            label.Content             = friend?.Name;

            name.Children.Add(label);

            StackPanel surname = new StackPanel();

            surname.Margin = new Thickness(5);

            Label label1 = new Label();

            label1.Foreground          = Brushes.White;
            label1.FontFamily          = new FontFamily("Arial");
            label1.HorizontalAlignment = HorizontalAlignment.Center;
            label1.VerticalAlignment   = VerticalAlignment.Center;
            label1.FontSize            = 22;
            label1.FontWeight          = FontWeights.Light;
            label1.Content             = friend?.Surname;

            surname.Children.Add(label1);

            stackPanel.Children.Add(name);
            stackPanel.Children.Add(surname);

            border.Child = stackPanel;

            return(border);
        }
Example #42
0
 public virtual bool VisitFriend(Friend friend)
 {
     return(true);
 }
Example #43
0
 public Holder <Friend> ConfirmFriendship([FromBody] Friend friend)
 {
     return(_userBusiness.ConfirmFriendship(friend));
 }
Example #44
0
 public void SetMyFrame(GameObject frame)
 {
     myFrame       = frame;
     myFrameScript = myFrame.GetComponent <Friend>();
 }
Example #45
0
        public Friend ModifyReceiver(Friend friend, int groupSize)
        {
            var random = new Random();

            if (!friend.IsFirstPostOnWall) // if it is just first mail to him, then setting hated contact and condition to true, so will not do it again
            {
                friend.HatedContact      = friend.Author;
                friend.IsFirstPostOnWall = true;
            }

            if (friend.LovedContact == friend.Author) // if received from loved contact, then it becomes hated
            {
                friend.HatedContact = friend.LovedContact;
                friend.LovedContact = friend.Contacts[random.Next(friend.Contacts.Count)];

                while (friend.HatedContact == friend.LovedContact) // random generating new loved contact, but different than the hated contact
                {
                    friend.LovedContact = friend.Contacts[random.Next(friend.Contacts.Count)];
                }
            }

            double forwardProbability = (double)friend.Contacts.Count / groupSize; // probability P = M/N

            var number = random.NextDouble();

            if (number < forwardProbability) // if will forward the message (the lower number, the biggest chance in case of high P)
            {
                friend.WillContinue = true;

                var futureRecipientsAmount = (int)Math.Round(forwardProbability * friend.Contacts.Count); // amount of forwards P*M

                if (futureRecipientsAmount == 0)                                                          // safe exit case if there is recipients amount equal to 0
                {
                    friend.WillContinue = false;
                    friend.FutureRecipients.Clear();

                    return(friend);
                }

                IList <int> listToChooseFrom = new List <int>();

                foreach (var item in friend.Contacts)
                {
                    listToChooseFrom.Add(item);
                }

                listToChooseFrom.Remove(friend.Author); // never sending back to author

                for (var i = 0; i < futureRecipientsAmount; i++)
                {
                    var freshRecipient = listToChooseFrom[random.Next(listToChooseFrom.Count)];
                    listToChooseFrom.Remove(freshRecipient);   // adding 1 recipient, then removing him from available recipients (can not send 2 times to the same recipients in 1 wave)

                    if (freshRecipient != friend.LovedContact) // never sending to loved contact
                    {
                        friend.FutureRecipients.Add(freshRecipient);
                    }
                }

                if (friend.HatedContact != 0 && friend.HatedContact != friend.Author)
                {
                    if (!friend.FutureRecipients.Contains(friend.HatedContact)) // always sending to hated contact
                    {
                        friend.FutureRecipients.Remove(random.Next(friend.FutureRecipients.Count));
                        friend.FutureRecipients.Add(friend.HatedContact);
                    }
                }
            }

            else // if not forwarding the message
            {
                friend.WillContinue = false;
                friend.FutureRecipients.Clear();
            }

            return(friend);
        }
Example #46
0
        public async Task <bool> DeleteFriendAsync(int id)
        {
            Friend friend = await _friendRepository.GetByIdAsync(id);

            return(await _userService.DeleteFriendAsync(friend));
        }
Example #47
0
        private void HandleBRSFriendNotify(TcpSession session, Packet p)
        {
            var accID    = p.ReadUInt64();
            var accepted = p.ReadInt32() > 0;
            var nickname = p.ReadCStringBuffer(31);
            //_logger.Debug("-C_ADD_FRIEND_REQ- ID: {0} Nickname: {1}", accID, nickname);

            Player plr;

            if (!_players.TryGetValue(session.Guid, out plr))
            {
                session.StopListening();
                return;
            }
            Packet ack;

            var plrFromRequest = _players.GetPlayerByID(accID);

            if (plrFromRequest == null)
            {
                return;
            }

            if (accepted)
            {
                SendBRSFriendNotify(plr, plrFromRequest, EFriendNotify.Accepted);
                SendBRSFriendNotify(plrFromRequest, plr, EFriendNotify.Accepted);
            }
            else
            {
                SendBRSFriendNotify(plr, plrFromRequest, EFriendNotify.Denied);
                SendBRSFriendNotify(plr, plrFromRequest, EFriendNotify.DeleteRelation);

                SendBRSFriendNotify(plrFromRequest, plr, EFriendNotify.DeleteRelation);
            }


            var friend = plrFromRequest.FriendList.FirstOrDefault(f => f.ID == plr.AccountID);

            if (friend == null)
            {
                return;
            }
            if (accepted)
            {
                friend.Accepted = true;
                GameDatabase.Instance.UpdateFriend(plrFromRequest.AccountID, friend.ID, friend.Accepted);

                var newFriend = new Friend()
                {
                    ID       = plrFromRequest.AccountID,
                    Nickname = plrFromRequest.Nickname,
                    Accepted = true
                };
                plr.FriendList.Add(newFriend);
                GameDatabase.Instance.AddFriend(plr.AccountID, newFriend.ID, newFriend.Nickname, newFriend.Accepted);
            }
            else
            {
                plrFromRequest.FriendList.Remove(friend);
                GameDatabase.Instance.RemoveFriend(plrFromRequest.AccountID, friend.ID);
            }
        }
Example #48
0
        // Unified protocol message parsing
        public static void parseProtocolMessage(ProtocolMessageCode code, byte[] data, RemoteEndpoint endpoint)
        {
            if (endpoint == null)
            {
                Logging.error("Endpoint was null. parseProtocolMessage");
                return;
            }
            try
            {
                switch (code)
                {
                case ProtocolMessageCode.hello:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            if (data[0] == 5)
                            {
                                CoreProtocolMessage.processHelloMessageV5(endpoint, reader);
                            }
                            else
                            {
                                CoreProtocolMessage.processHelloMessageV6(endpoint, reader);
                            }
                        }
                    }
                }
                break;


                case ProtocolMessageCode.helloData:
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            if (data[0] == 5)
                            {
                                if (!CoreProtocolMessage.processHelloMessageV5(endpoint, reader))
                                {
                                    return;
                                }

                                ulong  last_block_num       = reader.ReadUInt64();
                                int    bcLen                = reader.ReadInt32();
                                byte[] block_checksum       = reader.ReadBytes(bcLen);
                                int    wsLen                = reader.ReadInt32();
                                byte[] walletstate_checksum = reader.ReadBytes(wsLen);
                                int    consensus            = reader.ReadInt32(); // deprecated

                                endpoint.blockHeight = last_block_num;

                                int block_version = reader.ReadInt32();

                                // Check for legacy level
                                ulong legacy_level = reader.ReadUInt64();     // deprecated

                                int    challenge_response_len = reader.ReadInt32();
                                byte[] challenge_response     = reader.ReadBytes(challenge_response_len);
                                if (!CryptoManager.lib.verifySignature(endpoint.challenge, endpoint.serverPubKey, challenge_response))
                                {
                                    CoreProtocolMessage.sendBye(endpoint, ProtocolByeCode.authFailed, string.Format("Invalid challenge response."), "", true);
                                    return;
                                }

                                if (endpoint.presenceAddress.type != 'C')
                                {
                                    ulong highest_block_height = IxianHandler.getHighestKnownNetworkBlockHeight();
                                    if (last_block_num + 10 < highest_block_height)
                                    {
                                        CoreProtocolMessage.sendBye(endpoint, ProtocolByeCode.tooFarBehind, string.Format("Your node is too far behind, your block height is {0}, highest network block height is {1}.", last_block_num, highest_block_height), highest_block_height.ToString(), true);
                                        return;
                                    }
                                }

                                // Process the hello data
                                endpoint.helloReceived = true;
                                NetworkClientManager.recalculateLocalTimeDifference();

                                if (endpoint.presenceAddress.type == 'R')
                                {
                                    string[] connected_servers = StreamClientManager.getConnectedClients(true);
                                    if (connected_servers.Count() == 1 || !connected_servers.Contains(StreamClientManager.primaryS2Address))
                                    {
                                        if (StreamClientManager.primaryS2Address == "")
                                        {
                                            FriendList.requestAllFriendsPresences();
                                        }
                                        // TODO set the primary s2 host more efficiently, perhaps allow for multiple s2 primary hosts
                                        StreamClientManager.primaryS2Address = endpoint.getFullAddress(true);
                                        // TODO TODO do not set if directly connectable
                                        IxianHandler.publicIP           = endpoint.address;
                                        IxianHandler.publicPort         = endpoint.incomingPort;
                                        PresenceList.forceSendKeepAlive = true;
                                        Logging.info("Forcing KA from networkprotocol");
                                    }
                                }
                                else if (endpoint.presenceAddress.type == 'C')
                                {
                                    Friend f = FriendList.getFriend(endpoint.presence.wallet);
                                    if (f != null && f.bot)
                                    {
                                        StreamProcessor.sendGetBotInfo(f);
                                    }
                                }

                                if (endpoint.presenceAddress.type == 'M' || endpoint.presenceAddress.type == 'H')
                                {
                                    Node.setNetworkBlock(last_block_num, block_checksum, block_version);

                                    // Get random presences
                                    endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                        (byte)'R'
                                    });
                                    endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                        (byte)'M'
                                    });
                                    endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                        (byte)'H'
                                    });

                                    subscribeToEvents(endpoint);
                                }
                            }
                            else
                            {
                                if (!CoreProtocolMessage.processHelloMessageV6(endpoint, reader))
                                {
                                    return;
                                }

                                ulong  last_block_num = reader.ReadIxiVarUInt();
                                int    bcLen          = (int)reader.ReadIxiVarUInt();
                                byte[] block_checksum = reader.ReadBytes(bcLen);

                                endpoint.blockHeight = last_block_num;

                                int block_version = (int)reader.ReadIxiVarUInt();

                                if (endpoint.presenceAddress.type != 'C')
                                {
                                    ulong highest_block_height = IxianHandler.getHighestKnownNetworkBlockHeight();
                                    if (last_block_num + 10 < highest_block_height)
                                    {
                                        CoreProtocolMessage.sendBye(endpoint, ProtocolByeCode.tooFarBehind, string.Format("Your node is too far behind, your block height is {0}, highest network block height is {1}.", last_block_num, highest_block_height), highest_block_height.ToString(), true);
                                        return;
                                    }
                                }

                                // Process the hello data
                                endpoint.helloReceived = true;
                                NetworkClientManager.recalculateLocalTimeDifference();

                                if (endpoint.presenceAddress.type == 'R')
                                {
                                    string[] connected_servers = StreamClientManager.getConnectedClients(true);
                                    if (connected_servers.Count() == 1 || !connected_servers.Contains(StreamClientManager.primaryS2Address))
                                    {
                                        if (StreamClientManager.primaryS2Address == "")
                                        {
                                            FriendList.requestAllFriendsPresences();
                                        }
                                        // TODO set the primary s2 host more efficiently, perhaps allow for multiple s2 primary hosts
                                        StreamClientManager.primaryS2Address = endpoint.getFullAddress(true);
                                        // TODO TODO do not set if directly connectable
                                        IxianHandler.publicIP           = endpoint.address;
                                        IxianHandler.publicPort         = endpoint.incomingPort;
                                        PresenceList.forceSendKeepAlive = true;
                                        Logging.info("Forcing KA from networkprotocol");
                                    }
                                }
                                else if (endpoint.presenceAddress.type == 'C')
                                {
                                    Friend f = FriendList.getFriend(endpoint.presence.wallet);
                                    if (f != null && f.bot)
                                    {
                                        StreamProcessor.sendGetBotInfo(f);
                                    }
                                }

                                if (endpoint.presenceAddress.type == 'M' || endpoint.presenceAddress.type == 'H')
                                {
                                    Node.setNetworkBlock(last_block_num, block_checksum, block_version);

                                    // Get random presences
                                    endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                        (byte)'R'
                                    });
                                    endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                        (byte)'M'
                                    });
                                    endpoint.sendData(ProtocolMessageCode.getRandomPresences, new byte[1] {
                                        (byte)'H'
                                    });

                                    subscribeToEvents(endpoint);
                                }
                            }
                        }
                    }
                    break;

                case ProtocolMessageCode.s2data:
                {
                    StreamProcessor.receiveData(data, endpoint);
                }
                break;

                case ProtocolMessageCode.updatePresence:
                {
                    Logging.info("NET: Receiving presence list update");
                    // Parse the data and update entries in the presence list
                    Presence p = PresenceList.updateFromBytes(data);
                    if (p == null)
                    {
                        return;
                    }

                    Friend f = FriendList.getFriend(p.wallet);
                    if (f != null)
                    {
                        f.relayIP = p.addresses[0].address;
                    }
                }
                break;

                case ProtocolMessageCode.keepAlivePresence:
                {
                    byte[]   address   = null;
                    long     last_seen = 0;
                    byte[]   device_id = null;
                    bool     updated   = PresenceList.receiveKeepAlive(data, out address, out last_seen, out device_id, endpoint);
                    Presence p         = PresenceList.getPresenceByAddress(address);
                    if (p == null)
                    {
                        return;
                    }

                    Friend f = FriendList.getFriend(p.wallet);
                    if (f != null)
                    {
                        f.relayIP = p.addresses[0].address;
                    }
                }
                break;

                case ProtocolMessageCode.getPresence:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    walletLen = reader.ReadInt32();
                            byte[] wallet    = reader.ReadBytes(walletLen);

                            Presence p = PresenceList.getPresenceByAddress(wallet);
                            if (p != null)
                            {
                                lock (p)
                                {
                                    byte[][] presence_chunks = p.getByteChunks();
                                    foreach (byte[] presence_chunk in presence_chunks)
                                    {
                                        endpoint.sendData(ProtocolMessageCode.updatePresence, presence_chunk, null);
                                    }
                                }
                            }
                            else
                            {
                                // TODO blacklisting point
                                Logging.warn(string.Format("Node has requested presence information about {0} that is not in our PL.", Base58Check.Base58CheckEncoding.EncodePlain(wallet)));
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.getPresence2:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    walletLen = (int)reader.ReadIxiVarUInt();
                            byte[] wallet    = reader.ReadBytes(walletLen);

                            Presence p = PresenceList.getPresenceByAddress(wallet);
                            if (p != null)
                            {
                                lock (p)
                                {
                                    byte[][] presence_chunks = p.getByteChunks();
                                    foreach (byte[] presence_chunk in presence_chunks)
                                    {
                                        endpoint.sendData(ProtocolMessageCode.updatePresence, presence_chunk, null);
                                    }
                                }
                            }
                            else
                            {
                                // TODO blacklisting point
                                Logging.warn(string.Format("Node has requested presence information about {0} that is not in our PL.", Base58Check.Base58CheckEncoding.EncodePlain(wallet)));
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.balance:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    address_length = reader.ReadInt32();
                            byte[] address        = reader.ReadBytes(address_length);

                            // Retrieve the latest balance
                            IxiNumber balance = reader.ReadString();

                            if (address.SequenceEqual(Node.walletStorage.getPrimaryAddress()))
                            {
                                // Retrieve the blockheight for the balance
                                ulong block_height = reader.ReadUInt64();

                                if (block_height > Node.balance.blockHeight && (Node.balance.balance != balance || Node.balance.blockHeight == 0))
                                {
                                    byte[] block_checksum = reader.ReadBytes(reader.ReadInt32());

                                    Node.balance.address       = address;
                                    Node.balance.balance       = balance;
                                    Node.balance.blockHeight   = block_height;
                                    Node.balance.blockChecksum = block_checksum;
                                    Node.balance.verified      = false;
                                }
                                Node.balance.lastUpdate = Clock.getTimestamp();
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.balance2:
                {
                    using (MemoryStream m = new MemoryStream(data))
                    {
                        using (BinaryReader reader = new BinaryReader(m))
                        {
                            int    address_length = (int)reader.ReadIxiVarUInt();
                            byte[] address        = reader.ReadBytes(address_length);

                            // Retrieve the latest balance
                            IxiNumber balance = new IxiNumber(new BigInteger(reader.ReadBytes((int)reader.ReadIxiVarUInt())));

                            if (address.SequenceEqual(Node.walletStorage.getPrimaryAddress()))
                            {
                                // Retrieve the blockheight for the balance
                                ulong block_height = reader.ReadIxiVarUInt();

                                if (block_height > Node.balance.blockHeight && (Node.balance.balance != balance || Node.balance.blockHeight == 0))
                                {
                                    byte[] block_checksum = reader.ReadBytes((int)reader.ReadIxiVarUInt());

                                    Node.balance.address       = address;
                                    Node.balance.balance       = balance;
                                    Node.balance.blockHeight   = block_height;
                                    Node.balance.blockChecksum = block_checksum;
                                    Node.balance.verified      = false;
                                }
                                Node.balance.lastUpdate = Clock.getTimestamp();
                            }
                        }
                    }
                }
                break;

                case ProtocolMessageCode.newTransaction:
                case ProtocolMessageCode.transactionData:
                {
                    // TODO: check for errors/exceptions
                    Transaction transaction = new Transaction(data, true);

                    if (endpoint.presenceAddress.type == 'M' || endpoint.presenceAddress.type == 'H')
                    {
                        PendingTransactions.increaseReceivedCount(transaction.id, endpoint.presence.wallet);
                    }

                    TransactionCache.addUnconfirmedTransaction(transaction);

                    Node.tiv.receivedNewTransaction(transaction);
                }
                break;

                case ProtocolMessageCode.bye:
                    CoreProtocolMessage.processBye(data, endpoint);
                    break;

                case ProtocolMessageCode.blockHeaders2:
                {
                    // Forward the block headers to the TIV handler
                    Node.tiv.receivedBlockHeaders2(data, endpoint);
                }
                break;

                case ProtocolMessageCode.pitData2:
                {
                    Node.tiv.receivedPIT2(data, endpoint);
                }
                break;

                default:
                    break;
                }
            }
            catch (Exception e)
            {
                Logging.error(string.Format("Error parsing network message. Details: {0}", e.ToString()));
            }
        }
Example #49
0
 public Task <int> DeleteFriendAsync(Friend friend)
 {
     return(database.DeleteAsync(friend));
 }
 public FriendWrapper(Friend friend)
 {
     _friend = friend;
 }
Example #51
0
 public FriendWrapper(Friend model)
 {
     Model = model;
 }
Example #52
0
        public async Task <ActionResult <string> > Post([FromBody] Friend friend)
        {
            DataAccessResponse <string> response = await _service.Add(friend);

            return(HandleResponse(response));
        }
 public static async Task SendPlainAsync(this Friend friend, string plain)
 {
     _logger.LogInformation($"{_client.GetType().Name}(Friend) < {friend.Identifier} : {plain}");
     await _client.SendFriendMessageAsync(friend, new MessageChain(new MessageElement[] { new Plain(plain) }));
 }
Example #54
0
 public JsonResult updateFriend([FromBody] Friend friend)
 {
     return(saveFriend(friend, "update"));
 }
 public static async Task SendAsync(this Friend friend, MessageChain message)
 {
     _logger.LogInformation($"{_client.GetType().Name}(Friend) < {friend.Identifier} : {message}");
     await _client.SendFriendMessageAsync(friend, message);
 }
Example #56
0
        private void OnFriendSaved(Friend friend)
        {
            var navigationItem = Friends.Single(n => n.Id == friend.Id);

            navigationItem.DisplayMember = $"{friend.FirstName} {friend.LastName}";
        }
 public async Task LoadAsync(int friendId)
 {
     Friend = await _friendDataService.GetByIdAsync(friendId);
 }
        public async Task Add(Friend friend)
        {
            await _context.Friends.AddAsync(friend);

            await _context.SaveChangesAsync();
        }
Example #59
0
 public FriendViewModel()
 {
     Friend = new Friend();
 }
Example #60
0
 public bool VisitFriend(Friend friend)
 {
     throw new System.NotImplementedException();
 }