Example #1
0
 public void should_get_named_value()
 {
     var @object = new Members();
     @object["oh"] = "hai";
     new CachedMember(typeof(Members).GetProperty("Item"))
         .GetValue(@object, "oh").ShouldEqual("hai");
 }
Example #2
0
        public void All()
        {
            var members = new Members(databaseProvider);
            Member member = CreateAliceWithPhoneNumber();
            member = members.Insert(member);
            var donations = new Donations(databaseProvider);
            donations.Insert(new Donation {MemberId = member.Id, Amount = 12.50m, Date = DateTime.Today});
            donations.Insert(new Donation { MemberId = member.Id, Amount = 12.50m, Date = DateTime.Today.Subtract(TimeSpan.FromDays(1)) });

            var list = members.GetAll().ToList();
            Assert.IsNotNull(list);
            Assert.AreEqual(1, list.Count);
            member = list.FirstOrDefault();
            Assert.IsNotNull(member);
            Assert.AreEqual("ABC", member.Reference);
            Assert.AreEqual("Ms", member.Title);
            Assert.AreEqual("Alice", member.FirstName);
            Assert.AreEqual("Krige", member.LastName);
            Assert.AreEqual("Alice", member.Salutation);
            Assert.AreEqual("*****@*****.**", member.EmailAddress);
            Assert.AreEqual("Dunassimilatin", member.AddressLine1);
            Assert.AreEqual("Sector 4", member.AddressLine2);
            Assert.AreEqual("Nexus One", member.City);
            Assert.AreEqual("Delta Quadrant", member.Region);
            Assert.AreEqual("Wales", member.Country);
            Assert.AreEqual("CA1 0PP", member.PostalCode);
            Assert.AreEqual(25m, member.TotalDonations);

            Assert.AreEqual(1, member.PhoneNumbers.Count);
            PhoneNumber phone = member.PhoneNumbers.First();
            Assert.AreEqual(member.Id, phone.MemberId);
            Assert.AreEqual(PhoneNumberType.Home, phone.PhoneNumberType);
            Assert.AreEqual("01234 567890", phone.Number);
        }
Example #3
0
        public void Get()
        {
            var members = new Members(databaseProvider);
            Member member = CreateAliceWithPhoneNumber();
            member = members.Insert(member);

            member = members.GetById(member.Id);
            Assert.AreEqual("ABC", member.Reference);
            Assert.AreEqual("Ms", member.Title);
            Assert.AreEqual("Alice", member.FirstName);
            Assert.AreEqual("Krige", member.LastName);
            Assert.AreEqual("Alice", member.Salutation);
            Assert.AreEqual("*****@*****.**", member.EmailAddress);
            Assert.AreEqual("Dunassimilatin", member.AddressLine1);
            Assert.AreEqual("Sector 4", member.AddressLine2);
            Assert.AreEqual("Nexus One", member.City);
            Assert.AreEqual("Delta Quadrant", member.Region);
            Assert.AreEqual("Wales", member.Country);
            Assert.AreEqual("CA1 0PP", member.PostalCode);

            Assert.AreEqual(1, member.PhoneNumbers.Count);
            PhoneNumber phone = member.PhoneNumbers.First();
            Assert.AreEqual(member.Id, phone.MemberId);
            Assert.AreEqual(PhoneNumberType.Home, phone.PhoneNumberType);
            Assert.AreEqual("01234 567890", phone.Number);
        }
Example #4
0
 public void should_get_value(CachedMember cachedMember, MemberInfo memberInfo)
 {
     var @object = new Members();
     @object.SetPropertyOrFieldValue(memberInfo.Name,
         memberInfo.GetPropertyOrFieldType() == typeof(string) ?
             "hai" : (object)(Optional<string>)"hai");
     cachedMember.GetValue(@object).As<string>().ShouldEqual("hai");
 }
Example #5
0
 // Use this for initialization
 void Start()
 {
     Members m = new Members();
     m.FirstFunction();
     print(ImANumber());
     print(INeedANumber(1));
     //		int val = INeedANumber(3) + INeedANumber(7);
     //		print(val);
     int val = INeedTwoNumbers(3, 7);
     print(val);
 }
Example #6
0
        public void ReadTest()
        {
            var target = new Members();
            var currentDir = Directory.GetCurrentDirectory();
            var fileName = "members.json";
            var filePath = Path.Combine(currentDir, fileName);
            target.Read(filePath);

            var expected = 3;
            var actual = target.Profiles.Count();
            Assert.AreEqual(expected, actual);
        }
Example #7
0
        internal Members ToMembers()
        {
            Members m = new Members();
            m.Count = (uint)this.Members.Count;
            if (this.Level != null) m.Level = this.Level.Value;

            foreach (string s in this.Members)
            {
                m.Append(new Member() { Name = s });
            }

            return m;
        }
Example #8
0
        public void GetActiveUsersTest()
        {
            var currentDir = Directory.GetCurrentDirectory();
            var fileName = "members.json";
            var filePath = Path.Combine(currentDir, fileName);
            Members.Initailze(filePath);

            var target = new Members();
            target.Read(filePath);
            var result = target.GetActiveUsers(2);

            var expected = 2;
            var actual = result.Count();
            Assert.AreEqual(expected, actual);
        }
Example #9
0
        static void Main(string[] args)
        {
            Console.WriteLine("---- 処理開始 ----");

            //ディレクトリ
            var currentDir = Directory.GetCurrentDirectory();
            var messageFilePath = Path.Combine(currentDir, MESSAGE_DIR);

            //メッセージの読み込み
            var message = new Message();
            message.Read(messageFilePath);

            var mailList = new List<IMail>();
            //メンバー情報
            var members = new Members();
            var memberFilePath = Path.Combine(currentDir, MEMBER_FILE);
            //HACK:メンバーファイルを初期化したいときに使用する
            Members.Initailze(memberFilePath);
            //メンバーファイル読み込み
            members.Read(memberFilePath);

            var activeUsers = members.GetActiveUsers(message.Messages.Count());

            foreach (var user in activeUsers)
            {
                var index = user.Count - 1;
                var selectMessage = message.Messages[index];

                mailList.Add(Mail.CreateMail(user.Mail, string.Empty, user.Count, selectMessage));
            }
            foreach (var mail in mailList)
            {
                mail.Send();
            }

            members.CountUp();
            //メンバーファイルの更新
            var val = members.Serialize();
            Members.Save(memberFilePath, val);

            //終了
            Console.WriteLine("---- 処理終了 ----");
            Console.ReadKey();
        }
Example #10
0
        internal void FromMembers(Members m)
        {
            this.SetAllNull();

            if (m.Level != null) this.Level = m.Level.Value;

            Member mem;
            using (OpenXmlReader oxr = OpenXmlReader.Create(m))
            {
                while (oxr.Read())
                {
                    if (oxr.ElementType == typeof(Member))
                    {
                        mem = (Member)oxr.LoadCurrentElement();
                        this.Members.Add(mem.Name.Value);
                    }
                }
            }
        }
Example #11
0
        public void CountUpTest()
        {
            var currentDir = Directory.GetCurrentDirectory();
            var fileName = "members.json";
            var filePath = Path.Combine(currentDir, fileName);
            Members.Initailze(filePath);

            var target = new Members();
            target.Read(filePath);
            target.CountUp();

            var expected01 = 2;
            var actual01 = target.Profiles[0].Count;
            Assert.AreEqual(expected01, actual01);

            var expected02 = 3;
            var actual02 = target.Profiles[1].Count;
            Assert.AreEqual(expected02, actual02);

            var expected03 = 3;
            var actual03 = target.Profiles[1].Count;
            Assert.AreEqual(expected03, actual03);
        }
