Inheritance: System.Web.UI.Page
コード例 #1
0
ファイル: Program.cs プロジェクト: NicolajLarsen/PnP
        private static string GetSingleValuedProperty(UserProfile spUser,string userProperty)
        {
            string returnString = string.Empty;
            try
            {
                UserProfileValueCollection propCollection = spUser[userProperty];

                if (propCollection[0] != null)
                {
                    returnString = propCollection[0].ToString();
                }
                else
                {
                    LogMessage(string.Format("User '{0}' does not have a value in property '{1}'", spUser.DisplayName, userProperty), LogLevel.Warning);                       
                }
            }
            catch 
            {
                LogMessage(string.Format("User '{0}' does not have a value in property '{1}'", spUser.DisplayName, userProperty), LogLevel.Warning);                       
            }


            return returnString;
            
        }
コード例 #2
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            // Use EF to connect to SQL Server
            using (fit_trackEntities db = new fit_trackEntities())
            {
                // Use the UserProfile Model to save the new record
                UserProfile up = new UserProfile();
                String UserID = Convert.ToString(User.Identity.GetUserId());

                // Get the current UserProfile from the Enity Framework
                up = (from objS in db.UserProfiles
                      where objS.UserID == UserID
                      select objS).FirstOrDefault();

                up.FirstName = txtFirstName.Text;
                up.LastName = txtLastName.Text;
                up.Email = txtEmail.Text;
                up.UserHeight = Convert.ToDecimal(txtHeight.Text);
                up.UserWeight = Convert.ToDecimal(txtWeight.Text);
                up.Age = Convert.ToInt32(txtAge.Text);

                db.SaveChanges();

                // Redirect to the updated Profile page
                Response.Redirect("profile.aspx");
            }
        }
コード例 #3
0
        public override void Execute()
        {
            //Start loading => write to synch db? => profile + basedata always loaded synchroneously

            _userProfile = new UserProfile();
            //end loading => save to DB
        }
コード例 #4
0
        public override void DoProcessRequest(IExecutionContext context)
        {
            if (!Validate())
                return;

            UserProfile user = new UserProfile();

            user.UserName = username;
            user.Password = password;
            user.Email = email;
            user.FirstName = firstName;
            user.LastName = lastName;

            user.UserType = 
                ContentTypeUtility.AsUserType(
                    ContentTypeUtility.FromString(defaultContentType));

            if (user.UserType == UserType.Company) {
                user.roles = new List<UserProfile.role>();
                var role = new UserProfile.role();
                role.Name = "company";
                user.roles.Add(role);
            }

            UserDataAccess.Instance.SaveUser(user);
            context.Response.RenderWith(@"Templates\Profile\registered.django");
        }
コード例 #5
0
        public ActionResult Index()
        {
            var profile = Context.Database.UserProfiles.SingleOrDefault(x => x.UserId == WebSecurity.CurrentUserId);

            if (profile == null)
            {
                //TODO: use the existing language set on UI to create the default profile.
                var language = Context.Database.Languages.GetByName("English");
                profile = new UserProfile(WebSecurity.CurrentUserId, language.Id);
                Context.Database.UserProfiles.Add(profile);
                Context.SaveChanges();
            }

            var model = new UserProfileModel
            {
                Bio = profile.Bio,
                BirthDay = profile.BirthDay.HasValue ? profile.BirthDay : new DateTime?(),
                Department = profile.Department,
                Expertise = profile.Expertise,
                FacebookProfile = profile.FacebookProfile,
                SkypeName = profile.SkypeName,
                Interests = profile.Interests,
                JobTitle = profile.JobTitle,
                Languages = new SelectList(Context.Database.Languages.ToList(), "Id", "Name"),
                LanguageId = profile.LanguageId,
                LinkedinProfile = profile.LinkedinProfile,
                Location = profile.Location,
                MobilePhone = profile.MobilePhone,
                TwitterUserName = profile.TwitterUserName,
                WorkPhone = profile.WorkPhone,
                WorkPhoneExtension = profile.WorkPhoneExtension
            };

            return View("Account", model);
        }
コード例 #6
0
	public static UserProfile GetUserProfile(HttpContext context)
	{
        var profile = context.Items["Profile"] as UserProfile;
        if (profile == null)
        {
            var authCookie = context.Request.Cookies["u"];
            if (authCookie == null)
            {
                profile = new UserProfile
                {
                    Username = Guid.NewGuid().ToString()                   
                };
                context.Items["Profile"] = profile;
                return profile;
            }
            else
            {
                var userName = FormsAuthentication.Decrypt(authCookie.Value).Name;
                var userProfile = LoginProvider.GetUserProfile(context.Server.MapPath("~/App_Data"), userName);
                context.Items["Profile"] = userProfile;
                return userProfile;
            }
        }
        else
        {
            return context.Items["Profile"] as UserProfile;
        }
	}
コード例 #7
0
ファイル: UserTests.cs プロジェクト: sergioora/StationCAD
        public void AddUser()
        {
            using (var db = new StationCADDb())
            {
                var usr = new UserProfile();
                usr.FirstName = string.Format("FirstName_{0}", DateTime.Now.Ticks);
                usr.LastName = string.Format("LastName_{0}", DateTime.Now.Ticks);
                usr.IdentificationNumber = DateTime.Now.Ticks.ToString();
                //usr.UserName = string.Format("{0}.{1}", usr.FirstName, usr.LastName);
                usr.OrganizationAffiliations = new List<OrganizationUserAffiliation>();
                usr.OrganizationAffiliations.Add(new OrganizationUserAffiliation { Status = OrganizationUserStatus.Active, Role = OrganizationUserRole.User });
                usr.NotificationEmail = "*****@*****.**";
                usr.MobileDevices = new List<UserMobileDevice>();
                usr.MobileDevices.Add(new UserMobileDevice { Carrier = MobileCarrier.ATT, EnableSMS = true, MobileNumber = "6108833253" });

                db.UserProfiles.Add(usr);
                db.SaveChanges();

                Assert.IsTrue(usr.Id > 0);

                List<UserProfile> users = db.UserProfiles
                    .Include("MobileDevices")
                    .Include("OrganizationAffiliations")
                    .Where(w => w.OrganizationAffiliations.Where(x => x.CurrentOrganization.Id == 1).Count() > 0)
                    .ToList<UserProfile>();

                var afterUser = db.UserProfiles
                    .Include("OrganizationAffiliations")
                    .Include("MobileDevices")
                    .Where(x => x.IdentificationNumber == usr.IdentificationNumber)
                    .FirstOrDefault();
                db.UserProfiles.Remove(afterUser);
                db.SaveChanges();
            }
        }
