Beispiel #1
0
        /// <summary>
        /// 加入好友
        /// </summary>
        /// <param name="model">加好友 View Model</param>
        /// <returns>執行結果</returns>
        public async Task<ExecuteResult> Post(AddFriendViewModel model) {
            if (model == null || !this.ModelState.IsValid) {
                throw this.CreateResponseException(HttpStatusCode.Forbidden, Resources.NeedProvideUserNameToAdd);
            }

            if (model.Id == this.UserId) {
                throw this.CreateResponseException(HttpStatusCode.Forbidden, Resources.CannotAddSelfAsFriend);
            }

            var result = await this.ValidateFriendship(model.Id, false, false);

            switch (result.Check) {
                case RelationCheck.HasRelation:
                    throw this.CreateResponseException(HttpStatusCode.Conflict, "{0} {1}", model.Id, Resources.AlreadyYourFriend);
                case RelationCheck.NoRelation:
                    // TODO : 目前先自動建立雙向關係
                    DateTime date = DateTime.UtcNow;
                    var fs = new Friendship(this.UserId, model.Id, RelationshipStatus.Accepted, date, RelationshipStatus.Accepted, date, date);
                    this.DbContext.Friendships.Add(fs);

                    try {
                        await this.DbContext.SaveChangesAsync();
                        await PushFriendshipToClient(fs);
                    }
                    catch (Exception ex) {
                        throw this.CreateResponseException(HttpStatusCode.InternalServerError, ex.Message);
                    }
                    break;
            }

            return new ExecuteResult(true);
        }
        public ActionResult AddFamily(string userName)
        {
            Friendship newFriendship = new Friendship();
            newFriendship.Friender = CurrentMember;

            var friendee = db.Members.FirstOrDefault(a => a.User.UserName == userName);
            if(friendee.Id != CurrentMember.Id)
            {
                newFriendship.Friendee = friendee;
                newFriendship.IsFamilyMember = true;

                db.Friendships.Add(newFriendship);
                db.SaveChanges();

                TempData["message"] = friendee.User.FirstName
                    + " " + friendee.User.LastName + " added as family";
            }

            else
            {
                TempData["message"] = "You can not add yourself as family.";
            }

                return RedirectToAction("Index");
        }
        public TwitterClient(IRestClient client, string consumerKey, string consumerSecret, string callback)
            : base(client)
        {
            Encode = true;
            Statuses = new Statuses(this);
            Account = new Account(this);
            DirectMessages = new DirectMessages(this);
            Favourites = new Favourites(this);
            Block = new Block(this);
            Friendships = new Friendship(this);
            Lists = new List(this);
            Search = new Search(this);
            Users = new Users(this);
            FriendsAndFollowers = new FriendsAndFollowers(this);

            OAuthBase = "https://api.twitter.com/oauth/";
            TokenRequestUrl = "request_token";
            TokenAuthUrl = "authorize";
            TokenAccessUrl = "access_token";
            Authority = "https://api.twitter.com/";
            Version = "1";

#if !SILVERLIGHT
            ServicePointManager.Expect100Continue = false;
#endif
            Credentials = new OAuthCredentials
            {
                ConsumerKey = consumerKey,
                ConsumerSecret = consumerSecret,
            };

            if (!string.IsNullOrEmpty(callback))
                ((OAuthCredentials)Credentials).CallbackUrl = callback;
        }
        public IdenticaClient(string username, string password)
        {
            Statuses = new Statuses(this);
            Account = new Account(this);
            DirectMessages = new DirectMessages(this);
            Favourites = new Favourites(this);
            Block = new Block(this);
            Friendships = new Friendship(this);
            Lists = new List(this);
            Search = new Search(this);
            Users = new Users(this);
            FriendsAndFollowers = new FriendsAndFollowers(this);

            Credentials = new BasicAuthCredentials
            {
                Username = username,
                Password = password
            };

            Client = new RestClient
                         {
                             Authority = "http://identi.ca/api",

                         };            
            
            Authority = "http://identi.ca/api";

            Encode = false;
        }
Beispiel #5
0
        private FriendshipLink CreateFriendship(Person p1, Person p2)
        {
            FriendshipLink f = new FriendshipLink(p1, p2, Random.value);
            Friendship f1 = new Friendship(p1, p2, f);
            Friendship f2 = new Friendship(p2, p1, f);
            f1.Other = f2;
            f2.Other = f1;

            p1.AddFriendship(f1);
            p2.AddFriendship(f2);

            return f;
        }
        public void BeginDestroy_WithValidUser_SetsParameter()
        {
            const string username = "******";
            var twitterClient = Substitute.For<IBaseTwitterClient>();
            twitterClient.When(a => a.BeginRequest(Arg.Any<string>(), Arg.Any<IDictionary<string, string>>(), Arg.Any<WebMethod>(), Arg.Any<RestCallback>()))
                         .Do(c => c.AssertParameter("screen_name", username));
            var friendships = new Friendship(twitterClient);

            GenericResponseDelegate endSearch = (a, b, c) => { };

            // act
            friendships.BeginDestroy(username, endSearch);
        }
        public void BeginDestroy_WithValidUserName_ReturnsValidUser()
        {
            var wasCalled = false;
            var twitterClient = Substitute.For<IBaseTwitterClient>();
            twitterClient.SetReponseBasedOnRequestPath();
            var friendships = new Friendship(twitterClient);

            // assert
            GenericResponseDelegate endCreate = (a, b, c) =>
            {
                wasCalled = true;
                var results = c as User;
                Assert.That(results, Is.Not.Null);
            };

            // act
            friendships.BeginDestroy("abcde", endCreate);

            Assert.That(wasCalled, Errors.CallbackDidNotFire);
        }