Example #12
0
        protected override bool DoDefineMembers()
        {
            PredefinedType builder_type;
            PredefinedMember <MethodSpec> bf;
            PredefinedMember <MethodSpec> bs;
            PredefinedMember <MethodSpec> sr;
            PredefinedMember <MethodSpec> se;
            PredefinedMember <MethodSpec> sm;
            bool has_task_return_type = false;
            var  pred_members         = Module.PredefinedMembers;

            if (return_type.Kind == MemberKind.Void)
            {
                builder_type = Module.PredefinedTypes.AsyncVoidMethodBuilder;
                bf           = pred_members.AsyncVoidMethodBuilderCreate;
                bs           = pred_members.AsyncVoidMethodBuilderStart;
                sr           = pred_members.AsyncVoidMethodBuilderSetResult;
                se           = pred_members.AsyncVoidMethodBuilderSetException;
                sm           = pred_members.AsyncVoidMethodBuilderSetStateMachine;
            }
            else if (return_type == Module.PredefinedTypes.Task.TypeSpec)
            {
                builder_type = Module.PredefinedTypes.AsyncTaskMethodBuilder;
                bf           = pred_members.AsyncTaskMethodBuilderCreate;
                bs           = pred_members.AsyncTaskMethodBuilderStart;
                sr           = pred_members.AsyncTaskMethodBuilderSetResult;
                se           = pred_members.AsyncTaskMethodBuilderSetException;
                sm           = pred_members.AsyncTaskMethodBuilderSetStateMachine;
                task         = pred_members.AsyncTaskMethodBuilderTask.Get();
            }
            else
            {
                builder_type         = Module.PredefinedTypes.AsyncTaskMethodBuilderGeneric;
                bf                   = pred_members.AsyncTaskMethodBuilderGenericCreate;
                bs                   = pred_members.AsyncTaskMethodBuilderGenericStart;
                sr                   = pred_members.AsyncTaskMethodBuilderGenericSetResult;
                se                   = pred_members.AsyncTaskMethodBuilderGenericSetException;
                sm                   = pred_members.AsyncTaskMethodBuilderGenericSetStateMachine;
                task                 = pred_members.AsyncTaskMethodBuilderGenericTask.Get();
                has_task_return_type = true;
            }

            set_result      = sr.Get();
            set_exception   = se.Get();
            builder_factory = bf.Get();
            builder_start   = bs.Get();

            var istate_machine   = Module.PredefinedTypes.IAsyncStateMachine;
            var set_statemachine = sm.Get();

            if (!builder_type.Define() || !istate_machine.Define() || set_result == null || builder_factory == null ||
                set_exception == null || set_statemachine == null || builder_start == null ||
                !Module.PredefinedTypes.INotifyCompletion.Define())
            {
                Report.Error(1993, Location,
                             "Cannot find compiler required types for asynchronous functions support. Are you targeting the wrong framework version?");
                return(base.DoDefineMembers());
            }

            var bt = builder_type.TypeSpec;

            //
            // Inflate generic Task types
            //
            if (has_task_return_type)
            {
                var task_return_type = return_type.TypeArguments;
                if (mutator != null)
                {
                    task_return_type = mutator.Mutate(task_return_type);
                }

                bt               = bt.MakeGenericType(Module, task_return_type);
                set_result       = MemberCache.GetMember(bt, set_result);
                set_exception    = MemberCache.GetMember(bt, set_exception);
                set_statemachine = MemberCache.GetMember(bt, set_statemachine);

                if (task != null)
                {
                    task = MemberCache.GetMember(bt, task);
                }
            }

            builder = AddCompilerGeneratedField("$builder", new TypeExpression(bt, Location));

            var set_state_machine = new Method(this, new TypeExpression(Compiler.BuiltinTypes.Void, Location),
                                               Modifiers.COMPILER_GENERATED | Modifiers.DEBUGGER_HIDDEN | Modifiers.PUBLIC,
                                               new MemberName("SetStateMachine"),
                                               ParametersCompiled.CreateFullyResolved(
                                                   new Parameter(new TypeExpression(istate_machine.TypeSpec, Location), "stateMachine", Parameter.Modifier.NONE, null, Location),
                                                   istate_machine.TypeSpec),
                                               null);

            ToplevelBlock block = new ToplevelBlock(Compiler, set_state_machine.ParameterInfo, Location);

            block.IsCompilerGenerated = true;
            set_state_machine.Block   = block;

            Members.Add(set_state_machine);

            if (!base.DoDefineMembers())
            {
                return(false);
            }

            //
            // Fabricates SetStateMachine method
            //
            // public void SetStateMachine (IAsyncStateMachine stateMachine)
            // {
            //    $builder.SetStateMachine (stateMachine);
            // }
            //
            var mg = MethodGroupExpr.CreatePredefined(set_statemachine, bt, Location);

            mg.InstanceExpression = new FieldExpr(builder, Location);

            var param_reference = block.GetParameterReference(0, Location);

            param_reference.Type   = istate_machine.TypeSpec;
            param_reference.eclass = ExprClass.Variable;

            var args = new Arguments(1);

            args.Add(new Argument(param_reference));
            set_state_machine.Block.AddStatement(new StatementExpression(new Invocation(mg, args)));

            if (has_task_return_type)
            {
                HoistedReturnValue = TemporaryVariableReference.Create(bt.TypeArguments [0], StateMachineMethod.Block, Location);
            }

            return(true);
        }
Example #13
0
        private async void enterButton_Click(object sender, RoutedEventArgs e)
        {
            bool notNull = false;

            //null string check 4-9-2015
            #region NullStringCheck
            if (string.IsNullOrWhiteSpace(usernameBox.Text))
            {
                MessageDialog msg = new MessageDialog("username cannot be empty.");
                await msg.ShowAsync();
            }
            else if (string.IsNullOrWhiteSpace(passwordBox.Password))
            {
                MessageDialog msg1 = new MessageDialog("password cannot be empty");
                await msg1.ShowAsync();
            }
            else if (string.IsNullOrWhiteSpace(confirmPasswordBox.Password))
            {
                MessageDialog msg2 = new MessageDialog("confirm password cannot be empty");
                await msg2.ShowAsync();
            }
            else if (string.IsNullOrWhiteSpace(cityBox.Text))
            {
                MessageDialog msg3 = new MessageDialog("city cannot be left empty");
                await msg3.ShowAsync();
            }
            else if (string.IsNullOrWhiteSpace(stateBox.Text))
            {
                MessageDialog msg4 = new MessageDialog("state cannot be left empty");
                await msg4.ShowAsync();
            }
            else
            {
                notNull = true;
            }
            #endregion

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("http://nflff.azurewebsites.net/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                //values obtained through popup
                string username = usernameBox.Text;
                string password = null;
                if (passwordBox.Password.Equals(confirmPasswordBox.Password))
                {
                    password = passwordBox.Password;
                }
                else
                {
                    //what should happen if passwords invalid?
                    //They should be electrocuted for forgetting....
                    MessageDialog msg5 = new MessageDialog("passwords don't match");
                    await msg5.ShowAsync();

                    return; //stops method and prompts for error
                }
                string city  = cityBox.Text;
                string state = stateBox.Text;
                int    team  = 0;
                //teamIDs are 65 - 96. Need to create a combo box for this
                //team = Convert.ToInt32(teamBox.Text);
                ComboBoxItem typeItem = (ComboBoxItem)teamBox.SelectedItem;
                string       teamStr  = typeItem.Content.ToString();
                //string teamStr = t.ToString();
                team = Teams.getIdFromTeamName(teamStr);

                //trying to catch exception thrown from not filling in all fields
                Members addedMember = new Members(username, password, city, state, team);
                if (addedMember.usernameIsUnique(username))
                {
                    if (addedMember.completelyFilled())
                    {
                        //MembersListBox.Items.Add("username is unique");
                        String      newMemberStr = JsonConvert.SerializeObject(addedMember);
                        HttpContent postStr      = new StringContent(newMemberStr);
                        var         response     = await client.PostAsync("api/Members?newMember=" + WebUtility.UrlEncode(newMemberStr), postStr);

                        HttpResponseMessage memberResponse = await client.GetAsync("api/Members?MemberStr=" + username);

                        //if memberId displays as -1, means response failed. 0 means page not receiving value
                        int memberId = -1;
                        if (memberResponse.StatusCode == HttpStatusCode.OK)
                        {
                            // got the memberId...
                            memberId = Convert.ToInt32(memberResponse.Content.ReadAsStringAsync().Result);
                        }
                        //internet connection test
                        else
                        {
                            MessageDialog msg = new MessageDialog("You need internet connection to continue");
                            await msg.ShowAsync();

                            return;
                        }
                        if (notNull == true)
                        {
                            MessageDialog msg = new MessageDialog("Account created successfully");
                            await msg.ShowAsync();

                            this.Frame.Navigate(typeof(HomeHub), memberId);
                        }
                    }
                }
                else
                {
                    MessageDialog msg6 = new MessageDialog("username is already taken");
                    await msg6.ShowAsync();
                }
            }
        }