コード例 #8
0
        private GetNextSentenceResult HandleExerciseSection(UserProfile profile)
        {
            // PRE: By the time we come here. we have already been moved to either
            // starting next pack or being in a valid question dimension by the state evaluator
            // if starting exercise pack
            //       select sample sentence.
            //       return it.
            // else
            //       select sentence for this question dimension.
            //       return it.

            Sentence sentence = null;
            bool isQuestion = false;
            QuestionDimension dimension = QuestionDimension.Unknown;
            bool found = false;

            sentence = SentenceOperations.FindSentence(profile);

            if(sentence != null)
            {
                found = true;
            }

            if (!SectionUtilities.StartingExercisePack(profile))
            {
                isQuestion = true;
                dimension = profile.CurrentState.CourseLocationInfo.TopicLocationInfo.ExerciseSectionState.CurrentQuestionDimension;
            }

            GetNextSentenceResult result = new GetNextSentenceResult(sentence: sentence, success: found, isQuestion: isQuestion, dimension: dimension, isReview: false);

            return result;
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: NicolajLarsen/PnP
        private static string GetMultiValuedProperty(UserProfile spUser, string userProperty)
        {
            StringBuilder sb = new StringBuilder("");
            string seperator = ConfigurationManager.AppSettings["PROPERTYSEPERATOR"];

            string returnString = string.Empty;
            try
            {

                UserProfileValueCollection propCollection = spUser[userProperty];

                if (propCollection.Count > 1)
                {
                    for (int i = 0; i < propCollection.Count; i++)
                    {
                        if (i == propCollection.Count - 1) { seperator = ""; }
                        sb.AppendFormat("{0}{1}", propCollection[i], seperator);
                    }
                }
                else if (propCollection.Count == 1)
                {
                    sb.AppendFormat("{0}", propCollection[0]);
                }

            }
            catch
            {
                LogMessage(string.Format("User '{0}' does not have a value in property '{1}'", spUser.DisplayName, userProperty), LogLevel.Warning);
            }

            return sb.ToString();

        }
        /// <summary>
        /// Called when [execute].
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override BaseReturnContainer OnExecute(RequestContext context)
        {
            GetAgentsForAutoCompleteRequestContainer requestContainer = context.InParam as GetAgentsForAutoCompleteRequestContainer;
            GetAgentsForAutoCompleteReturnContainer returnContainer = new GetAgentsForAutoCompleteReturnContainer();

            ISqlProvider sqlProvider = (ISqlProvider)ProviderFactory.Instance.CreateProvider<ISqlProvider>(requestContainer.ProviderName);
            Dictionary<string, object> parameters = new Dictionary<string, object>() { { "@deleted", false } };
            parameters.Add("@name", string.Format("%{0}%", requestContainer.Text));

            DataSet result = sqlProvider.ExecuteQuery(SqlQueries.GetAgentForAutoComplete, parameters);

            returnContainer.Agents = new List<UserProfile>();
            if (result.Tables.Count > 0)
            {
                foreach (DataRow row in result.Tables[0].Rows)
                {
                    UserProfile agent = new UserProfile();
                    agent.Name = row["Name"].ToString();
                    agent.UserId = row["UserId"].ToString();
                    agent.PhoneNumber = row["PhoneNumber"].ToString();
                    double tempDouble;
                    double.TryParse(row["AgentRating"].ToString(), out tempDouble);
                    agent.AgentRating = tempDouble;

                    int tempInt;
                    int.TryParse(row["AgentRatingCount"].ToString(), out tempInt);
                    agent.AgentRatingCount = tempInt;

                    returnContainer.Agents.Add(agent);
                }
            }

            returnContainer.ReturnCode = ReturnCodes.C101;
            return returnContainer;
        }
コード例 #11
0
 public bool DeleteUserProfile(UserProfile entity)
 {
     if (entity == null) return false;
     _unitOfWork.UserProfileRepository.Delete(entity);
     _unitOfWork.Save();
     return true;
 }
コード例 #12
0
ファイル: BookmarkManager.cs プロジェクト: rowan84/BibleApp
 public BookmarkManager(
     UserProfile user_profile,
     UserSession user_session)
 {
     bookmark_verse = null;
     loadVBookMarkFromDB(user_profile, user_session);//load history at start.
 }
コード例 #13
0
		public JsonSerializerTests()
		{
			var user = new UserProfile(101, "Popeye")
			{
				Avatar = "/:mono:/",
				Gender = JsonSerializerTests.Gender.Male,
				FullName = "Popeye Zhong",
				Email = "*****@*****.**",
				PhoneNumber = "18912345678",
				Birthdate = new DateTime(1979, 5, 15),
				Grade = 0,
				TotalPoints = Zongsoft.Common.RandomGenerator.GenerateInt32(),
				Description = "我是凹凸猫的一号员工!",
				PrincipalId = "1",
				Principal = new Employee()
				{
					EmployeeId = 1,
					EmployeeNo = "A001",
					Hiredate = new DateTime(2015, 4, 20),
					UserId = 101,
				},
			};

			((Employee)user.Principal).User = user;

			_credential = new Security.Credential("20150801", user, "Web", TimeSpan.FromHours(2));

			_credential.ExtendedProperties.Add("QQ", "9555****");
			_credential.ExtendedProperties.Add("WeChatNo", "Automao");
			_credential.ExtendedProperties.Add("NativePlace", "湖南邵阳");
		}
コード例 #14
0
        public List<ViewModels.StackEventLogViewModel> GetAllStackEvents(UserProfile user)
        {
            var StackEvents = _unitOfWork.StackEventRepository.Get();
            var events = (from c in StackEvents select new ViewModels.StackEventLogViewModel { EventDate = c.EventDate, StackEventType = c.StackEventType.Name, Description = c.Description, Recommendation = c.Recommendation, FollowUpDate = c.FollowUpDate.Value }).ToList();

            return events;
        }
コード例 #15
0
 /// <summary>
 /// constructor with the testable repositories and the user
 /// the user is required because we need to decide what wareshouses to display for her.
 /// </summary>
 public ReceiveViewModel(List<Commodity> commodities, List<CommodityGrade> commodityGrades, List<Transporter> transporters, List<CommodityType> commodityTypes,
     List<CommoditySource> commoditySources, List<Program> programs, List<Donor> donors, List<Hub> hubs, UserProfile user,List<Unit> units  )
 {
     _UserProfile = user;
     InitalizeViewModel(commodities, commodityGrades, transporters, commodityTypes,
      commoditySources, programs, donors, hubs, user, units);
 }
コード例 #16
0
 public WebFormEditAdminViewModel(StoreFront storeFront, UserProfile userProfile, WebForm webForm, string activeTab, bool isStoreAdminEdit = false, bool isReadOnly = false, bool isDeletePage = false, bool isCreatePage = false, string sortBy = "", bool? sortAscending = true)
 {
     if (storeFront == null)
     {
         throw new ArgumentNullException("storeFront");
     }
     if (userProfile == null)
     {
         throw new ArgumentNullException("userProfile");
     }
     if (webForm == null)
     {
         throw new ArgumentNullException("webForm", "Web form cannot be null");
     }
     this.IsStoreAdminEdit = isStoreAdminEdit;
     this.IsActiveDirect = webForm.IsActiveDirect();
     this.IsActiveBubble = webForm.IsActiveBubble();
     this.IsReadOnly = isReadOnly;
     this.IsDeletePage = isDeletePage;
     this.IsCreatePage = isCreatePage;
     this.ActiveTab = activeTab;
     this.SortBy = sortBy;
     this.SortAscending = sortAscending;
     LoadValues(storeFront, userProfile, webForm);
 }
コード例 #17
0
 public void UserProfile_WhenDeleted_IsNotRemovedFromTheDatabase()
 {
     StoreExpectedProfile();
     db.DeleteUser(expectedProfile.UserId);
     actualProfile = (from p in db.UserProfiles where p.UserId == expectedProfile.UserId select p).First();
     Assert.AreEqual(false, actualProfile.Status);
 }
コード例 #18
0
 public ValueListEditAdminViewModel(StoreFront storeFront, UserProfile userProfile, ValueList valueList, string activeTab, bool isStoreAdminEdit = false, bool isReadOnly = false, bool isDeletePage = false, bool isCreatePage = false, string sortBy = "", bool? sortAscending = true)
 {
     if (storeFront == null)
     {
         throw new ArgumentNullException("storeFront");
     }
     if (userProfile == null)
     {
         throw new ArgumentNullException("userProfile");
     }
     if (valueList == null)
     {
         throw new ArgumentNullException("valueList", "valueList cannot be null");
     }
     this.IsStoreAdminEdit = isStoreAdminEdit;
     this.IsActiveDirect = valueList.IsActiveDirect();
     this.IsActiveBubble = valueList.IsActiveBubble();
     this.IsReadOnly = isReadOnly;
     this.IsDeletePage = isDeletePage;
     this.IsCreatePage = isCreatePage;
     this.ActiveTab = activeTab;
     this.SortBy = sortBy;
     this.SortAscending = sortAscending;
     LoadValues(storeFront, userProfile, valueList);
 }
コード例 #19
0
        public UserProfile Update(UserProfile user)
        {
            try
            {
                if (ApiUrl == string.Empty)
                {
                    throw new Exception(Errors.ERR_PROFILEM_MISSING_APIURL);
                }

                var uriBuilder = new UriBuilder(ApiUrl + "/users/id/" + user.id);

                if (DevKey != string.Empty)
                {
                    uriBuilder.Query = "subscription-key=" + DevKey;
                }

                var strModel = ModelManager.ModelToJson(user);

                var json = Rest.Put(uriBuilder.Uri, strModel);

                user = ModelManager.JsonToModel<UserProfile>(json);
            }
            catch (Exception err)
            {
                var errString = string.Format(Errors.ERR_PROFILEM_PROFILE_NOT_CREATED, user.firstname + " " + user.lastname) + ", " + err.Message;
                if (err.InnerException != null)
                    errString += ", " + err.InnerException.Message;
                throw new Exception(errString);
            }

            return user;
        }
コード例 #20
0
 //This functions receives two strings, the first is the job id, the second is the recruitee id.
 //then, it looks at the expressions array (all jobs ids) to find the index of the given JobID,
 //then, it looks at the users array (all users ids and self ratings) to find the index of the given recruitee id.
 //then it returns the value of the rating for that job and recruitee on the Y matrix.
 public int[,] getYIndex(String jobID, String recruiteeID, String[] expressions, UserProfile[] users)
 {
     try
     {
         int column = 0, row = 0;
         for (int i = 0; i < expressions.Length; i++)
         {
             if ((expressions[i].ToUpper()).Equals(jobID.ToUpper()))
             {
                 row = i;
                 break;
             }
         }
         for (int i = 0; i < users.Length; i++)
         {
             if ((users[i].UserID.ToUpper()).Equals(recruiteeID.ToUpper()))
             {
                 column = i;
                 break;
             }
         }
         int[,] result = new int[1, 2];
         result[0, 0] = row;
         result[0, 1] = column;
         return result;
     }
     catch (Exception ex)
     {
         return null;
     }
 }
コード例 #21
0
ファイル: UserProfileEditModel.cs プロジェクト: hbulzy/SYS
 public UserProfileEditModel(UserProfile userProfile, User user)
 {
     if (userProfile != null)
     {
         Birthday = userProfile.Birthday;
         BirthdayType = userProfile.BirthdayType;
         Email = !string.IsNullOrEmpty(userProfile.Email) ? userProfile.Email : user.AccountEmail;
         Gender = userProfile.Gender;
         HomeAreaCode = userProfile.HomeAreaCode;
         Introduction = userProfile.Introduction;
         Mobile = userProfile.Mobile;
         Msn = userProfile.Msn;
         NowAreaCode = userProfile.NowAreaCode;
         QQ = userProfile.QQ;
         UserId = userProfile.UserId;
     }
     if (user != null)
     {
         TrueName = user.TrueName;
         NickName = user.NickName;
         AccountEmail = user.AccountEmail;
         UserName = user.UserName;
         IsEmailVerified = user.IsEmailVerified;
     }
 }
コード例 #22
0
        // PUT api/UserProfiles/5
        public HttpResponseMessage PutUserProfile(int id, UserProfile userprofile)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            if (id != userprofile.Id)
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            }

            db.Entry(userprofile).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK);
        }
コード例 #23
0
        public void Edit_GET_InvalidUserId()
        {
            // arrange

            List<CompanyProfile> companies = new List<CompanyProfile>();
            companies.Add(new CompanyProfile { Id = 1, CompanyName = "some company" });
            companies.Add(new CompanyProfile { Id = 2, CompanyName = "some other company" });

            UserProfile theUser = new UserProfile
            {
                CompanyId = 1,
                UserId = 1,
                Company = companies.Where(x => x.Id == 1).Single(),
                Email = "*****@*****.**",
                FirstName = "some",
                LastName = "fool",
                JobTitle = "nerf herder"
            };

            Mock<IUserProfileServiceLayer> service = new Mock<IUserProfileServiceLayer>();
            service.Setup(s => s.GetEnumerableCompanies()).Returns(companies);
            service.Setup(s => s.Get(theUser.UserId)).Returns(theUser);

            Mock<IWebSecurityWrapper> security = new Mock<IWebSecurityWrapper>();
            Mock<IEmailSender> email = new Mock<IEmailSender>();

            UserController controller = new UserController(service.Object, security.Object, email.Object);

            // act
            var result = controller.Edit(2) as ViewResult;

            // assert
        }
コード例 #24
0
ファイル: FrmProfile.cs プロジェクト: tomfuru/StarlitTwit
 public FrmProfile(FrmMain mainForm, bool canEdit, string screen_name, ImageListWrapper imagelistwrapper)
     : this(mainForm, canEdit, imagelistwrapper)
 {
     ScreenName = screen_name;
     _profile = null;
     _gotProfile = false;
 }
コード例 #25
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Grab username and userID from AspNet Authentication
            String userName = Convert.ToString(User.Identity.GetUserName());
            String userID = Convert.ToString(User.Identity.GetUserId());
            lblUsername.Text = userName;
            UserProfile userP = new UserProfile();
            using (fit_trackEntities db = new fit_trackEntities())
            {
                userP = (from up in db.UserProfiles
                         join u in db.AspNetUsers on up.UserID equals u.Id
                         where up.UserID == userID
                         select up).FirstOrDefault();

                // If user already has a profile, print the details to the screen
                if (userP != null)
                {
                    lblFirstName.Text = userP.FirstName;
                    lblLastName.Text = userP.LastName;
                    lblEmail.Text = userP.Email;
                    lblUserHeight.Text = Convert.ToString(userP.UserHeight);
                    lblUserWeight.Text = Convert.ToString(userP.UserWeight);
                    lblAge.Text = Convert.ToString(userP.Age);
                }
                // If the user doesn't have a profile yet (New User), add a new entry to the UserProfile table with their UserID
                else
                {
                    userP = new UserProfile();
                    userP.UserID = userID;
                    db.UserProfiles.Add(userP);
                    db.SaveChanges();
                }

            }
        }