Beispiel #8
0
        /// <summary>
        /// 推送朋友關係
        /// </summary>
        /// <param name="fs">朋友關係</param>
        async Task PushFriendshipToClient(Friendship fs) {
            var fss = await this.DbContext.Users
                .Where(u => u.Id == fs.UserId || u.Id == fs.InviteeId)
                .Select(u => new FriendInfo {
                    Alias = u.Alias,
                    Id = u.Id,
                    MyReadTime = fs.UserId == u.Id ? fs.UserReadTime : fs.InviteeReadTime,
                    PersonalSign = u.PersonalSign,
                    PortraitUrl = u.Portrait.Filename,
                    ReadTime = fs.UserId == u.Id ? fs.InviteeReadTime : fs.UserReadTime,
                    Thumbnail = u.Portrait.Thumbnail,
                    UnreadMessageCount = 0,
                    UserName = u.UserName
                }).ToArrayAsync();

            foreach (var f in fss) {
                f.PortraitUrl = PortraitController.GenerateUrl(f.PortraitUrl);
                string id = f.Id == fs.UserId ? fs.InviteeId.ToString() : fs.UserId.ToString();
                this.HubContext.Clients.User(id).updateRelationship(f);
            }
        }
 public void ConfirmRequest(User sender, User receiver)
 {
     this._userValidator.Validate(sender);
     this._userValidator.Validate(receiver);
     try
     {
         ICollection<FriendshipRequest> friendshipRequests =
             sender.UserProfile.FriendshipRequests;
         FriendshipRequest request =
             friendshipRequests.FirstOrDefault(p => p.Receiver.Key.Equals(receiver.Key));
         if (request != null && sender.Key != receiver.Key)
         {
             var friendship = new Friendship(sender.UserProfile, receiver.UserProfile);
             this.UnitOfWork.Repository<Friendship, int>().Insert(friendship);
             request.IsConfirmed = true;
             this.UnitOfWork.Repository<FriendshipRequest, int>().Update(request);
             this.UnitOfWork.Save();
         }
     }
     catch (DbException ex)
     {
         throw new FriendshipServiceException(EntityValidationException.DefaultMessage, ex);
     }
 }
Beispiel #10
0
 public void NotifyFriendWasKilled(Friendship f)
 {
     //Debug.Log("I am " + id + " and my friend " + f.Friend.Id + " was killed");
     numAliveFriends--;
     numDeadFriends++;
     deadFriendsList.Add(f);
 }
Beispiel #11
0
 public void SendFriendshipRequestToClient(IReadOnlyList <IOnlineClient> clients, Friendship friend, bool isOwnRequest, bool isFriendOnline)
 {
 }
Beispiel #12
0
 public bool EmitFriendship(Friendship friendship) => Emit("friendship", friendship);
Beispiel #13
0
        protected void InitPuppetEventBridge(WechatyPuppet puppet)
        {
            _logger.LogInformation("init puppet event bridge");
            _ = puppet.OnDong(payload => EmitDong(payload.Data))
                .OnError(payload => EmitError(payload.Exception))
                .OnHeartbeat(payload => EmitHearbeat(payload.Data))
                .OnFriendship(async payload =>
            {
                var friendship = Friendship.Load(payload.FriendshipId);
                await friendship.Ready();
                _ = EmitFriendship(friendship);
                _ = friendship.Contact.Emit("friendship", friendship);
            })
                .OnLogin(async payload =>
            {
                var contact = ContactSelf.Load(payload.ContactId);
                await contact.Ready();
                _ = EmitLogin(contact);
            })
                .OnLogout(async payload =>
            {
                var contact = ContactSelf.Load(payload.ContactId);
                await contact.Ready();
                _ = EmitLogout(contact, payload.Data);
            })
                .OnMessage(async payload =>
            {
                var message = Message.Load(payload.MessageId);
                await message.Ready;
                _        = EmitMessage(message);
                var room = message.Room;
                if (room != null)
                {
                    _ = room.EmitMessage(message);
                }
            }).OnReady(payload =>
            {
                _ = Emit("ready");
                _readyState.IsOn = true;
            })
                .OnRoomInvite(payload =>
            {
                var roomInvitation = RoomInvitation.Load(payload.RoomInvitationId);
                _ = EmitRoomInvite(roomInvitation);
            })
                .OnRoomJoin(async payload =>
            {
                var room = Room.Load(payload.RoomId);
                await room.Sync();

                var inviteeList = payload
                                  .InviteeIdList
                                  .Select(Contact.Load)
                                  .ToList();
                await Task.WhenAll(inviteeList.Select(c => c.Ready()));

                var inviter = Contact.Load(payload.InviterId);
                await inviter.Ready();
                var date = payload.Timestamp.TimestampToDateTime();

                _ = EmitRoomJoin(room, inviteeList, inviter, date);
                _ = room.EmitJoin(inviteeList, inviter, date);
            })
                .OnRoomLeave(async payload =>
            {
                var room = Room.Load(payload.RoomId);
                await room.Sync();

                var leaverList = payload.RemoverIdList.Select(Contact.Load).ToList();
                await Task.WhenAll(leaverList.Select(c => c.Ready()));

                var remover = Contact.Load(payload.RemoverId);
                await remover.Ready();

                var date = payload.Timestamp.TimestampToDateTime();

                _ = EmitRoomLeave(room, leaverList, remover, date);
                _ = room.EmitLeave(leaverList, remover, date);

                var selftId = Puppet.SelfId;
                if (!string.IsNullOrEmpty(selftId) && payload.RemoverIdList.Contains(selftId))
                {
                    await Puppet.RoomPayloadDirty(payload.RoomId);
                    await Puppet.RoomMemberPayloadDirty(payload.RoomId);
                }
            }).OnRoomTopic(async payload =>
            {
                var room = Room.Load(payload.RoomId);
                await room.Sync();

                var changer = Contact.Load(payload.ChangerId);
                await changer.Ready();
                var date = payload.Timestamp.TimestampToDateTime();

                _ = EmitRoomTopic(room, payload.NewTopic, payload.OldTopic, changer, date);
            })
                .OnScan(payload => _ = EmitScan(payload.Data ?? "", payload.Status, payload.Data));
        }
