예제 #1
0
        public static InviteStatus IsValidInvite(Invitation newInvitation)
        {
            if (HasPendingAnswers(newInvitation.From))
            {
                return new InviteStatus { Message = "You can not send another invite until you answer all your pending invites or they expire.", StatusType = InviteStatusType.Invalid };
            }

            if (HasPendingInvites(newInvitation.From))
            {
                return new InviteStatus { Message = "You can not send another invite until all your pending invites send are answered or expire.", StatusType = InviteStatusType.Invalid };
            }

            if (!_invitations.Contains(newInvitation))
            {
                newInvitation.SentDate = DateTime.Now;
                _invitations.Add(newInvitation);
                return new InviteStatus { Message = "Invite was added successfully.", StatusType = InviteStatusType.Valid };
            }
            else
            {
                Invitation first = null;
                _invitations.TryTake(out first);
                if (first != null && newInvitation.IsValidInvitation(first))
                {
                    _invitations.Add(newInvitation);
                    return new InviteStatus { Message = "Invite was added successfully.", StatusType = InviteStatusType.Valid };
                }
                else
                {
                    _invitations.Add(first);
                    return new InviteStatus { Message = "Invite already sent. You must wait 5 minutes before sending another one.", StatusType = InviteStatusType.Invalid }; ;
                }
            }
        }
 protected void OnGotInvitation(Invitation invitation, bool shouldAutoAccept) {
     if (invitation.InvitationType != Invitation.InvType.TurnBased) {
         // wrong type of invitation!
         return;
     }
     mInMatch = true;
     gameObject.GetComponent<MainMenuGui>().HandleInvitation(invitation, shouldAutoAccept);
 }
예제 #3
0
        public static Invitation GetInvitationByInvitationId(Guid invitationId)
        {
            if (invitationId == Guid.Empty) return null;

            //deep copy
            Invitation invitation = new Invitation(_invitations.Where(i => i.InviteId == invitationId).FirstOrDefault());

            return invitation;
        }