コード例 #26
0
    public virtual EditProfile GetProfile(UserProfile userProfile)
    {
      var properties = this.userProfileProvider.GetCustomProperties(userProfile);

      var model = new EditProfile();
      if (properties.ContainsKey(this.FirstName))
      {
        model.FirstName = properties[this.FirstName];
      }
      if (properties.ContainsKey(this.LastName))
      {
        model.LastName = properties[this.LastName];
      }
      if (properties.ContainsKey(this.PhoneNumber))
      {
        model.PhoneNumber = properties[this.PhoneNumber];
      }
      if (properties.ContainsKey(this.Interest))
      {
        model.Interest = properties[this.Interest];
      }

      model.InterestTypes = this.profileSettingsService.GetInterests();

      return model;
    }
コード例 #27
0
ファイル: TopicPolicies.cs プロジェクト: usmanghani/Quantae
        public static double GetUnderstandingScore(UserProfile profile)
        {
            int successCount = profile.CurrentState.CourseLocationInfo.CurrentTopic.AnswerDimensionSuccessCount[AnswerDimension.Understanding];
            int failureCount = profile.CurrentState.CourseLocationInfo.CurrentTopic.AnswerDimensionFailureCount[AnswerDimension.Understanding];

            return (double)successCount / (successCount + failureCount);
        }
コード例 #28
0
        public GetNextSentenceResult GetNextSentence(UserProfile profile)
        {
            // ALGO: GetNextSentence
            // PRE: Session exists
            // PRE: We are in Exercise or Review Section.
            // What we need:
            // 1. All histories
            // 2. All user current state.
            // 3. Access to sentence repository.
            // What do we do:
            // 1. Assert correct section.
            // 2. Handle Exercise section. OR
            // 3. Handle Review Section.

            var currentSection = profile.CurrentState.CourseLocationInfo.TopicLocationInfo.CurrentSection;
            if(currentSection != TopicSectionType.Review && currentSection != TopicSectionType.Exercise)
            {
                // BUG: Clean this up.
                throw new Exception("Invalid section");
            }

            GetNextSentenceResult result = null;
            if(currentSection == TopicSectionType.Exercise)
            {
                result = HandleExerciseSection(profile);
            }
            else
            {
                result = HandleReviewSection(profile);
            }

            return result;
        }
コード例 #29
0
    public void SetCustomProfileShouldSetEmptyProperties([CoreDb]Db db, UserProfileProvider userProfileProvider, UserProfile userProfile, IDictionary<string, string> properties, string nullKey)
    {
      properties.Add(nullKey, null);

      userProfileProvider.SetCustomProfile(userProfile, properties);
      userProfile.Received()[nullKey] = string.Empty;
    }
コード例 #30
0
ファイル: TopicPolicies.cs プロジェクト: usmanghani/Quantae
 public static bool HasUserSuccessfullyDoneTopic(UserProfile userProfile, TopicHandle topic)
 {
     // TODO: Figure out if IsSuccessful condition is required or not. This might potentially lead to infinite
     // loops since we will keep forcing the user to cover failed topics. Those are already taken care of by
     // failure counters.
     return userProfile.History.TopicHistory.Any(thi => thi.Topic.Equals(topic) && (thi.IsSuccessful || thi.IsSkipped));
 }
コード例 #31
0
        private void SeedSubmissionsAndTestRuns(OjsDbContext context)
        {
            foreach (var submission in context.Submissions)
            {
                context.Submissions.Remove(submission);
            }

            foreach (var testRun in context.TestRuns)
            {
                context.TestRuns.Remove(testRun);
            }

            foreach (var participantToDelete in context.Participants)
            {
                context.Participants.Remove(participantToDelete);
            }

            Random random = new Random();

            List <TestRun> testRuns = new List <TestRun>();

            var test = new Test
            {
                IsTrialTest = false,
                OrderBy     = 1
            };

            for (int i = 0; i < 1000; i++)
            {
                testRuns.Add(new TestRun
                {
                    TimeUsed   = random.Next() % 10 + 1,
                    MemoryUsed = random.Next() % 1500 + 200,
                    ResultType = (TestRunResultType)(random.Next() % 5),
                    Test       = test
                });
            }

            var contest = new Contest
            {
                Name      = "Contest batka 2",
                StartTime = DateTime.Now.AddDays(1),
                EndTime   = DateTime.Now.AddDays(2),
                IsDeleted = false,
                IsVisible = true,
                OrderBy   = 1
            };

            var problem = new Problem
            {
                OldId         = 0,
                Contest       = contest,
                Name          = "Problem",
                MaximumPoints = 100,
                MemoryLimit   = 100,
                OrderBy       = 1
            };

            var user = new UserProfile
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            var participant = new Participant
            {
                Contest    = contest,
                IsOfficial = false,
                User       = user
            };

            for (int i = 0; i < 100; i++)
            {
                var submission = new Submission
                {
                    Problem     = problem,
                    Participant = participant
                };

                for (int j = 0; j < random.Next() % 20 + 5; j++)
                {
                    submission.TestRuns.Add(testRuns[random.Next() % 1000]);
                }

                context.Submissions.Add(submission);
            }
        }
コード例 #32
0
        private void SeedCategoryContestProblem(OjsDbContext context)
        {
            foreach (var categoryToBeDeleted in context.ContestCategories)
            {
                context.ContestCategories.Remove(categoryToBeDeleted);
            }

            foreach (var contestToBeDeleted in context.Contests)
            {
                context.Contests.Remove(contestToBeDeleted);
            }

            foreach (var problemToBeDeleted in context.Problems)
            {
                context.Problems.Remove(problemToBeDeleted);
            }

            var category = new ContestCategory
            {
                Name      = "Category",
                OrderBy   = 1,
                IsVisible = true,
                IsDeleted = false,
            };

            var otherCategory = new ContestCategory
            {
                Name      = "Other Category",
                OrderBy   = 1,
                IsVisible = true,
                IsDeleted = false,
            };

            var contest = new Contest
            {
                Name              = "Contest",
                OrderBy           = 1,
                PracticeStartTime = DateTime.Now.AddDays(-2),
                StartTime         = DateTime.Now.AddDays(-2),
                IsVisible         = true,
                IsDeleted         = false,
                Category          = category
            };

            var otherContest = new Contest
            {
                Name              = "Other Contest",
                OrderBy           = 2,
                PracticeStartTime = DateTime.Now.AddDays(-2),
                StartTime         = DateTime.Now.AddDays(-2),
                IsVisible         = true,
                IsDeleted         = false,
                Category          = category
            };

            var problem = new Problem
            {
                Name          = "Problem",
                MaximumPoints = 100,
                TimeLimit     = 10,
                MemoryLimit   = 10,
                OrderBy       = 1,
                ShowResults   = true,
                IsDeleted     = false,
                Contest       = contest
            };

            var otherProblem = new Problem
            {
                Name          = "Other Problem",
                MaximumPoints = 100,
                TimeLimit     = 10,
                MemoryLimit   = 10,
                OrderBy       = 1,
                ShowResults   = true,
                IsDeleted     = false,
                Contest       = contest
            };

            var test = new Test
            {
                InputDataAsString  = "Input",
                OutputDataAsString = "Output",
                OrderBy            = 0,
                IsTrialTest        = false,
                Problem            = problem,
            };

            var user = new UserProfile
            {
                UserName = "******",
                Email    = "*****@*****.**"
            };

            var participant = new Participant
            {
                Contest    = contest,
                IsOfficial = false,
                User       = user
            };

            var submission = new Submission
            {
                Problem     = problem,
                Participant = participant,
                CreatedOn   = DateTime.Now
            };

            for (int i = 0; i < 10; i++)
            {
                test.TestRuns.Add(new TestRun
                {
                    MemoryUsed       = 100,
                    TimeUsed         = 100,
                    CheckerComment   = "Checked!",
                    ExecutionComment = "Executed!",
                    ResultType       = TestRunResultType.CorrectAnswer,
                    Submission       = submission
                });
            }

            context.Problems.Add(problem);
            contest.Problems.Add(otherProblem);
            context.Contests.Add(otherContest);
            context.ContestCategories.Add(otherCategory);
            context.Tests.Add(test);
        }
コード例 #33
0
 public GroupStartService(UserProfile userProfile)
 {
     this.Initialize(typeof(IGroupStartService), userProfile);
 }
コード例 #34
0
 public ActionResult Edit_profile(UserProfile up)
 {
     db.Entry(up).State = EntityState.Modified;
     db.SaveChanges();
     return(RedirectToAction("AllProfiles", "Home"));
 }
コード例 #35
0
 public MoveNonStdChangePkgService(UserProfile userProfile)
 {
     this.Initialize(typeof(IMoveNonStdChangePkgService), userProfile);
 }
コード例 #36
0
 public ActivityTemplateInvestigationMaintService(UserProfile userProfile)
 {
     this.Initialize(typeof(IActivityTemplateInvestigationMaintService), userProfile);
 }
コード例 #37
0
 public void Update(UserProfile userProfile)
 {
     throw new NotImplementedException();
 }
コード例 #38
0
        public static void CreateAccounts()
        {
            // Instatiate object from class;
            SampleAccounts sampleaccounts = new SampleAccounts();

            Item item = Sitecore.Client.CoreDatabase.GetItem("/sitecore/system/Settings/Security/Profiles/User");

            Assert.IsNotNull(item, "Item \"/sitecore/system/Settings/Security/Profiles/User\" not found");

            foreach (UserAccount myUser in sampleaccounts.UserAccounts)
            {
                // delete user if exists
                if (User.Exists(myUser.UserName.ToString()))
                {
                    User user = User.FromName(myUser.UserName, true);
                    user.Delete();
                }

                // Create User if not exists
                if (!User.Exists(myUser.UserName.ToString()))
                {
                    User.Create(myUser.UserName, myUser.Password);
                }

                // If user not in role, add user to role
                foreach (string roleName in myUser.UserAddToRoles)
                {
                    //System.Web.Security.Roles.
                    if (!Roles.IsUserInRole(myUser.UserName, roleName))
                    {
                        //System.Web.Security.Roles.
                        Roles.AddUserToRole(myUser.UserName, roleName);
                    }
                }

                // Need to Add USer Profile Stuff
                // get user and then profile; edit profile
                // Sitecore.Security.Accounts.User AND Sitecore.Security.UserProfile
                User        newUser = User.FromName(myUser.UserName, true);
                UserProfile profile = newUser.Profile;

                // Edit profile with defined class properties
                profile.Initialize(myUser.UserName, true);
                profile.ProfileItemId = item.ID.ToString();
                profile.FullName      = myUser.FullName.ToString();
                profile.Portrait      = myUser.Portrait.ToString();
                profile.Comment       = myUser.Comment.ToString();
                profile.Email         = myUser.Email.ToString();
                profile.SetCustomProperty("Wallpaper", myUser.Wallpaper);
                profile.RegionalIsoCode = string.Empty;


                // for bill and hidden items
                // profile["Sitecore.Shell.UserOptions.View.ShowHiddenItems"] = "true";
                profile.Save();

                // Enable the Account
                MembershipUser mUser = Membership.GetUser(myUser.UserName);
                try
                {
                    mUser.IsApproved = true;
                    Membership.UpdateUser(mUser);
                    continue;
                }
                catch
                {
                    continue;
                }
            }
        }