Example #14
0
        public bool SaveMember(object obj)
        {
            try
            {
                if (SelectedMember.Address != null)
                {
                    if (string.IsNullOrEmpty(SelectedMember.Address.Mobile))
                    {
                        MessageBox.Show("Fill Member Mobile Number!!");
                        MemberAddress();
                        return(false);
                    }
                }

                if (EmployeeShortImage != null && EmployeeShortImage.UriSource != null)
                {
                    if (_photoAttachment != null)
                    {
                        _photoAttachment.AttachedFile = ImageUtil.ToBytes(EmployeeShortImage);
                        SelectedMember.Photo          = _photoAttachment;
                    }
                    else
                    {
                        _photoAttachment = new AttachmentDTO {
                            AttachedFile = ImageUtil.ToBytes(EmployeeShortImage)
                        };
                        SelectedMember.Photo = _photoAttachment;
                    }
                }

                var newObject = SelectedMember.Id;
                SelectedMember.Type = (MemberTypes)SelectedMemberType.Value;

                var stat = _memberService.InsertOrUpdate(SelectedMember);

                if (stat != string.Empty)
                {
                    MessageBox.Show("Can't save"
                                    + Environment.NewLine + stat, "Can't save", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                }

                else if (newObject == 0)
                {
                    SelectedMember.Number = _memberService.GetMemberNumber(SelectedMember.Id);
                    stat = _memberService.InsertOrUpdate(SelectedMember);
                    if (stat != string.Empty)
                    {
                        MessageBox.Show("Can't save Number"
                                        + Environment.NewLine + stat, "Can't save", MessageBoxButton.OK,
                                        MessageBoxImage.Error);
                        return(false);
                    }
                    else
                    {
                        var criteria = new SearchCriteria <MemberDTO>();
                        criteria.FiList.Add(m => m.Id == SelectedMember.Id);
                        SelectedMember = _memberService.GetAll(criteria).FirstOrDefault();
                        Members.Insert(0, SelectedMember);
                        //Load();
                        //if (Members != null) SelectedMember = Members.FirstOrDefault();
                        return(true);
                    }
                }
                else
                {
                    //var memId = SelectedMember.Id;

                    //Load();
                    //if (Members != null) SelectedMember = Members.FirstOrDefault(m => m.Id == memId);
                }
                return(true);
            }
            catch (Exception exception)
            {
                MessageBox.Show("Can't save"
                                + Environment.NewLine + exception.Message, "Can't save", MessageBoxButton.OK,
                                MessageBoxImage.Error);
                return(false);
            }
        }
Example #15
0
        private bool CacheAttributeConstructedWithParam(CustomAttribute attribute, Members cachedMembers)
        {
            if (attribute == null || attribute.ConstructorArguments.Count == 0)
            {
                return false;
            }

            return Equals(attribute.ConstructorArguments.Single().Value, (int)cachedMembers);
        }
 public Image(string number, Members members)
 {
     Number = number;
     Members = members;
 }
Example #17
0
        public void VisitConstructorInitializer(Members.ConstructorInitializer initializer)
        {
            Formatter.StartNode(initializer);

            Formatter.WriteKeyword(Members.ConstructorInitializer.VariantToString(initializer.Variant));
            Formatter.WriteToken("(");
            WriteCommaSeparatedNodes(initializer.Arguments);
            Formatter.WriteToken(")");

            Formatter.EndNode();
        }
 /// <summary>
 /// Gets the enumerator for the list of members.
 /// </summary>
 /// <returns></returns>
 public SyntaxList <MemberDeclarationSyntax> .Enumerator GetEnumerator()
 {
     return(Members.GetEnumerator());
 }
Example #19
0
 public Member?TryGetMember(Snowflake id) => Members.FirstOrDefault(m => m.Id == id);
        /// <summary>
        /// Update the membership user using the membership provider (for things like email, etc...)
        /// If a password change is detected then we'll try that too.
        /// </summary>
        /// <param name="contentItem"></param>
        /// <returns>
        /// If the password has been reset then this method will return the reset/generated password, otherwise will return null.
        /// </returns>
        private string UpdateWithMembershipProvider(MemberSave contentItem)
        {
            //Get the member from the provider

            var membershipUser = _provider.GetUser(contentItem.PersistedContent.Key, false);

            if (membershipUser == null)
            {
                //This should never happen! so we'll let it YSOD if it does.
                throw new InvalidOperationException("Could not get member from membership provider " + _provider.Name + " with key " + contentItem.PersistedContent.Key);
            }

            var shouldReFetchMember = false;
            var providedUserName    = contentItem.PersistedContent.Username;

            //if the user doesn't have access to sensitive values, then we need to check if any of the built in member property types
            //have been marked as sensitive. If that is the case we cannot change these persisted values no matter what value has been posted.
            //There's only 3 special ones we need to deal with that are part of the MemberSave instance
            if (Security.CurrentUser.HasAccessToSensitiveData() == false)
            {
                var sensitiveProperties = contentItem.PersistedContent.ContentType
                                          .PropertyTypes.Where(x => contentItem.PersistedContent.ContentType.IsSensitiveProperty(x.Alias))
                                          .ToList();

                foreach (var sensitiveProperty in sensitiveProperties)
                {
                    //if found, change the value of the contentItem model to the persisted value so it remains unchanged
                    switch (sensitiveProperty.Alias)
                    {
                    case Constants.Conventions.Member.Comments:
                        contentItem.Comments = contentItem.PersistedContent.Comments;
                        break;

                    case Constants.Conventions.Member.IsApproved:
                        contentItem.IsApproved = contentItem.PersistedContent.IsApproved;
                        break;

                    case Constants.Conventions.Member.IsLockedOut:
                        contentItem.IsLockedOut = contentItem.PersistedContent.IsLockedOut;
                        break;
                    }
                }
            }

            //Update the membership user if it has changed
            try
            {
                var requiredUpdating = Members.UpdateMember(membershipUser, _provider,
                                                            contentItem.Email.Trim(),
                                                            contentItem.IsApproved,
                                                            comment: contentItem.Comments);

                if (requiredUpdating.Success)
                {
                    //re-map these values
                    shouldReFetchMember = true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WarnWithException <MemberController>("Could not update member, the provider returned an error", ex);
                ModelState.AddPropertyError(
                    //specify 'default' just so that it shows up as a notification - is not assigned to a property
                    new ValidationResult("Could not update member, the provider returned an error: " + ex.Message + " (see log for full details)"), "default");
            }

            //if they were locked but now they are trying to be unlocked
            if (membershipUser.IsLockedOut && contentItem.IsLockedOut == false)
            {
                try
                {
                    var result = _provider.UnlockUser(membershipUser.UserName);
                    if (result == false)
                    {
                        //it wasn't successful - but it won't really tell us why.
                        ModelState.AddModelError("custom", "Could not unlock the user");
                    }
                    else
                    {
                        shouldReFetchMember = true;
                    }
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("custom", ex);
                }
            }
            else if (membershipUser.IsLockedOut == false && contentItem.IsLockedOut)
            {
                //NOTE: This should not ever happen unless someone is mucking around with the request data.
                //An admin cannot simply lock a user, they get locked out by password attempts, but an admin can un-approve them
                ModelState.AddModelError("custom", "An admin cannot lock a user");
            }

            //password changes ?
            if (contentItem.Password == null)
            {
                //If the provider has changed some values, these values need to be reflected in the member object
                //that will get mapped to the display object
                if (shouldReFetchMember)
                {
                    RefetchMemberData(contentItem, LookupType.ByKey);
                    RestoreProvidedUserName(contentItem, providedUserName);
                }

                return(null);
            }

            var passwordChangeResult = Members.ChangePassword(membershipUser.UserName, contentItem.Password, _provider);

            if (passwordChangeResult.Success)
            {
                //If the provider has changed some values, these values need to be reflected in the member object
                //that will get mapped to the display object
                if (shouldReFetchMember)
                {
                    RefetchMemberData(contentItem, LookupType.ByKey);
                    RestoreProvidedUserName(contentItem, providedUserName);
                }

                //even if we weren't resetting this, it is the correct value (null), otherwise if we were resetting then it will contain the new pword
                return(passwordChangeResult.Result.ResetPassword);
            }

            //it wasn't successful, so add the change error to the model state
            ModelState.AddPropertyError(
                passwordChangeResult.Result.ChangeError,
                string.Format("{0}password", Constants.PropertyEditors.InternalGenericPropertiesPrefix));

            return(null);
        }
Example #21
0
        public Members GetMember(string username)
        {
            Members m = db.Members.Where(a => a.UserName == username).SingleOrDefault();

            return(m);
        }
 protected override void PopulateDisplayMembers()
 {
     DisplayMembers = Members.Where(x => SelectedMembers.Distinct().Contains(x.Id)).ToList();
 }
Example #23
0
        private bool CacheAttributeMembersExplicitly(CustomAttribute attribute, Members requiredFlag)
        {
            if (attribute == null || attribute.ConstructorArguments.Count == 0)
            {
                return false;
            }

            Members constructorArgument = (Members)attribute.ConstructorArguments.Single().Value;

            return constructorArgument.HasFlag(requiredFlag);
        }
Example #24
0
        public virtual bool HasMember(Artist member)
        {
            ParamIs.NotNull(() => member);

            return(Members.Any(a => a.Member.Equals(member)));
        }
Example #25
0
 public void Register(Members newMember)
 {
     newMember.Password = HashPassword(newMember.Password);
     db.Members.Add(newMember);
     db.SaveChanges();
 }
Example #26
0
 public void UpdateMeta(SwimMeta meta)
 {
     Members.UpdateMeta(meta);
 }
Example #27
0
 public async Task<MessageConsultation> SendMessage(Members.Models.MessageEntity entity)
 {
     return await MembersController.UserContext.SendMessage(entity.Message);
 }
Example #28
0
        public async Task <QueryResult <IDictionary <string, object> > > QueryMembersDynamic(
            MemberQueryProjection projection,
            IDictionary <string, object> tempData = null,
            MemberQueryFilter filter   = null,
            MemberQuerySort sort       = null,
            MemberQueryPaging paging   = null,
            MemberQueryOptions options = null)
        {
            var query = Members.AsNoTracking();

            if (filter != null)
            {
                query = query.Filter(filter, tempData);
            }
            int?totalCount = null; Task <int> countTask = null;
            var countQuery = query;

            query = query.Project(projection);
            if (options != null && !options.single_only)
            {
                #region List query
                if (sort != null)
                {
                    query = query.Sort(sort);
                }
                if (paging != null && (!options.load_all || !MemberQueryOptions.IsLoadAllAllowed))
                {
                    query = query.SelectPage(paging.page, paging.limit);
                }
                #endregion
                #region Count query
                if (options.count_total)
                {
                    countTask = countQuery.CountAsync();
                }
                #endregion
            }
            if (options != null && options.count_total)
            {
                totalCount = await countTask;
            }
            var queryResult = await query.ToListAsync();

            if (options != null && options.single_only)
            {
                var single = queryResult.FirstOrDefault();
                if (single == null)
                {
                    return(null);
                }
                var singleResult = GetMemberDynamic(single, projection, options);
                return(new QueryResult <IDictionary <string, object> >()
                {
                    SingleResult = singleResult
                });
            }
            var results = GetMemberDynamic(queryResult, projection, options);
            return(new QueryResult <IDictionary <string, object> >()
            {
                Results = results,
                TotalCount = totalCount
            });
        }
Example #29
0
 public void InsertMemberWithPhoneNumber()
 {
     var members = new Members(databaseProvider);
     Member member = CreateAliceWithPhoneNumber();
     member = members.Insert(member);
     Assert.AreNotEqual(0, member.Id);
     Assert.AreEqual(1, member.PhoneNumbers.Count);
     Assert.AreEqual(member.Id, member.PhoneNumbers.First().MemberId);
 }
Example #30
0
 public void AddMember(Character character)
 {
     Members.Add(character);
     Members.Sort();
 }
 public List<FileInfo> GetImageFiles(Members member)
 {
     return Images.Where(i => i.Members.HasFlag(member)).Select(ImageFileInfo).ToList();
 }
Example #32
0
        public ActionResult Login(LoginModel model)
        {
            var recaptcha = ModelState["ReCaptcha"];

            if (recaptcha != null && HttpContext.Request.IsLocal)
            {
                recaptcha.Errors.Clear();
            }

            if (ModelState.IsValid == false)
            {
                return(CurrentUmbracoPage());
            }

            var memberService = Services.MemberService;
            int totalMembers;
            var members = memberService.FindByEmail(model.Username, 0, 100, out totalMembers).ToList();

            if (totalMembers > 1)
            {
                var duplicateMembers = new List <DuplicateMember>();
                foreach (var member in members)
                {
                    var totalKarma      = member.GetValue <int>("reputationTotal");
                    var duplicateMember = new DuplicateMember {
                        MemberId = member.Id, TotalKarma = totalKarma
                    };
                    duplicateMembers.Add(duplicateMember);
                }

                // rename username/email for each duplicate member
                // EXCEPT for the one with the highest karma (Skip(1))
                foreach (var duplicateMember in duplicateMembers.OrderByDescending(x => x.TotalKarma).ThenByDescending(x => x.MemberId).Skip(1))
                {
                    var member      = memberService.GetById(duplicateMember.MemberId);
                    var newUserName = member.Username.Replace("@", "@__" + member.Id);
                    member.Username = newUserName;
                    member.Email    = newUserName;
                    memberService.Save(member, false);
                }
            }

            var memberToLogin = memberService.FindByEmail(model.Username, 0, 1, out totalMembers).SingleOrDefault();

            if (memberToLogin != null)
            {
                // Note: After July 23rd 2015 we need people to activate their accounts! Don't approve automatically
                // otherwise:
                // Automatically approve all members, as we don't have an approval process now
                // This is needed as we added new membership after upgrading so IsApproved is
                // currently empty. First time a member gets saved now (login also saves the member)
                // IsApproved would turn false (default value of bool) so we want to prevent that
                if (memberToLogin.CreateDate < DateTime.Parse("2015-07-23") && memberToLogin.Properties.Contains(Constants.Conventions.Member.IsApproved) && memberToLogin.IsApproved == false)
                {
                    memberToLogin.IsApproved = true;
                    memberService.Save(memberToLogin, false);
                }
            }

            if (Members.Login(model.Username, model.Password))
            {
                return(Redirect("/"));
            }

            ModelState.AddModelError("", "That username and password combination isn't valid here");
            return(CurrentUmbracoPage());
        }
Example #33
0
 public MemberSerializationInfo GetMember(int index)
 {
     return(Members.FirstOrDefault(x => x.IntKey == index));
 }
Example #34
0
 public bool Contains(string node)
 {
     return(Members.ContainsKey(node) || Promotables.ContainsKey(node) || Watchers.ContainsKey(node));
 }
Example #35
0
 public void AddMembers(params Person[] newMembers)
 {
     Members.AddRange(newMembers);
 }
Example #36
0
        protected override bool DoDefineMembers()
        {
            current_field   = AddCompilerGeneratedField("$current", iterator_type_expr);
            disposing_field = AddCompilerGeneratedField("$disposing", new TypeExpression(Compiler.BuiltinTypes.Bool, Location));

            if (Iterator.IsEnumerable && hoisted_params != null)
            {
                //
                // Iterators are independent, each GetEnumerator call has to
                // create same enumerator therefore we have to keep original values
                // around for re-initialization
                //
                hoisted_params_copy = new List <HoistedParameter> (hoisted_params.Count);
                foreach (HoistedParameter hp in hoisted_params)
                {
                    //
                    // Don't create field copy for unmodified captured parameters
                    //
                    HoistedParameter hp_copy;
                    if (hp.IsAssigned)
                    {
                        hp_copy = new HoistedParameter(hp, "<$>" + hp.Field.Name);
                    }
                    else
                    {
                        hp_copy = null;
                    }

                    hoisted_params_copy.Add(hp_copy);
                }
            }

            if (generic_enumerator_type != null)
            {
                Define_Current(true);
            }

            Define_Current(false);
            new DisposeMethod(this);
            Define_Reset();

            if (Iterator.IsEnumerable)
            {
                FullNamedExpression explicit_iface = new TypeExpression(Compiler.BuiltinTypes.IEnumerable, Location);
                var name = new MemberName("GetEnumerator", null, explicit_iface, Location.Null);

                if (generic_enumerator_type != null)
                {
                    explicit_iface = new TypeExpression(generic_enumerable_type, Location);
                    var    gname           = new MemberName("GetEnumerator", null, explicit_iface, Location.Null);
                    Method gget_enumerator = GetEnumeratorMethod.Create(this, new TypeExpression(generic_enumerator_type, Location), gname);

                    //
                    // Just call generic GetEnumerator implementation
                    //
                    var    stmt           = new Return(new Invocation(new DynamicMethodGroupExpr(gget_enumerator, Location), null), Location);
                    Method get_enumerator = GetEnumeratorMethod.Create(this, new TypeExpression(Compiler.BuiltinTypes.IEnumerator, Location), name, stmt);

                    Members.Add(get_enumerator);
                    Members.Add(gget_enumerator);
                }
                else
                {
                    Members.Add(GetEnumeratorMethod.Create(this, new TypeExpression(Compiler.BuiltinTypes.IEnumerator, Location), name));
                }
            }

            return(base.DoDefineMembers());
        }
        public ActionResult HandleSubmit(RegisterModel model)
        {
            var recaptcha = ModelState["ReCaptcha"];

            if (recaptcha != null && HttpContext.Request.IsLocal)
            {
                recaptcha.Errors.Clear();
            }

            var locationInvalid = string.IsNullOrEmpty(model.Latitude) || string.IsNullOrEmpty(model.Longitude);

            if (!ModelState.IsValid || locationInvalid || model.AgreeTerms == false)
            {
                if (locationInvalid)
                {
                    ModelState.AddModelError("Location", "Please tell us a little bit about where you live.");
                }

                if (model.AgreeTerms == false)
                {
                    ModelState.AddModelError("AgreeTerms", "You can only continue if you agree to our terms and conditions.");
                }

                return(CurrentUmbracoPage());
            }

            var memberService = Services.MemberService;

            if (memberService.GetByEmail(model.Email) != null)
            {
                ModelState.AddModelError("Email", "A member with that email address already exists");
                return(CurrentUmbracoPage());
            }

            // If spammer then this will stop account creation
            var spamResult = Forum.Library.Utils.CheckForSpam(model.Email, model.Name, true);

            if (spamResult != null && spamResult.Blocked)
            {
                return(Redirect("/"));
            }

            if (string.IsNullOrWhiteSpace(model.Flickr) == false || string.IsNullOrWhiteSpace(model.Bio) == false)
            {
                //These fields are hidden, only a bot will know to fill them in
                //This honeypot catches them
                return(Redirect("/"));
            }

            // these values are enforced in MemberDto which is internal ;-(
            // we should really have ways to query for Core meta-data!
            const int maxEmailLength     = 400;
            const int maxLoginNameLength = 200;
            const int maxPasswordLength  = 400;
            const int maxPropertyLength  = 400;

            if (model.Email != null && model.Email.Length > maxEmailLength ||
                model.Name != null && model.Name.Length > maxLoginNameLength ||
                model.Password != null && model.Password.Length > maxPasswordLength ||
                model.Location != null && model.Location.Length > maxPropertyLength ||
                model.Longitude != null && model.Longitude.Length > maxPropertyLength ||
                model.Latitude != null && model.Latitude.Length > maxPropertyLength ||
                model.TwitterAlias != null && model.TwitterAlias.Length > maxPropertyLength
                )
            {
                // has to be a rogue registration
                // go away!
                return(Redirect("/"));
            }

            var member = memberService.CreateMember(model.Email, model.Email, model.Name, "member");

            member.SetValue("location", model.Location);
            member.SetValue("longitude", model.Longitude);
            member.SetValue("latitude", model.Latitude);
            member.SetValue("company", model.Company);
            member.SetValue("twitter", model.TwitterAlias);

            member.SetValue("treshold", "-10");
            member.SetValue("bugMeNot", false);

            member.SetValue("reputationTotal", 20);
            member.SetValue("reputationCurrent", 20);
            member.SetValue("forumPosts", 0);

            member.SetValue("tos", DateTime.Now);

            member.IsApproved = false;
            memberService.Save(member);

            // Now that we have a memberId we can use it
            var avatarPath = GetAvatarPath(member);

            member.SetValue("avatar", avatarPath);
            memberService.Save(member);

            memberService.AssignRole(member.Username, "standard");

            memberService.SavePassword(member, model.Password);

            Members.Login(model.Email, model.Password);

            if (spamResult != null && spamResult.TotalScore >= int.Parse(ConfigurationManager.AppSettings["PotentialSpammerThreshold"]))
            {
                spamResult.MemberId = member.Id;

                memberService.AssignRole(member.Id, "potentialspam");
                Forum.Library.Utils.SendPotentialSpamMemberMail(spamResult);
            }
            else
            {
                Forum.Library.Utils.SendActivationMail(member);
                Forum.Library.Utils.SendMemberSignupMail(member);
            }
            memberService.AssignRole(member.Id, "notactivated");
            memberService.AssignRole(member.Id, "newaccount");

            var redirectPage   = "/";
            var contentService = ApplicationContext.Current.Services.ContentService;
            var rootNode       = contentService.GetRootContent().OrderBy(x => x.SortOrder).First(x => x.ContentType.Alias == "Community");

            var memberNode = rootNode.Children().FirstOrDefault(x => x.Name == "Member");

            if (memberNode != null)
            {
                var umbracoHelper         = new UmbracoHelper(UmbracoContext.Current);
                var pendingActivationPage = memberNode.Children().FirstOrDefault(x => x.Name == "Pending activation");
                if (pendingActivationPage != null)
                {
                    var pendingActivationContentItem = umbracoHelper.TypedContent(pendingActivationPage.Id);
                    if (pendingActivationContentItem != null)
                    {
                        redirectPage = pendingActivationContentItem.Url;
                    }
                }
            }

            return(Redirect(redirectPage));
        }
 private void ChangeSignatureDialog_Loaded(object sender, RoutedEventArgs e)
 {
     Members.Focus();
 }
Example #39
0
        public ActionResult Register([Bind(Exclude = "IsEmailVerified,ActivationCode")] RegisterViewModel model)
        {
            bool    Status  = false;
            string  message = "";
            Members user    = new Members();

            user.MemberId        = model.MemberId;
            user.Membercity      = model.Membercity;
            user.LastName        = model.LastName;
            user.IsEmailVerified = model.IsEmailVerified;
            user.IsActive        = model.IsActive;
            user.FirstName       = model.FristName;
            user.Email           = model.Email;
            user.CreatedOn       = model.CreatedOn;
            user.Memberphoto     = model.Memberphoto;
            user.ModifiedOn      = model.ModifiedOn;
            user.Password        = model.Password;

            //Model validation
            if (ModelState.IsValid)
            {
                //Email is already exist
                #region
                var isExist = IsEmailExist(model.Email);
                if (isExist)
                {
                    ModelState.AddModelError("EmailExist", "Email already exist");
                    return(View(model));
                }
                #endregion


                #region Generate Activation code
                user.ActivationCode = Guid.NewGuid();
                #endregion


                #region Password  Hashing
                model.Password        = Crypto.Hash(model.Password);
                model.ConfirmPassword = Crypto.Hash(model.ConfirmPassword);

                #endregion


                user.IsEmailVerified = false;
                #region Save to Database
                using (Db_MawjoudEntities1 dc = new Db_MawjoudEntities1())
                {
                    dc.Members.Add(user);
                    dc.SaveChanges();

                    //Send Email to User
                    SendVerificationLinkEmail(user.Email, user.ActivationCode.ToString());
                    message = "Registration successfully done. Account activation link " +
                              " has been sent to your email id:" + user.Email;
                    Status = true;
                }
                #endregion
            }

            else
            {
                message = "Invalid request";
            }
            //Email is already Exist
            //Generate Activation Code
            //Password HAshing
            //Save data to Database
            //Send Email to user
            ViewBag.Message = message;
            ViewBag.Status  = Status;
            return(View(model));
        }
Example #40
0
 public void Add(Settler member)
 {
     Members.Add(member);
     member.Family = this;
 }
 protected bool ContainsMember(string name) => Members.ContainsKey(name);
Example #42
0
 public List <long> GetIdentifyers()
 {
     return(Members.Select(m => m.A.Id).Union(Members.Select(m => m.B.Id)).Distinct().ToList());
 }
Example #43
0
 private bool PasswordCheck(Members user, string password)
 {
     return (user.Password.Equals(HashPassword(password)));
 }
Example #44
0
        /// <summary>
        /// 获取可见大楼信息
        /// </summary>
        /// <param name="mb">用户信息</param>
        /// <returns></returns>
        public IList <LanData> getbuildings(string mid)
        {
            SysFunc         sf          = new SysFunc();
            UseFunc         uf          = new UseFunc();
            Members         mb          = uf.GetMembers(int.Parse(mid));
            IList <LanData> landatalist = new List <LanData>();

            if (mb.Type == 0)  // 超级权限
            {
                landatalist = uf.GetLandataList();
            }
            else if (mb.Type == 1)
            {
                Area curArea = sf.GetArea((short)sf.GetFireManage((short)mb.LinkId).Aid);
                if (curArea.Type == true)
                {
                    IList <Area> areas = sf.GetAreaList(curArea.Cid, false);
                    for (int i = 0; i < areas.Count; i++)
                    {
                        IList <LanData> tmp = uf.GetLandataList(areas[i].ID);
                        for (int j = 0; j < tmp.Count; j++)
                        {
                            landatalist.Add(tmp[j]);
                        }
                    }
                }
                else
                {
                    landatalist = uf.GetLandataList(curArea.ID);
                }
            }
            else if (mb.Type == 2)
            {
                Area curArea = sf.GetArea((short)sf.GetFireHouse((short)mb.LinkId).Aid);
                if (curArea.Type == true)
                {
                    IList <Area> areas = sf.GetAreaList(curArea.Cid, false);
                    for (int i = 0; i < areas.Count; i++)
                    {
                        IList <LanData> tmp = uf.GetLandataList(areas[i].ID);
                        for (int j = 0; j < tmp.Count; j++)
                        {
                            landatalist.Add(tmp[j]);
                        }
                    }
                }
                else
                {
                    landatalist = uf.GetLandataList(curArea.ID);
                }
            }
            else if (mb.Type == 3)
            {
                Area curArea = sf.GetArea((short)sf.GetControlCenter((short)mb.LinkId).Aid);
                if (curArea.Type == true)
                {
                    IList <Area> areas = sf.GetAreaList(curArea.Cid, false);
                    for (int i = 0; i < areas.Count; i++)
                    {
                        IList <LanData> tmp = uf.GetLandataList(areas[i].ID);
                        for (int j = 0; j < tmp.Count; j++)
                        {
                            landatalist.Add(tmp[j]);
                        }
                    }
                }
                else
                {
                    landatalist = uf.GetLandataList(curArea.ID);
                }
            }
            else if (mb.Type == 6)
            {
                landatalist.Add(uf.GetLandata((int)mb.LinkId));
            }
            else if (mb.Type == 5)
            {
                landatalist = uf.GetLandataListPt((short)mb.LinkId);
            }
            else if (mb.Type == 4)
            {
                landatalist = uf.GetLandataListMt((short)mb.LinkId);
            }
            else
            {
                landatalist = null;
            }
            return(landatalist);
        }
Example #45
0
	// Use this for initialization
	void Start () {
		Members m = new Members();
		m.FirstFunction();
	}
Example #46
0
        /// <summary>
        /// Adds <see cref="MemberAccessor"/>.
        /// </summary>
        /// <param name="member">Instance of <see cref="MemberAccessor"/>.</param>
        protected void AddMember(MemberAccessor member)
        {
            Members.Add(member);

            _membersByName[member.MemberInfo.Name] = member;
        }
Example #47
0
 private static Member CreateBob()
 {
     var member = new Member
                      {
                          Reference = "ABC123",
                          Title = "Mr",
                          FirstName = "Bob",
                          LastName = "Along",
                          Salutation = "Bob",
                          EmailAddress = "*****@*****.**"
                      };
     member = new Members().Insert(member);
     return member;
 }
Example #48
0
 public void should_set_value(CachedMember cachedMember, MemberInfo memberInfo)
 {
     var @object = new Members();
     cachedMember.SetValue(@object, "hai");
     var value = @object.GetPropertyOrFieldValue(memberInfo.Name);
     (memberInfo.GetPropertyOrFieldType() == typeof(string) ? "hai" :
         (string)(Optional<string>)value).ShouldEqual("hai");
 }
Example #49
0
 public void InsertMember()
 {
     var members = new Members(databaseProvider);
     Member member = CreateAlice();
     member = members.Insert(member);
     Assert.AreNotEqual(0, member.Id);
 }
Example #50
0
    public Member GetUser(string UserId, string Password)
    {
        Member AuthenticatedUser;
        AuthenticatedUser = new Member();
        Boolean Success = false;
        SqlConnection StudentConnection;
        StudentConnection = new SqlConnection();
        StudentConnection.ConnectionString = "Data Source= (localDB)\\v11.0;Initial Catalog=GolfClubBaist;Integrated Security = True";

        SqlCommand StudentCommand;
        StudentCommand = new SqlCommand();
        StudentCommand.CommandType = CommandType.StoredProcedure;
        StudentCommand.Connection = StudentConnection;
        StudentCommand.CommandText = "GetUser";

        SqlParameter programcode;
        programcode = new SqlParameter();
        programcode.ParameterName = "@UserId";
        programcode.SqlDbType = SqlDbType.VarChar;
        programcode.Value = UserId;
        programcode.Direction = ParameterDirection.Input;
        StudentCommand.Parameters.Add(programcode);

        StudentConnection.Open();

        StudentCommand.ExecuteNonQuery();

        SqlDataReader BAIS3150Reader;
        BAIS3150Reader = StudentCommand.ExecuteReader();
        while (BAIS3150Reader.Read())
        {
            AuthenticatedUser.Password = BAIS3150Reader["Password"].ToString();

        }
        StudentConnection.Close();
        if (AuthenticatedUser.Password == Password)
        {
            Members CurrentMember;
            CurrentMember = new Members();
            AuthenticatedUser = CurrentMember.FindMember(UserId);
            AuthenticatedUser.IsValid = true;
        }
        else
        {
            AuthenticatedUser.IsValid = false;
        }

        return AuthenticatedUser;
    }
 public virtual void Set_VisibleMember(Members part, bool isVisible)
 {
     try
     {
         Control ctrl = null;
         switch (part)
         {
             case Members.KeyField:
                 ctrl = this.FindControl("cbbKeyField");
                 break;
             case Members.Operator:
                 ctrl = this.FindControl("cbbOperator");
                 break;
             case Members.Value:
                 ctrl = this.FindControl("txtValue");
                 break;
             case Members.AndOr:
                 ctrl = this.FindControl("cbbAndOr");
                 break;
         }
         if (ctrl != null) ctrl.Visible = isVisible;
     }
     catch { }
 }
Example #52
0
 /// <summary>
 /// Clone the group address.
 /// </summary>
 /// <remarks>
 /// Clones the group address.
 /// </remarks>
 /// <returns>The cloned group address.</returns>
 public override InternetAddress Clone()
 {
     return(new GroupAddress(Encoding, Name, Members.Select(x => x.Clone())));
 }
 public Image(string name, string extension, Members members)
 {
 }
        public async Task <ActionResult> CreateMatch([Bind(Prefix = "Match", Include = "Season")] Match postedMatch)
        {
            if (postedMatch is null)
            {
                throw new ArgumentNullException(nameof(postedMatch));
            }

            var model = new EditFriendlyMatchViewModel(CurrentPage, Services.UserService)
            {
                Match = postedMatch
            };

            model.Match.MatchType = MatchType.FriendlyMatch;
            _editMatchHelper.ConfigureModelFromRequestData(model, Request.Unvalidated.Form, Request.Form, ModelState);

            if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Season = model.Match.Season = await _seasonDataSource.ReadSeasonByRoute(Request.RawUrl, false).ConfigureAwait(false);
            }
            else if (model.Match.Season != null && !model.Match.Season.SeasonId.HasValue)
            {
                model.Match.Season = null;
            }
            else if (model.Match.Season != null)
            {
                // Get the season, to support validation against season dates
                model.Match.Season = await _seasonDataSource.ReadSeasonById(model.Match.Season.SeasonId.Value).ConfigureAwait(false);
            }

            _matchValidator.DateIsValidForSqlServer(() => model.MatchDate, ModelState, "MatchDate", "match");
            _matchValidator.DateIsWithinTheSeason(() => model.MatchDate, model.Match.Season, ModelState, "MatchDate", "match");
            _matchValidator.AtLeastOneTeamId(model, ModelState);

            model.IsAuthorized[AuthorizedAction.CreateMatch] = User.Identity.IsAuthenticated;

            if (model.IsAuthorized[AuthorizedAction.CreateMatch] && ModelState.IsValid &&
                (model.Season == null || model.Season.MatchTypes.Contains(MatchType.FriendlyMatch)))
            {
                var currentMember = Members.GetCurrentMember();
                var createdMatch  = await _matchRepository.CreateMatch(model.Match, currentMember.Key, currentMember.Name).ConfigureAwait(false);

                await _cacheClearer.ClearCacheFor(createdMatch).ConfigureAwait(false);

                return(Redirect(createdMatch.MatchRoute));
            }

            if (Request.RawUrl.StartsWith("/teams/", StringComparison.OrdinalIgnoreCase))
            {
                model.Team = await _teamDataSource.ReadTeamByRoute(Request.RawUrl, false).ConfigureAwait(false);

                var possibleSeasons = _createMatchSeasonSelector.SelectPossibleSeasons(model.Team.Seasons, model.Match.MatchType);
                model.PossibleSeasons    = _editMatchHelper.PossibleSeasonsAsListItems(possibleSeasons);
                model.Metadata.PageTitle = $"Add a {MatchType.FriendlyMatch.Humanize(LetterCasing.LowerCase)} for {model.Team.TeamName}";
            }
            else if (Request.RawUrl.StartsWith("/competitions/", StringComparison.OrdinalIgnoreCase))
            {
                model.Metadata.PageTitle = $"Add a {MatchType.FriendlyMatch.Humanize(LetterCasing.LowerCase)} in the {model.Season.SeasonFullName()}";
            }

            if (!string.IsNullOrEmpty(Request.Form["HomeTeamName"]))
            {
                model.HomeTeamName = Request.Form["HomeTeamName"];
            }
            if (!string.IsNullOrEmpty(Request.Form["AwayTeamName"]))
            {
                model.AwayTeamName = Request.Form["AwayTeamName"];
            }

            model.Breadcrumbs.Add(new Breadcrumb {
                Name = Constants.Pages.Matches, Url = new Uri(Constants.Pages.MatchesUrl, UriKind.Relative)
            });

            return(View("CreateFriendlyMatch", model));
        }
 /// <summary>
 /// Get SQL description of a member of this entity type.
 /// Requires: member must belong to this type
 /// </summary>
 /// <param name="member">Member for which to retrieve SQL</param>
 /// <param name="sql">Outputs SQL describing this member</param>
 /// <returns>Whether sql is cached for this member</returns>
 internal bool TryGetMemberSql(EdmMember member, out string sql)
 {
     Debug.Assert(Members.Contains(member));
     sql = null;
     return(null != _memberSql && _memberSql.TryGetValue(member, out sql));
 }
Example #56
0
		/// <summary> Initializes a new instance of the DiscordClient class. </summary>
		public DiscordClient(DiscordClientConfig config = null)
			: base(config ?? new DiscordClientConfig())
		{
			_rand = new Random();
			_api = new DiscordAPIClient(_config.LogLevel, _config.UserAgent, _config.APITimeout);
			if (Config.UseMessageQueue)
				_pendingMessages = new ConcurrentQueue<Message>();
			if (Config.EnableVoiceMultiserver)
				_voiceClients = new ConcurrentDictionary<string, DiscordSimpleClient>();

			object cacheLock = new object();
			_channels = new Channels(this, cacheLock);
			_members = new Members(this, cacheLock);
			_messages = new Messages(this, cacheLock);
			_roles = new Roles(this, cacheLock);
			_servers = new Servers(this, cacheLock);
			_users = new Users(this, cacheLock);
			_status = UserStatus.Online;

			this.Connected += async (s, e) =>
			{
				_api.CancelToken = CancelToken;
				await SendStatus();
			};

			VoiceDisconnected += (s, e) =>
			{
				foreach (var member in _members)
				{
					if (member.ServerId == e.ServerId && member.IsSpeaking)
					{
						member.IsSpeaking = false;
						RaiseUserIsSpeaking(member, false);
					}
				}
			};

			bool showIDs = _config.LogLevel > LogMessageSeverity.Debug; //Hide this for now
			if (_config.LogLevel >= LogMessageSeverity.Info)
			{
				ServerCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Server: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Destroyed Server: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Server: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerAvailable += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Unavailable: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ServerUnavailable += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Server Unavailable: {e.Server?.Name}" +
					(showIDs ? $" ({e.ServerId})" : ""));
				ChannelCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Channel: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId})" : ""));
				ChannelDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Destroyed Channel: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId})" : ""));
				ChannelUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Channel: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId})" : ""));
				MessageCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				MessageDeleted += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Deleted Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				MessageUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				RoleCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Created Role: {e.Server?.Name ?? "[Private]"}/{e.Role.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.RoleId})." : ""));
				RoleUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Role: {e.Server?.Name ?? "[Private]"}/{e.Role.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.RoleId})." : ""));
				RoleDeleted += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Deleted Role: {e.Server?.Name ?? "[Private]"}/{e.Role.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.RoleId})." : ""));
				BanAdded += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Added Ban: {e.Server?.Name ?? "[Private]"}/{e.User?.Name ?? "Unknown"}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				BanRemoved += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Removed Ban: {e.Server?.Name ?? "[Private]"}/{e.User?.Name ?? "Unknown"}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				UserAdded += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Added Member: {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				UserRemoved += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Removed Member: {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				MemberUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Member: {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})." : ""));
				UserVoiceStateUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated Member (Voice State): {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "0"}/{e.UserId})" : ""));
				UserUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Info, LogMessageSource.Client,
					$"Updated User: {e.User.Name}" +
					(showIDs ? $" ({e.UserId})." : ""));
			}
			if (_config.LogLevel >= LogMessageSeverity.Verbose)
			{
				UserIsTyping += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client,
					$"Updated User (Is Typing): {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.UserId})" : ""));
				MessageReadRemotely += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Read Message (Remotely): {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				MessageSent += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Sent Message: {e.Server?.Name ?? "[Private]"}/{e.Channel.Name}/{e.MessageId}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.ChannelId}/{e.MessageId})" : ""));
				UserPresenceUpdated += (s, e) => RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Client, 
					$"Updated Member (Presence): {e.Server?.Name ?? "[Private]"}/{e.User.Name}" +
					(showIDs ? $" ({e.ServerId ?? "[Private]"}/{e.UserId})" : ""));
				
				_api.RestClient.OnRequest += (s, e) =>
				{
					if (e.Payload != null)
						RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Rest, $"{e.Method.Method} {e.Path}: {Math.Round(e.ElapsedMilliseconds, 2)} ms ({e.Payload})");
					else
						RaiseOnLog(LogMessageSeverity.Verbose, LogMessageSource.Rest, $"{e.Method.Method} {e.Path}: {Math.Round(e.ElapsedMilliseconds, 2)} ms");
				};
			}
			if (_config.LogLevel >= LogMessageSeverity.Debug)
			{
				_channels.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Channel {e.Item?.ServerId ?? "[Private]"}/{e.Item.Id}");
				_channels.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Channel {e.Item.ServerId ?? "[Private]"}/{e.Item.Id}");
				_channels.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Channels");
				_members.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Member {e.Item.ServerId ?? "[Private]"}/{e.Item.UserId}");
				_members.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Member {e.Item.ServerId ?? "[Private]"}/{e.Item.UserId}");
				_members.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Members");
				_messages.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Message {e.Item.ServerId ?? "[Private]"}/{e.Item.ChannelId}/{e.Item.Id}");
				_messages.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Message {e.Item.ServerId ?? "[Private]"}/{e.Item.ChannelId}/{e.Item.Id}");
				_messages.ItemRemapped += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Remapped Message {e.Item.ServerId ?? "[Private]"}/{e.Item.ChannelId}/[{e.OldId} -> {e.NewId}]");
				_messages.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Messages");
				_roles.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Role {e.Item.ServerId}/{e.Item.Id}");
				_roles.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Role {e.Item.ServerId}/{e.Item.Id}");
				_roles.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Roles");
				_servers.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created Server {e.Item.Id}");
				_servers.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed Server {e.Item.Id}");
				_servers.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Servers");
				_users.ItemCreated += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Created User {e.Item.Id}");
				_users.ItemDestroyed += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Destroyed User {e.Item.Id}");
				_users.Cleared += (s, e) => RaiseOnLog(LogMessageSeverity.Debug, LogMessageSource.Cache, $"Cleared Users");
			}

			if (Config.UseMessageQueue)
				_pendingMessages = new ConcurrentQueue<Message>();

			_serializer = new JsonSerializer();