Beispiel #14
0
 public ShoutBubble(int startTime, Friendship friendship)
 {
     this.startTime = startTime;
     this.endTime = startTime + (int) Utils.GetRandomValue(700, 250, 3);
     friends = friendship;
 }
        // DELETE: api/Friendship/5
        public void Delete(int Id)
        {
            Friendship friendship = this.repository.FindById(Id);

            this.repository.Delete(friendship);
        }
 // POST: api/Friendship
 public void Post([FromBody] Friendship value)
 {
     this.repository.Create(value);
 }
 // PUT: api/Friendship/5
 public void Put(int Id, [FromBody] Friendship value)
 {
     value.Id = Id;
     this.repository.Update(value);
 }
Beispiel #18
0
 /// <summary>Get parsed data about the friendship between a player and NPC.</summary>
 /// <param name="player">The player.</param>
 /// <param name="npc">The NPC.</param>
 /// <param name="friendship">The current friendship data.</param>
 public FriendshipModel GetFriendshipForVillager(Farmer player, NPC npc, Friendship friendship)
 {
     return(this.DataParser.GetFriendshipForVillager(player, npc, friendship, this.Metadata));
 }
Beispiel #19
0
        internal static void DoMarriage(Farmer player, string npcName, bool local)
        {
            Log.Debug(player.Name + " selected " + npcName + " (" + local + ")");
            foreach (var farmer in Game1.getAllFarmers())
            {
                if (farmer.spouse == npcName)
                {
                    return;
                }
            }

            // Prepare house
            if (local)
            {
                Utility.getHomeOfFarmer(player).moveObjectsForHouseUpgrade(1);
                Utility.getHomeOfFarmer(player).setMapForUpgradeLevel(1);
            }
            player.HouseUpgradeLevel = 1;
            Game1.removeFrontLayerForFarmBuildings();
            Game1.addNewFarmBuildingMaps();
            Utility.getHomeOfFarmer(player).RefreshFloorObjectNeighbors();

            // Do spouse stuff
            if (local)
            {
                if (!player.friendshipData.TryGetValue(npcName, out Friendship friendship))
                {
                    friendship = new Friendship();
                    player.friendshipData.Add(npcName, friendship);
                }

                friendship.Points      = 2500;
                player.spouse          = npcName;
                friendship.WeddingDate = new WorldDate(Game1.Date);
                friendship.Status      = FriendshipStatus.Married;
            }

            NPC spouse = Game1.getCharacterFromName(npcName);

            spouse.Schedule               = null;
            spouse.DefaultMap             = player.homeLocation.Value;
            spouse.DefaultPosition        = Utility.PointToVector2((Game1.getLocationFromName(player.homeLocation.Value) as FarmHouse).getSpouseBedSpot(player.spouse)) * Game1.tileSize;
            spouse.DefaultFacingDirection = 2;

            spouse.Schedule            = null;
            spouse.ignoreScheduleToday = true;
            spouse.shouldPlaySpousePatioAnimation.Value = false;
            spouse.controller          = null;
            spouse.temporaryController = null;
            if (local)
            {
                spouse.Dialogue.Clear();
            }
            spouse.currentMarriageDialogue.Clear();
            Game1.warpCharacter(spouse, "Farm", Utility.getHomeOfFarmer(player).getPorchStandingSpot());
            spouse.faceDirection(2);
            if (local)
            {
                if (Game1.content.LoadStringReturnNullIfNotFound("Strings\\StringsFromCSFiles:" + spouse.Name + "_AfterWedding") != null)
                {
                    spouse.addMarriageDialogue("Strings\\StringsFromCSFiles", spouse.Name + "_AfterWedding");
                }
                else
                {
                    spouse.addMarriageDialogue("Strings\\StringsFromCSFiles", "Game1.cs.2782");
                }

                Game1.addHUDMessage(new HUDMessage(Mod.Instance.Helper.Translation.Get("married")));
            }
        }
        public void SendFriendshipRequestToClient(IReadOnlyList <IOnlineClient> clients, Friendship friendship, bool isOwnRequest, bool isFriendOnline)
        {
            foreach (var client in clients)
            {
                var signalRClient = GetSignalRClientOrNull(client);
                if (signalRClient == null)
                {
                    return;
                }

                var friendshipRequest = friendship.MapTo <FriendDto>();
                friendshipRequest.IsOnline = isFriendOnline;

                signalRClient.getFriendshipRequest(friendshipRequest, isOwnRequest);
            }
        }
Beispiel #21
0
        private void UpdateFriendshipForLevelUp(PBEBattlePokemon pkmn)
        {
            PartyPokemon pp = SpritedParties[pkmn.Trainer.Id][pkmn].PartyPkmn;

            Friendship.AdjustFriendship(pkmn, pp, Friendship.Event.LevelUpBattle);
        }