コード例 #39
0
        public int SaveCustomers(CustomerProfileAndRegistration CustomerProfileAndRegistration)
        {
            try
            {
                if (CustomerProfileAndRegistration.UserProfile.Id == 0)
                {
                    //CustomerProfileAndRegistration.VendorRegistration.Type = "Customer";
                    if (CustomerProfileAndRegistration.UserRegistration.Type != null)
                    {
                        CustomerProfileAndRegistration.UserRegistration.Type = CustomerProfileAndRegistration.UserRegistration.Type;
                    }
                    else
                    {
                        CustomerProfileAndRegistration.UserRegistration.Type = "Customer";
                    }
                    _db.UserRegistrations.Add(CustomerProfileAndRegistration.UserRegistration);
                    _db.SaveChanges();

                    CustomerProfileAndRegistration.UserProfile.UserRegistrationId = CustomerProfileAndRegistration.UserRegistration.Id;
                    CustomerProfileAndRegistration.UserProfile.Email    = CustomerProfileAndRegistration.UserRegistration.Email;
                    CustomerProfileAndRegistration.UserProfile.IsActive = true;

                    _db.UserProfiles.Add(CustomerProfileAndRegistration.UserProfile);
                    _db.SaveChanges();
                }
                else
                {
                    UserRegistration UserRegistrations = new UserRegistration();
                    UserRegistrations                 = _db.UserRegistrations.Where(x => x.Id == CustomerProfileAndRegistration.UserRegistration.Id).FirstOrDefault();
                    UserRegistrations.UserName        = CustomerProfileAndRegistration.UserRegistration.UserName;
                    UserRegistrations.ConfirmPassword = CustomerProfileAndRegistration.UserRegistration.ConfirmPassword;
                    UserRegistrations.Password        = CustomerProfileAndRegistration.UserRegistration.Password;
                    UserRegistrations.Email           = CustomerProfileAndRegistration.UserRegistration.Email;
                    if (CustomerProfileAndRegistration.UserRegistration.Type != null)
                    {
                        UserRegistrations.Type = CustomerProfileAndRegistration.UserRegistration.Type;
                    }
                    else
                    {
                        UserRegistrations.Type = "Customer";
                    }

                    _db.SaveChanges();

                    UserProfile UserProfile = new UserProfile();
                    UserProfile                = _db.UserProfiles.Where(x => x.Id == CustomerProfileAndRegistration.UserProfile.Id).FirstOrDefault();
                    UserProfile.FirstName      = CustomerProfileAndRegistration.UserProfile.FirstName;
                    UserProfile.MiddleName     = CustomerProfileAndRegistration.UserProfile.MiddleName;
                    UserProfile.LastName       = CustomerProfileAndRegistration.UserProfile.LastName;
                    UserProfile.Email          = CustomerProfileAndRegistration.UserRegistration.Email;
                    UserProfile.PhoneNo        = CustomerProfileAndRegistration.UserProfile.PhoneNo;
                    UserProfile.MobileNo       = CustomerProfileAndRegistration.UserProfile.MobileNo;
                    UserProfile.PrimaryAddress = CustomerProfileAndRegistration.UserProfile.PrimaryAddress;
                    UserProfile.DOB            = CustomerProfileAndRegistration.UserProfile.DOB;
                    UserProfile.CNIC           = CustomerProfileAndRegistration.UserProfile.CNIC;
                    _db.SaveChanges();
                }


                return(CustomerProfileAndRegistration.UserProfile.Id);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #40
0
 public void Add(UserProfile up)
 {
     _context.Add(up);
     _context.SaveChanges();
 }
コード例 #41
0
ファイル: FileBrowser.aspx.cs プロジェクト: mlp987/portal
        protected void Page_Load(object sender, EventArgs e)
        {
            //plcEditFile.Visible = EditFile;

            if (!UserProfile.HasEditThisPageAccess() && !UserProfile.HasAdminPageAccess())
            {
                PortalSecurity.AccessDenied();
                return;
            }
            ImageFolder = (!String.IsNullOrEmpty(HF_FileBrowserConfig.Attributes["data-imagefolder"]) ?
                           HF_FileBrowserConfig.Attributes["data-imagefolder"] : "images");

            FlashFolder = (!String.IsNullOrEmpty(HF_FileBrowserConfig.Attributes["data-flashfolder"]) ?
                           HF_FileBrowserConfig.Attributes["data-flashfolder"] : "flash");

            MediaFolder = (!String.IsNullOrEmpty(HF_FileBrowserConfig.Attributes["data-mediafolder"]) ?
                           HF_FileBrowserConfig.Attributes["data-mediafolder"] : "media");

            FilesFolder = (!String.IsNullOrEmpty(HF_FileBrowserConfig.Attributes["data-filesfolder"]) ?
                           HF_FileBrowserConfig.Attributes["data-filesfolder"] : "files");

            string useCustomStr    = String.IsNullOrEmpty(HF_CustomRoots.Attributes[USE_CUSTOMROOTS]) ? "" : HF_CustomRoots.Attributes[USE_CUSTOMROOTS];
            string useDefaultStr   = String.IsNullOrEmpty(HF_CustomRoots.Attributes[USE_DEFAULTROOTS]) ? "" : HF_CustomRoots.Attributes[USE_DEFAULTROOTS];
            string hideCommandsStr = String.IsNullOrEmpty(HF_FileBrowserConfig.Attributes[READONLY_HIDECOMMANDS]) ? "" : HF_FileBrowserConfig.Attributes[READONLY_HIDECOMMANDS];

            UseCustomRoots  = useCustomStr.ToLower() != "false";
            UseDefaultRoots = useDefaultStr.ToLower() == "true";
            HideCommands    = hideCommandsStr != "false";

            UseDefaultRoots = false;

            //if (Request.Url.Host.IndexOf("localhost") > -1)
            //    FileManager1.DefaultAccessMode = AccessMode.Write;

            CultureInfo culture = new CultureInfo("en-US");

            FileManager1.Culture = new CultureInfo("en-US");
            //FileManager1.ShowAddressBar = false;
            //FileManager1.AllowUpload = false;

            String cbReference =
                Page.ClientScript.GetCallbackEventReference(this,
                                                            "arg", "ReceiveServerData", "context");
            String callbackScript;

            callbackScript = "function CallServer(arg, context)" +
                             "{ " + cbReference + ";}";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
                                                        "CallServer", callbackScript, true);

            if (!IsPostBack)
            {
                HF_EditableFiles.Value = System.Configuration.ConfigurationManager.AppSettings["FileManager.Edit.SupportExtenstion"];

                /**
                 * -------- Parameters --------------
                 * CKEDITOR automatically call FileManager service adding two custom parameters
                 * CKEditorFuncNum e type.
                 * First parameter allows you to pass choosen file url back to CKEDITOR
                 * through callback function
                 * Type paramete is used to restrict the file search to a
                 * specific folder
                 *
                 * Tiny MCE 4 use the type parameter and field parameter wich is
                 * the id of the field whose value must be set.
                 *
                 *
                 * Other recognized parameters
                 * caller:
                 *      allowed values: ckeditor, tinymce, parent, top
                 *      default: caller id defaulted to ckeditor if the CKEditor parameter is specified otherwise to parent
                 *      Idicates the object to wich the callback must be return
                 *
                 * fn:
                 *      allowed values: any string
                 *      default: null
                 *      Function name to be called.
                 *
                 * langCode:
                 *      allowed value: a standard language code
                 *      default: current language
                 *      CKEdito pass this paramenter automatically
                 *
                 */

                int    fnumber = 0;
                string caller, fn;

                // the caller is CKEditor
                if (!string.IsNullOrEmpty(Request["CKEditor"]))
                {
                    caller = "ckeditor";
                }
                else
                {
                    caller = (String.IsNullOrEmpty(Request["caller"]) ? "parent" : Request["caller"]);
                }

                HF_Opener.Value = caller;

                fn = Request["fn"];

                if (!String.IsNullOrEmpty(fn))
                {
                    HF_CallBack.Value = fn;
                }

                if (int.TryParse(Request["CKEditorFuncNum"], out fnumber))
                {
                    HF_CKEditorFunctionNumber.Value = fnumber.ToString();
                }

                if (!String.IsNullOrEmpty(Request["field"]))
                {
                    HF_Field.Value = Request["field"];
                }

                string type     = "";
                string mainRoot = "~/userfiles";

                if (FileManager1.Culture == null)
                {
                    FileManager1.Culture = culture;
                }

                HF_CurrentCulture.Value = FileManager1.Culture.Name;

                FileManager1.CustomToolbarButtons[0].Text = FileManager1.Controller.GetResourceString("View_file", "View File");
                Upload_button.InnerText = FileManager1.Controller.GetResourceString("Upload_file_click", "Click here to upload a file");
                DND_message.InnerText   = FileManager1.Controller.GetResourceString("Upload_dnd", "Or drag 'nd drop one or more files on the above area");

                if (!String.IsNullOrEmpty(FileManager1.MainDirectory))
                {
                    mainRoot = FileManager1.MainDirectory;
                }
                //mainRoot = ResolveClientUrl(mainRoot);
                if (!Directory.Exists(Server.MapPath(ResolveClientUrl(mainRoot))))
                {
                    throw new Exception("User directory with write privileges is needed.");
                }

                DirectoryInfo mainRootInfo = new DirectoryInfo(Server.MapPath(ResolveClientUrl(mainRoot)));

                if (!String.IsNullOrEmpty(Request["type"]))
                {
                    type = Request["type"];
                }

                RootDirectory images, flash, files, media;
                // Display text of root folders are localized using WebFileBrowser resources files
                // in "/App_GlobalResources/WebFileManager" and GetResoueceString method
                // of FileManager.Controller class
                MB.FileBrowser.MagicSession.Current.FileBrowserAccessMode = AccessMode.Delete;
                //FileManager1.RootDirectories.Clear();
                //FileManager1.RootDirectories.Add(new RootDirectory(){ })

                var    root          = FileManager1.RootDirectories[0].DirectoryPath;
                string allowedFolder = System.Configuration.ConfigurationManager.AppSettings["FileManager.AllowFolders.Tree"];
                if (!string.IsNullOrEmpty(allowedFolder))
                {
                    string[] folders = allowedFolder.Split('|');
                    FileManager1.RootDirectories.Clear();
                    int i = 0;
                    foreach (var fldr in folders)
                    {
                        RootDirectory rp = new RootDirectory();
                        rp.ShowRootIndex = false;
                        //rp.DirectoryPath = Server.MapPath(ResolveClientUrl(root + fldr));
                        rp.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + fldr;;
                        //  rp.Text = FileManager1.Controller.GetResourceString("Root_Image", fldr);
                        rp.Text          = fldr;
                        rp.ExpandDepth   = i == 0 ? 1 : 0;
                        rp.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/folder-document-alt.png";
                        rp.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/folder-document-alt.png";
                        FileManager1.RootDirectories.Add(rp);
                        i++;
                    }
                }
                else
                {
                    if (UseDefaultRoots)
                    {
                        mainRootInfo.CreateSubdirectory(ImageFolder);
                        mainRootInfo.CreateSubdirectory(FilesFolder);
                        mainRootInfo.CreateSubdirectory(FlashFolder);
                        mainRootInfo.CreateSubdirectory(MediaFolder);

                        switch (type)
                        {
                        case "images":
                        case "image":
                            FileManager1.RootDirectories.Clear();
                            images = new RootDirectory();
                            images.ShowRootIndex = false;
                            images.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + ImageFolder;
                            images.Text          = FileManager1.Controller.GetResourceString("Root_Image", "Images");
                            images.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/camera.png";
                            images.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/camera.png";
                            FileManager1.RootDirectories.Add(images);
                            break;

                        case "flash":
                            FileManager1.RootDirectories.Clear();
                            flash = new RootDirectory();
                            flash.ShowRootIndex = false;
                            flash.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + FlashFolder;
                            flash.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/folder-flash.png";
                            flash.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/folder-flash.png";
                            flash.Text          = FileManager1.Controller.GetResourceString("Root_Flash", "Flash Movies");
                            FileManager1.RootDirectories.Add(flash);
                            break;

                        case "files":
                            FileManager1.RootDirectories.Clear();
                            files = new RootDirectory();
                            files.ShowRootIndex = false;
                            files.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + FilesFolder;
                            files.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/folder-document-alt.png";
                            files.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/folder-document-alt.png";
                            files.Text          = FileManager1.Controller.GetResourceString("Root_File", "Files");
                            FileManager1.RootDirectories.Add(files);
                            break;

                        case "media":
                            FileManager1.RootDirectories.Clear();
                            media = new RootDirectory();
                            media.ShowRootIndex = false;
                            media.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + MediaFolder;
                            media.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/folder-video-alt.png";
                            media.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/folder-video-alt.png";
                            media.Text          = FileManager1.Controller.GetResourceString("Root_Media", "Media");
                            FileManager1.RootDirectories.Add(media);
                            break;

                        default:
                            FileManager1.RootDirectories.Clear();
                            files = new RootDirectory();
                            files.ShowRootIndex = false;
                            files.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + FilesFolder;
                            files.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/folder-document-alt.png";
                            files.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/folder-document-alt.png";
                            // Display text of root folders are localized using WebFileBrowser resources files
                            // in "/App_GlobalResources/WebFileManager" and GetResoueceString method
                            // of FileManager.Controller class
                            files.Text = FileManager1.Controller.GetResourceString("Root_File", "Files");
                            FileManager1.RootDirectories.Add(files);

                            flash = new RootDirectory();
                            flash.ShowRootIndex = false;
                            flash.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + FlashFolder;
                            flash.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/folder-flash.png";
                            flash.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/folder-flash.png";
                            flash.Text          = FileManager1.Controller.GetResourceString("Root_Flash", "Flash Movies");
                            FileManager1.RootDirectories.Add(flash);

                            images = new RootDirectory();
                            images.ShowRootIndex = false;
                            images.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + ImageFolder;
                            images.Text          = FileManager1.Controller.GetResourceString("Root_Image", "Images");
                            images.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/camera.png";
                            images.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/camera.png";
                            FileManager1.RootDirectories.Add(images);

                            media = new RootDirectory();
                            media.ShowRootIndex = false;
                            media.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + MediaFolder;
                            media.LargeImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/32/folder-video-alt.png";
                            media.SmallImageUrl = "~/DesktopModules/CoreModules/FileBrowser/img/16/folder-video-alt.png";
                            media.Text          = FileManager1.Controller.GetResourceString("Root_Media", "Media");
                            FileManager1.RootDirectories.Add(media);

                            break;
                        }
                    }
                }


                if (UseCustomRoots)
                {
                    // Memorizza il parametro querystring "cs" che consente di visualizzare una sola customroot
                    int selectedCustomRoot;
                    if (!int.TryParse(Request["cs"], out selectedCustomRoot))
                    {
                        selectedCustomRoot = -1;
                    }

                    // Folder containing custom roots icon images
                    string rootsImageFolder = String.IsNullOrEmpty(HF_CustomRoots.Attributes[ROOTS_IMAGEFOLDER]) ? "" : HF_CustomRoots.Attributes[ROOTS_IMAGEFOLDER];

                    //Arrays: roots names, roots folders, small icons, large icons
                    string[] rootsNames, rootsFolders, rootsSmallImages, rootsLargeImages;

                    // Convert data-roots-names value in array
                    string temp = String.IsNullOrEmpty(HF_CustomRoots.Attributes[ROOTS_NAMES]) ? "" : HF_CustomRoots.Attributes[ROOTS_NAMES];
                    if (temp == "")
                    {
                        return;
                    }
                    rootsNames = temp.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    // Count of custom roots
                    int rootsCount = rootsNames.Length;

                    // If data-roots-folder is empty, will use root names
                    if (String.IsNullOrEmpty(HF_CustomRoots.Attributes[ROOTS_FOLDERS]))
                    {
                        rootsFolders = temp.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    }
                    else
                    {
                        rootsFolders = HF_CustomRoots.Attributes[ROOTS_FOLDERS].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    }


                    if (rootsCount > rootsFolders.Length)
                    {
                        rootsCount = rootsFolders.Length;
                    }

                    if (!String.IsNullOrEmpty(HF_CustomRoots.Attributes[ROOTS_SMALLIMAGES]))
                    {
                        rootsSmallImages = HF_CustomRoots.Attributes[ROOTS_SMALLIMAGES].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (rootsCount > rootsSmallImages.Length)
                        {
                            rootsCount = rootsSmallImages.Length;
                        }
                    }
                    else
                    {
                        rootsSmallImages = new string[] { };
                        rootsCount       = 0;
                    }

                    if (!String.IsNullOrEmpty(HF_CustomRoots.Attributes[ROOTS_LARGEIMAGES]))
                    {
                        rootsLargeImages = HF_CustomRoots.Attributes[ROOTS_LARGEIMAGES].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (rootsCount > rootsLargeImages.Length)
                        {
                            rootsCount = rootsLargeImages.Length;
                        }
                    }
                    else
                    {
                        rootsLargeImages = new string[] { };
                        rootsCount       = 0;
                    }

                    if (rootsCount == 0)
                    {
                        throw new Exception("If UseCustomRoots option is setted you must provide Custom Roots full info (Names, Folders, small an large images).");
                    }
                    else
                    {
                        if (selectedCustomRoot >= 0 && selectedCustomRoot < rootsCount)
                        {
                            mainRootInfo.CreateSubdirectory(rootsFolders[selectedCustomRoot]);
                            RootDirectory myCustomRoot = new RootDirectory();
                            myCustomRoot.ShowRootIndex = false;
                            myCustomRoot.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + rootsFolders[selectedCustomRoot];
                            myCustomRoot.LargeImageUrl = VirtualPathUtility.AppendTrailingSlash(rootsImageFolder) + rootsLargeImages[selectedCustomRoot];
                            myCustomRoot.SmallImageUrl = VirtualPathUtility.AppendTrailingSlash(rootsImageFolder) + rootsLargeImages[selectedCustomRoot];
                            myCustomRoot.Text          = rootsNames[selectedCustomRoot];
                            FileManager1.RootDirectories.Add(myCustomRoot);
                        }
                        else
                        {
                            for (int i = 0; i < rootsCount; i++)
                            {
                                mainRootInfo.CreateSubdirectory(rootsFolders[i]);
                                RootDirectory myCustomRoot = new RootDirectory();
                                myCustomRoot.ShowRootIndex = false;
                                myCustomRoot.DirectoryPath = VirtualPathUtility.AppendTrailingSlash(mainRoot) + rootsFolders[i];
                                myCustomRoot.LargeImageUrl = VirtualPathUtility.AppendTrailingSlash(rootsImageFolder) + rootsLargeImages[i];
                                myCustomRoot.SmallImageUrl = VirtualPathUtility.AppendTrailingSlash(rootsImageFolder) + rootsLargeImages[i];
                                myCustomRoot.Text          = rootsNames[i];
                                FileManager1.RootDirectories.Add(myCustomRoot);
                            }
                        }
                    }
                }
            }

            AccessMode fbAccessMode;

            if (MagicSession.Current.FileBrowserAccessMode == AccessMode.Default)
            {
                fbAccessMode = FileManager1.DefaultAccessMode;
            }
            else
            {
                fbAccessMode = MagicSession.Current.FileBrowserAccessMode;
            }

            Literal content;

            switch (fbAccessMode)
            {
            case AccessMode.Delete:
                FileManager1.Visible        = true;
                Panel_upload.Visible        = true;
                Panel_deny.Visible          = false;
                FileManager1.ReadOnly       = false;
                FileManager1.AllowDelete    = true;
                FileManager1.AllowOverwrite = true;
                break;

            case AccessMode.DenyAll:
                FileManager1.Visible = false;
                Panel_upload.Visible = false;
                Panel_deny.Visible   = true;
                content      = new Literal();
                content.Text = "<h1>" + FileManager1.Controller.GetResourceString("Upload_Error_3", "User does not have sufficient privileges.") + "<br/>&nbsp;</h1>";
                Panel_deny.Controls.Add(content);
                break;

            case AccessMode.ReadOnly:
            case AccessMode.Default:
                FileManager1.Visible  = true;
                Panel_upload.Visible  = false;
                Panel_deny.Visible    = false;
                FileManager1.ReadOnly = true;
                if (HideCommands)
                {
                    FileManager1.ShowToolBar       = false;
                    FileManager1.EnableContextMenu = false;
                    Panel_upload.Visible           = true;
                    Upload_button.Visible          = false;
                    DND_message.InnerText          = FileManager1.Controller.GetResourceString("No_Command_Help", "DoubleClick to open a folder. DoubleClick to download a file.");
                }
                break;

            case AccessMode.Write:
                FileManager1.Visible        = true;
                Panel_upload.Visible        = true;
                Panel_deny.Visible          = false;
                FileManager1.ReadOnly       = false;
                FileManager1.AllowDelete    = false;
                FileManager1.AllowOverwrite = false;
                break;

            default:
                break;
            }
        }
コード例 #42
0
 public User(string name, string password, string email, UserProfile profile) : base(name)
 {
     Password = password;
     Email    = email;
     Profile  = profile;
 }
コード例 #43
0
        public async Task <UserManagerOut> SaveAsync(UserManagerIn model)
        {
            //UserManagerOut result = new UserManagerOut { Result = new ResultRequest { Type = ResultRequestType.Error } };
            ApplicationUser userEntity = null;
            UserManagerOut  result     = new UserManagerOut();

            try
            {
                using (IDBWorker worker = kernel.Get <IDBWorker>())
                {
                    if (model.Id.Equals(Guid.Empty))
                    {
                        UserProfile profileEntity = worker.UserProfileRepository.Add(new UserProfile
                        {
                            Surname    = model.Profile.Surname,
                            FirstName  = model.Profile.FirstName,
                            Patronymic = model.Profile.Patronymic,
                            IsRemove   = false,
                            IsNecessaryChangePassword = false
                        });

                        userEntity = new ApplicationUser
                        {
                            Id          = Guid.NewGuid(),
                            UserName    = Person.FIO(profileEntity.Surname, profileEntity.FirstName, profileEntity.Patronymic),
                            UserProfile = profileEntity
                        };

                        await worker.UserManager.CreateAsync(userEntity, model.Password);

                        result.UserId    = userEntity.Id;
                        result.ProfileId = profileEntity.Id;
                    }
                    else
                    {
                        userEntity = await worker.UserManager.FindByIdAsync(model.Id);

                        userEntity.UserName = Person.FIO(model.Profile.Surname, model.Profile.FirstName, model.Profile.Patronymic);

                        result.UserId    = userEntity.Id;
                        result.ProfileId = await UpdateProfileAsync(worker, model.Profile);

                        if (!string.IsNullOrWhiteSpace(model.Password))
                        {
                            await worker.UserManager.RemovePasswordAsync(userEntity.Id);

                            await worker.UserManager.AddPasswordAsync(userEntity.Id, model.Password);
                        }

                        await worker.SaveAsync();
                    }

                    var oldRoles = await worker.UserManager.GetRolesAsync(userEntity.Id);

                    await worker.UserManager.RemoveFromRolesAsync(userEntity.Id, oldRoles.ToArray());

                    var newRoles = model.Roles.Select(r => r.Name).ToArray();
                    await worker.UserManager.AddToRolesAsync(userEntity.Id, newRoles);
                }
            }
            catch (InvalidOperationException ioex)
            {
            }
            catch (Exception ex)
            {
            }

            return(result);
        }
コード例 #44
0
 public void Add(UserProfile userProfile)
 {
     var lastUserProfile = _data.Last();
     userProfile.Id = lastUserProfile.Id + 1;
     _data.Add(userProfile);
 }
コード例 #45
0
        private static ReportDataRow TeamRatingsOverTime(IEnumerable <ReviewRound> reviewRounds, UserProfile ratedUser,
                                                         ReviewCategory category)
        {
            var title = ratedUser != null ? ratedUser.UserName + " (by team)" : "team (by team)";

            return(CreateReportDataRow(reviewRounds, ratedUser, category, title, false));
        }
コード例 #46
0
        private static ReportDataRow CreateReportDataRow(IEnumerable <ReviewRound> reviewRounds, UserProfile ratedUser,
                                                         ReviewCategory category, string title, bool onlyOwnRatings)
        {
            return(new ReportDataRow
            {
                Title = title,
                Values = reviewRounds
                         .Select(round => {
                    var assessments = round.Feedback.SelectMany(feedback => feedback.Assessments)
                                      .Where(ass => ass.ReviewCategory == category)
                                      .Where(ass => onlyOwnRatings ? ass.ReviewedPeer == ratedUser : (ratedUser == null || ass.ReviewedPeer == ratedUser))
                                      .Where(ass => !onlyOwnRatings || ass.Reviewer == ratedUser)
                                      .ToList();

                    return Convert.ToDecimal(assessments.Any()
                                                                                                ? assessments.Average(ass => ass.Rating)
                                                                                                : 0);
                }).ToList()
            });
        }
コード例 #47
0
 private static void VerifyIntegrityOfLoggedInUser(string loggedInUserEmail, bool myRatingsOnly, UserProfile peer)
 {
     if (myRatingsOnly && peer.EmailAddress != loggedInUserEmail)
     {
         throw new ArgumentException("There's a mismatch between the logged in user and the requested peer!",
                                     "loggedInUserEmail");
     }
 }
コード例 #48
0
        private static ReportDataRow OwnRatingsOverTime(IEnumerable <ReviewRound> reviewRounds, UserProfile ratedUser,
                                                        ReviewCategory category)
        {
            var title = string.Format("{0} (by {0})", ratedUser.UserName);

            return(CreateReportDataRow(reviewRounds, ratedUser, category, title, true));
        }
コード例 #49
0
 public RegisSuccPage(UserProfile user)
 {
     InitializeComponent();
     UserProfile = user;
 }
コード例 #50
0
        public ActionResult UserProfile(Models.UserProfile model)
        {
            var   emailid = User.Identity.Name.ToString();
            Users obj     = dbobj.Users.Where(x => x.EmailID == emailid).FirstOrDefault();

            if (ModelState.IsValid)
            {
                var isnew = dbobj.UserProfile.Where(x => x.UserID == obj.ID).FirstOrDefault();

                if (isnew == null)   // For new user
                {
                    UserProfile upobj = new UserProfile();
                    upobj.UserID = obj.ID;
                    upobj.DOB    = model.DateOfBirth;
                    upobj.Gender = model.Gender;
                    upobj.PhoneNumberCountryCode = model.CountryCode;
                    upobj.PhoneNumber            = model.PhoneNumber;
                    upobj.AddressLine1           = model.AddressLine1;
                    upobj.AddressLine2           = model.AddressLine2;
                    upobj.City        = model.City;
                    upobj.State       = model.State;
                    upobj.ZipCode     = model.ZipCode;
                    upobj.Country     = model.CountryID;
                    upobj.University  = model.University;
                    upobj.College     = model.College;
                    upobj.CreatedDate = DateTime.Now;
                    upobj.CreatedBy   = obj.ID;
                    upobj.IsActive    = true;

                    string path = Path.Combine(Server.MapPath("~/Members"), obj.ID.ToString());

                    //Checking for directory

                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    //Saving Profile Picture
                    if (model.ProfilePicture != null && model.ProfilePicture.ContentLength > 0)
                    {
                        var ProfilePicture = DateTime.Now.ToString().Replace(':', '-').Replace(' ', '_') + Path.GetExtension(model.ProfilePicture.FileName);
                        var ImageSavePath  = Path.Combine(Server.MapPath("~/Members/" + obj.ID + "/") + "DP_" + ProfilePicture);
                        model.ProfilePicture.SaveAs(ImageSavePath);
                        upobj.ProfilePicture = Path.Combine(("Members/" + obj.ID + "/"), "DP_" + ProfilePicture);
                        dbobj.SaveChanges();
                    }
                    else
                    {
                        /*upobj.ProfilePicture = "Default/User.jpg";*/
                        upobj.ProfilePicture = dbobj.SystemConfigurations.Where(x => x.Key == "DefaultProfilePicture").Select(x => x.Value).ToString();
                        dbobj.SaveChanges();
                    }

                    dbobj.UserProfile.Add(upobj);
                    dbobj.SaveChanges();

                    return(RedirectToAction("SearchNotes", "SearchNotes"));
                }
                else
                {
                    UserProfile oldupobj = dbobj.UserProfile.Where(x => x.UserID == obj.ID).FirstOrDefault();

                    Users olduserobj = dbobj.Users.Where(x => x.ID == obj.ID).FirstOrDefault();

                    olduserobj.FirstName    = model.FirstName;
                    olduserobj.LastName     = model.LastName;
                    olduserobj.EmailID      = model.EmailID;
                    olduserobj.ModifiedDate = DateTime.Now;
                    olduserobj.ModifiedBy   = olduserobj.ID;

                    oldupobj.DOB    = model.DateOfBirth;
                    oldupobj.Gender = model.Gender;
                    oldupobj.PhoneNumberCountryCode = model.CountryCode;
                    oldupobj.PhoneNumber            = model.PhoneNumber;
                    oldupobj.AddressLine1           = model.AddressLine1;
                    oldupobj.AddressLine2           = model.AddressLine2;
                    oldupobj.City         = model.City;
                    oldupobj.State        = model.State;
                    oldupobj.ZipCode      = model.ZipCode;
                    oldupobj.Country      = model.CountryID;
                    oldupobj.University   = model.University;
                    oldupobj.College      = model.College;
                    oldupobj.ModifiedDate = DateTime.Now;
                    oldupobj.ModifiedBy   = obj.ID;

                    string path = Path.Combine(Server.MapPath("~/Members"), obj.ID.ToString());

                    //Saving Profile Picture
                    if (model.ProfilePicture != null && model.ProfilePicture.ContentLength > 0)
                    {
                        var      OldProfilePicture = Server.MapPath(oldupobj.ProfilePicture);
                        FileInfo file = new FileInfo(OldProfilePicture);
                        if (file.Exists)
                        {
                            file.Delete();
                        }
                        var ProfilePicture = DateTime.Now.ToString().Replace(':', '-').Replace(' ', '_') + Path.GetExtension(model.ProfilePicture.FileName);
                        var ImageSavePath  = Path.Combine(Server.MapPath("~/Members/" + obj.ID + "/") + "DP_" + ProfilePicture);
                        model.ProfilePicture.SaveAs(ImageSavePath);
                        oldupobj.ProfilePicture = Path.Combine(("Members/" + obj.ID + "/"), "DP_" + ProfilePicture);
                        dbobj.SaveChanges();
                    }

                    dbobj.Entry(olduserobj).State = System.Data.Entity.EntityState.Modified;
                    dbobj.Entry(oldupobj).State   = System.Data.Entity.EntityState.Modified;
                    dbobj.SaveChanges();

                    return(RedirectToAction("SearchNotes", "SearchNotes"));
                }
            }
            ViewBag.ProfilePicture = dbobj.UserProfile.Where(x => x.UserID == obj.ID).Select(x => x.ProfilePicture).FirstOrDefault();
            return(View(model));
        }
コード例 #51
0
ファイル: ChatEntry.cs プロジェクト: menduz/explorer
    public void Populate(Model chatEntryModel)
    {
        this.model = chatEntryModel;

        string userString = GetDefaultSenderString(chatEntryModel.senderName);

        if (chatEntryModel.subType == Model.SubType.PRIVATE_FROM)
        {
            userString = $"<b>From {chatEntryModel.senderName}:</b>";
        }
        else
        if (chatEntryModel.subType == Model.SubType.PRIVATE_TO)
        {
            userString = $"<b>To {chatEntryModel.recipientName}:</b>";
        }

        switch (chatEntryModel.messageType)
        {
        case ChatMessage.Type.PUBLIC:
            body.color = worldMessageColor;

            if (username != null)
            {
                username.color = chatEntryModel.senderName == UserProfile.GetOwnUserProfile().userName ? playerNameColor : nonPlayerNameColor;
            }
            break;

        case ChatMessage.Type.PRIVATE:
            body.color = worldMessageColor;

            if (username != null)
            {
                if (model.subType == Model.SubType.PRIVATE_TO)
                {
                    username.color = privateToMessageColor;
                }
                else
                {
                    username.color = privateFromMessageColor;
                }
            }

            break;

        case ChatMessage.Type.SYSTEM:
            body.color = systemColor;

            if (username != null)
            {
                username.color = systemColor;
            }
            break;
        }

        chatEntryModel.bodyText = RemoveTabs(chatEntryModel.bodyText);

        if (username != null && !string.IsNullOrEmpty(userString))
        {
            if (username != null)
            {
                username.text = userString;
            }

            body.text = $"{userString} {chatEntryModel.bodyText}";
        }
        else
        {
            if (username != null)
            {
                username.text = "";
            }

            body.text = $"{chatEntryModel.bodyText}";
        }

        messageLocalDateTime = UnixTimeStampToLocalDateTime(chatEntryModel.timestamp).ToString();

        Utils.ForceUpdateLayout(transform as RectTransform);

        if (fadeEnabled)
        {
            group.alpha = 0;
        }
    }
コード例 #52
0
 public ChangeQtyService(UserProfile userProfile)
 {
     this.Initialize(typeof(IChangeQtyService), userProfile);
 }
コード例 #53
0
        //// GET: UserProfiles/Details/5
        //public ActionResult Details(Guid? id)
        //{
        //    if (id == null)
        //    {
        //        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        //    }
        //    UserProfile userProfile = db.UserProfiles.Find(id);
        //    if (userProfile == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(userProfile);
        //}


        // GET: UserProfiles/Create
        public ActionResult Create()
        {
            UserProfile_Conf UserProfile_Conf;

            HomeController.UserAuth user = new HomeController.UserAuth();

            if (ConfigurationManager.AppSettings["requireGroupMembership"] == "true")
            {
                user = HomeController.AuthorizeUser(User.Identity.Name.ToString());

                if (!user.authorized && !user.authorizedAdmin)
                {
                    //return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                    return(RedirectToAction("Unauthorized", "Home"));
                }
                if (User.Identity.IsAuthenticated)
                {
                    proceed = true;
                }
                else
                {
                    proceed = false;
                }
                UserProfile_Conf = db.UserProfile_Conf.SingleOrDefault(x => x.NTUserName == User.Identity.Name.ToString());
            }
            else
            {
                // Anonymous user without Authentication can still run this app
                proceed          = true;
                UserProfile_Conf = db.UserProfile_Conf.SingleOrDefault(x => x.NTUserName == "AnonymousUser");
            }


            // web.config debug setting
            ViewBag.debug  = HttpContext.IsDebuggingEnabled;
            ViewBag.agency = ConfigurationManager.AppSettings["agency"];
            ViewBag.ori    = ConfigurationManager.AppSettings["ori"];
            //ViewBag.useContractCity = Convert.ToBoolean(ConfigurationManager.AppSettings["useContractCity"] == "1" ? true : false);
            string useContractCity = ConfigurationManager.AppSettings["useContractCity"];

            ViewBag.useContractCity  = useContractCity;
            ViewBag.useContractEvent = ConfigurationManager.AppSettings["useContractEvent"];
            ViewBag.admin            = user.authorizedAdmin;
            UserProfile usrProf = new UserProfile();

            if (proceed && UserProfile_Conf == null)
            {
                if (useContractCity == "1")
                {
                    //create SelectListItem
                    usrProf.citiesList = dbl.ContractCities.
                                         Select(a => new SelectListItem
                    {
                        Text  = a.ContractCity.ToString().Trim(),                           // name to show in html dropdown
                        Value = a.ContractCity.ToString().Trim(),                           // value of html dropdown
                                                                                            //Selected = (a.City.ToString().Trim() == "ACAMPO")
                    }).ToList();
                }

                return(View(usrProf));
            }
            else
            {
                return(RedirectToAction("Index", "Home"));
            }
        }
コード例 #54
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CreateUserWizardStep1_CreatedUser(object sender, EventArgs e)
    {
        // Create an empty Profile for the newly created user
        //ProfileCommon p = (ProfileCommon)ProfileCommon.Create(CreateUserWizard1.UserName, true);

        // Populate some Profile properties off of the create user wizard
        //p.FirstName = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("FirstName")).Text;
        //p.LastName = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("LastName")).Text;


        //load new membership user and set 'Comment' property to {FirstName}|{LastName}

        MembershipUser mu = String.IsNullOrEmpty(CreateUserWizard1.UserName) ? Membership.GetUser(CreateOpenIDWizard.UserName) : Membership.GetUser(CreateUserWizard1.UserName.Trim());

        //approved = false by default

        if (mu != null)
        {
            //set approved
            mu.IsApproved = Website.Config.MembershipUserApprovedByDefault;
            string targetRole = "Users";
            if (!Roles.IsUserInRole(mu.UserName, targetRole))
            {
                Roles.AddUserToRole(mu.UserName, targetRole);
            }

            //create user profile

            UserProfile p = null;

            string memGUID = mu.ProviderUserKey.ToString().Trim();
            string fName   = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("FirstName")).Text;
            string lName   = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("LastName")).Text;
            string email   = ((TextBox)CreateUserWizard1.CreateUserStep.Controls[0].FindControl("Email")).Text;

            try
            {
                p          = UserProfileDB.InsertUserProfile(memGUID, fName, lName, email, email, email);
                mu.Comment = p.FirstName.Trim() + "|" + p.LastName.Trim();

                Membership.UpdateUser(mu);
                PermissionsManager mgr = new PermissionsManager();
                mgr.AddUserToGroup(System.Configuration.ConfigurationManager.AppSettings["DefaultAdminName"], vwarDAL.DefaultGroups.AllUsers, mu.UserName);
                if (Website.Config.SendEmailForNewRegistrations)
                {
                    Website.Mail.SendNewRegistrationNotificationEmail(mu);
                }
                mgr.Dispose();
            }
            catch
            {
            }
        }

        // Save profile - must be done since we explicitly created it
        // p.Save();

        if (Website.Config.MembershipUserApprovedByDefault == false)
        {
            //not approved
            FormsAuthentication.SignOut();
            MultiView1.SetActiveView(ConfirmationView);
        }
        else
        {
            //approved
            FormsAuthentication.RedirectFromLoginPage(CreateUserWizard1.UserName, false);
            Website.Mail.SendRegistrationApprovalEmail(mu.Email);
        }
    }