예제 #4
0
        public ActionResult Create(FormCollection input)
        {
            InviteModel invite = new InviteModel();
            UpdateModel(invite, "InviteModel");
            if (ModelState.IsValid)
            {
                //If a user is already registered with this email
                //let them enroll themselves
                if (UserHelpers.IsEmailRegistered(invite.Email))
                {
                    FlashMessageHelper.AddMessage(string.Format(@"""{0}"" is already registered.", invite.Email));
                    return RedirectToAction("Index", new { siteShortName = site.ShortName });
                }
                Invitation inv = new Invitation();
                try
                {
                    inv = new Invitation()
                    {
                        Accepted = false,
                        CourseTermAccessLevel = (byte?)invite.CourseTermAccessLevel,
                        CourseTermID = (Guid?)invite.CourseTermID,
                        Email = invite.Email,
                        Site = site,
                        SiteAccessLevel = (byte)invite.SiteAccessLevel
                    };

                    site.Invitations.Add(inv);
                    dataRepository.Save();
                    if (!inv.CourseTermID.HasValue)
                    {
                        EmailHelper.SendInvitationEmail(inv.Email, site.Title, inv.InvitationID);
                    }
                    else
                    {
                        CourseTerm ct = dataRepository.GetCourseTermByID(inv.CourseTermID.Value);
                        //If the CourseTerm can't be found, an exception should be raised when we try to save
                        //the Invitation
                        EmailHelper.SendInvitationEmail(inv.Email, site.Title, ct.Name, inv.InvitationID);

                    }
                    FlashMessageHelper.AddMessage("Invite created successfully.");
                    return RedirectToAction("Index", new { siteShortName = site.ShortName });
                }
                catch (RuleViolationException)
                {
                    ModelState.AddModelErrors(inv.GetRuleViolations());
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("_FORM", ex);
                }
            }
            IEnumerable<CourseTerm> courseTerms = dataRepository.GetAllCourseTerms(site);
            invite.SetCourseTermList(courseTerms);
            return View(invite);
        }
예제 #5
0
		public void Ctor()
		{
			const string id = "identity";
			var group = new Group (1);
			var person = new Person ("persno");
			var invitation = new Invitation (group, person, InvitationResponse.Accepted);

			Assert.AreEqual (InvitationResponse.Accepted, invitation.Response);
			Assert.AreSame (group, invitation.Group);
			Assert.AreSame (person, invitation.Person);
		}
예제 #6
0
 public static Game CreateGame(Invitation invite)
 {
     Game result = null;
     if (invite != null)
     {
         if (invite.From != null && invite.To != null)
         {
             result = new Game(invite.From, invite.To);
             _games.TryAdd(result.GameId, result);
         }
     }
     return result;
 }
		public object Deserialize(JsonValue json, JsonMapper mapper)
		{
			Invitation invite = null;
			if ( json != null && !json.IsNull )
			{
				invite = new Invitation();
				invite.EventId    = json.ContainsName("id"        ) ? json.GetValue<string>("id"  ) : String.Empty;
				invite.Name       = json.ContainsName("name"      ) ? json.GetValue<string>("name") : String.Empty;
				invite.StartTime  = json.ContainsName("start_time") ? JsonUtils.ToDateTime(json.GetValue<string>("start_time"), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;
				invite.EndTime    = json.ContainsName("end_time"  ) ? JsonUtils.ToDateTime(json.GetValue<string>("end_time"  ), "yyyy-MM-ddTHH:mm:ss") : DateTime.MinValue;
				invite.RsvpStatus = RsvpStatusDeserializer(json.GetValue("rsvp_status"));
			}
			return invite;
		}
        public int Add(Invitation invitationData)
        {
            var invitation = new Invitation()
            {
                Email = invitationData.Email,
                VerificationToken = invitationData.VerificationToken,
                DecryptionKey = invitationData.DecryptionKey,
                InitializationVector = invitationData.InitializationVector,
            };

            this.invitations.Add(invitation);
            this.invitations.SaveChanges();

            return invitation.ID;
        }
    protected void OnGotInvitation(Invitation invitation, bool shouldAutoAccept) {
    	if (invitation.InvitationType != Invitation.InvType.TurnBased) {
    		// wrong type of invitation!
    		return;
    	}
    	
    	if (shouldAutoAccept) {
			// if shouldAutoAccept is true, we know the user has indicated (via an external UI)
			// that they wish to accept this invitation right now, so we take the user to the
			// game screen without further delay:
			SetStandBy("Accepting invitation...");
    		PlayGamesPlatform.Instance.TurnBased.AcceptInvitation(invitation.InvitationId, OnMatchStarted);
    	} else {
    		// if shouldAutoAccept is false, we got this invitation in the background, so
    		// we should not jump directly into the game
    		mIncomingInvite = invitation;
    	}
    }
예제 #10
0
        public void Invitation_CreateGameFromInvite_CreatesANewValidObject()
        {
            //Arrange
            Guid id = Guid.Parse("A499F757-C538-4559-A156-5D658BDEC0F3");
            Player p1 = new Player("Alex", "9C6109F9-5320-4411-9D1C-FA13D1CEC544", string.Empty);
            Player p2 = new Player("Bogdan", "3D072B37-0937-43EB-A77F-137B4DD08E03", string.Empty);
            DateTime dateTime = new DateTime(2012, 12, 9, 10, 0, 0);
            Invitation invite = new Invitation(id, p1, p2, dateTime);
            Game gameToTest = null;

            //Act
            gameToTest = invite.CreateGameFromInvite();

            //Assert
            Assert.IsNotNull(gameToTest.GameId);
            Assert.AreEqual(p1, gameToTest.Player1);
            Assert.AreEqual(p2, gameToTest.Player2);
        }
예제 #11
0
    // Update is called once per frame
    void Update()
    {
        inv = (inv != null) ? inv : InvitationManager.Instance.Invitation;
        if (inv == null && !processed)
        {
          //  Debug.Log("No Invite -- back to main");
            NavigationUtil.ShowMainMenu();
            return;
        }

        if (inviterName == null)
        {
            inviterName = (inv.Inviter == null || inv.Inviter.DisplayName == null) ? "Someone" :
            inv.Inviter.DisplayName;
            message.text = inviterName + " is challenging you to Reverso!";
        }

        if (ReversoGooglePlay.Instance != null)
        {
            ReversoGooglePlay.Instance.OpponentName = (inv.Inviter == null || inv.Inviter.DisplayName == null) ? "" : inv.Inviter.DisplayName;
            switch (ReversoGooglePlay.Instance.State)
            {
                case ReversoGooglePlay.GameState.Aborted:
                    Debug.Log("Aborted -- back to main");
                  //  NavigationUtil.ShowMainMenu();
                    break;
                case ReversoGooglePlay.GameState.Finished:
                    Debug.Log("Finished-- back to main");
                //    NavigationUtil.ShowMainMenu();
                    break;
                case ReversoGooglePlay.GameState.Playing:
                 //   NavigationUtil.ShowPlayingPanel();
                    break;
                case ReversoGooglePlay.GameState.SettingUp:
              //      message.text = "Setting up Race...";
                    break;
                case ReversoGooglePlay.GameState.SetupFailed:
                    Debug.Log("Failed -- back to main");
               //     NavigationUtil.ShowMainMenu();
                    break;
            }
        }
    }
예제 #12
0
        public void Invitation_DeepCopyConstructor_ReturnsSameObjectDiffrentReference()
        {
            //Arrange
            Guid id = Guid.Parse("A499F757-C538-4559-A156-5D658BDEC0F3");
            Player p1 = null;
            Player p2 = null;
            DateTime dateTime = DateTime.MinValue;
            Invitation first = new Invitation(id, p1, p2, dateTime);

            //Act
            Invitation other = new Invitation(first);

            //Arrage
            Assert.AreEqual<Guid>(first.InviteId, other.InviteId);
            Assert.AreEqual<DateTime>(first.SentDate, other.SentDate);
            Assert.AreEqual(first.From, other.From);
            Assert.AreEqual(first.To, other.To);

            Assert.AreNotSame(first, other);
        }
예제 #13
0
        public void Invitation_Equals_CheckIEquitableImplemenetationIgnoresReferenceEquals()
        {
            //Act
            Invitation first = new Invitation();
            Invitation second = new Invitation();
            Player p1 = new Player("Alex", "9C6109F9-5320-4411-9D1C-FA13D1CEC544", string.Empty);
            Player p2 = new Player("Alex", "9C6109F9-5320-4411-9D1C-FA13D1CEC544", string.Empty);

            //Arrange
            first.From = p1;
            first.To = p2;
            first.SentDate = new DateTime(2012, 12, 9, 10, 0, 0);

            second.From = p1;
            second.To = p2;
            second.SentDate = new DateTime(2012, 12, 9, 10, 0, 0);

            //Assert
            Assert.IsTrue(first.Equals(second));
        }
 public async Task <int> Add(Invitation invite)
 {
     _dbContext.Invitations.Add(invite);
     return(await _dbContext.SaveChangesAsync());
 }
예제 #15
0
        protected override void ShowPage()
        {
            pagetitle = "用户注册";

            if (userid != -1)
            {
                SetUrl(BaseConfigs.GetForumPath);
                SetMetaRefresh();
                SetShowBackLink(false);
                AddMsgLine("不能重复注册用户");
                ispost     = true;
                createuser = "******";
                agree      = "yes";
                return;
            }


            if (config.Regstatus < 1)
            {
                AddErrLine("论坛当前禁止新用户注册");
                return;
            }

            allowinvite = Utils.InArray(config.Regstatus.ToString(), "2,3");

            #region 用户IP判断
            string msg = Users.CheckRegisterDateDiff(DNTRequest.GetIP());
            if (msg != null)
            {
                AddErrLine(msg);
                return;
            }
            //if (config.Regctrl > 0)
            //{
            //    ShortUserInfo userinfo = Users.GetShortUserInfoByIP(DNTRequest.GetIP());
            //    if (userinfo != null)
            //    {
            //        int Interval = Utils.StrDateDiffHours(userinfo.Joindate, config.Regctrl);
            //        if (Interval <= 0)
            //        {
            //            AddErrLine("抱歉, 系统设置了IP注册间隔限制, 您必须在 " + (Interval * -1) + " 小时后才可以注册");
            //            return;
            //        }
            //    }
            //}

            //if (config.Ipregctrl.Trim() != "")
            //{
            //    string[] regctrl = Utils.SplitString(config.Ipregctrl, "\n");
            //    if (Utils.InIPArray(DNTRequest.GetIP(), regctrl))
            //    {
            //        ShortUserInfo userinfo = Users.GetShortUserInfoByIP(DNTRequest.GetIP());
            //        if (userinfo != null)
            //        {
            //            int Interval = Utils.StrDateDiffHours(userinfo.Joindate, 72);
            //            if (Interval < 0)
            //            {
            //                AddErrLine("抱歉, 系统设置了特殊IP注册限制, 您必须在 " + (Interval * -1) + " 小时后才可以注册");
            //                return;
            //            }
            //        }
            //    }
            //}
            #endregion

            //如果提交了用户注册信息...
            if (!Utils.StrIsNullOrEmpty(createuser) && ispost)
            {
                SetShowBackLink(true);
                InviteCodeInfo inviteCode = null;
                if (allowinvite)
                {
                    if (config.Regstatus == 3 && invitecode == "")
                    {
                        AddErrLine("邀请码不能为空!");
                        return;
                    }
                    if (invitecode != "")
                    {
                        inviteCode = Invitation.GetInviteCodeByCode(invitecode.ToUpper());
                        if (!Invitation.CheckInviteCode(inviteCode))
                        {
                            AddErrLine("邀请码不合法或已过期!");
                            return;
                        }
                    }
                }

                string tmpUserName = DNTRequest.GetString(config.Antispamregisterusername);
                string section     = DNTRequest.GetString("diseaseSection");
                if (!string.IsNullOrEmpty(section))
                {
                    tmpUserName = section + "_" + tmpUserName;
                }
                string email   = DNTRequest.GetString(config.Antispamregisteremail).Trim().ToLower();
                string tmpBday = DNTRequest.GetString("bday").Trim();

                if (tmpBday == "")
                {
                    tmpBday = string.Format("{0}-{1}-{2}", DNTRequest.GetString("bday_y").Trim(),
                                            DNTRequest.GetString("bday_m").Trim(), DNTRequest.GetString("bday_d").Trim());
                }
                tmpBday = (tmpBday == "--" ? "" : tmpBday);

                ValidateUserInfo(tmpUserName, email, tmpBday);

                if (IsErr())
                {
                    return;
                }

                //如果用户名符合注册规则, 则判断是否已存在
                if (Users.GetUserId(tmpUserName) > 0)
                {
                    AddErrLine("请不要重复提交!");
                    return;
                }

                UserInfo userInfo = CreateUser(tmpUserName, email, tmpBday);

                #region 发送欢迎信息
                if (config.Welcomemsg == 1)
                {
                    // 收件箱
                    PrivateMessageInfo privatemessageinfo = new PrivateMessageInfo();
                    privatemessageinfo.Message      = config.Welcomemsgtxt;
                    privatemessageinfo.Subject      = "欢迎您的加入! (请勿回复本信息)";
                    privatemessageinfo.Msgto        = userInfo.Username;
                    privatemessageinfo.Msgtoid      = userInfo.Uid;
                    privatemessageinfo.Msgfrom      = PrivateMessages.SystemUserName;
                    privatemessageinfo.Msgfromid    = 0;
                    privatemessageinfo.New          = 1;
                    privatemessageinfo.Postdatetime = Utils.GetDateTime();
                    privatemessageinfo.Folder       = 0;
                    PrivateMessages.CreatePrivateMessage(privatemessageinfo, 0);
                }
                #endregion

                //发送同步数据给应用程序
                Sync.UserRegister(userInfo.Uid, userInfo.Username, userInfo.Password, "");



                SetUrl("index.aspx");
                SetShowBackLink(false);
                SetMetaRefresh(config.Regverify == 0 ? 2 : 5);
                Statistics.ReSetStatisticsCache();

                if (inviteCode != null)
                {
                    Invitation.UpdateInviteCodeSuccessCount(inviteCode.InviteId);
                    if (config.Regstatus == 3)
                    {
                        if (inviteCode.SuccessCount + 1 >= inviteCode.MaxCount)
                        {
                            Invitation.DeleteInviteCode(inviteCode.InviteId);
                        }
                    }
                }

                if (config.Regverify == 0)
                {
                    UserCredits.UpdateUserCredits(userInfo.Uid);
                    ForumUtils.WriteUserCookie(userInfo, -1, config.Passwordkey);
                    OnlineUsers.UpdateAction(olid, UserAction.Register.ActionID, 0, config.Onlinetimeout);
                    MsgForward("register_succeed");
                    AddMsgLine("注册成功, 返回登录页");
                }
                else
                {
                    if (config.Regverify == 1)
                    {
                        AddMsgLine("注册成功, 请您到您的邮箱中点击激活链接来激活您的帐号");
                    }
                    else if (config.Regverify == 2)
                    {
                        AddMsgLine("注册成功, 但需要系统管理员审核您的帐户后才可登录使用");
                    }
                }
                //ManyouApplications.AddUserLog(userInfo.Uid, UserLogActionEnum.Add);
                agree = "yes";
            }
        }
예제 #16
0
 public async Task <Invitation> CreateGuestInvitationAsync(Invitation invite)
 {
     return(await graphClient.Invitations.Request().AddAsync(invite));
 }
 private void OnInvitationReceived(Invitation invitation, bool fromNotification)
 {
     string inviterName = invitation.Inviter != null ? invitation.Inviter.DisplayName : "(null)";
     mStatus = "!!! Got invitation " + (fromNotification ? " (from notification):" : ":") +
     " from " + inviterName + ", id " + invitation.InvitationId;
     mLastInvitationId = invitation.InvitationId;
 }
예제 #18
0
        public ActionResult Create(int personId, Invitation invitation)
        {
            var person = Repository.OfType<Person>().GetNullableById(personId);
            var seminar = SiteService.GetLatestSeminar(Site);

            if (person == null || seminar == null) return this.RedirectToAction<ErrorController>(a => a.Index());

            if (AddToInvitationList(seminar, person, Site, invitation.Title, invitation.FirmName))
            {
                Message = "Invitation Created Successfully";

                return this.RedirectToAction<PersonController>(a => a.AdminEdit(person.User.Id, null, true));
            }

            Message = "Person already on invitation list.";

            invitation.Person = person;
            invitation.Seminar = seminar;

            return View(invitation);
        }
예제 #19
0
 /// <summary>
 /// Transfer editable values from source to destination.  Use of AutoMapper is recommended
 /// </summary>
 private static void TransferValues(Invitation source, Invitation destination)
 {
     destination.Title = source.Title;
     destination.FirmName = source.FirmName;
 }
예제 #20
0
 public static string GenerateMeetingTitle(Invitation invitation)
 => $"Invitation for punch-out, IPO-{invitation.Id}, Project: {invitation.ProjectName}";
예제 #21
0
        public async Task <bool> ValidateUpdate(Invitation item, CancellationToken cancellationToken)
        {
            await ValidateDuplicateCounterparty(item, cancellationToken);

            return(Errors.Count == 0);
        }
예제 #22
0
 void handleInvitation(Invitation v, bool b)
 {
     Debug.Log("Handle Invite");
 }
예제 #23
0
 private string GetRepresentativeText(Invitation invitation)
 {
     return(string.Format(RepresentativeInvitationRequestFormat, GetInviterText(invitation.InviterId)));
 }
예제 #24
0
 private string GetFriendText(Invitation invitation)
 {
     return(string.Format(FriendInvitationRequestFormat, GetInviterText(invitation.InviterId)));
 }
예제 #25
0
 private void MoveToAcceptPage()
 {
     invitation = new Invitation();
        try
        {
     invitation.Load(inviteFile);
        }
        catch(Exception e)
        {
     Console.WriteLine("Unable to load file: {0}", inviteFile);
     MessageDialog md = new MessageDialog(win,
        DialogFlags.DestroyWithParent | DialogFlags.Modal,
        MessageType.Error,
        ButtonsType.Close,
        "Unable to open file or file is not an iFolder Invitation:\n" + inviteFile);
     md.Run();
     md.Hide();
     MoveToLoadPage();
     return;
        }
        WizardBox.PackEnd(acceptPage);
        BackButton.Sensitive = true;
        if(acceptPathEntry.Text.Length > 0)
     ForwardButton.Sensitive = true;
        else
     ForwardButton.Sensitive = false;
        page = IW_ACCEPT_PAGE;
        acceptiFolderName.Text = invitation.CollectionName;
        acceptSharerName.Text = invitation.FromName;
        acceptSharerEmail.Text = invitation.FromEmail;
        acceptRights.Text = invitation.CollectionRights;
        if(acceptPathEntry.Text.Length < 1)
     acceptPathEntry.Text = Invitation.DefaultRootPath;
 }
        public void Initialize()
        {
            var mockContext = new MockDataContext();

            var user1 = new AppUser {
                ID       = 1,
                UserName = "******",
                Email    = "*****@*****.**"
            };

            mockContext.AppUsers.Add(user1);

            var user2 = new AppUser {
                ID       = 2,
                UserName = "******",
                Email    = "*****@*****.**"
            };

            mockContext.AppUsers.Add(user2);

            var project1 = new Project {
                ID          = 1,
                OwnerID     = 1,
                Name        = "Project1",
                DateCreated = new DateTime(2017, 1, 1),
                AppUser     = user1,
                ProjectType = "Javascript"
            };

            mockContext.Projects.Add(project1);

            var project2 = new Project {
                ID          = 2,
                OwnerID     = 1,
                Name        = "Project2",
                DateCreated = new DateTime(2017, 1, 1),
                AppUser     = user1,
                ProjectType = "HTML"
            };

            mockContext.Projects.Add(project2);

            var userProject1 = new UserProjects {
                ID        = 1,
                AppUserID = 1,
                ProjectID = 1,
                AppUser   = user1,
                Project   = project1
            };

            mockContext.UserProjects.Add(userProject1);

            var userProject2 = new UserProjects {
                ID        = 2,
                AppUserID = 1,
                ProjectID = 2,
                AppUser   = user1,
                Project   = project2
            };

            mockContext.UserProjects.Add(userProject2);

            var userProject3 = new UserProjects {
                ID        = 3,
                AppUserID = 2,
                ProjectID = 2,
                AppUser   = user2,
                Project   = project2
            };

            mockContext.UserProjects.Add(userProject3);

            var document1 = new Document {
                ID            = 1,
                Name          = "Document1",
                Type          = "HTML",
                CreatedBy     = "User1",
                DateCreated   = new DateTime(2017, 1, 1),
                Content       = null,
                LastUpdatedBy = null,
                ProjectID     = 1,
                Project       = project1
            };

            mockContext.Documents.Add(document1);

            var invitation1 = new Invitation {
                ID           = 1,
                fromUserName = "******",
                AppUserID    = 2,
                ProjectID    = 1,
                AppUser      = user2,
                Project      = project1
            };

            mockContext.Invitations.Add(invitation1);

            _ProjectService = new ProjectService(mockContext);
        }
 public void OnInvitationReceived(Invitation inv, bool shouldAutoAccept)
 {
     mInvitation       = inv;
     mShouldAutoAccept = shouldAutoAccept;
 }
예제 #28
0
 private static void NotifyInvitationRemoved(Invitation invitation)
 {
     Instance.CallClient(invitation.Invitee,
                         _ => _.ClientRemote_InvitationRemoved(invitation.Inviter.Name));
 }
예제 #29
0
        public ActionResult Delete(int id, Invitation invitation)
        {
            var invitationToDelete = _invitationRepository.GetNullableById(id);

            if (invitationToDelete == null) return RedirectToAction("Index");

            var person = invitationToDelete.Person;
            var seminar = invitationToDelete.Seminar;
            _notificationService.RemoveFromMailingList(seminar, person, MailingLists.Invitation);

            _invitationRepository.Remove(invitationToDelete);

            Message = "Invitation Removed Successfully";

            return RedirectToAction("Index", new {id=seminar.Id});
        }
예제 #30
0
 public ReceivedInvite(ChannelInvitation c, Invitation i)
 {
     this.ChannelInvitation = c;
     this.Invitation        = i;
 }
예제 #31
0
        public static InvitationViewModel Create(IRepository repository, Invitation invitation = null)
        {
            Check.Require(repository != null, "Repository must be supplied");

            var viewModel = new InvitationViewModel {Invitation = invitation ?? new Invitation()};

            return viewModel;
        }
예제 #32
0
        private void HandleChannelSubscriber_NotifyUpdateChannelState(RPCContext context)
        {
            UpdateChannelStateNotification updateChannelStateNotification = UpdateChannelStateNotification.ParseFrom(context.Payload);

            base.ApiLog.LogDebug("HandleChannelSubscriber_NotifyUpdateChannelState: " + updateChannelStateNotification);
            ChannelAPI.ChannelReferenceObject channelReferenceObject = this.GetChannelReferenceObject(context.Header.ObjectId);
            if (channelReferenceObject == null)
            {
                base.ApiLog.LogError("HandleChannelSubscriber_NotifyUpdateChannelState had unexpected traffic for objectId : " + context.Header.ObjectId);
                return;
            }
            ChannelAPI.ChannelType channelType = channelReferenceObject.m_channelData.m_channelType;
            switch (channelType)
            {
            case ChannelAPI.ChannelType.PRESENCE_CHANNEL:
                if (updateChannelStateNotification.StateChange.HasPresence)
                {
                    bnet.protocol.presence.ChannelState presence = updateChannelStateNotification.StateChange.Presence;
                    this.m_battleNet.Presence.HandlePresenceUpdates(presence, channelReferenceObject);
                }
                return;

            case ChannelAPI.ChannelType.CHAT_CHANNEL:
            case ChannelAPI.ChannelType.GAME_CHANNEL:
                break;

            case ChannelAPI.ChannelType.PARTY_CHANNEL:
                this.m_battleNet.Party.PreprocessPartyChannelUpdated(channelReferenceObject, updateChannelStateNotification);
                break;

            default:
                return;
            }
            ChannelAPI.ChannelData channelData = (ChannelAPI.ChannelData)channelReferenceObject.m_channelData;
            if (channelData != null)
            {
                bool flag  = channelType == ChannelAPI.ChannelType.PARTY_CHANNEL;
                bool flag2 = false;
                Map <string, Variant> map = null;
                bnet.protocol.channel.ChannelState channelState = channelData.m_channelState;
                bnet.protocol.channel.ChannelState stateChange  = updateChannelStateNotification.StateChange;
                if (stateChange.HasMaxMembers)
                {
                    channelState.MaxMembers = stateChange.MaxMembers;
                }
                if (stateChange.HasMinMembers)
                {
                    channelState.MinMembers = stateChange.MinMembers;
                }
                if (stateChange.HasMaxInvitations)
                {
                    channelState.MaxInvitations = stateChange.MaxInvitations;
                }
                if (stateChange.HasPrivacyLevel && channelState.PrivacyLevel != stateChange.PrivacyLevel)
                {
                    channelState.PrivacyLevel = stateChange.PrivacyLevel;
                    flag2 = true;
                }
                if (stateChange.HasName)
                {
                    channelState.Name = stateChange.Name;
                }
                if (stateChange.HasDelegateName)
                {
                    channelState.DelegateName = stateChange.DelegateName;
                }
                if (stateChange.HasChannelType)
                {
                    if (!flag)
                    {
                        channelState.ChannelType = stateChange.ChannelType;
                    }
                    if (flag && stateChange.ChannelType != PartyAPI.PARTY_TYPE_DEFAULT)
                    {
                        channelState.ChannelType = stateChange.ChannelType;
                        int num = -1;
                        for (int i = 0; i < channelState.AttributeList.get_Count(); i++)
                        {
                            if (channelState.AttributeList.get_Item(i).Name == "WTCG.Party.Type")
                            {
                                num = i;
                                break;
                            }
                        }
                        Attribute attribute = ProtocolHelper.CreateAttribute("WTCG.Party.Type", channelState.ChannelType);
                        if (num >= 0)
                        {
                            channelState.AttributeList.set_Item(num, attribute);
                        }
                        else
                        {
                            channelState.AttributeList.Add(attribute);
                        }
                    }
                }
                if (stateChange.HasProgram)
                {
                    channelState.Program = stateChange.Program;
                }
                if (stateChange.HasAllowOfflineMembers)
                {
                    channelState.AllowOfflineMembers = stateChange.AllowOfflineMembers;
                }
                if (stateChange.HasSubscribeToPresence)
                {
                    channelState.SubscribeToPresence = stateChange.SubscribeToPresence;
                }
                if (stateChange.AttributeCount > 0 && map == null)
                {
                    map = new Map <string, Variant>();
                }
                for (int j = 0; j < stateChange.AttributeCount; j++)
                {
                    Attribute attribute2 = stateChange.AttributeList.get_Item(j);
                    int       num2       = -1;
                    for (int k = 0; k < channelState.AttributeList.get_Count(); k++)
                    {
                        Attribute attribute3 = channelState.AttributeList.get_Item(k);
                        if (attribute3.Name == attribute2.Name)
                        {
                            num2 = k;
                            break;
                        }
                    }
                    if (attribute2.Value.IsNone())
                    {
                        if (num2 >= 0)
                        {
                            channelState.AttributeList.RemoveAt(num2);
                        }
                    }
                    else if (num2 >= 0)
                    {
                        channelState.Attribute.set_Item(num2, attribute2);
                    }
                    else
                    {
                        channelState.AddAttribute(attribute2);
                    }
                    map.Add(attribute2.Name, attribute2.Value);
                }
                if (stateChange.HasReason)
                {
                    IList <Invitation> invitationList  = stateChange.InvitationList;
                    IList <Invitation> invitationList2 = channelState.InvitationList;
                    for (int l = 0; l < invitationList.get_Count(); l++)
                    {
                        Invitation invitation = invitationList.get_Item(l);
                        for (int m = 0; m < invitationList2.get_Count(); m++)
                        {
                            Invitation invitation2 = invitationList2.get_Item(m);
                            if (invitation2.Id == invitation.Id)
                            {
                                channelState.InvitationList.RemoveAt(m);
                                break;
                            }
                        }
                    }
                }
                else
                {
                    channelState.Invitation.AddRange(stateChange.InvitationList);
                }
                channelData.m_channelState = channelState;
                if (flag)
                {
                    if (flag2)
                    {
                        this.m_battleNet.Party.PartyPrivacyChanged(channelData.m_channelId, channelState.PrivacyLevel);
                    }
                    if (stateChange.InvitationList.get_Count() > 0)
                    {
                        uint?removeReason = default(uint?);
                        if (stateChange.HasReason)
                        {
                            removeReason = new uint?(stateChange.Reason);
                        }
                        using (List <Invitation> .Enumerator enumerator = stateChange.InvitationList.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                Invitation current = enumerator.get_Current();
                                this.m_battleNet.Party.PartyInvitationDelta(channelData.m_channelId, current, removeReason);
                            }
                        }
                    }
                    if (map != null)
                    {
                        foreach (KeyValuePair <string, Variant> current2 in map)
                        {
                            this.m_battleNet.Party.PartyAttributeChanged(channelData.m_channelId, current2.get_Key(), current2.get_Value());
                        }
                    }
                }
            }
        }
예제 #33
0
파일: MainMenuGui.cs 프로젝트: damard/Unity
 void ShowIncomingInviteUi()
 {
     string inviterName = mIncomingInvite.Inviter == null ? "Someone" :
       mIncomingInvite.Inviter.DisplayName == null ? "Someone" :
       mIncomingInvite.Inviter.DisplayName;
       GuiLabel(CenterLabelCfg, inviterName + " is challenging you to a match!");
       Invitation inv = mIncomingInvite;
       if (GuiButton(AcceptButtonCfg)) {
     mIncomingInvite = null;
     SetStandBy("Accepting invitation...");
     PlayGamesPlatform.Instance.TurnBased.AcceptInvitation(inv.InvitationId, OnMatchStarted);
       } else if (GuiButton(DeclineButtonCfg)) {
     mIncomingInvite = null;
     PlayGamesPlatform.Instance.TurnBased.DeclineInvitation(inv.InvitationId);
       }
 }
예제 #34
0
        public async Task <User> InviteMember(string displayName, string firstName, string emailAddress)
        {
            const string emailSender  = "*****@*****.**";
            const string emailSubject = ".NET Foundation: Please Activate Your Membership";
            const string redirectUrl  = "https://dotnetfoundation.org/member/profile";

            var path         = Path.Combine(_webHostEnvironment.ContentRootPath, "MemberInvitation");
            var mailTemplate = await System.IO.File.ReadAllTextAsync(Path.Combine(path, "email-template.html"));

            var attachments = new MessageAttachmentsCollectionPage
            {
                await GetImageAttachement(path, "header.png"),
                await GetImageAttachement(path, "footer.png")
            };

            //const string groupId = "6eee9cd2-a055-433d-8ff1-07ca1d0f6fb7"; //Test Members
            //We can look up the Members group by name, but in this case it's constant
            //var group = await _graphApplicationClient
            //        .Groups.Request().Filter("startswith(displayName,'Members')")
            //        .GetAsync();
            //string groupId = group[0].Id;

            string redeemUrl;
            User   invitedUser;

            try
            {
                //If we wanted to check if members are in the group first, could use this
                //var existing = await _graphApplicationClient
                //        .Groups[groupId]
                //        .Members.Request().Select("id,mail").GetAsync();

                var invite = new Invitation
                {
                    InvitedUserEmailAddress = emailAddress,
                    SendInvitationMessage   = false,
                    InviteRedirectUrl       = redirectUrl,
                    InvitedUserDisplayName  = displayName
                };

                var result = await _graphApplicationClient.Invitations.Request().AddAsync(invite);

                redeemUrl   = result.InviteRedeemUrl;
                invitedUser = result.InvitedUser;

                // Add to member group
                await _graphApplicationClient
                .Groups[Constants.MembersGroupId]
                .Members.References.Request()
                .AddAsync(result.InvitedUser);
            }
            catch (Exception)
            {
                //They're already added to the group, so we can break without sending e-mail
                _logger.LogWarning("User exists: {DisplayName}: {EMail}", displayName, emailAddress);
                return(null);
            }

            var recipients = new List <Recipient>
            {
                new Recipient
                {
                    EmailAddress = new EmailAddress
                    {
                        Name    = displayName,
                        Address = emailAddress
                    }
                }
            };

            // Create the message.
            var email = new Message
            {
                Body = new ItemBody
                {
                    //TODO Replace with e-mail template
                    Content = mailTemplate
                              .Replace("{{action}}", redeemUrl)
                              .Replace("{{name}}", firstName),
                    ContentType = BodyType.Html,
                },
                HasAttachments = true,
                Attachments    = attachments,
                Subject        = emailSubject,
                ToRecipients   = recipients
            };

            // Send the message.
            await _graphApplicationClient.Users[emailSender].SendMail(email, true).Request().PostAsync();

            _logger.LogInformation("Invite: {DisplayName}: {EMail}", displayName, emailAddress);

            return(invitedUser);
        }
예제 #35
0
    /*
     * Process chat messages/commands
     * Available commands:
     * /w [or /whisper] <username> <text>
     * /add <username>
     * /rm [or /remove] <username>
     * /inv [or /invite] <username>
     * /accept
     * /refuse
     * /j [or /join] <gameName> [<gamePassword>]
     * /h [or /help]
     */
    public void processChatMessage(string theMessage)
    {
        string[] splittedMessage = theMessage.Split(' ');
        int parametersLength = splittedMessage.Length;
        ISFSObject parameters = new SFSObject();
        string buddyUsername, gameName, gamePassword;
        if (theMessage.Length == 0)
            return;
        char[] chars = splittedMessage[0].ToCharArray();
        bool isCommand = chars[0] == '/'?true:false;
        Room gameRoom;

        if(isCommand){
            switch (splittedMessage[0]){

                /*
                 * whisper a user
                 * /whisper <username> <text>
                 */
            case "/whisper":
            case "/w": //private message

                if(parametersLength == 1 || splittedMessage[1]=="")//missing username and message
                {
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: missing username and message \n usage: /w <username> <text>");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }

                if(parametersLength == 2 || splittedMessage[2]=="")//missing message
                {
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: missing message \n usage: /w <username> <text>");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }

                User recipient = smartFox.UserManager.GetUserByName(splittedMessage[1]);
                theMessage = "";
                if(recipient == null){
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: user " + splittedMessage[1] + " is not online");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }
                if(recipient.Name == smartFox.MySelf.Name){
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: you can't whisper yourself");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }
                for(int j = 2; j<splittedMessage.Length;j++)
                    theMessage += " "+splittedMessage[j];
                parameters.PutUtfString("recipientName", recipient.Name);
                smartFox.Send(new PrivateMessageRequest(theMessage,recipient.Id,parameters));
                break;

                /*
                 * add to buddy list
                 * /add <username>
                 */
            case "/add": //add Buddy

                if(parametersLength == 1)//missing username and message
                {
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: missing username \n usage: /add <username>");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }

                buddyUsername = splittedMessage[1];
                if(buddyUsername == smartFox.MySelf.Name){
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: you can't add yourself to your buddy list");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }
                if(smartFox.UserManager.ContainsUserName(buddyUsername))
                {
                    if(!smartFox.BuddyManager.ContainsBuddy(buddyUsername))
                    {
                        smartFox.Send(new AddBuddyRequest(buddyUsername));
                        lock(messagesLocker){
                            chatMessages.Add("[SASHA]: " + buddyUsername + " added to buddy list");
                            chatScrollPosition.y = Mathf.Infinity;
                        }
                    }
                }else{
                    lock (messagesLocker){
                        chatMessages.Add("[SASHA]: " + buddyUsername + " is not online");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                }
                break;

                /*
                 * remove from buddy list
                 * /remove <username>
                 */
            case "/remove":
            case "/rm": //remove Buddy
                if(parametersLength == 1) //missing username and message
                {
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: missing username \n usage: [/rm][/remove] <username>");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }

                buddyUsername = splittedMessage[1];
                if(smartFox.BuddyManager.ContainsBuddy(buddyUsername)){
                    smartFox.Send (new RemoveBuddyRequest(buddyUsername));
                    lock(messagesLocker){
                        chatMessages.Add("[SASHA]: " + buddyUsername + " removed from buddy list");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                }else{
                    lock(messagesLocker){
                        chatMessages.Add("[SASHA]: " + buddyUsername + " not present in your buddy list");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                }
                break;

                /*
                 * invite to current Game
                 * /invite <username>
                 */
            case "/invite":
            case "/inv":
                if(parametersLength == 1) //missing username and message
                {
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: missing username \n usage: [/inv][/invite] <username>");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }

                buddyUsername = splittedMessage[1];
                User user1 = smartFox.UserManager.GetUserByName(buddyUsername);
                if(user1.Name == smartFox.MySelf.Name){
                    lock(messagesLocker)
                        chatMessages.Add ("[SASHA]: you can't add yourself to current game");
                    break;
                }
                if(smartFox.UserManager.ContainsUser(user1)){
                    List<object> invitedUsers = new List<object>();
                    invitedUsers.Add(user1);
                    parameters.PutUtfString("gameName", smartFox.LastJoinedRoom.Name);
                    smartFox.Send(new InviteUsersRequest(invitedUsers, 20, parameters));
                    smartFox.Send(new PublicMessageRequest(smartFox.MySelf.Name + " invited " + buddyUsername + " to current game"));
                }else{
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: " + buddyUsername + " is not online");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                }
                break;

                /*
                 * join an existing Game
                 * /join <gameName> [<gamePassword>]
                 */
            case "/join":
            case "/j":
                if(parametersLength < 2)
                {
                    lock(messagesLocker){
                        chatMessages.Add ("[SASHA]: missing parameters \n usage: [/j][/join] <gameName> [<gamePassword>]");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }
                gameName = splittedMessage[1];
                if(parametersLength > 2) //if there is a password
                    gamePassword = splittedMessage[2];
                else
                    gamePassword = "";

                if(smartFox.RoomManager.ContainsRoom(gameName))
                {
                    //if gameLobby exist join it
                    smartFox.Send (new JoinRoomRequest(gameName,gamePassword));
                    creatingGame = false;
                    tutorial = false;
                    showLoadingScreen = false;
                    showGameLobby = true;
                }
                else
                {
                    //if not, create a new gameLobby
                    parameters.PutUtfString("name", gameName);
                    parameters.PutBool("isGame", false);
                    parameters.PutUtfString("password", gamePassword);
                    if(gamePassword!="")
                        parameters.PutBool("isPrivate", true);
                    else
                        parameters.PutBool("isPrivate", false);
                    smartFox.Send(new ExtensionRequest("createGameLobby",parameters));
                    creatingGame = false;
                    tutorial = false;
                    showLoadingScreen = false;
                    showGameLobby = true;
                }
                break;

                /*
                 * accept current invite
                 * /accept
                 */
            case "/accept": //accept an invite to a game
                if(currentInvitation == null){
                    lock(messagesLocker){
                        chatMessages.Add("[SASHA]: You don't have any game invitation to accept");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }
                parameters = (SFSObject)currentInvitation.Params;
                gameName = (string) parameters.GetUtfString("gameName");
                gameRoom = smartFox.RoomManager.GetRoomByName(gameName);
                smartFox.Send (new InvitationReplyRequest(currentInvitation,InvitationReply.ACCEPT));
                if(gameRoom!=null && !gameRoom.IsHidden){
                    smartFox.Send (new JoinRoomRequest(gameName));
                }else if(gameRoom.IsHidden){
                    parameters.PutUtfString("gameName", gameName);
                    smartFox.Send(new ExtensionRequest("acceptInvite",parameters));
                }
                creatingGame = false;
                tutorial = false;
                showLoadingScreen = false;
                showGameLobby = true;
                break;

                /*
                 * refuse current invite
                 * /refuse
                 */
            case "/refuse": //accept an invite to a game
                if(currentInvitation == null){
                    lock(messagesLocker){
                        chatMessages.Add("[SASHA]: You don't have any game invitation to refuse");
                        chatScrollPosition.y = Mathf.Infinity;
                    }
                    break;
                }
                parameters = (SFSObject)currentInvitation.Params;
                smartFox.Send (new InvitationReplyRequest(currentInvitation,InvitationReply.REFUSE));
                currentInvitation = null;
                break;

                /*
                 * leave current gameLobby
                 * /leave
                 */
            case "/leave":
                if(currentActiveRoom.Name != "Lobby")
                    ExitGameLobby();
                else
                lock(messagesLocker){
                    chatMessages.Add("[SASHA]: You can't leave general lobby");
                    chatScrollPosition.y = Mathf.Infinity;
                }
                break;

                /*
                 * logout from server
                 * /logout
                 */
            case "/logout":
                smartFox.Send(new LogoutRequest());
                break;

                /*
                 * quit the application
                 * /quit
                 */
            case "/quit":
                CloseApplication();
                break;

            case "/help":
            case "/h":
                lock(messagesLocker){
                    chatMessages.Add("--------------------------HELP--------------------------");
                    chatMessages.Add("[/w][/whisper] <username> <text> : send a PM to username");
                    chatMessages.Add("[/add] <username> : add username to buddy list");
                    chatMessages.Add("[/rm][/remove] <username> : remove username from buddy list");
                    chatMessages.Add("[/inv][/invite] <username> : invite username to current game");
                    chatMessages.Add("[/accept] : accept current invite request");
                    chatMessages.Add("[/refuse] : refuse current invite request");
                    chatMessages.Add("[/j][/join] <gameName> [<gamePassword>]: join/create gameName with an \n\t\t\t\t\t\t optional password");
                    chatMessages.Add("--------------------------------------------------------");
                    chatScrollPosition.y = Mathf.Infinity;
                }
                //chatMessages.Add("[/h][/help] : shows this messages");

                break;
            default: //command not found
                lock(messagesLocker){
                    chatMessages.Add("[SASHA]: can't find command "+splittedMessage[0]);
                    chatScrollPosition.y = Mathf.Infinity;
                }
                break;
            }
        }else{
            //public message
            smartFox.Send(new PublicMessageRequest(theMessage, null , currentActiveRoom));
        }
    }
 public Invitation CreateInvitation(Invitation invitation, string tenancy)
 {
     return(invitationManager.CreateInvitation(invitation, tenancy));
 }
예제 #37
0
 public Task <bool> SendInvitationEmail(Invitation invitation)
 {
     return(Task.FromResult(true));
 }
 public bool InvitationRejected(Invitation invitation)
 {
     return(invitationManager.RejectInvitation(invitation));
 }
예제 #39
0
        private void CheckForConnectionExtras()
        {
            // check to see if we have a pending invitation in our gamehelper
            Logger.d("AndroidClient: CheckInvitationFromNotification.");
            Logger.d("AndroidClient: looking for invitation in our GameHelper.");
            Invitation        invFromNotif = null;
            AndroidJavaObject invObj       = mGHManager.GetInvitation();
            AndroidJavaObject matchObj     = mGHManager.GetTurnBasedMatch();

            mGHManager.ClearInvitationAndTurnBasedMatch();

            if (invObj != null)
            {
                Logger.d("Found invitation in GameHelper. Converting.");
                invFromNotif = ConvertInvitation(invObj);
                Logger.d("Found invitation in our GameHelper: " + invFromNotif);
            }
            else
            {
                Logger.d("No invitation in our GameHelper. Trying SignInHelperManager.");
                AndroidJavaClass cls = JavaUtil.GetClass(JavaConsts.SignInHelperManagerClass);
                using (AndroidJavaObject inst = cls.CallStatic <AndroidJavaObject>("getInstance")) {
                    if (inst.Call <bool>("hasInvitation"))
                    {
                        invFromNotif = ConvertInvitation(inst.Call <AndroidJavaObject>("getInvitation"));
                        Logger.d("Found invitation in SignInHelperManager: " + invFromNotif);
                        inst.Call("forgetInvitation");
                    }
                    else
                    {
                        Logger.d("No invitation in SignInHelperManager either.");
                    }
                }
            }

            TurnBasedMatch match = null;

            if (matchObj != null)
            {
                Logger.d("Found match in GameHelper. Converting.");
                match = JavaUtil.ConvertMatch(mUserId, matchObj);
                Logger.d("Match from GameHelper: " + match);
            }
            else
            {
                Logger.d("No match in our GameHelper. Trying SignInHelperManager.");
                AndroidJavaClass cls = JavaUtil.GetClass(JavaConsts.SignInHelperManagerClass);
                using (AndroidJavaObject inst = cls.CallStatic <AndroidJavaObject>("getInstance")) {
                    if (inst.Call <bool>("hasTurnBasedMatch"))
                    {
                        match = JavaUtil.ConvertMatch(mUserId,
                                                      inst.Call <AndroidJavaObject>("getTurnBasedMatch"));
                        Logger.d("Found match in SignInHelperManager: " + match);
                        inst.Call("forgetTurnBasedMatch");
                    }
                    else
                    {
                        Logger.d("No match in SignInHelperManager either.");
                    }
                }
            }

            // if we got an invitation from the notification, invoke the delegate
            if (invFromNotif != null)
            {
                if (mInvitationDelegate != null)
                {
                    Logger.d("Invoking invitation received delegate to deal with invitation " +
                             " from notification.");
                    PlayGamesHelperObject.RunOnGameThread(() => {
                        if (mInvitationDelegate != null)
                        {
                            mInvitationDelegate.Invoke(invFromNotif, true);
                        }
                    });
                }
                else
                {
                    Logger.d("No delegate to handle invitation from notification; queueing.");
                    mInvitationFromNotification = invFromNotif;
                }
            }

            // if we got a turn-based match, hand it over to the TBMP client who will know
            // better what to do with it
            if (match != null)
            {
                mTbmpClient.HandleMatchFromNotification(match);
            }
        }
 public bool UpdateInvitation(Invitation invitation, string appUserId)
 {
     return(new UserManager().UpdateUserData(appUserId, invitation));
 }
예제 #41
0
 public void HandleInvitation(Invitation invitation, bool shouldAutoAccept)
 {
     MakeActive();
     OnGotInvitation(invitation, shouldAutoAccept);
 }
예제 #42
0
        public async Task DataShareE2E()
        {
            Account expectedAccount = new Account(new Identity(), ScenarioTestBase <DataShareE2EScenarioTests> .AccountLocation);

            Func <DataShareManagementClient, Task> action = async(client) =>
            {
                await AccountScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    expectedAccount);

                await ShareScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareName,
                    ShareScenarioTests.GetShare());

                var synchronizationSetting = await SynchronizationSettingScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareName,
                    DataShareE2EScenarioTests.synchronizationSettingName,
                    SynchronizationSettingScenarioTests.GetSynchronizationSetting()) as ScheduledSynchronizationSetting;

                DataSet dataSet = await DataSetScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareName,
                    DataShareE2EScenarioTests.dataSetName,
                    DataSetScenarioTests.GetDataSet());

                Invitation invitation = await InvitationScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareName,
                    DataShareE2EScenarioTests.invitationName,
                    InvitationScenarioTests.GetExpectedInvitation());

                await ShareSubscriptionScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareSubscriptionName,
                    ShareSubscriptionScenarioTests.GetShareSubscription(invitation.InvitationId, DataShareE2EScenarioTests.sourceShareLocationName));

                await TriggerScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareSubscriptionName,
                    DataShareE2EScenarioTests.triggerName,
                    TriggerScenarioTests.GetTrigger(
                        synchronizationSetting.RecurrenceInterval,
                        synchronizationSetting.SynchronizationTime));

                await DataSetMappingScenarioTests.CreateAsync(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareSubscriptionName,
                    DataShareE2EScenarioTests.dataSetMappingName,
                    DataSetMappingScenarioTests.GetDataSetMapping());

                ShareSubscriptionScenarioTests.Synchronize(
                    client,
                    this.ResourceGroupName,
                    this.AccountName,
                    DataShareE2EScenarioTests.shareSubscriptionName);
            };

            Func <DataShareManagementClient, Task> finallyAction = async(client) =>
            {
                await AccountScenarioTests.Delete(
                    client,
                    this.ResourceGroupName,
                    this.AccountName);
            };

            await this.RunTest(action, finallyAction);
        }
예제 #43
0
 public Task SendInvitations(Invitation invitation, IList <Friend> friends, int limit)
 {
     throw new NotImplementedException();
 }
 public async Task CreateAsync(Invitation invitation)
 {
     await _unitOfWork.InsertAsync(invitation);
 }
 public void OnInvitationReceived(Invitation inv, bool shouldAutoAccept)
 {
     mInvitation = inv;
     mShouldAutoAccept = shouldAutoAccept;
 }
 public async Task UpdateAsync(Invitation invitation)
 {
     await _unitOfWork.UpdateAsync(invitation);
 }
 public void HandleInvitation(Invitation invitation, bool shouldAutoAccept)
 {
     MakeActive();
     OnGotInvitation(invitation, shouldAutoAccept);
 }
        public int InviteUser(CreateInvitationBindingModel model, string loggerUserId)
        {
            var contest = this.Data.Contests.Find(model.ContestId);

            if (contest == null)
            {
                throw new NotFoundException(string.Format("Contest with id {0} not found", model.ContestId));
            }

            var loggedUser = this.Data.Users.Find(loggerUserId);

            if (contest.OrganizatorId != loggedUser.Id)
            {
                throw new BadRequestException("Only the contest organizator can invite users.");
            }

            if (model.Type == InvitationType.Committee
                && contest.VotingStrategy.VotingStrategyType != VotingStrategyType.Closed)
            {
                throw new BadRequestException("The contest voting strategy type is not 'CLOSED'.");
            }

            if (model.Type == InvitationType.ClosedContest
                && contest.ParticipationStrategy.ParticipationStrategyType != ParticipationStrategyType.Closed)
            {
                throw new BadRequestException("The contest participation strategy type is not 'CLOSED'.");
            }

            if (!contest.IsOpenForSubmissions)
            {
                throw new BadRequestException("The contest is closed for submissions/registrations.");
            }

            var userToInvite = this.Data.Users.All().FirstOrDefault(u => u.UserName == model.Username);

            if (userToInvite == null)
            {
                throw new NotFoundException(string.Format("User with username {0} not found", model.Username));
            }

            if (contest.Participants.Contains(userToInvite))
            {
                throw new BadRequestException("You cannot invite user who already participates in the contest");
            }

            if (contest.Committee.Contains(userToInvite))
            {
                throw new BadRequestException("You cannot invite user who already is in the contest committee");
            }

            if (userToInvite.UserName == loggedUser.UserName)
            {
                throw new BadRequestException("Users cannot invite themselves.");
            }

            if (userToInvite.PendingInvitations.Any(i => i.ContestId == model.ContestId && i.Type == model.Type))
            {
                throw new BadRequestException(string.Format("User is already invited to contest with id {0}", contest.Id));
            }

            var invitation = new Invitation
            {
                ContestId = model.ContestId,
                InviterId = loggedUser.Id,
                InvitedId = userToInvite.Id,
                DateOfInvitation = DateTime.Now,
                Type = model.Type,
                Status = InvitationStatus.Neutral
            };

            if (model.Type == InvitationType.ClosedContest)
            {
                contest.InvitedUsers.Add(userToInvite);
            }

            userToInvite.PendingInvitations.Add(invitation);
            loggedUser.SendedInvitations.Add(invitation);

            this.Data.SaveChanges();

            return invitation.Id;
        }
예제 #49
0
        public ActionResult Edit(int id, Invitation invitation)
        {
            var invitationToEdit = _invitationRepository.GetNullableById(id);

            if (invitationToEdit == null) return RedirectToAction("Index");

            TransferValues(invitation, invitationToEdit);

            if (ModelState.IsValid)
            {
                _invitationRepository.EnsurePersistent(invitationToEdit);

                Message = "Invitation Edited Successfully";

                return RedirectToAction("Index");
            }

            return View(invitationToEdit);
        }
예제 #50
0
 /*
  * Handle a invitation recived
  */
 public void onInvitationReceived(BaseEvent evt)
 {
     currentInvitation = (Invitation) evt.Params["invitation"];
     lock(messagesLocker)
         chatMessages.Add(currentInvitation.Inviter.Name + " invited you to a game. Type /accept to join");
 }
예제 #51
0
        /// <summary>
        /// Add a person to the invitation list with checks to make sure duplicates are not inserted
        /// </summary>
        /// <param name="seminar"></param>
        /// <param name="person"></param>
        /// <param name="title"></param>
        /// <param name="firmname"></param>
        private bool AddToInvitationList(Seminar seminar, Person person, string siteId, string title = null, string firmname = null)
        {
            Check.Require(person != null, "person is required.");
            Check.Require(seminar != null, "seminar is required.");

            var invitationList = seminar.Invitations;

            // not yet in the list
            if (!invitationList.Where(a => a.Person == person).Any())
            {
                var invitation = new Invitation(person){Title=title, FirmName = firmname, Seminar = seminar};
                _invitationRepository.EnsurePersistent(invitation);

                _eventService.Invite(person, siteId);

                return true;
            }

            return false;
        }
예제 #52
0
        ///<summary></summary>
        /// <seealso cref="GooglePlayGames.BasicApi.IPlayGamesClient.Authenticate"/>
        public void Authenticate(Action <bool, string> callback, bool silent)
        {
            lock (AuthStateLock)
            {
                // If the user is already authenticated, just fire the callback, we don't need
                // any additional work.
                if (mAuthState == AuthState.Authenticated)
                {
                    InvokeCallbackOnGameThread(callback, true, null);
                    return;
                }
            }

            InitializeTokenClient();

            Debug.Log("Starting Auth with token client.");
            mTokenClient.FetchTokens(silent, (int result) =>
            {
                bool succeed = result == 0 /* CommonStatusCodes.SUCCEED */;
                InitializeGameServices();
                if (succeed)
                {
                    using (var signInTasks = new AndroidJavaObject("java.util.ArrayList"))
                    {
                        if (mInvitationDelegate != null)
                        {
                            mInvitationCallback = new AndroidJavaObject(
                                "com.google.games.bridge.InvitationCallbackProxy",
                                new InvitationCallbackProxy(mInvitationDelegate));
                            using (var invitationsClient = getInvitationsClient())
                                using (var taskRegisterCallback =
                                           invitationsClient.Call <AndroidJavaObject>("registerInvitationCallback",
                                                                                      mInvitationCallback))
                                {
                                    signInTasks.Call <bool>("add", taskRegisterCallback);
                                }
                        }

                        AndroidJavaObject taskGetPlayer =
                            getPlayersClient().Call <AndroidJavaObject>("getCurrentPlayer");
                        AndroidJavaObject taskGetActivationHint =
                            getGamesClient().Call <AndroidJavaObject>("getActivationHint");
                        AndroidJavaObject taskIsCaptureSupported =
                            getVideosClient().Call <AndroidJavaObject>("isCaptureSupported");

                        if (!mConfiguration.IsHidingPopups)
                        {
                            AndroidJavaObject taskSetViewForPopups;
                            using (var popupView = AndroidHelperFragment.GetDefaultPopupView())
                            {
                                taskSetViewForPopups =
                                    getGamesClient().Call <AndroidJavaObject>("setViewForPopups", popupView);
                            }

                            signInTasks.Call <bool>("add", taskSetViewForPopups);
                        }

                        signInTasks.Call <bool>("add", taskGetPlayer);
                        signInTasks.Call <bool>("add", taskGetActivationHint);
                        signInTasks.Call <bool>("add", taskIsCaptureSupported);

                        using (var tasks = new AndroidJavaClass(TasksClassName))
                            using (var allTask = tasks.CallStatic <AndroidJavaObject>("whenAll", signInTasks))
                            {
                                AndroidTaskUtils.AddOnCompleteListener <AndroidJavaObject>(
                                    allTask,
                                    completeTask =>
                                {
                                    if (completeTask.Call <bool>("isSuccessful"))
                                    {
                                        using (var resultObject = taskGetPlayer.Call <AndroidJavaObject>("getResult"))
                                        {
                                            mUser = AndroidJavaConverter.ToPlayer(resultObject);
                                        }

                                        var account = mTokenClient.GetAccount();
                                        lock (GameServicesLock)
                                        {
                                            mSavedGameClient = new AndroidSavedGameClient(account);
                                            mEventsClient    = new AndroidEventsClient(account);
                                            bool isCaptureSupported;
                                            using (var resultObject =
                                                       taskIsCaptureSupported.Call <AndroidJavaObject>("getResult"))
                                            {
                                                isCaptureSupported = resultObject.Call <bool>("booleanValue");
                                            }

                                            mVideoClient     = new AndroidVideoClient(isCaptureSupported, account);
                                            mRealTimeClient  = new AndroidRealTimeMultiplayerClient(this, account);
                                            mTurnBasedClient = new AndroidTurnBasedMultiplayerClient(this, account);
                                            mTurnBasedClient.RegisterMatchDelegate(mConfiguration.MatchDelegate);
                                        }

                                        mAuthState = AuthState.Authenticated;
                                        InvokeCallbackOnGameThread(callback, true, "Authentication succeed");
                                        try
                                        {
                                            using (var activationHint =
                                                       taskGetActivationHint.Call <AndroidJavaObject>("getResult"))
                                            {
                                                if (mInvitationDelegate != null)
                                                {
                                                    try
                                                    {
                                                        using (var invitationObject =
                                                                   activationHint.Call <AndroidJavaObject>("getParcelable",
                                                                                                           "invitation" /* Multiplayer.EXTRA_INVITATION */))
                                                        {
                                                            Invitation invitation =
                                                                AndroidJavaConverter.ToInvitation(invitationObject);
                                                            mInvitationDelegate(invitation, /* shouldAutoAccept= */
                                                                                true);
                                                        }
                                                    }
                                                    catch (Exception)
                                                    {
                                                        // handle null return
                                                    }
                                                }


                                                if (mTurnBasedClient.MatchDelegate != null)
                                                {
                                                    try
                                                    {
                                                        using (var matchObject =
                                                                   activationHint.Call <AndroidJavaObject>("getParcelable",
                                                                                                           "turn_based_match" /* Multiplayer#EXTRA_TURN_BASED_MATCH */)
                                                               )
                                                        {
                                                            TurnBasedMatch turnBasedMatch =
                                                                AndroidJavaConverter.ToTurnBasedMatch(matchObject);
                                                            mTurnBasedClient.MatchDelegate(
                                                                turnBasedMatch, /* shouldAutoLaunch= */ true);
                                                        }
                                                    }
                                                    catch (Exception)
                                                    {
                                                    }
                                                }
                                            }
                                        }
                                        catch (Exception)
                                        {
                                            // handle null return
                                        }

                                        LoadAchievements(ignore => { });
                                    }
                                    else
                                    {
                                        SignOut();
                                        InvokeCallbackOnGameThread(callback, false, "Authentication failed");
                                    }
                                }
                                    );
                            }
                    }
                }
                else
                {
                    lock (AuthStateLock)
                    {
                        if (result == 16 /* CommonStatusCodes.CANCELED */)
                        {
                            InvokeCallbackOnGameThread(callback, false, "Authentication canceled");
                        }
                        else if (result == 8 /* CommonStatusCodes.DEVELOPER_ERROR */)
                        {
                            InvokeCallbackOnGameThread(callback, false, "Authentication failed - developer error");
                        }
                        else
                        {
                            InvokeCallbackOnGameThread(callback, false, "Authentication failed");
                        }
                    }
                }
            });
        }
예제 #53
0
        /// <summary>
        /// Add a person to the invitation list
        /// </summary>
        /// <returns></returns>
        public ActionResult Create(int personId)
        {
            var person = Repository.OfType<Person>().GetNullableById(personId);
            var seminar = SiteService.GetLatestSeminar(Site);

            if (person == null || seminar == null) return this.RedirectToAction<ErrorController>(a => a.Index());

            var reg = person.GetLatestRegistration(Site);

            var invitation = new Invitation(person) {Seminar = seminar, Title= reg != null ? reg.Title : string.Empty, FirmName = reg != null && reg.Firm != null ? reg.Firm.Name : string.Empty};

            return View(invitation);
        }
 public void SetInvitation(Invitation val)
 {
     this.Invitation = val;
 }
예제 #55
0
 public void InviteToPlay(Invitation invitation)
 {
     if (invitation != null)
     {
         invitation.ErrorOccurred += OnErrorOccured;
         InviteStatus status = InviteManager.IsValidInvite(invitation);
         switch (status.StatusType)
         {
             case InviteStatusType.Invalid:
             case InviteStatusType.Rejected:
                 Clients.Caller.notify(new UserNotification(status.Message, UserNotificationType.Red));
                 break;
             case InviteStatusType.Valid:
             default:
                 Clients.Client(invitation.To.Id).showInviteModal(invitation.InviteToMarkup());
                 break;
         }
     }
 }
예제 #56
0
 public void AddInvitation(Invitation invitation)
 {
     this.invitationRepository.Add(invitation);
 }
예제 #57
0
 public void CreateInvittation(Invitation invitation)
 {
     this._invitationRepository.Add(invitation);
     this._unitOfWork.Commit();
 }
예제 #58
0
        public void SendInvitation([FromBody] dynamic inv)
        {
            ReviveCommunicationsDBEntities3 db = new ReviveCommunicationsDBEntities3();

            db.Configuration.ProxyCreationEnabled = false;
            DbContextTransaction transaction = db.Database.BeginTransaction();

            if (inv != null) //if object not null
            {
                try
                {
                    Invitation dynamicInvitation = new Invitation();

                    //create new announcement based on Object received
                    dynamicInvitation.InvitationDate           = inv.InvitationDate.ToString("yyyy-mm-dd");
                    dynamicInvitation.InvitationSenderPersonID = inv.PersonID;
                    dynamicInvitation.InvitationDetail         = inv.InvitationDetail;
                    dynamicInvitation.StartTime = inv.StartTime.ToString("HH:mm");
                    dynamicInvitation.EndTime   = inv.EndTime.ToString("HH:mm");
                    dynamicInvitation.Summary   = inv.Summary;


                    db.Invitations.Add(dynamicInvitation);                                                    // add Invite to database
                    db.SaveChanges();                                                                         //save

                    string d = inv.InvitationDetail;                                                          //write new Invite detail to string

                    Invitation created = db.Invitations.Where(x => x.InvitationDetail == d).FirstOrDefault(); //retrieve created Invite



                    foreach (dynamic p in inv.SelectedReceivers)// foreach person in receiver list
                    {
                        //create new Person_Announcement entry
                        Person_Invitation person_Invitation = new Person_Invitation();
                        person_Invitation.PersonID     = p.PersonID;
                        person_Invitation.InvitationID = created.InvitationID;


                        db.Person_Invitation.Add(person_Invitation);// Add to data base
                        db.SaveChanges();
                    }
                    int id = db.Invitations.OrderByDescending(x => x.InvitationID).Select(x => x.InvitationID).FirstOrDefault();

                    Audit_Trail auditLog = new Audit_Trail();
                    auditLog.PersonID         = inv.PersonID;
                    auditLog.EventDescription = "Sent invitation with ID: " + id;
                    auditLog.EventDateTime    = DateTime.Now;
                    db.Audit_Trail.Add(auditLog);

                    db.SaveChanges();//save
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    dynamic toReturn = new ExpandoObject();
                    toReturn = e.Message + e.InnerException;// else error
                }
            }
        }
예제 #59
0
 public InvitationCreatedDomainEvent(Invitation invitation)
 {
     Invitation = invitation;
 }
예제 #60
0
 /*
  * Handle a invitation reply
  */
 public void OnInvitationReply(BaseEvent evt)
 {
     currentInvitation = (Invitation) evt.Params["invitation"];
     User invitee = (User)evt.Params["invitee"];
     if ((InvitationReply)evt.Params["reply"] == InvitationReply.REFUSE)
     {
         lock(messagesLocker)
             chatMessages.Add("[SASHA]: " + invitee.Name + " has refused the invitation");
     }
 }