Beispiel #22
0
        public async Task SendFriendshipRequestToClient(IReadOnlyList <IOnlineClient> clients, Friendship friendship, bool isOwnRequest, bool isFriendOnline)
        {
            foreach (var client in clients)
            {
                var signalRClient = GetSignalRClientOrNull(client);
                if (signalRClient == null)
                {
                    return;
                }

                var friendshipRequest = _objectMapper.Map <FriendDto>(friendship);
                friendshipRequest.IsOnline = isFriendOnline;

                await signalRClient.SendAsync("getFriendshipRequest", friendshipRequest, isOwnRequest);
            }
        }
Beispiel #23
0
        public string AreFriends()
        {
            AreFriendsParams actionParams = JavaScriptConvert.DeserializeObject <AreFriendsParams>(JsonParams);

            return(GetResult(Friendship.IsFriendshipExist(actionParams.UId1, actionParams.UId2) == IsFriendshipExistEnum.Exist));
        }
 public async Task SendFriendshipRequestToClient(IReadOnlyList <IOnlineClient> clients, Friendship friend, bool isOwnRequest, bool isFriendOnline)
 {
     await Task.CompletedTask;
 }
Beispiel #25
0
        public SuccessfullOperated<FriendshipResponseModel> RequestFriendship(FriendshipResponseModel model)
        {
            var successfullOperated = new SuccessfullOperated<FriendshipResponseModel>()
            {
                IsSuccessfull = false,
                Element = model
            };

            var firstUser = this.data.Users
                .All()
                .FirstOrDefault(f => f.Id == model.FirstUserId);

            if (firstUser == null)
            {
                return successfullOperated;
            }

            var secondUser = this.data.Users
               .All()
               .FirstOrDefault(f => f.Id == model.SecondUserId);

            if (secondUser == null)
            {
                return successfullOperated;
            }

            var friendshipForDb = new Friendship()
            {
                FirstUserId = model.FirstUserId,
                FirstUser = firstUser,
                SecondUserId = model.SecondUserId,
                SecondUser = secondUser,
                IsApproved = false,
                CreatedOn = DateTime.Now,
                ModifiedOn = DateTime.Now,
                IsDeleted = false,
                IsFirstUserSender = true
            };

            try
            {
                this.data.Friendships.Add(friendshipForDb);
                this.data.SaveChanges();

                successfullOperated.IsSuccessfull = true;

                return successfullOperated;
            }
            catch (Exception)
            {
                return successfullOperated;
            }
        }
Beispiel #26
0
 public async Task Add(Friendship friendship, CancellationToken cancellationToken = default)
 {
     await Context.Friendships.AddAsync(friendship, cancellationToken);
 }
Beispiel #27
0
        public static MsCrmResult CreateFriendship(Friendship friendship, IOrganizationService service)
        {
            MsCrmResult returnValue = new MsCrmResult();
            try
            {
                Entity ent = new Entity("new_friendship");

                ent["new_name"] = friendship.PartyOne.Name + "-" + friendship.PartyTwo.Name;

                if (friendship.PartyOne != null && friendship.PartyOne.Id != Guid.Empty)
                {
                    ent["new_partyoneid"] = friendship.PartyOne;
                }

                if (friendship.PartyTwo != null && friendship.PartyTwo.Id != Guid.Empty)
                {
                    ent["new_partytwoid"] = friendship.PartyTwo;
                }

                if (friendship.Portal != null && friendship.Portal.Id != Guid.Empty)
                {
                    ent["new_portalid"] = friendship.Portal;
                }

                if (friendship.FriendshipRequest != null && friendship.FriendshipRequest.Id != Guid.Empty)
                {
                    ent["new_friendshiprequestid"] = friendship.FriendshipRequest;
                }

                returnValue.CrmId = service.Create(ent);
                returnValue.Success = true;
                returnValue.Result = "M043"; //"Arkadaşlığınız başlamıştır.";
            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result = ex.Message;
            }
            return returnValue;
        }
Beispiel #28
0
 public static UserIdentifier ToUserIdentifier(this Friendship friendship)
 {
     return(new UserIdentifier(friendship.TenantId, friendship.UserId));
 }
 /// <summary>
 /// Given all param will define if has a Mutual FriendShip with param 'currentMember'
 /// </summary>
 /// <param name="friendship"></param>
 /// <param name="db"></param>
 /// <param name="currentMember"></param>
 public MutualFriendShip(Friendship friendship, ApplicationDbContext db, Member currentMember)
 {
     this.currentMember = currentMember;
     this.db = db;
     Friendship = friendship;
     DefineIfMutual();
 }
Beispiel #30
0
 public void AddFriendship(Friendship f)
 {
     friendsList.Add(f);
     numAliveFriends++;
     friendCount++;
 }