コード例 #55
0
        public bool AddUserImages(int user_id, IEnumerable <HttpPostedFileBase> Images, string user_name = "", string caption = "", string description = "")
        {
            UserProfile user = DAManager.UserProfilesRepository.Get(us => us.UserId == user_id).FirstOrDefault();

            if (user == null)
            {
                return(false);
            }

            if (Images != null)
            {
                foreach (HttpPostedFileBase image in Images)
                {
                    if (image != null)
                    {
                        Image img = new Image()
                        {
                            AddDate = DateTime.Now, Caption = caption, Description = description, URL = ""
                        };


                        DAManager.ImagesRepository.Insert(img);
                        user.UserImages.Add(new UserImage()
                        {
                            UserProfile = user, Image = img
                        });
                        try
                        {
                            DAManager.Save();

                            //Original
                            string file_name = "";
                            if (user_name == "")
                            {
                                file_name = (img.ImageId.ToString() + "-" + image.FileName).Replace(" ", "-");
                            }
                            else
                            {
                                file_name = (img.ImageId.ToString() + "-" + user_name + Path.GetExtension(image.FileName)).Replace(" ", "-");
                            }

                            System.Drawing.Image web_image = System.Drawing.Image.FromStream(image.InputStream);


                            //save Original Image
                            ImageService.SaveImage((System.Drawing.Image)web_image.Clone(), file_name);

                            //Save Thumnails 200x200
                            ImageService.SaveImage((System.Drawing.Image)web_image.Clone(), file_name, UserThumbWidth, UserThumbHeight);
                            ImageService.SaveImage((System.Drawing.Image)web_image.Clone(), file_name, UserMediumThumbWidth, UserMediumThumbHeight);
                            ImageService.SaveImage((System.Drawing.Image)web_image.Clone(), file_name, UserSmallThumbWidth, UserSmallThumbHeight);
                            ImageService.SaveImage((System.Drawing.Image)web_image.Clone(), file_name, UserThumbWidth2, UserThumbHeight2);

                            //Update the DB value
                            img.URL     = ImageService.GetImagesDirectory() + file_name;
                            user.Avatar = img.URL;
                            DAManager.Save();
                        }
                        catch (Exception ex)
                        {
                            logService.WriteError(ex.Message, ex.Message, ex.StackTrace, ex.Source);
                            return(false);
                        }
                    }
                }
            }
            return(true);
        }