#if TEST_RESPONSES
			_serializer.CheckAdditionalContent = true;
			_serializer.MissingMemberHandling = MissingMemberHandling.Error;
#endif
		}
Example #57
0
 public void should_get_value(CachedMember cachedMember, MemberInfo memberInfo, Type type)
 {
     var @object = new Members();
     @object.SetPropertyOrFieldValue(memberInfo.Name, "hai");
     cachedMember.GetValue(@object).ShouldEqual("hai");
 }
Example #58
0
 internal void Initialize()
 {
     Members.AddRange(GetDefaultMembers());
 }
Example #59
0
        public Members GetMember(string Email, string Password)
        {
            _Connection.Sheet = "Fundraisers";
            _logger.LogInformation($"GOT TO GETMEMBER AT DL FOR {Email}");
            var range = $"{_Connection.Sheet}!A:AP";

            SpreadsheetsResource.ValuesResource.GetRequest request =
                _Connection.Service.Spreadsheets.Values.Get(_Connection.SpreadsheetId, range);
            var response = request.Execute();
            IList <IList <object> > values = response.Values;

            if (values != null && values.Count > 0)
            {
                foreach (var row in values)
                {
                    if (row.Count != 0)
                    {
                        Members CurrentMember = new Members();
                        if (row.Count > 8)
                        {
                            if (row[8].ToString().ToLower() == Email.ToLower())
                            {
                                if (row[2].ToString() == Password)
                                {
                                    CurrentMember.ID                  = row[0].ToString();
                                    CurrentMember.FullName            = row[1].ToString();
                                    CurrentMember.Password            = row[2].ToString();
                                    CurrentMember.FirstName           = row[3].ToString();
                                    CurrentMember.LastName            = row[4].ToString();
                                    CurrentMember.Confirmed           = bool.Parse(row[5].ToString());
                                    CurrentMember.Gender              = row[6].ToString();
                                    CurrentMember.AgeGroup            = row[7].ToString();
                                    CurrentMember.Email               = row[8].ToString();
                                    CurrentMember.PhoneNumber         = row[9].ToString();
                                    CurrentMember.Country             = row[10].ToString();
                                    CurrentMember.City                = row[11].ToString();
                                    CurrentMember.TotalDonations      = int.Parse(row[12].ToString());
                                    CurrentMember.TotalCallsMade      = int.Parse(row[13].ToString());
                                    CurrentMember.FluentHebrew        = bool.Parse(row[14].ToString());
                                    CurrentMember.FluentRussian       = bool.Parse(row[15].ToString());
                                    CurrentMember.FluentEnglish       = bool.Parse(row[16].ToString());
                                    CurrentMember.AnashIsrael         = bool.Parse(row[17].ToString());
                                    CurrentMember.AnashUSA            = bool.Parse(row[18].ToString());
                                    CurrentMember.PinskSchoolGraduate = bool.Parse(row[19].ToString());
                                    CurrentMember.KievSchoolGraduate  = bool.Parse(row[20].ToString());
                                    CurrentMember.YeshivaGraduate     = bool.Parse(row[21].ToString());
                                    CurrentMember.InPinsk             = bool.Parse(row[22].ToString());
                                    CurrentMember.BusinessAssociate   = bool.Parse(row[23].ToString());
                                    CurrentMember.BoysCounselor       = bool.Parse(row[24].ToString());
                                    CurrentMember.GirlsCounselor      = bool.Parse(row[25].ToString());
                                    CurrentMember.HelpedByPinsk       = bool.Parse(row[26].ToString());
                                    CurrentMember.GeneralSupporter    = bool.Parse(row[27].ToString());
                                    CurrentMember.MHSG                = bool.Parse(row[28].ToString());
                                    CurrentMember.BelarusAnsectors    = bool.Parse(row[29].ToString());
                                    CurrentMember.BelarusTourism      = bool.Parse(row[30].ToString());
                                    CurrentMember.YYFundraiser        = bool.Parse(row[31].ToString());
                                    CurrentMember.YYFamily            = bool.Parse(row[32].ToString());
                                    CurrentMember.YYStaff             = bool.Parse(row[33].ToString());
                                    CurrentMember.RShteiermanFamily   = bool.Parse(row[34].ToString());
                                    CurrentMember.RFimaFamily         = bool.Parse(row[35].ToString());
                                    CurrentMember.MarriedAYYGraduate  = bool.Parse(row[36].ToString());
                                    CurrentMember.YearsInYadYisroel   = Int32.Parse(row[37].ToString());
                                    CurrentMember.YearsInYadYisroel   = Int32.Parse(row[38].ToString());
                                    _logger.LogInformation($"FOUND MEMBER AND IS ABOUT TO RETURN FROM DL");
                                    return(CurrentMember);
                                }
                            }
                        }
                    }
                }
                return(null);
            }
            return(null);
        }
Example #60
0
 public CacheAttribute(Members membersToCache)
 {
 }