Beispiel #31
0
        public static unsafe void Main(string[] args)
        {
            TrinityConfig.CurrentRunningMode = RunningMode.Embedded;

            // Characters
            Character Rachel = new Character(Name: "Rachel Green", Gender: 0, Married: true);
            Character Monica = new Character(Name: "Monica Geller", Gender: 0, Married: true);
            Character Phoebe = new Character(Name: "Phoebe Buffay", Gender: 0, Married: true);
            Character Joey = new Character(Name: "Joey Tribbiani", Gender: 1, Married: false);
            Character Chandler = new Character(Name: "Chandler Bing", Gender: 1, Married: true);
            Character Ross = new Character(Name: "Ross Geller", Gender: 1, Married: true);

            // Performers
            Performer Jennifer = new Performer(Name: "Jennifer Aniston", Age: 43, Characters: new List<long>());
            Performer Courteney = new Performer(Name: "Courteney Cox", Age: 43, Characters: new List<long>());
            Performer Lisa = new Performer(Name: "Lisa Kudrow", Age: 43, Characters: new List<long>());
            Performer Matt = new Performer(Name: "Matt Le Blanc", Age: 43, Characters: new List<long>());
            Performer Matthew = new Performer(Name: "Matthew Perry", Age: 43, Characters: new List<long>());
            Performer David = new Performer(Name: "David Schwimmer", Age: 43, Characters: new List<long>());

            // Portrayal Relationship
            Rachel.Performer = Jennifer.CellID;
            Jennifer.Characters.Add(Rachel.CellID);

            Monica.Performer = Courteney.CellID;
            Courteney.Characters.Add(Monica.CellID);

            Phoebe.Performer = Lisa.CellID;
            Lisa.Characters.Add(Phoebe.CellID);

            Joey.Performer = Matt.CellID;
            Matt.Characters.Add(Joey.CellID);

            Chandler.Performer = Matthew.CellID;
            Matthew.Characters.Add(Chandler.CellID);

            Ross.Performer = David.CellID;
            David.Characters.Add(Ross.CellID);

            // Marriage relationship
            Monica.Spouse = Chandler.CellID;
            Chandler.Spouse = Monica.CellID;

            Rachel.Spouse = Ross.CellID;
            Ross.Spouse = Rachel.CellID;

            // Friendship
            Friendship friend_ship = new Friendship(new List<long>());
            friend_ship.friends.Add(Rachel.CellID);
            friend_ship.friends.Add(Monica.CellID);
            friend_ship.friends.Add(Phoebe.CellID);
            friend_ship.friends.Add(Joey.CellID);
            friend_ship.friends.Add(Chandler.CellID);
            friend_ship.friends.Add(Ross.CellID);

            // Save Runtime cells to Trinity memory storage
            Global.LocalStorage.SavePerformer(Jennifer);
            Global.LocalStorage.SavePerformer(Courteney);
            Global.LocalStorage.SavePerformer(Lisa);
            Global.LocalStorage.SavePerformer(Matt);
            Global.LocalStorage.SavePerformer(Matthew);
            Global.LocalStorage.SavePerformer(David);

            Global.LocalStorage.SaveCharacter(Rachel);
            Global.LocalStorage.SaveCharacter(Monica);
            Global.LocalStorage.SaveCharacter(Phoebe);
            Global.LocalStorage.SaveCharacter(Joey);
            Global.LocalStorage.SaveCharacter(Chandler);
            Global.LocalStorage.SaveCharacter(Ross);

            // Dump memory storage to disk for persistence
            Global.LocalStorage.SaveStorage();

            long spouse_id = -1;

            using (var cm = Global.LocalStorage.UseCharacter(Monica.CellID))
            {
                if (cm.Married)
                    spouse_id = cm.Spouse;
            }

            using (var cm = Global.LocalStorage.UseCharacter(spouse_id))
            {
                Console.WriteLine(cm.Name);
            }
        }
Beispiel #32
0
        public void NoticeDeath(Friendship f)
        {
            int deathTime = GameLevel.GameTime;
            int sinceLastDeath = numDeadFriends == 0 ? int.MaxValue/2 : deathTime - lastFriendDeath;

            float strategyOutput = Strategy.GetAwarenessChange(numDeadFriends, numAliveFriends, sinceLastDeath);

            AwarenessLevel = Mathf.Min(AwarenessLevel + strategyOutput, 1f);

            if (Random.value < 0.2f)
            {
                CurrentStatus = new ShoutBubble(GameLevel.GameTime, f);
            }

            //Debug.Log("I am " + id + " and I know my friend " + f.Friend.Id + " was killed.. " + strategyOutput);
        }
Beispiel #33
0
        public MsCrmResult CloseFriendshipRequest(string token, string requestId, int statusCode)
        {
            MsCrmResult returnValue = new MsCrmResult();
            LoginSession ls = new LoginSession();

            try
            {
                if (!string.IsNullOrEmpty(token))
                {
                    #region | CHECK SESSION |
                    MsCrmResultObject sessionResult = GetUserSession(token);

                    if (!sessionResult.Success)
                    {
                        returnValue.Result = sessionResult.Result;
                        return returnValue;
                    }
                    else
                    {
                        ls = (LoginSession)sessionResult.ReturnObject;
                    }

                    #endregion

                    sda = new SqlDataAccess();
                    sda.openConnection(Globals.ConnectionString);

                    IOrganizationService service = MSCRM.GetOrgService(true);

                    returnValue = FriendshipHelper.CloseFriendshipRequest(new Guid(requestId), (FriendshipRequestStatus)statusCode, service);

                    if (returnValue.Success)
                    {
                        FriendshipRequest req = new FriendshipRequest();
                        MsCrmResultObject reqResult = FriendshipHelper.GetFriendshipRequestInfo(new Guid(requestId), sda);

                        if (reqResult.Success && ((FriendshipRequestStatus)statusCode) == FriendshipRequestStatus.Accepted)
                        {
                            req = (FriendshipRequest)reqResult.ReturnObject;

                            Friendship fr = new Friendship();
                            fr.PartyOne = req.From;
                            fr.PartyTwo = req.To;
                            fr.Portal = req.Portal;
                            fr.FriendshipRequest = new EntityReference("new_friendshiprequest", req.Id);

                            returnValue = FriendshipHelper.CreateFriendship(fr, service);
                        }
                    }
                }
                else
                {
                    returnValue.Success = false;
                    returnValue.Result = "M003"; //"Eksik parametre!-CloseFriendshipRequest";
                }

            }
            catch (Exception ex)
            {
                returnValue.Success = false;
                returnValue.Result = ex.Message;
            }
            finally
            {
                if (sda != null)
                    sda.closeConnection();
            }
            return returnValue;
        }