コード例 #56
0
        public ActionResult Edit([Bind(Include = "ID,Agency,ORI,Years,Assignment,AssignmentOther,ContractFundedPosition,ContractCity,ContractFundedEvent,citiesList")] UserProfile userProfile)
        {
            HomeController.UserAuth user = new HomeController.UserAuth();
            if (ConfigurationManager.AppSettings["requireGroupMembership"] == "true")
            {
                user = HomeController.AuthorizeUser(User.Identity.Name.ToString());

                if (!user.authorized && !user.authorizedAdmin)
                {
                    //return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
                    return(RedirectToAction("Unauthorized", "Home"));
                }
            }
            // web.config debug setting
            ViewBag.debug = HttpContext.IsDebuggingEnabled;
            ViewBag.admin = user.authorizedAdmin;
            string useContractCity = ConfigurationManager.AppSettings["useContractCity"];

            ViewBag.useContractCity  = useContractCity;
            ViewBag.useContractEvent = ConfigurationManager.AppSettings["useContractEvent"];

            if (useContractCity == "1")
            {
                //create SelectListItem
                userProfile.citiesList = dbl.ContractCities.
                                         Select(a => new SelectListItem
                {
                    Text  = a.ContractCity.ToString().Trim(),                           // name to show in html dropdown
                    Value = a.ContractCity.ToString().Trim(),                           // value of html dropdown
                }).ToList();
            }


            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(userProfile.Assignment))
                {
                    userProfile.AssignmentKey = Int32.Parse(userProfile.Assignment.Substring(0, userProfile.Assignment.IndexOf(' ')));
                    userProfile.Assignment    = userProfile.Assignment.Substring(userProfile.Assignment.IndexOf(' ') + 1, userProfile.Assignment.Length - userProfile.Assignment.IndexOf(' ') - 1);
                    if (userProfile.AssignmentKey != 10)
                    {
                        userProfile.AssignmentOther = null;
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(userProfile.AssignmentOther))
                        {
                            ViewBag.ErrorOtherType = "Please enter a description for assignment";
                            return(View(userProfile));
                        }
                        if (userProfile.AssignmentOther.Length < 3)
                        {
                            ViewBag.ErrorOtherType = "Please enter at least 3 characters for this field.";
                            return(View(userProfile));
                        }
                    }
                }


                if (userProfile.ContractFundedPosition == true)
                {
                    if (string.IsNullOrEmpty(userProfile.ContractCity))
                    {
                        ViewBag.ErrorOtherType = "Please select a contracted city";
                        return(View(userProfile));
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(userProfile.ContractCity))
                    {
                        ViewBag.ErrorOtherType = "Please select true for Position Contract Funded";
                        return(View(userProfile));
                    }
                }
                userProfile.Agency = ConfigurationManager.AppSettings["agency"];
                userProfile.ORI    = ConfigurationManager.AppSettings["ori"];

                db.Entry(userProfile).State = EntityState.Modified;
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }
            // web.config debug setting
            //ViewBag.debug = HttpContext.IsDebuggingEnabled;
            return(View(userProfile));
        }
コード例 #57
0
        public ActionResult Create(PublicationModel publicationmodel, string[] keywordsId, string keyword, int pubId)
        {
            string      name = Membership.GetUser().UserName;
            UserProfile user = followPeersDB.UserProfiles.SingleOrDefault(p => p.UserName == name);

            publicationmodel.publicationID = pubId;
            if (ModelState.IsValid)
            {
                if (publicationmodel.author == null)
                {
                    publicationmodel.author = "default";
                }
                if (publicationmodel.conference == null)
                {
                    publicationmodel.conference = "default";
                }
                if (publicationmodel.description == null)
                {
                    publicationmodel.description = "default";
                }
                if (publicationmodel.issue == null)
                {
                    publicationmodel.issue = "default";
                }
                if (publicationmodel.journal == null)
                {
                    publicationmodel.journal = "default";
                }
                if (publicationmodel.keyword == null)
                {
                    publicationmodel.keyword = "default";
                }
                if (publicationmodel.page == null)
                {
                    publicationmodel.page = "default";
                }
                if (publicationmodel.publisher == null)
                {
                    publicationmodel.publisher = "default";
                }
                if (publicationmodel.referenceID == null)
                {
                    publicationmodel.referenceID = "Singapore";
                }
                if (publicationmodel.status == null)
                {
                    publicationmodel.status = "default";
                }
                if (publicationmodel.title == null)
                {
                    publicationmodel.title = "default";
                }
                if (publicationmodel.type == null)
                {
                    publicationmodel.type = "default";
                }
                if (publicationmodel.university == null)
                {
                    publicationmodel.university = "default";
                }
                if (publicationmodel.volume == null)
                {
                    publicationmodel.volume = "default";
                }
                if (publicationmodel.year == null)
                {
                    publicationmodel.year = 2014;
                }
                if (publicationmodel.viewCount == 0)
                {
                    publicationmodel.viewCount = 0;
                }
                if (publicationmodel.specialisation == null)
                {
                    publicationmodel.specialisation = "Physics";
                }
                publicationmodel.timestamp = DateTime.Now.ToString();
                if (Pubfilename != "")
                {
                    publicationmodel.filename = Pubfilename;
                    Pubfilename = "";
                }
                if (Imagename != "")
                {
                    publicationmodel.imagename = Imagename;
                    Imagename = "";
                }

                //Adding Tags
                //To keep track of tags being added
                List <Tag> AddedTags = new List <Tag>();

                //Adding the Tag
                if (keywordsId != null)
                {
                    //Selected Existing Tags
                    foreach (string tag in keywordsId)
                    {
                        int TagId = Convert.ToInt32(tag);
                        Tag Item  = followPeersDB.Tags.FirstOrDefault(p => p.TagId == TagId);
                        if (Item != null && !(Item.Publications.Any(p => p.publicationID == publicationmodel.publicationID)))
                        {
                            AddedTags.Add(Item);
                            //When Tag Linked to Item, incremented to keep count
                            Item.TagLinkedItems += 1;
                            publicationmodel.Tags.Add(Item);
                            Item.Publications.Add(publicationmodel);
                        }
                    }
                }
                if (keyword != null)
                {
                    //If written new tag
                    string[] Tags = keyword.Split(';');
                    foreach (string tagname in Tags)
                    {
                        string Trimtagname = tagname.Trim();
                        Tag    Item        = followPeersDB.Tags.FirstOrDefault(p => p.TagName.ToLower() == Trimtagname.ToLower());
                        if (Item != null)
                        {
                            if (AddedTags.Contains(Item) != true && !(Item.Publications.Any(p => p.publicationID == publicationmodel.publicationID)))
                            {
                                Item.TagLinkedItems += 1;
                                publicationmodel.Tags.Add(Item);
                                Item.Publications.Add(publicationmodel);
                                AddedTags.Add(Item);
                            }
                        }
                        else //If (Item == null)
                        {
                            //Create a New Tag
                            Tag NewItem = new Tag();
                            NewItem.TagName        = Trimtagname;
                            NewItem.TagLinkedItems = 1;
                            followPeersDB.Tags.Add(NewItem);
                            publicationmodel.Tags.Add(NewItem);
                            NewItem.Publications.Add(publicationmodel);
                            AddedTags.Add(NewItem);
                        }
                    }
                }
                //-----------End of Adding Tags



                user.Publication.Add(publicationmodel);
                CreateUpdates("Published a new publication titled " + publicationmodel.title, "/PublicationModel/Details/" + publicationmodel.publicationID.ToString(), 6, user.UserProfileId, publicationmodel.keyword);

                //followPeersDB.PublicationModels.Add(publicationmodel);
                followPeersDB.Entry(user).State = EntityState.Modified;
                followPeersDB.SaveChanges();

                return(RedirectToAction("Details", "PublicationModel", new { id = publicationmodel.publicationID }));
            }

            return(RedirectToAction("Index", "Profile", new { message = "Publication could not be created, please try again", id = user.UserProfileId }));
            //return View(publicationmodel);
        }