Beispiel #34
0
        //確認好友、修改好友暱稱(checkFD來判別為確認好友或修改暱稱)
        public IHttpActionResult Put(string FriendID, string memID, string newNick, bool checkFD)
        {
            //確認好友
            if (checkFD)
            {
                //新增資料至friendship資料表
                var FDdata1 = db.Friendship.Where(m => m.memId == memID && m.friendMemId == FriendID).FirstOrDefault();
                var FDdata2 = db.Friendship.Where(m => m.memId == FriendID && m.friendMemId == memID).FirstOrDefault();
                if (FDdata1 == null)
                {
                    Friendship friend1 = new Friendship();
                    friend1.memId       = memID;
                    friend1.friendMemId = FriendID;
                    db.Friendship.Add(friend1);
                    db.SaveChanges();
                }
                if (FDdata2 == null)
                {
                    Friendship friend2 = new Friendship();
                    friend2.memId       = FriendID;
                    friend2.friendMemId = memID;
                    db.Friendship.Add(friend2);
                    db.SaveChanges();
                }

                //修改FriendShip資料表中的approved欄位
                var editFD1 = db.Friendship.Where(m => m.memId == memID && m.friendMemId == FriendID).FirstOrDefault();
                var editFD2 = db.Friendship.Where(m => m.memId == FriendID && m.friendMemId == memID).FirstOrDefault();
                editFD1.Approved = true;
                editFD2.Approved = true;
                //若成為好友前尚未為粉絲或追蹤關係時,新增粉絲及追蹤關係
                Fans     fan    = new Fans();
                FollowUp follow = new FollowUp();

                var fan1      = db.Fans.Where(m => m.memId == FriendID && m.fanMemId == memID).FirstOrDefault();
                var fan2      = db.Fans.Where(m => m.memId == memID && m.fanMemId == FriendID).FirstOrDefault();
                var followUp1 = db.FollowUp.Where(m => m.memId == FriendID && m.FoMemId == memID).FirstOrDefault();
                var followUp2 = db.FollowUp.Where(m => m.memId == memID && m.FoMemId == FriendID).FirstOrDefault();
                if (fan1 == null && fan2 == null && followUp1 == null && followUp2 == null)
                {
                    //新增fans資料表中雙方資料
                    fan.fanMemId = memID;
                    fan.memId    = FriendID;
                    db.Fans.Add(fan);
                    db.SaveChanges();

                    Fans fan3 = new Fans();
                    fan3.fanMemId = FriendID;
                    fan3.memId    = memID;
                    db.Fans.Add(fan3);
                    db.SaveChanges();
                    //新增followup資料表中雙方資料
                    follow.FoMemId = memID;
                    follow.memId   = FriendID;
                    db.FollowUp.Add(follow);
                    db.SaveChanges();

                    FollowUp follow3 = new FollowUp();
                    follow3.FoMemId = FriendID;
                    follow3.memId   = memID;
                    db.FollowUp.Add(follow3);
                    db.SaveChanges();
                }
                //當A已追蹤B時,新增B方資料至fans及followup資料表中
                else if (fan1 == null && fan2 != null && followUp1 == null && followUp2 != null)
                {
                    //新增B方資料至fans資料表
                    Fans fan4 = new Fans();
                    fan4.fanMemId = memID;
                    fan4.memId    = FriendID;
                    db.Fans.Add(fan4);
                    //新增B方資料至followup資料表
                    FollowUp follow4 = new FollowUp();
                    follow4.FoMemId = memID;
                    follow4.memId   = FriendID;
                    db.FollowUp.Add(follow4);
                }
                //當B已追蹤A時,新增A方資料至fans及followup資料表中
                else if (fan1 != null && fan2 == null && followUp1 != null && followUp2 == null)
                {
                    //新增A方資料至fans資料表
                    Fans fan5 = new Fans();
                    fan5.fanMemId = FriendID;
                    fan5.memId    = memID;
                    db.Fans.Add(fan5);

                    //新增A方資料至followup資料表
                    FollowUp follow5 = new FollowUp();
                    follow5.FoMemId = FriendID;
                    follow5.memId   = memID;
                    db.FollowUp.Add(follow5);
                }
                //確認好友後寄送通知
                Common com = new Common();
                var    M1  = db.Member.Find(FriendID).memNick;
                var    M2  = db.Member.Find(memID).memNick;
                com.CreateNoti(true, "", memID, "您已和" + M1 + "成為好友", "恭喜您和<a href = '/Member/Info?memID=" + memID + "'>" + M1 + "</a>成為好友<br />Join Fun營運團隊");
                com.CreateNoti(true, "", FriendID, "您已和" + M2 + "成為好友", "恭喜您和<a href = '/Member/Info?memID=" + memID + "'>" + M2 + "</a>成為好友<br />Join Fun營運團隊");
            }
            //已為好友關係,僅修改好友暱稱
            else
            {
                var FDdata1 = db.Friendship.Where(m => m.memId == memID && m.friendMemId == FriendID).FirstOrDefault();
                FDdata1.friendNick = newNick;
            }
            db.SaveChanges();
            return(Ok());
        }