コード例 #58
0
        public ActionResult Recommend(int id, string Names)
        {
            UserProfile user = followPeersDB.UserProfiles.SingleOrDefault(p => p.UserName == name);

            string[] usersToRec = Names.Split(';');
            if (usersToRec.Length != 0)
            {
                foreach (string fullUserName in usersToRec)
                {
                    String[] splitNames = fullUserName.Split(' ');
                    if (splitNames.Length > 0)
                    {
                        String      userFirstName     = splitNames[0];
                        UserProfile userFromFirstName = followPeersDB.UserProfiles.SingleOrDefault(p => p.FirstName == userFirstName);
                        if (userFromFirstName == null)
                        {
                            return(RedirectToAction("Details", "PublicationModel", new { message = "No user with that First Name exists", id = id }));
                        }
                        if (splitNames.Length > 1)
                        {
                            String      userLastName     = splitNames[1];
                            UserProfile userFromLastName = followPeersDB.UserProfiles.SingleOrDefault(p => p.LastName == userLastName);
                            if (userFromFirstName.UserName != userFromLastName.UserName)
                            {
                                return(RedirectToAction("Details", "PublicationModel", new { message = "No such user exists", id = id }));
                            }
                        }

                        int         recommendid = userFromFirstName.UserProfileId;
                        UserProfile invitee     = followPeersDB.UserProfiles.SingleOrDefault(p => p.UserProfileId == recommendid);
                        Bookmark    model       = new Bookmark();

                        try
                        {
                            if (user.UserProfileId != recommendid)
                            {
                                model.bookmarkType = "Publication";
                                model.itemID       = id;
                                model.userID       = recommendid;
                                followPeersDB.Bookmarks.Add(model);
                                followPeersDB.SaveChanges();

                                //Adding a notification item to the recommended person
                                PublicationModel book    = followPeersDB.PublicationModels.SingleOrDefault(b => b.publicationID == id);
                                Notification     newnoti = new Notification
                                {
                                    message   = user.FirstName + user.LastName + " has recommeded you a publication : " + book.title,
                                    link      = "/PublicationModel/Details/" + id,
                                    New       = true,
                                    imagelink = user.PhotoUrl,
                                };

                                invitee.Notifications.Add(newnoti);
                                followPeersDB.Entry(invitee).State = EntityState.Modified;
                                followPeersDB.SaveChanges();
                                return(RedirectToAction("Details", "PublicationModel", new { message = "Recommendation sent", id = id }));
                            }
                        }
                        catch
                        {
                        }
                    }
                }
            }
            return(RedirectToAction("Details", "PublicationModel", new { message = "Enter at least one user to recommend", id = id }));
        }
コード例 #59
0
 public void Update(UserProfile up)
 {
     _context.Entry(up).State = EntityState.Modified;
     _context.SaveChanges();
 }
コード例 #60
0
 public BonusReasonGroupMaintService(UserProfile userProfile)
 {
     this.Initialize(typeof(IBonusReasonGroupMaintService), userProfile);
 }