Beispiel #35
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LB_Next_Click(object sender, EventArgs e)
        {
            if (TxtEmail.Text.Length == 0)
            {
                return;
            }

            CY.UME.Core.Business.SystemLog.SaveLog("Info", "注册开始");

            if (Session["CaptchaImageText"] == null)// 验证码
            {
                ShowAlert("注册失败", "服务器忙,请稍后再试!");
                return;
            }

            string validateCode = Session["CaptchaImageText"].ToString();

            if (TxtValidCode.Text != validateCode)
            {
                ShowAlert("注册失败", "验证码错误!");
                return;
            }
            if (string.IsNullOrEmpty(TxtSudentCode.Text))
            {
                ShowAlert("注册失败", "学号不能为空");
                return;
            }
            if (string.IsNullOrEmpty(TxtUserName.Text))
            {
                ShowAlert("注册失败", "姓名不能为空");
                return;
            }
            if (TxtUserPassword.Text.Length < 6 ||
                TxtUserPassword.Text.Length > 20)
            {
                ShowAlert("注册失败", "密码长度必须在6至20之间");
                return;
            }
            String ZipRegex = @"/^\w{0,19}$/";
            if (System.Text.RegularExpressions.Regex.IsMatch(TxtUserPassword.Text, ZipRegex))
            {
                ShowAlert("注册失败", "密码含有非法字符,只能输入数字、字母和\"_\"的组合。");
                return;
            }
            if (String.Compare(TxtUserPassword.Text.Trim(), TxtUserPasswordAgain.Text.Trim()) != 0)
            {
                ShowAlert("注册失败", "两次密码输入不一致,请重新输入。");
                return;
            }
            if (!RBGenderFemale.Checked && !RBGenderMale.Checked)
            {
                ShowAlert("注册失败", "性别不能为空");
                return;
            }

            if (YearHF.Value == "0" && MonthHF.Value == "0" && DayHF.Value == "0")
            {
                ;
            }
            else if (YearHF.Value == "0" || MonthHF.Value == "0" || DayHF.Value == "0")
            {
                ShowAlert("提示", "请完善您的生日信息!");
                return;
            }

            CY.UME.Core.Business.AccountExtend aeTemp = CY.UME.Core.Business.AccountExtend.Load(TxtEmail.Text.Trim());
            if (aeTemp != null)
            {
                ShowAlert("提示", "该邮箱已被使用!");
                return;
            }

            CY.Security.SecurityHelper sh = new CY.Security.SecurityHelper();

            CY.UME.Core.Business.Account account = new CY.UME.Core.Business.Account();
            account.Code = TxtSudentCode.Text;
            account.DateCreated = DateTime.Now;
            account.HasAvatar = false;
            account.IsTeacher = false;
            account.Name = TxtUserName.Text;
            account.NickName = string.Empty;
            account.ViewNumber = 0;
            account.Save();

            // extend info
            CY.UME.Core.Business.AccountExtend ae = CY.UME.Core.Business.AccountExtend.Load(account.Id);

            if (YearHF.Value == "0" && MonthHF.Value == "0" && DayHF.Value == "0")
            {
                ae.Birthday = UME.Core.Global.MinDateTime;
            }
            else
            {
                int day = 0, month = 0, year = 0;
                if (int.TryParse(DayHF.Value, out day))
                    ae.BirthDate = day;
                if (int.TryParse(MonthHF.Value, out month))
                    ae.BirthMonth = month;
                if (int.TryParse(YearHF.Value, out year))
                    ae.BirthYear = year;

                ae.Birthday = new DateTime(year, month, day);//生日
            }
            ae.Email = TxtEmail.Text.Trim();
            ae.Gender = RBGenderMale.Checked ? 1 : 0;
            ae.IsEmailChecked = true;
            //ae.LibUserId = 0;
            ae.Password = sh.ComputeMD5Hash(TxtUserPassword.Text);
            ae.UniversityId = CY.Utility.Common.ConvertUtility.ConvertToInt(HFUniversity.Value, -1);// 学校
            ae.CollegeId = CY.Utility.Common.ConvertUtility.ConvertToInt(HFCollege.Value, -1);// 学院
            ae.GradeId = int.Parse(DDLGrades.SelectedValue);
            ae.IsShow = 0;
            ae.Save();

            try
            {
                /**************************************************废除的代码/*************************************************/
                /************************MySQL数据库同步开始*************************
                CY.UME.Core.Business.Ask_members members = new CY.UME.Core.Business.Ask_members();
                members.Id = account.Id;
                members.Username = ae.Email;
                members.Password = ae.Password;
                //members.Secques = "";
                members.Save();

                CY.UME.Core.Business.Ask_memberfields memberfields = new CY.UME.Core.Business.Ask_memberfields();
                memberfields.Id = account.Id;
                memberfields.Username = ae.Email;
                memberfields.Email = ae.Email;
                memberfields.Nickname = account.NickName;
                memberfields.Realname = account.Name;//HFURLEncodeName.Value;
                memberfields.Gender = ae.Gender;
                memberfields.Birthday = 0;
                memberfields.Score = 200;//后面去改
                memberfields.Save();
                /************************MySQL数据库同步结束*************************/
            }
            catch (Exception ex)
            {
                CY.UME.Core.Business.SystemLog.SaveLog("Error", "用户同步失败:" + ex.Message);
            }

            CY.UME.Core.Business.SystemLog.SaveLog("Info", account.Name + "注册成功");

            if (Session["user"] != null)
            {
                Session["user"] = account.Id.ToString();
            }
            else
            {
                Session.Add("user", account.Id.ToString());
            }
            try
            {
                if (!string.IsNullOrEmpty(Request.QueryString["inviterId"]))
                {
                    long inviterId = CY.Utility.Common.ConvertUtility.ConvertToLong(Request.QueryString["inviterId"], -1);

                    if (inviterId != -1)
                    {
                        Core.Business.Account InviteFriendAccount = Core.Business.Account.Load(inviterId);

                        if (InviteFriendAccount != null)
                        {//邀请用户须存在
                            AccountInviteInfo ai = new AccountInviteInfo();
                            ai.Id = Guid.NewGuid();
                            ai.InviterId = inviterId;
                            ai.InviteeEmail = ae.Email;
                            ai.DateCreated = account.DateCreated;
                            ai.IsAccepted = true;
                            ai.Remark = "从活动过来的";
                            ai.Save();

                            CY.UME.Core.Business.Friendship fs = new Friendship();

                            fs.AccountId = account.Id;
                            fs.DateCreated = DateTime.Now;
                            fs.FriendId = InviteFriendAccount.Id;
                            fs.IsChecked = true;
                            fs.Remark = "活动邀请";
                            fs.Save();

                            CY.UME.Core.Business.Friendship fs2 = new Friendship();

                            fs2.AccountId = InviteFriendAccount.Id;
                            fs2.FriendId = account.Id;
                            fs2.DateCreated = DateTime.Now;
                            fs2.IsChecked = true;
                            fs2.Remark = "活动邀请";
                            fs2.Save();
                        }
                    }
                }
                if (!string.IsNullOrEmpty(Request.QueryString["invId"]))
                {
                    long invId = CY.Utility.Common.ConvertUtility.ConvertToLong(Request.QueryString["invId"], -1);

                    if (invId != -1)
                    {
                        Core.Business.AccountInviteInfo InviteAccount = new AccountInviteInfo();
                        InviteAccount.Id = Guid.NewGuid();
                        InviteAccount.InviterId = invId;
                        InviteAccount.DateCreated = DateTime.Now;
                        InviteAccount.InviteeEmail = ae.Email;
                        InviteAccount.IsAccepted = true;
                        InviteAccount.Save();

                        #region 更新邀请人的积分

                        int inviteFriendCredit;
                        if (CY.UME.Core.Business.SystemSetting.TryLoadInt32Setting("CreditInviteAccount", out inviteFriendCredit) &&
                            (inviteFriendCredit != 0))
                        {
                            CY.UME.Core.Business.Account invitor = CY.UME.Core.Business.Account.Load(invId);
                            if (invitor != null)
                            {
                                CY.UME.Core.Business.Friendship fs = new Friendship();

                                fs.AccountId = account.Id;
                                fs.DateCreated = DateTime.Now;
                                fs.FriendId = invitor.Id;
                                fs.IsChecked = true;
                                fs.Remark = "被链接邀请";
                                fs.Save();

                                CY.UME.Core.Business.Friendship fs2 = new Friendship();

                                fs2.AccountId = invitor.Id;
                                fs2.FriendId = account.Id;
                                fs2.DateCreated = DateTime.Now;
                                fs2.IsChecked = true;
                                fs2.Remark = "链接邀请";
                                fs2.Save();

                                int orgCredit = invitor.Credit;
                                int modifiedCredit = orgCredit + inviteFriendCredit;

                                invitor.Credit = modifiedCredit;
                                invitor.Save();

                                CreditHistory ch = new CreditHistory();
                                ch.AccountId = invitor.Id;
                                ch.DateCreated = DateTime.Now;
                                ch.Id = Guid.NewGuid();
                                ch.InstanceId = invId.ToString();
                                ch.Original = orgCredit;
                                ch.Modified = modifiedCredit;
                                ch.Variation = inviteFriendCredit;
                                ch.Type = "invitefriend";
                                ch.Description = "成功邀请用户 " + account.Name;
                                ch.AssistAccountId = account.Id;
                                ch.Save();

                                // 邀请层级效应
                                CY.UME.Core.Business.Account invitor2 = invitor.GetInviter();
                                if (invitor2 != null)
                                {
                                    int inviteFriendCredit2;
                                    if (CY.UME.Core.Business.SystemSetting.TryLoadInt32Setting("CreditInviteAccount2", out inviteFriendCredit2) &&
                                        (inviteFriendCredit2 != 0))
                                    {
                                        orgCredit = invitor2.Credit;
                                        modifiedCredit = orgCredit + inviteFriendCredit2;
                                        invitor2.Credit = modifiedCredit;
                                        invitor2.Save();

                                        ch = new CreditHistory();
                                        ch.AccountId = invitor2.Id;
                                        ch.DateCreated = DateTime.Now;
                                        ch.Id = Guid.NewGuid();
                                        ch.InstanceId = invId.ToString();
                                        ch.Original = orgCredit;
                                        ch.Modified = modifiedCredit;
                                        ch.Variation = inviteFriendCredit2;
                                        ch.Type = "invitefriend";
                                        ch.Description = "所邀请用户 " + invitor.Name + " 成功邀请了 " + account.Name;
                                        ch.Save();
                                    }
                                }
                            }
                        }

                        #endregion
                    }
                }

            }
            catch (Exception)
            { }

            //ShowAlert("注册成功", "恭喜您已经成功注册UME账号,现在系统将引导您至完善个人信息页面");
            //ExecuteClientScript("setTimeout(function(){window.location.href='UploadAvatar.aspx?type=firstNum'}, 1000)")
            SaveAccountCookie(TxtEmail.Text.Trim(), sh.ComputeMD5Hash(TxtUserPassword.Text));//保存Cookie用于问问吧登录
            Server.Transfer("UploadAvatar.aspx?type=firstNum");
        }
Beispiel #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FriendshipRemovedDomainEvent"/> class.
 /// </summary>
 /// <param name="friendship">The friendship.</param>
 internal FriendshipRemovedDomainEvent(Friendship friendship) => Friendship = friendship;