Пример #1
0
        public static List<UserDetail> GetUserDetails()
        {
            List<UserDetail> userDetails = new List<UserDetail>();
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                {
                    SPUserCollection users = web.SiteUsers;

                    SPServiceContext context = SPServiceContext.Current;
                    UserProfileManager upm = new UserProfileManager(context);

                    foreach (SPUser user in users)
                    {
                        UserProfile profile = null;
                        if (upm.UserExists(user.LoginName))
                        {
                            profile = upm.GetUserProfile(user.LoginName);
                        }
                        UserDetail userDetail = GetUserDetail(user, profile);
                        userDetails.Add(userDetail);
                    }
                }
            });
            return userDetails;
        }
 private static IEnumerable<Microsoft.Office.Server.UserProfiles.UserProfile> GetUserProfileList(UserProfileManager manager)
 {
     foreach (Microsoft.Office.Server.UserProfiles.UserProfile userProfile in manager)
     {
         yield return userProfile;
     }
 }
Пример #3
0
        public static UserProfile GetUserProfileByLoginName(string userAccount)
        {
            UserProfile userProfile = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite osite = new SPSite(MOSSContext.Current!=null?MOSSContext.Current.Site.ID:SPContext.Current.Site.ID))
                    {
                        SPServiceContext context = SPServiceContext.GetContext(osite);
                        UserProfileManager profileManager = new UserProfileManager(context);

                        if (profileManager.UserExists(userAccount))
                        {
                            userProfile = profileManager.GetUserProfile(userAccount);
                        }
                    }
                }
                );
            }
            catch (Exception e)
            {
                throw new Exception("获取当前的用户信息出错:" + e.Message);
            }

            return userProfile;
        }
Пример #4
0
        internal static string GetEmployeeId(string userAccount, SPWeb web)
        {
            string employeeId = string.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(web.Site.ID))
                {
                    ServerContext context = ServerContext.GetContext(site);
                    UserProfileManager profileManager = new UserProfileManager(context);

                    if (profileManager.UserExists(userAccount))
                    {
                        UserProfile userProfile = profileManager.GetUserProfile(userAccount);
                        if (userProfile["EmployeeID"].Value != null)
                        {
                            employeeId = userProfile["EmployeeID"].Value.ToString();
                        }
                    }
                    else
                    {
                        ConsoleApp.Module.SystemEntry.LogInfoToLogFile(string.Format("There isn't user info ({0}) in ssp, please check it.", userAccount),
                                                                       string.Format("profileManager.UserExists(userAccount) return {0}", bool.FalseString),
                                                                       "GetEmployeeId");
                    }
                }
            });

            return employeeId;
        }
        public void CreateOrUpdateUserProfiles(IEnumerable<UserProfileViewObject> collection)
        {
            var profileManager = new UserProfileManager(spContext);

            foreach (var user in collection)
            {
                Microsoft.Office.Server.UserProfiles.UserProfile userProfile;
                if (profileManager.UserExists(user.Login))
                {
                    userProfile = profileManager.GetUserProfile(user.Login);
                }
                else
                {
                    userProfile = profileManager.CreateUserProfile(user.Login);
                    spLogger.DebugFormat("User profile for {0} was created.", user.Login);
                }

                userProfile["WorkEmail"].Add(user.Email);
                userProfile["FirstName"].Add(user.FirstName);
                userProfile["LastName"].Add(user.LastName);
                userProfile["PreferredName"].Add(user.FullName);

                userProfile.Commit();
                spLogger.DebugFormat("User profile for {0} was updated", user.Login);
            }
        }
Пример #6
0
        public static UserProfileUpdateStatus UpdateUserProfileByAccount(UserProfileManager upm, string account, DataRow userInfo, DataColumnCollection columns)
        {
            upm.AssertNotNull("upm");
            userInfo.AssertNotNull("userInfo");
            columns.AssertNotNull("columns");

            bool exists = upm.UserExists(account);

            UserProfile profile = exists ? upm.GetUserProfile(account) : upm.CreateUserProfile(account);

            foreach (string colName in from DataColumn column in columns select column.ColumnName)
            {
                bool editable = profile[colName].Property.IsAdminEditable;

                if (editable)
                {
                    try
                    {
                        profile[colName].Value = userInfo[colName];
                    }
                    catch
                    {
                    }
                }

            }

            profile.Commit();

            return exists ? UserProfileUpdateStatus.Updated : UserProfileUpdateStatus.NewlyAdded;
        }
        public static string GetUserProfile(SPWeb web, string userName)
        {
            string res = "";
            try
            {
                SPServiceContext serviceContext = SPServiceContext.GetContext(web.Site);
                UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
                UserProfile userProfile = userProfileMgr.GetUserProfile(userName);
                ProfileSubtypePropertyManager pspm = userProfileMgr.DefaultProfileSubtypeProperties;
                res += "<br/><table><tr><td>DisplayName</td><td>Name</td><td>Value</td></tr>";
                foreach (ProfileSubtypeProperty prop in pspm.PropertiesWithSection)
                {
                    if (prop.IsSection)
                        res += "<tr><td colspan='3'><b>" + prop.DisplayName + "</b></td></tr>";
                    else
                    {
                        res += "<tr><td>" + prop.DisplayName + "</td><td>" + prop.Name + "</td><td>" + userProfile[prop.Name].Value + "</td></tr>";
                    }
                }
                res += "</table>";
            }
            catch (Exception ex)
            {
                UlsLogging.LogError("UserInfo. GetUserProfile. Message {0}. StackTrace {1}", ex.Message, ex.StackTrace);
                res += "<br/><strong>UserInfo. GetUserProfile.</strong> <br/>ex.Message: " + ex.Message + "<br/>ex.StackTrace" + ex.StackTrace;

            }
            return res;
        }
        public void GenerateMyQuickLinks()
        {
            ServerContext _serviceContext = ServerContext.Current;
            UserProfileManager profilmanager = new UserProfileManager(_serviceContext);

            UserProfile _userProfile = profilmanager.GetUserProfile(true);

            if (_userProfile.PersonalSite != null)
            {

                QuickLinkManager qlmanager = new QuickLinkManager(_userProfile);
                QuickLink[] ql = qlmanager.GetItems();

                if (ql.Length != 0)
                {
                    HtmlGenericControl ul = new HtmlGenericControl("ul");
                    ul.Attributes["class"] = "rightsideul";
                    foreach (QuickLink objql in ql)
                    {
                        HtmlGenericControl li = new HtmlGenericControl("li");
                        li.Attributes["class"] = "rightsideli";

                        HtmlGenericControl a = new HtmlGenericControl("a");
                        a.Attributes["href"] = objql.Url;
                        a.InnerText = objql.Title;
                        li.Controls.Add(a);
                        ul.Controls.Add(li);
                    }

                    //this.Controls.Add(ul);
                    upanel2.ContentTemplateContainer.Controls.Add(ul);
                }
            }
        }
        internal static BillingShippingUserInfo GetCustomerBillingAndShippingInfo(User user, OrdersManager ordersManager, UserProfileManager userProfileManager)
        {
            if (user == null)
            {
                return null; //don't do anything
            }

            CustomerRetriever customerRetriever = new CustomerRetriever(ordersManager, userProfileManager);

            Customer customer = customerRetriever.GetCustomerOfUser(user);

            if (customer == null)
            {
                return LoadDataFromSitefinityProfile();
            }

            IQueryable<CustomerAddress> customerAddresses = ordersManager.GetPrimaryCustomerAddressesByCustomerId(customer.Id);

            if (customerAddresses.Count() == 0)
            {
                return LoadDataFromSitefinityProfile();
            }

            var billingShippingInfo = new BillingShippingUserInfo();

            CustomerAddress customerBillingAddress = GetPrimaryCustomerAddress(customerAddresses, AddressType.Billing);

            billingShippingInfo.BillingFirstName = customerBillingAddress.FirstName;
            billingShippingInfo.BillingLastName = customerBillingAddress.LastName;
            billingShippingInfo.BillingCompany = customerBillingAddress.Company;
            billingShippingInfo.BillingEmail = customerBillingAddress.Email;
            billingShippingInfo.BillingAddress1 = customerBillingAddress.Address;
            billingShippingInfo.BillingAddress2 = customerBillingAddress.Address2;
            billingShippingInfo.BillingCity = customerBillingAddress.City;
            billingShippingInfo.BillingCountry = customerBillingAddress.Country;
            billingShippingInfo.BillingState = customerBillingAddress.StateRegion;
            billingShippingInfo.BillingZip = customerBillingAddress.PostalCode;
            billingShippingInfo.BillingPhoneNumber = customerBillingAddress.Phone;

            CustomerAddress customerShippingAddress = GetPrimaryCustomerAddress(customerAddresses, AddressType.Shipping);
            if (customerShippingAddress == null)
            {
                customerShippingAddress = customerBillingAddress;
            }
            billingShippingInfo.ShippingFirstName = customerShippingAddress.FirstName;
            billingShippingInfo.ShippingLastName = customerShippingAddress.LastName;
            billingShippingInfo.ShippingCompany = customerShippingAddress.Company;
            billingShippingInfo.ShippingEmail = customerShippingAddress.Email;
            billingShippingInfo.ShippingAddress1 = customerShippingAddress.Address;
            billingShippingInfo.ShippingAddress2 = customerShippingAddress.Address2;
            billingShippingInfo.ShippingCity = customerShippingAddress.City;
            billingShippingInfo.ShippingCountry = customerShippingAddress.Country;
            billingShippingInfo.ShippingState = customerShippingAddress.StateRegion;
            billingShippingInfo.ShippingZip = customerShippingAddress.PostalCode;
            billingShippingInfo.ShippingPhoneNumber = customerShippingAddress.Phone;

            return billingShippingInfo;
        }
		public static Object GetValue(String propertyName, Type propertyType)
		{
			var serviceContext = SPServiceContext.GetContext(HttpContext.Current);
			var upm = new UserProfileManager(serviceContext);
			var up = upm.GetUserProfile(false);
			var propertyValue = (up[propertyName] != null) ? up[propertyName].Value : null;

			return (Convert(propertyValue, propertyType));
		}
Пример #11
0
        /// <summary>
        /// Gets the user project leader.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="serviceContext">The service context.</param>
        /// <param name="context">The context.</param>
        /// <returns>The Project Leader SPUser object.</returns>
        public static SPUser GetUserProjectLeader(SPUser user, SPServiceContext serviceContext, SPContext context)
        {
            return context.Web.AllUsers["fp\\fps_pm"];

            UserProfileManager manager = new UserProfileManager(serviceContext);
            var userProfile = manager.GetUserProfile(user.LoginName);
            var projectLeaderProfile = userProfile.GetManager();
            return context.Web.AllUsers[projectLeaderProfile.MultiloginAccounts[0]];
        }
        public void RemoveUserProfiles(IEnumerable<string> accounts)
        {
            var profileManager = new UserProfileManager(spContext);

            foreach (var account in accounts.Where(profileManager.UserExists))
            {
                profileManager.RemoveUserProfile(account);
                spLogger.DebugFormat("User Profile for {0} was removed.", account);
            }
        }
Пример #13
0
 static void InitUsers(SPServiceContext context) {
     UserProfileManager manager = new UserProfileManager(context);
     using (var db = new CMSMIPEntities()) {
         var users = db.CMS_SA_USER_INFO_V;
         foreach (var user in users) {
             if (!manager.UserExists(user.SP账号)) {
                 UserProfile userProfile = manager.CreateUserProfile(user.SP账号);
             }
         }
     }
 }
 protected UserProfile AddUser()
 {
     var manager = new UserProfileManager();
     var profile = new UserProfile
     {
         Name = "test",
         UserCode = "123456",
         Password = "******"
     };
     var error = manager.Create(profile);
     Assert.IsTrue(string.IsNullOrEmpty(error));
     return profile;
 }
Пример #15
0
        static void Main(string[] args)
        {
            UserProfileManager upm = new UserProfileManager();

            // Office 365 Multi-tenant sample
            upm.User = "******";
            upm.Password = GetPassWord();
            upm.TenantAdminUrl = "https://bertonline-admin.sharepoint.com";
            string userLoginName = "i:0#.f|membership|[email protected]";

            // On-premises or Office 365 Dedicated sample
            //string userLoginName = @"SET1\KevinC";
            //upm.User = "******";
            //upm.Password = GetPassWord();
            //upm.Domain = "SET1";
            //upm.MySiteHost = "https://sp2013-my.set1.bertonline.info";

            Console.Write(String.Format("Value of {0} for {1} :", "AboutMe", userLoginName));
            Console.WriteLine(upm.GetPropertyForUser<String>("AboutMe", userLoginName));
            Console.WriteLine("-----------------------------------------------------");
            Console.WriteLine("");
            Console.Write(String.Format("Value of {0} for {1} :", "SPS-LastKeywordAdded", userLoginName));
            Console.WriteLine((upm.GetPropertyForUser<DateTime>("SPS-LastKeywordAdded", userLoginName)).ToLongDateString());
            Console.WriteLine("-----------------------------------------------------");
            Console.WriteLine("");
            Console.WriteLine(String.Format("Set value of {0} for {1} to {2}:", "AboutMe", userLoginName, "I love using Office AMS!"));
            upm.SetPropertyForUser<String>("AboutMe", "I love using Office AMS!", userLoginName);
            Console.WriteLine("");
            Console.Write(String.Format("Value of {0} for {1} :", "AboutMe", userLoginName));
            Console.WriteLine(upm.GetPropertyForUser<String>("AboutMe", userLoginName));
            Console.WriteLine("-----------------------------------------------------");            
            Console.WriteLine("");
            //nl-BE,fr-BE,en-US,de-DE
            Console.Write(String.Format("Value of {0} for {1} :", "SPS-MUILanguages", userLoginName));
            UserProfileASMX.PropertyData p = upm.GetPropertyForUser("SPS-MUILanguages", userLoginName);
            Console.WriteLine(p.Values[0].Value.ToString());
            Console.WriteLine("");
            Console.WriteLine(String.Format("Set value of {0} for {1} to {2}:", "SPS-MUILanguages", userLoginName, "nl-BE,en-US"));
            UserProfileASMX.PropertyData[] pMui = new UserProfileASMX.PropertyData[1];
            pMui[0] = new UserProfileASMX.PropertyData();
            pMui[0].Name = "SPS-MUILanguages";
            pMui[0].Values = new UserProfileASMX.ValueData[1];
            pMui[0].Values[0] = new UserProfileASMX.ValueData();
            pMui[0].Values[0].Value = "nl-BE,en-US";
            pMui[0].IsValueChanged = true;
            upm.SetPropertyForUser("SPS-MUILanguages", pMui, userLoginName);
            Console.WriteLine("-----------------------------------------------------");
            Console.WriteLine("");

            Console.ReadLine();
        }
    protected void Page_Load(object sender, EventArgs e)
    {

        using (SPSite site = SPContext.Current.Site)
        {
            SPServiceContext context =
                SPServiceContext.GetContext(site);
            upm = new UserProfileManager(context);
            up = upm.GetUserProfile("abcph\\administrator");
            Response.Write("work email is " + up[PropertyConstants.WorkEmail].Value + "<br>");
            Response.Write("state is " + up["State"].Value);

        }
    }
 /// <summary>
 /// Sets the picture URL for the specfied user.
 /// </summary>
 /// <param name="profManager">The prof manager.</param>
 /// <param name="username">The username.</param>
 /// <param name="path">The path.</param>
 /// <param name="overwrite">if set to <c>true</c> [overwrite].</param>
 /// <param name="ignoreMissingData">if set to <c>true</c> [ignore missing data].</param>
 /// <param name="validateUrl">if set to <c>true</c> validate the url.</param>
 public static void SetPicture(UserProfileManager profManager, string username, string path, bool overwrite, bool ignoreMissingData, bool validateUrl)
 {
     if (!String.IsNullOrEmpty(username))
     {
         if (!profManager.UserExists(username))
         {
             throw new SPException("The username specified cannot be found.");
         }
         UserProfile profile = profManager.GetUserProfile(username);
         SetPicture(profile, path, overwrite, ignoreMissingData, validateUrl);
     }
     else
         throw new ArgumentNullException("username", "The username parameter cannot be null or empty.");
 }
Пример #18
0
 public string parseUser(string userValue, SPSite site)
 {
     try
     {
         SPServiceContext svcCtx = SPServiceContext.GetContext(site);
         UserProfileManager profileManager = new UserProfileManager(svcCtx);
         var profile = profileManager.GetUserProfile(userValue);
         return null != profile["WorkEmail"].Value ? profile["WorkEmail"].ToString() : string.Empty;
     }
     catch (Exception exception)
     {
         SharePointUtilities.TraceDebugException(" Could not parse user! ", GetType(), exception);
         return string.Empty;
     }
 }
        protected override void CreateChildControls()
        {
            var control = Page.LoadControl(_ascxPath) as UserProfileListWebPartUserControl;
            if (control != null)
            {
                // full access
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    var profileManager = new UserProfileManager(SPServiceContext.Current);
                    control.UserProfileList = GetUserProfileList(profileManager);
                });

                Controls.Add(control);
            }
        }
Пример #20
0
        //Employee
        /// <summary>
        /// 得到EmployeeMail
        /// </summary>
        /// <param name="userAccount"></param>
        /// <returns></returns>
        public static string GetEmployeeMail(string userAccount)
        {
            string sMail = string.Empty;
            if (string.IsNullOrEmpty(userAccount))
            {
                return sMail;
            }
            try
            {
                //从SSP里面取用户。
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(sSiteName))
                    {
                        using (SPWeb web = site.OpenWeb(sWebName))
                        {
                            Microsoft.Office.Server.ServerContext context = Microsoft.Office.Server.ServerContext.GetContext(site);
                            UserProfileManager profileManager = new UserProfileManager(context);
                            if (profileManager.UserExists(userAccount))
                            {
                                UserProfile userProfile = profileManager.GetUserProfile(userAccount);

                                if (null!=userProfile["WorkEmail"].Value)
                                {
                                    sMail = userProfile["WorkEmail"].Value.ToString().Trim();
                                }
                                else
                                {
                                    WriteErrorLog(string.Format("共享服务(SSP)中没有为用户:{0}的配置邮件信息,可能是共享服务(SSP)没有和AD同步所致,请联系IT管理员联系!", userAccount));
                                }
                            }
                            else
                            {
                                WriteErrorLog(string.Format("共享服务(SSP)中没有用户:{0}的信息,可能是共享服务(SSP)没有和AD同步所致,请联系IT管理员联系!", userAccount));
                            }
                        }
                    }
                }
                );
            }
            catch (Exception e)
            {
                WriteErrorLog(string.Format("获取当前的用户 {0} 信息出错:{1}", userAccount, e.Message.ToString()));
            }

            return sMail;
        }
        internal static Customer GetCustomerInfoOrCreateOneIfDoesntExsist(UserProfileManager userProfileManager, OrdersManager ordersManager, CheckoutState checkoutState)
        {
            var customerRetriever = new CustomerRetriever(ordersManager, userProfileManager);

            User customerUser = null;
            Customer customer = null;

            Guid userId = SecurityManager.CurrentUserId;
            if (userId != Guid.Empty)
            {
                customerUser = SecurityManager.GetUser(userId);
                if (customerUser != null)
                {

                    customer = customerRetriever.GetCustomer(customerUser, checkoutState);
                }
            }

            return customer;
        }
        public void ProfileCreated(ProfileCreated eventinfo)
        {
            UserManager userManager = UserManager.GetManager();

            Telerik.Sitefinity.Security.Model.User user = userManager.GetUser(eventinfo.UserId);

            UserProfileManager userProfileManager = UserProfileManager.GetManager();
            SitefinityProfile  profile            = userProfileManager.GetUserProfile(user, eventinfo.ProfileType) as SitefinityProfile;

            // user.ExternalProviderName is null means registrating through normal registration
            // Otherwise registring through External provider like LinkedIn, Facebook, etc...
            // In case external provider, we will recieve the password as null but JXTNext Member database table requires
            // password should not be empty, so generating some random password of 8 characters length.
            JXTNext_MemberRegister memberReg = new JXTNext_MemberRegister
            {
                Email     = user.Email,
                FirstName = profile.FirstName,
                LastName  = profile.LastName,
                Password  = user.ExternalProviderName.IsNullOrEmpty() ? user.Password : GeneralHelper.GeneratePassword(8)
            };

            IEnumerable <IJobListingMapper> jobListingMappers = new List <IJobListingMapper> {
                new JXTNext_JobListingMapper()
            };
            IEnumerable <IMemberMapper> memberMappers = new List <IMemberMapper> {
                new JXTNext_MemberMapper()
            };
            IRequestSession requestSession = new SFEventRequestSession {
                UserEmail = user.Email
            };

            IBusinessLogicsConnector connector = new JXTNextBusinessLogicsConnector(jobListingMappers, memberMappers, requestSession);
            bool registerSuccess = connector.MemberRegister(memberReg, out string errorMessage);

            if (!registerSuccess)
            {
                //eventinfo.IsApproved = false;
            }
        }
Пример #23
0
        //最新的关注的网站和取消的网站
        private void FollowingAndStopFollowing()
        {
            SPUser us = SPContext.Current.Web.CurrentUser;
            SPSocialFollowingManager _followManager = null;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite elevatedSite = new SPSite(SPContext.Current.Web.Url))
                {
                    SPServiceContext serverContext    = SPServiceContext.GetContext(SPContext.Current.Site);
                    UserProfileManager profileManager = new UserProfileManager(serverContext);
                    UserProfile profile = profileManager.GetUserProfile(us.LoginName);
                    if (profile != null)
                    {
                        //Create a Social Manager profile
                        _followManager = new SPSocialFollowingManager(profile);
                        SPSocialActorInfo actorInfo = null;
                        //SPSocialActor[] actors = _followManager.GetFollowers();
                        SPSocialActor[] ifollow = _followManager.GetFollowed(SPSocialActorTypes.Sites);
                        foreach (SPSocialActor follower in ifollow)
                        {
                            actorInfo            = new SPSocialActorInfo();
                            actorInfo.ContentUri = follower.Uri;
                            actorInfo.ActorType  = SPSocialActorType.Site;
                            if (!_followManager.IsFollowed(actorInfo))
                            {
                                _followManager.Follow(actorInfo);
                                des.Text = "follow:OK";
                            }
                            else
                            {
                                _followManager.StopFollowing(actorInfo);
                                des.Text = "stoppFollowing OK";
                            }
                        }
                    }
                }
            });
        }
Пример #24
0
        private void btnSelectionCircle_Click(object sender, EventArgs e)
        {
            this.btnSelectionCircle.BackColor  = this.btnSelectionCircle.SelectedBackgroundColor;
            this.btnSelectionCircle.IsSelected = true;
            this.btnSelectionCircle.Invalidate();

            this.btnSelectionSquare.BackColor  = Color.White;
            this.btnSelectionSquare.IsSelected = false;
            this.btnSelectionSquare.Invalidate();

            SceneView.MAGSAISelectionMarker.Diameter = UserProfileManager.UserProfiles[0].Settings_Studio_SelectionBox_Size * 10;
            UserProfileManager.UserProfiles[0].Settings_Studio_SelectionBox_Type = Core.Models.MAGSAIMarkSelectionGizmo.TypeOfSelectionBox.Circle;
            UserProfileManager.Save();

            SceneView.MAGSAISelectionMarker.UpdateSelectionBox(new SelectionBoxSizeEventArgs(
                                                                   UserProfileManager.UserProfiles[0].Settings_Studio_SelectionBox_Type),
                                                               frmStudioMain.SceneControl.Width,
                                                               frmStudioMain.SceneControl.Height,
                                                               new Point(frmStudioMain.SceneControl.Width / 2, frmStudioMain.SceneControl.Height / 2));

            frmStudioMain.SceneControl.Render();
        }
Пример #25
0
        public UsersDataController(
            SiteManager siteManager,
            ClientManager clientManager,
            UserProfileManager profileManager,
            UserManager userManager,
            Identity.SecurityPoolManager poolManager,
            ILogger <UsersDataController> logger,
            DirectoryManager directoryManager,
            TemplateEmailService messaging,
            IOptions <AegisOptions> openIdOptions

            ) : base(logger)
        {
            _siteManager      = siteManager;
            _clientManager    = clientManager;
            _profileManager   = profileManager;
            _userManager      = userManager;
            _poolManager      = poolManager;
            _directoryManager = directoryManager;
            _messaging        = messaging;
            _openIdOptions    = openIdOptions.Value;
        }
        private void getEmps()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite oSite                      = new SPSite(SPContext.Current.Web.Url);
                    SPWeb spWeb                       = oSite.OpenWeb();
                    SPPrincipalInfo pinfo             = SPUtility.ResolvePrincipal(spWeb, strEmpDisplayName, SPPrincipalType.User, SPPrincipalSource.All, null, false);
                    SPServiceContext serviceContext   = SPServiceContext.GetContext(oSite);
                    UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
                    UserProfile cUserProfile          = userProfileMgr.GetUserProfile(pinfo.LoginName);

                    List <UserProfile> directReports = new List <UserProfile>(cUserProfile.GetDirectReports());
                    foreach (UserProfile up in directReports)
                    {
                        DataRow row = tblEmps.NewRow();

                        if (up.GetProfileValueCollection("AboutMe")[0] != null && up.GetProfileValueCollection("AboutMe")[0].ToString() != string.Empty)
                        {
                            row["EmpName"] = up.GetProfileValueCollection("AboutMe")[0].ToString();
                        }
                        else
                        {
                            row["EmpName"] = up.DisplayName;
                        }

                        row["EnglishName"] = up.DisplayName;


                        row["EmpJob"] = up.GetProfileValueCollection("Title")[0].ToString();
                        tblEmps.Rows.Add(row);
                    }
                });
            }
            catch (Exception)
            {
            }
        }
        protected void removeFromFavouritesButton_OnClick(object sender, EventArgs e)
        {
            SPSite             site           = SPContext.Current.Site;
            SPServiceContext   serviceContext = SPServiceContext.GetContext(site);
            UserProfileManager profileManager = new UserProfileManager(serviceContext);
            UserProfile        profile        = profileManager.GetUserProfile(true);

            UserProfileValueCollection myFavouriteWorkBoxesPropertyValue = profile[WorkBox.USER_PROFILE_PROPERTY__MY_FAVOURITE_WORK_BOXES];

            string myFavouriteWorkBoxesString = "";


            if (myFavouriteWorkBoxesPropertyValue.Value != null)
            {
                myFavouriteWorkBoxesString = myFavouriteWorkBoxesPropertyValue.Value.ToString();
            }

            string guidStringToRemove = WorkBoxGuid.Value;

            List <String> updatedFavouritesList = new List <String>();

            string[] favouriteWorkBoxes = myFavouriteWorkBoxesString.Split(';');
            foreach (string favouriteWorkBox in favouriteWorkBoxes)
            {
                if (!favouriteWorkBox.Contains(guidStringToRemove))
                {
                    updatedFavouritesList.Add(favouriteWorkBox);
                }
            }

            myFavouriteWorkBoxesPropertyValue.Value = String.Join(";", updatedFavouritesList.ToArray());

            site.AllowUnsafeUpdates = true;
            profile.Commit();
            site.AllowUnsafeUpdates = false;

            CloseDialogAndRefresh();
        }
Пример #28
0
        public ActionResult Login(BusinessObject.UserProfile model)
        {
            if (!string.IsNullOrEmpty(model.Password) && !string.IsNullOrEmpty(model.UserName))
            {
                if (ModelState.IsValid && UserProfileManager.IsValidUser(model.UserName, model.Password))
                {
                    BusinessObject.UserProfile profileObj = new UserProfileManager().GetUserRoleProfileByUserNameAndPassword(model.UserName, model.Password);
                    FormsAuthenticationTicket  ticket     = new FormsAuthenticationTicket
                                                            (
                        1,
                        model.UserName,
                        DateTime.Now,
                        DateTime.Now.AddMinutes(30),
                        false,
                        profileObj.RoleName + "," + profileObj.FirstName,
                        FormsAuthentication.FormsCookiePath
                                                            );
                    Response.Cookies.Add
                    (
                        new HttpCookie
                        (
                            FormsAuthentication.FormsCookieName,
                            FormsAuthentication.Encrypt(ticket)
                        )
                    );
                    ModelState.AddModelError("", "Login Success");
                    return(RedirectToAction("Index", "Customer"));
                }

                // If we got this far, something failed, redisplay form
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
            else
            {
                ModelState.AddModelError("", "The user name and password fields are required.");
            }
            return(View(model));
        }
        /// <summary>
        /// Gets the Gigya UID for the current logged in user. If the user isn't logged in, null is returned.
        /// </summary>
        /// <param name="settings">Current site settings.</param>
        /// <returns>The UID value.</returns>
        public string GetUidForCurrentUser(IGigyaModuleSettings settings)
        {
            // check user is logged in
            var currentIdentity = ClaimsManager.GetCurrentIdentity();

            if (!currentIdentity.IsAuthenticated)
            {
                return(null);
            }

            // get mapping field - hopefully the Sitefinity username field maps to Gigya's UID
            var field = settings.MappedMappingFields.FirstOrDefault(i => i.GigyaFieldName == Constants.GigyaFields.UserId);

            if (field == null || field.CmsFieldName == Constants.SitefinityFields.UserId)
            {
                return(currentIdentity.Name);
            }

            // get UID field from profile
            UserProfileManager profileManager = UserProfileManager.GetManager();
            UserManager        userManager    = UserManager.GetManager();

            var user = userManager.GetUser(currentIdentity.Name);

            if (user == null)
            {
                return(currentIdentity.Name);
            }

            var profile = profileManager.GetUserProfile <SitefinityProfile>(user);

            if (profile == null)
            {
                return(currentIdentity.Name);
            }

            return(profile.GetValue <string>(field.CmsFieldName));
        }
Пример #30
0
        private void btnEnum_Click(object sender, EventArgs e)
        {
            SPSite site = new SPSite("http://localhost");

            try
            {
                SPServiceContext   serviceContext = SPServiceContext.GetContext(site);
                UserProfileManager upm            = new UserProfileManager(serviceContext);
                string             accountName    = "ccc\\" + txtUser.Text.ToString();//xueqingxia";// SPContext.Current.Web.CurrentUser.LoginName;
                //accountName = accountName.Substring(accountName.LastIndexOf("|") + 1);
                //if (accountName == "sharepoint\\system")
                //    accountName = "ccc\\xueqingxia";
                if (upm.UserExists(accountName))
                {
                    UserProfile u = upm.GetUserProfile(accountName);
                    //Response.Write(u[PropertyConstants.PictureUrl].Value);
                    SPSocialFollowingManager follow     = new SPSocialFollowingManager(u, serviceContext);
                    SPSocialActorInfo        socialInfo = new SPSocialActorInfo();
                    StringBuilder            txt        = new StringBuilder();
                    //des.Text = follow.GetFollowedCount(SPSocialActorTypes.Sites).ToString();
                    foreach (SPSocialActor spFollow in follow.GetFollowed(SPSocialActorTypes.Sites))
                    {
                        //spFollow.Status = SPSocialStatusCode.InternalError;
                        socialInfo.ContentUri = spFollow.Uri;
                        //socialInfo.AccountName = u.AccountName;
                        socialInfo.ActorType = SPSocialActorType.Site;
                        //follow.StopFollowing(socialInfo);
                        //des.Text += "ok! ";
                        txt.AppendLine(spFollow.Uri.ToString());
                    }
                    this.txtResult.Text = txt.ToString();
                }
            }
            catch (Exception ex)
            {
                this.txtResult.Text = ex.ToString();
            }
        }
Пример #31
0
        protected void Page_Load(object sender, EventArgs e)
        {
            UserManager userManager = UserManager.GetManager();
            List <User> users       = userManager.GetUsers().ToList();

            DataTable output = new DataTable("ASA");

            output.Columns.Add("LastName");
            output.Columns.Add("FirstName");
            output.Columns.Add("Email");
            output.Columns.Add("Username");
            output.Columns.Add("UserID");


            foreach (User user in users)
            {
                UserProfileManager profileManager = UserProfileManager.GetManager();
                SitefinityProfile  profile        = profileManager.GetUserProfile <SitefinityProfile>(user);

                DataRow dr;
                dr = output.NewRow();
                dr["FirstName"] = profile.FirstName;
                dr["Username"]  = user.UserName;
                dr["Email"]     = user.Email;
                dr["LastName"]  = profile.LastName;
                dr["UserID"]    = user.Id;

                output.Rows.Add(dr);
            }

            Document d = new Document();



            SitefinityUsersGridView.DataSource = output;
            //if (!IsPostBack)
            SitefinityUsersGridView.DataBind();
        }
Пример #32
0
        public UserProfileManager GetUserProfileManager()
        {
            SPFarm farm = SPFarm.Local;

            SPWebService service = farm.Services.GetValue <SPWebService>("");

            SPSite site = GetFirstSPSite();

            SPServiceContext serviceContext = SPServiceContext.GetContext(site);

            try
            {
                UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
                return(userProfileMgr);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.GetType().ToString() + ": " + e.Message);
                Console.Read();
            }

            return(null);
        }
Пример #33
0
        public ActionResult Edit(string id)
        {
            MembershipUser     user = Membership.GetUser(id);
            UserProfileManager pMgr = new UserProfileManager(user);

            var userModules = ModRepository.GetUserModules((Guid)user.ProviderUserKey);
            var allModules  = new List <IModule>();          //ModRepository.GetAllStaticModules();

            EditUserViewModel viewModel = new EditUserViewModel()
            {
                UserId      = (Guid)user.ProviderUserKey,
                Email       = user.Email,
                UserProfile = pMgr.UserProfile,
                UserModules = userModules,
                AllModules  = allModules.Where(module => userModules.FirstOrDefault(mod => mod.Id == module.Id) == null)
            };

            // add the list with all available database types
            // TODO: Move this code to the profile-related namespace
            List <object> databaseTypes = new List <object>();

            return(View(viewModel));
        }
Пример #34
0
        private static ProfileViewModel GetCurrentSitefinityUserProfile()
        {
            var identity        = ClaimsManager.GetCurrentIdentity();
            var currentUserGuid = identity.UserId;

            if (currentUserGuid != Guid.Empty)
            {
                UserProfileManager profileManager = UserProfileManager.GetManager();
                var user = SecurityManager.GetUser(currentUserGuid);
                if (user != null)
                {
                    var profile = profileManager.GetUserProfile <SitefinityProfile>(user);
                    if (profile != null)
                    {
                        var result = new ProfileViewModel();
                        result.FirstName = profile.FirstName;
                        return(result);
                    }
                }
            }

            return(new ProfileViewModel());
        }
Пример #35
0
        private static void ChangeProfile()
        {
// Replace "domain\\username" and "servername" with actual values.
            string targetAccountName = "spdom\\donald.duck";

            using (SPSite site = new SPSite("http://sp2016"))
            {
                SPServiceContext serviceContext = SPServiceContext.GetContext(site);
                try
                {
                    // Retrieve and iterate through all of the user profiles in this context.
                    Console.WriteLine("Retrieving user profiles:");
                    UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
                    IEnumerator        userProfiles   = userProfileMgr.GetEnumerator();
                    while (userProfiles.MoveNext())
                    {
                        UserProfile userProfile = (UserProfile)userProfiles.Current;
                        Console.WriteLine(userProfile.AccountName);
                    }

                    // Retrieve a specific user profile. Change the value of a user profile property
                    // and save (commit) the change on the server.
                    UserProfile user = userProfileMgr.GetUserProfile(targetAccountName);
                    Console.WriteLine("\\nRetrieving user profile for " + user.DisplayName + ".");
                    user.DisplayName = "The Don";
                    user.Commit();
                    Console.WriteLine("\\nThe user\\'s display name has been changed.");
                    Console.Read();
                }

                catch (System.Exception e)
                {
                    Console.WriteLine(e.GetType().ToString() + ": " + e.Message);
                    Console.Read();
                }
            }
        }
Пример #36
0
        /// <summary>
        /// 根据登录名从SSP得到当前用户部门
        /// </summary>
        /// <param name="userAccount">用户的登录名</param>
        /// <returns></returns>
        public static Employee GetEmployee(string userAccount)
        {
            Employee employee = null;
            try
            {
                //从SSP里面取得当前用户所在的部门名称
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        ServerContext context = ServerContext.GetContext(site);
                        UserProfileManager profileManager = new UserProfileManager(context);

                        if (profileManager.UserExists(userAccount) || SPContext.Current.Web.CurrentUser.IsSiteAdmin)
                        {
                            if (SPContext.Current.Web.CurrentUser.IsSiteAdmin && userAccount == SPContext.Current.Web.CurrentUser.LoginName)
                            {
                                userAccount = System.Web.HttpContext.Current.User.Identity.Name;
                            }
                            UserProfile userProfile = profileManager.GetUserProfile(userAccount);
                            employee = InstanceEmployee(userProfile, site);
                        }
                        else
                        {
                            //throw new Exception("共享服务(SSP)中没有该用户的信息,可能是共享服务(SSP)没有和AD同步所致,请联系IT管理员联系!");
                        }
                    }
                }
                );
            }
            catch (Exception e)
            {
                throw new Exception("获取当前的用户信息出错:" + e.Message);
            }

            return employee;
        }
Пример #37
0
        private void picAutoHide_Click(object sender, EventArgs e)
        {
            this.AutoHide = !this.AutoHide;

            UserProfileManager.SaveDocking(this);

            if (this.AutoHide)
            {
                this.Visible = false;

                if (frmStudioMain.SUPPORTPROPERTIESPANEL.Visible)
                {
                    frmStudioMain.SUPPORTPROPERTIESPANEL.ShowPanel((Form)this.Parent);
                }
                else if (frmStudioMain.MODELPROPERTIESPANEL.Visible)
                {
                    frmStudioMain.MODELPROPERTIESPANEL.ShowPanel((Form)this.Parent);
                }
                else if (frmStudioMain.PRINTJOBPROPERTIESPANEL.Visible)
                {
                    frmStudioMain.PRINTJOBPROPERTIESPANEL.ShowPanel((Form)this.Parent);
                }
            }
        }
Пример #38
0
        protected void btn_update_profile(object sender, EventArgs e)
        {
            UserProfileEntities userprof = new UserProfileEntities();

            userprof.id       = int.Parse(hfUserID_prof.Value);
            userprof.Name     = txtName.Text;
            userprof.Family   = TextBox1.Text;
            userprof.Phone    = TextBox4.Text;
            userprof.Email    = txtEmail.Text;
            userprof.Address  = txtAddress.Text;
            userprof.Gender   = ddlGender.Text;
            userprof.Username = TextBox2.Text;
            userprof.Password = TextBox3.Text;
            UserProfileManager userProfileManager = new UserProfileManager();

            if (userProfileManager.Update_prof(userprof))
            {
                Label10.Text = "اطلاعات شما با موفقیت بروزرسانی شد:)";
            }
            else
            {
                Response.Write("<script>alert('اطلاعات شما به روز رسانی نشد.')</script>");
            }
        }
Пример #39
0
        /// <summary>
        ///     Get user account name by searching user profile by user display name
        /// </summary>
        /// <param name="displayName"></param>
        /// <param name="currentWeb"></param>
        /// <param name="site"></param>
        /// <returns></returns>
        public string getUserAccountName(string displayName, SPWeb currentWeb, SPSite site)
        {
            string acctName = "";

            try
            {
                //SPSite site = SPContext.Current.Site;
                ServerContext      ospServerContext      = ServerContext.GetContext(site);
                UserProfileManager ospUserProfileManager = new UserProfileManager(ospServerContext);

                if (ospUserProfileManager != null)
                {
                    upFieldName  = new List <string>();
                    upFieldValue = new List <string>();

                    //Search through all user profile property fields
                    foreach (UserProfile user in ospUserProfileManager)
                    {
                        if (user.DisplayName.ToLower() == displayName.ToLower())
                        {
                            return(user.MultiloginAccounts[0]); //Search user has been found
                        }
                    }
                }
            }
            catch (Exception err)
            {
                LogErrorHelper objErr = new LogErrorHelper(LIST_SETTING_NAME, currentWeb);
                objErr.logSysErrorEmail(APP_NAME, err, "Error at getUserAccountName function");
                objErr = null;

                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory(APP_NAME, TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, err.Message.ToString(), err.StackTrace);
            }

            return(acctName);
        }
Пример #40
0
        public User GetUserByAccountName(string accountName)
        {
            UPSClaimProviderLogger.LogDebug("UPSUsersDAL.GetUserByAccountName invoked!");
            UPSClaimProviderLogger.LogDebug($"accountName: {accountName}");
            User foundUser = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    UPSClaimProviderLogger.LogDebug("Running with elevated privileges");
                    // Access the User Profile Service
                    try
                    {
                        SPServiceContext serviceContext = SPServiceContext.GetContext(SPServiceApplicationProxyGroup.Default, SPSiteSubscriptionIdentifier.Default);
                        UPSClaimProviderLogger.LogDebug("Reference to SPServiceContext obtained");
                        UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                        UPSClaimProviderLogger.LogDebug("Reference to UserProfileManager obtained");

                        UserProfile userProfile = userProfileManager.GetUserProfile(accountName);
                        UPSClaimProviderLogger.LogDebug($"userProfile: {userProfile}");
                        foundUser = UserProfileToUser(userProfile);
                    }
                    catch (System.Exception e)
                    {
                        UPSClaimProviderLogger.LogError(e.Message);
                    }
                });
            }
            catch (System.Exception e)
            {
                UPSClaimProviderLogger.LogError($"Error while trying to elevate privileges: {e.Message}");
            };

            return(foundUser);
        }
Пример #41
0
        /// <summary>
        /// Creates and populates the user profiles.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="profileProperties">A dictionary containing the profile properties.</param>
        protected virtual void CreateUserProfiles(User user, IDictionary <string, string> profileProperties)
        {
            if (string.IsNullOrEmpty(this.ProfileBindings))
            {
                if (!VirtualPathManager.FileExists(RegistrationModel.ProfileBindingsFile))
                {
                    return;
                }

                var fileStream = VirtualPathManager.OpenFile(RegistrationModel.ProfileBindingsFile);
                using (var streamReader = new StreamReader(fileStream))
                {
                    this.ProfileBindings = streamReader.ReadToEnd();
                }
            }

            var profiles           = new JavaScriptSerializer().Deserialize <List <ProfileBindingsContract> >(this.ProfileBindings);
            var userProfileManager = UserProfileManager.GetManager();

            using (new ElevatedModeRegion(userProfileManager))
            {
                foreach (var profileBinding in profiles)
                {
                    var userProfile = userProfileManager.CreateProfile(user, profileBinding.ProfileType);
                    foreach (var property in profileBinding.Properties)
                    {
                        var value = profileProperties.GetValueOrDefault(property.Name);
                        userProfile.SetValue(property.FieldName, value);
                    }

                    userProfileManager.RecompileItemUrls(userProfile);
                }

                userProfileManager.SaveChanges();
            }
        }
        public IHttpActionResult EditProfile([FromBody] UserProfileDto userProfileDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var profileManager = new UserProfileManager();
                var response       = profileManager.EditProfile(userProfileDto, Request.Headers.Authorization.Parameter);
                if (response.Error != null)
                {
                    return(BadRequest(response.Error));
                }

                return(Ok(response));
            }

            catch (Exception)
            {
                return(InternalServerError());
            }
        }
Пример #43
0
        protected virtual GigyaLoginStatusViewModel GetViewModel(ClaimsIdentityProxy currentIdentity)
        {
            var model = new GigyaLoginStatusViewModel
            {
                SiteId       = SystemManager.CurrentContext.IsMultisiteMode ? SystemManager.CurrentContext.CurrentSite.Id : Guid.Empty,
                IsLoggedIn   = currentIdentity.IsAuthenticated,
                IsDesignMode = SystemManager.IsDesignMode
            };

            if (model.IsLoggedIn)
            {
                // check if Sitefinity is the session leader and sign in if required
                GigyaAccountHelper.ProcessRequestChecks(System.Web.HttpContext.Current);

                var userManager = UserManager.GetManager();
                var currentUser = userManager.GetUser(currentIdentity.UserId);
                if (currentUser != null)
                {
                    model.Email = currentUser.Email;

                    var profileManager = UserProfileManager.GetManager();
                    var profile        = profileManager.GetUserProfile <SitefinityProfile>(currentUser);
                    if (profile != null)
                    {
                        model.FirstName = profile.FirstName;
                        model.LastName  = profile.LastName;
                    }
                }
                else
                {
                    model.IsLoggedIn = false;
                }
            }

            return(model);
        }
Пример #44
0
        public static SPPrincipal GetUserAssistant(this SPUser user)
        {
            SPPrincipal usersAssistant = null;

            SPServiceContext   spServiceContext   = SPServiceContext.GetContext(user.ParentWeb.Site);
            UserProfileManager userProfileManager = new UserProfileManager(spServiceContext);

            if (!userProfileManager.UserExists(user.LoginName))
            {
                return(usersAssistant);
            }

            UserProfile userProfile    = userProfileManager.GetUserProfile(user.LoginName);
            string      assistantLogin = userProfile["Assistant"].Value as string;

            if (String.IsNullOrEmpty(assistantLogin))
            {
                return(usersAssistant);
            }

            usersAssistant = user.ParentWeb.EnsureUser(assistantLogin);

            return(usersAssistant);
        }
Пример #45
0
            public static void GetSPUserProfileInfoToLog(SPWeb web, int userID)
            {
                try
                {
                    SPUser spUser = web.AllUsers.GetByID(userID);
                    UlsLogging.LogInformation("SPUser LoginName: {0}", spUser.LoginName);
                    SPList userList = web.SiteUserInfoList;
                    SPListItem userItem = userList.GetItemById(userID);
                    foreach (SPField f in userList.Fields)
                    {
                        UlsLogging.LogInformation("SiteUserInfoList InternalName: {0}, Title: {1}, Value: {}", f.InternalName, f.Title, Convert.ToString(userItem[f.InternalName]));
                    }

                    SPServiceContext serviceContext = SPServiceContext.GetContext(web.Site);
                    UserProfileManager userProfileMgr = new UserProfileManager(serviceContext);
                    UserProfile userProfile = userProfileMgr.GetUserProfile(spUser.LoginName);
                    ProfileSubtypePropertyManager pspm = userProfileMgr.DefaultProfileSubtypeProperties;
                    foreach (ProfileSubtypeProperty prop in pspm.PropertiesWithSection)
                    {
                        if (prop.IsSection)
                            UlsLogging.LogInformation("SiteUserInfoList DisplayName: {0}, Title: {1}, Value: {}", prop.DisplayName);
                        else
                        {
                            UlsLogging.LogInformation("SiteUserInfoList Name: {0}, DisplayName: {1}, Value: {}", prop.Name, prop.DisplayName, userProfile[prop.Name].Value);
                        }
                    }
                }
                catch (Exception ex)
                {
                    UlsLogging.LogError("SiteUserInfoList. GetSPUserProfileInfoToLog(SPWeb web, int userID). Message: {0}, StackTrace: {1}", ex.Message, ex.StackTrace);
                }
            }
Пример #46
0
        public static void Delete(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber, SPUrlZone zone)
        {
            SPSite site = null;

            try
            {
                site = new SPSite(WebApplication.GetResponseUri(zone).AbsoluteUri);

                SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(zone);

                foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders)
                {
                    if (provider is SPFormsAuthenticationProvider)
                    {
                        SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider;

                        SPServiceContext   serviceContext = SPServiceContext.GetContext(site);
                        UserProfileManager uPM            = new UserProfileManager(serviceContext);

                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            string search = ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|";

                            List <UserProfile> uPAResults = uPM.Search(search).Cast <UserProfile>().ToList();
                            List <SearchResult> usersList = users.Cast <SearchResult>().ToList();

                            var query = usersList.Select(sr => sr.GetDirectoryEntry().Properties["distinguishedName"].Value.ToString());

                            HashSet <string> paths = new HashSet <string>(query);

                            var profiles = uPAResults.Select(profile => new
                            {
                                ShouldKeep = paths.Contains(profile[PropertyConstants.DistinguishedName].Value.ToString()),
                                Profile    = profile
                            });

                            foreach (var profile in profiles.Where(result => !result.ShouldKeep))
                            {
                                try
                                {
                                    uPM.RemoveProfile(profile.Profile);
                                    Logging.LogMessage(212, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Removed profile " +
                                                       profile.Profile[PropertyConstants.DistinguishedName].Value, new object[] { null });
                                }
                                catch (Exception ex)
                                {
                                    Logging.LogMessage(502, Logging.LogCategories.Profiles,
                                                       TraceSeverity.Unexpected,
                                                       "Failed to delete profile " + profile.Profile[PropertyConstants.DistinguishedName].Value +
                                                       " " + ex.Message, new object[] { null });
                                }
                            }
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message, new object[] { null });
            }

            finally
            {
                if (site != null)
                {
                    site.Dispose();
                }
            }
        }
Пример #47
0
        public static void Create(SearchResultCollection users, string loginAttribute, SPWebApplication webApplication, string serverName, int portNumber, SPUrlZone zone)
        {
            foreach (SearchResult user in users)
            {
                DirectoryEntry de2  = user.GetDirectoryEntry();
                SPSite         site = null;
                try
                {
                    site = new SPSite(WebApplication.GetResponseUri(zone).AbsoluteUri);

                    SPIisSettings iisSettings = webApplication.GetIisSettingsWithFallback(zone);

                    foreach (SPAuthenticationProvider provider in iisSettings.ClaimsAuthenticationProviders)
                    {
                        if (provider is SPFormsAuthenticationProvider)
                        {
                            SPFormsAuthenticationProvider formsProvider = provider as SPFormsAuthenticationProvider;
                            SPServiceContext   serviceContext           = SPServiceContext.GetContext(site);
                            UserProfileManager uPM = new UserProfileManager(serviceContext);

                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                if (de2.Properties[loginAttribute].Value != null)
                                {
                                    if (!uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                        de2.Properties[loginAttribute].Value.ToString()))
                                    {
                                        Department = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty :
                                                     de2.Properties[DepartmentAttrib].Value.ToString();
                                        DistinguishedName = de2.Properties[DistinguishedNameAttrib].Value.ToString();
                                        FirstName         = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty :
                                                            de2.Properties[FirstNameAttrib].Value.ToString();
                                        LastName = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty :
                                                   de2.Properties[LastNameAttrib].Value.ToString();
                                        Office = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty :
                                                 de2.Properties[OfficeAttrib].Value.ToString();
                                        PreferredName = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty :
                                                        de2.Properties[PreferredNameAttrib].Value.ToString();
                                        UserTitle = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty :
                                                    de2.Properties[UserTitleAttrib].Value.ToString();
                                        WebSite = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty :
                                                  de2.Properties[WebSiteAttrib].Value.ToString();
                                        WorkEmail = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty :
                                                    de2.Properties[WorkEmailAttrib].Value.ToString();
                                        WorkPhone = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty :
                                                    de2.Properties[WorkPhoneAttrib].Value.ToString();

                                        UserProfile newProfile = uPM.CreateUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                                                       de2.Properties[loginAttribute].Value.ToString(), PreferredName);

                                        newProfile[PropertyConstants.Department].Add(Department);
                                        newProfile[PropertyConstants.DistinguishedName].Add(DistinguishedName);
                                        newProfile[PropertyConstants.FirstName].Add(FirstName);
                                        newProfile[PropertyConstants.LastName].Add(LastName);
                                        newProfile[PropertyConstants.Office].Add(Office);
                                        newProfile[PropertyConstants.Title].Add(UserTitle);
                                        newProfile[PropertyConstants.WebSite].Add(WebSite);
                                        newProfile[PropertyConstants.WorkEmail].Add(WorkEmail);
                                        newProfile[PropertyConstants.WorkPhone].Add(WorkPhone);

                                        try
                                        {
                                            newProfile.Commit();
                                            Logging.LogMessage(210, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Created profile " +
                                                               DistinguishedName, new object[] { null });
                                        }
                                        catch (Exception ex)
                                        {
                                            Logging.LogMessage(510, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to create profile " +
                                                               DistinguishedName + " " + ex.Message, new object[] { null });
                                        }
                                    }
                                    else if (uPM.UserExists(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                            de2.Properties[loginAttribute].Value.ToString()))
                                    {
                                        UserProfile updateProfile = uPM.GetUserProfile(ClaimsIdentifier + "|" + formsProvider.MembershipProvider + "|" +
                                                                                       de2.Properties[loginAttribute].Value.ToString());

                                        updateProfile[PropertyConstants.Department].Value = (de2.Properties[DepartmentAttrib].Value == null) ? String.Empty :
                                                                                            de2.Properties[DepartmentAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.DistinguishedName].Value = de2.Properties[DistinguishedNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.FirstName].Value         = (de2.Properties[FirstNameAttrib].Value == null) ? String.Empty :
                                                                                                   de2.Properties[FirstNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.LastName].Value = (de2.Properties[LastNameAttrib].Value == null) ? String.Empty :
                                                                                          de2.Properties[LastNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.Office].Value = (de2.Properties[OfficeAttrib].Value == null) ? String.Empty :
                                                                                        de2.Properties[OfficeAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.PreferredName].Value = (de2.Properties[PreferredNameAttrib].Value == null) ? String.Empty :
                                                                                               de2.Properties[PreferredNameAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.Title].Value = (de2.Properties[UserTitleAttrib].Value == null) ? String.Empty :
                                                                                       de2.Properties[UserTitleAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.WebSite].Value = (de2.Properties[WebSiteAttrib].Value == null) ? String.Empty :
                                                                                         de2.Properties[WebSiteAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.WorkEmail].Value = (de2.Properties[WorkEmailAttrib].Value == null) ? String.Empty :
                                                                                           de2.Properties[WorkEmailAttrib].Value.ToString();
                                        updateProfile[PropertyConstants.WorkPhone].Value = (de2.Properties[WorkPhoneAttrib].Value == null) ? String.Empty :
                                                                                           de2.Properties[WorkPhoneAttrib].Value.ToString();

                                        try
                                        {
                                            updateProfile.Commit();
                                            Logging.LogMessage(211, Logging.LogCategories.Profiles, TraceSeverity.Verbose, "Updated profile " +
                                                               updateProfile[PropertyConstants.DistinguishedName].Value, new object[] { null });
                                        }
                                        catch (Exception ex)
                                        {
                                            Logging.LogMessage(511, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, "Failed to update profile " +
                                                               updateProfile[PropertyConstants.DistinguishedName].Value + " " + ex.Message, new object[] { null });
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogMessage(502, Logging.LogCategories.Profiles, TraceSeverity.Unexpected, ex.Message, new object[] { null });
                }

                finally
                {
                    if (site != null)
                    {
                        site.Dispose();
                    }
                }
            }
        }
Пример #48
0
 private void AppSturtUp(object sender, StartupEventArgs e)
 {
     UserProfileManager.Initialize();  // Initializing user profiles in UserProfileManager static class
 }
Пример #49
0
        public override void Execute(Guid targetInstanceId)
        {
            IServiceLocator serviceLocatortest = SharePointServiceLocator.GetCurrent();
            ILogger         loggertest         = serviceLocatortest.GetInstance <ILogger>();

            loggertest.LogToOperations("Executing UoB Delete Old MySite DocLibs Timer Job", EventSeverity.Information);

            base.Execute(targetInstanceId);
            SPWebApplication webApplication  = SPWebApplication.Lookup(new Uri(MySiteUri));
            SPSiteCollection siteCollections = webApplication.Sites;
            bool             recycle         = false;
            bool             armed           = false;

            if (String.Compare(RecyleOrDelete, "recycle", false) == 0)
            {
                recycle = true;
            }
            if (MySiteDeleteArmed)
            {
                armed = true;
            }


            foreach (SPSite siteCollection in siteCollections)
            {
                try
                {
                    string             username           = siteCollection.RootWeb.Site.Owner.LoginName;
                    SPServiceContext   serviceContext     = SPServiceContext.GetContext(siteCollection);
                    UserProfileManager userProfileManager = new UserProfileManager(serviceContext);
                    UserProfile        u = null;
                    try
                    {
                        u = userProfileManager.GetUserProfile(siteCollection.RootWeb.Site.Owner.LoginName);
                        try
                        {
                            if (u["uob-Migrated"].Count > 0)
                            {
                                DateTime dt    = DateTime.Parse(u["uob-Migrated"].Value.ToString());
                                DateTime df    = DateTime.Now;
                                double   weeks = (df - dt).TotalDays / 7;
                                if (weeks > UoBMigrationDeletePeriod)
                                {
                                    string logEntry = string.Empty;
                                    try
                                    {
                                        if (armed)
                                        {
                                            logEntry = "DELETED MYSITE ***MyFiles*** : " + username;
                                            if (recycle)
                                            {
                                                siteCollection.RootWeb.Lists["MyFiles"].Recycle();
                                            }
                                            else
                                            {
                                                siteCollection.RootWeb.Lists["MyFiles"].Delete();
                                            }
                                        }
                                        else
                                        {
                                            logEntry = "DELETE (SOFT) MYSITE MyFiles: " + username;
                                        }
                                    }
                                    catch
                                    {
                                        //todo if deletion failed...
                                    }
                                    finally
                                    {
                                        IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
                                        ILogger         logger         = serviceLocator.GetInstance <ILogger>();
                                        logger.LogToOperations(logEntry, EventSeverity.Information);
                                    }
                                }
                            }
                        }
                        catch
                        {
                            string          logEntry       = "FAILED TO DELETE MYSITE: " + siteCollection.RootWeb.Site.Owner.LoginName;
                            IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
                            ILogger         logger         = serviceLocator.GetInstance <ILogger>();
                            logger.LogToOperations(logEntry, EventSeverity.Error);
                        }
                    }
                    catch (Exception ex)
                    {
                        string          logEntry       = "MYSITE HAS NO PROFILE: " + username;
                        IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
                        ILogger         logger         = serviceLocator.GetInstance <ILogger>();
                        logger.LogToOperations(logEntry, EventSeverity.Warning);
                    }
                }
                catch
                {
                    //ex
                }
                siteCollection.Close();
                siteCollection.Dispose();
            }
        }
Пример #50
0
 public SecurityManager(UserProfileManager userProfileManager, IOptions <SecurityOptions> options, ILogger <SecurityManager> logger)
 {
     _userProfileManager = userProfileManager;
     _options            = options.Value;
     _logger             = logger;
 }
Пример #51
0
        /// <summary>
        /// Edits the profile properties.
        /// </summary>
        /// <param name="profileProperties">The profile properties.</param>
        /// <param name="userProfileManager">The user profile manager.</param>
        private void EditProfileProperties(IDictionary <string, string> profileProperties, UserProfileManager userProfileManager)
        {
            if (profileProperties != null)
            {
                var bindingContract = new JavaScriptSerializer().Deserialize <List <ProfileBindingsContract> >(this.ProfileBindings);

                using (new ElevatedModeRegion(userProfileManager))
                {
                    foreach (var profileBinding in bindingContract)
                    {
                        var userProfile = this.SelectedUserProfiles.Where(prof => prof.GetType().FullName == profileBinding.ProfileType).SingleOrDefault();
                        foreach (var property in profileBinding.Properties)
                        {
                            var value = profileProperties.GetValueOrDefault(property.Name);
                            userProfile.SetValue(property.FieldName, value);
                        }

                        userProfileManager.RecompileItemUrls(userProfile);
                    }
                }
            }
        }
        /// <summary>
        /// Synchronizes the taxonomy fields from specified mappings
        /// The source property will build the destination property taxonomy tree.
        /// </summary>
        /// <param name="site">The site for the service context.</param>
        /// <param name="user">The user for which to sync the profile properties.</param>
        /// <param name="mappings">The taxonomy property mappings.  The key is the source property name. The value is the destination property name.</param>
        public void SyncTaxonomyFieldsForUser(SPSite site, SPUser user, IDictionary<string, string> mappings)
        {
            using (new SPMonitoredScope(string.Format(CultureInfo.InvariantCulture, "{0}::{1}", MonitoredScopePrefix, "SyncTaxonomyFieldsForUser")))
            {
                // Get user profile objects
                var context = SPServiceContext.GetContext(site);
                var userProfileManager = new UserProfileManager(context);
                var profileSubtypeProperties = this.userProfilePropertyHelper.GetProfileSubtypePropertyManager(site);
                var userProfile = userProfileManager.GetUserProfile(user.LoginName);

                // For each property, update mapping
                foreach (var mapping in mappings)
                {
                    var targetPropertyName = mapping.Value;
                    var targetSubtypeProp = profileSubtypeProperties.GetPropertyByName(targetPropertyName);
                    this.SyncTaxonomyFields(
                        site,
                        userProfile,
                        mapping,
                        targetSubtypeProp.CoreProperty.TermSet.TermStore.Id,
                        targetSubtypeProp.CoreProperty.TermSet.Id,
                        user.ParentWeb);
                }
            }
        }
Пример #53
0
        /// <summary>
        /// 根据登录名从SSP得到当前用户
        /// </summary>
        /// <param name="id">用户的ID</param>
        /// <returns></returns>
        public static Employee GetEmployee(Guid id)
        {
            Employee employee = null;
            try
            {
                //从SSP里面取得当前用户所在的部门名称
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        ServerContext context = ServerContext.GetContext(site);
                        UserProfileManager profileManager = new UserProfileManager(context);

                        UserProfile userProfile = profileManager.GetUserProfile(id);
                        if (userProfile != null)
                            employee = InstanceEmployee(userProfile, site);
                    }
                }
                );
            }
            catch (Exception e)
            {
                //throw new Exception("获取当前的用户信息出错:" + e.Message);
            }

            return employee;
        }
Пример #54
0
        public static List<Employee> GetEmployeeFromSSPByDept(string dept)
        {
            List<Employee> lstEmployees = new List<Employee>();
            Employee employee = null;
            try
            {
                //从SSP里面取得当前用户所在的部门名称
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        ServerContext context = ServerContext.GetContext(site);
                        UserProfileManager profileManager = new UserProfileManager(context);

                        foreach (UserProfile profile in profileManager)
                        {
                            if (profile[PropertyConstants.Department].Value == null)
                                continue;

                            string[] depts = profile[PropertyConstants.Department].Value.ToString().ToLower().Split(new Char[] {';', '/'});

                            employee = InstanceEmployee(profile, site);

                            if (depts.Contains(dept.ToLower()))
                            {

                                switch (dept.ToLower())
                                {
                                    case "admin" :
                                        if (employee.Title != "Receptionist")
                                        {
                                            lstEmployees.Add(employee);
                                        }
                                        break;
                                    default :
                                        lstEmployees.Add(employee);
                                        break;
                                }
                                //lstEmployees.Add(employee);
                            }
                            else if (string.IsNullOrEmpty(dept))
                            {
                                lstEmployees.Add(employee);
                            }

                            if (dept.ToLower() == "hr" && employee.Title == "Receptionist")
                            {
                                lstEmployees.Add(employee);
                            }

                        }

                    }
                }
                );

            }
            catch (Exception e)
            {
                throw new Exception("获取部门用户信息出错:" + e.Message);
            }
            return lstEmployees;
        }
Пример #55
0
        protected override void Fill() {

            try {
                if (SPA.User.Count() == 0) {
                    UserProfileManager userProfileManager = new UserProfileManager(SPServiceContext.GetContext(SPContext.Current.Site));
                    ProfilePropertyManager profilePropMgr = new UserProfileConfigManager(SPServiceContext.GetContext(SPContext.Current.Site)).ProfilePropertyManager;
                    ProfileSubtypePropertyManager subtypePropMgr = profilePropMgr.GetProfileSubtypeProperties("UserProfile");
                    UserProfile userProfile = userProfileManager.GetUserProfile(Context.User.Identity.Name.Replace("i:0#.w|", "").Replace("0#.w|", ""));
                    hfUserProfileRecordID.Value = (userProfile.RecordId.ToString());

                    IEnumerator<ProfileSubtypeProperty> userProfileSubtypeProperties = subtypePropMgr.GetEnumerator();
                    while (userProfileSubtypeProperties.MoveNext()) {
                        string propName = userProfileSubtypeProperties.Current.Name;
                        ProfileValueCollectionBase values = userProfile.GetProfileValueCollection(propName);
                        if (values.Count > 0) {

                            // Handle multivalue properties.
                            foreach (var value in values) {
                                switch (propName) {
                                    case "AccountName":
                                        lblAccountNameView.Text = value.ToString();
                                        break;
                                    case "FirstName":
                                        lblFirstNameView.Text = value.ToString();
                                        break;
                                    case "LastName":
                                        lblLastNameView.Text = value.ToString();
                                        break;
                                    case "PreferredName":
                                        lblPreferredNameView.Text = value.ToString();
                                        break;
                                    case "UserProfile_GUID":
                                        lblUserProfileGuidView.Text = value.ToString();
                                        break;
                                    case "SPS-UserPrincipalName":
                                        lblUserPrincipalNameView.Text = value.ToString();
                                        break;
                                    case "SPS-DistinguishedName":
                                        lblDistinguishedNameView.Text = value.ToString();
                                        break;
                                }
                                if (ShowDebug)
                                    lblErrorMessage.Text += string.Format("Name: {0} Value: {1}</br>", propName, value.ToString());
                            }
                        }
                    }
                } else {
                    trAccountName.Visible = false;
                    trLastName.Visible = false;
                    trFirstName.Visible = false;
                    trPreferredName.Visible = false;
                    trUserProfile_GUID.Visible = false;
                    trUserPrincipalName.Visible = false;
                    trDistinguishedName.Visible = false;
                    lblMessageView.CssClass = "ms-error";
                    lblMessageView.Text = "There are already users in the data system.  This option is only available when no user records exist.";
                    btnSave.Visible = false;
                }
            }
            catch (Exception ex) {
                SPA.Error.WriteError(ex);
                lblErrorMessage.Text += string.Format("ERROR: {0}", ex.ToString());
            }
        }
        /// <summary>
        /// Synchronizes the taxonomy fields from specified mappings for changed user profile in the last specified window of time.
        /// The source property will build the destination property taxonomy tree.
        /// </summary>
        /// <param name="site">The site for the service context.</param>
        /// <param name="changeStartDate">The start date for which to include user changes.</param>
        /// <param name="mappings">The taxonomy property mappings.  The key is the source property name. The value is the destination property name.</param>
        public void SyncTaxonomyFieldsForChangedUsers(SPSite site, DateTime changeStartDate, IDictionary<string, string> mappings)
        {
            using (new SPMonitoredScope(string.Format(CultureInfo.InvariantCulture, "{0}::{1}", MonitoredScopePrefix, "SyncTaxonomyFieldsForChangedUsers")))
            {
                // Get user profile objects
                var context = SPServiceContext.GetContext(site);
                var userProfileManager = new UserProfileManager(context);
                var profileSubtypeManager = ProfileSubtypeManager.Get(context);
                var profileSubtype =
                    profileSubtypeManager.GetProfileSubtype(
                        ProfileSubtypeManager.GetDefaultProfileName(ProfileType.User));
                var profileSubtypeProperties = profileSubtype.Properties;

                // For each property, update mapping
                foreach (var mapping in mappings)
                {
                    var sourcePropertyName = mapping.Key;
                    var targetPropertyName = mapping.Value;

                    var srcSubtypeProp = profileSubtypeProperties.GetPropertyByName(sourcePropertyName);
                    var targetSubtypeProp = profileSubtypeProperties.GetPropertyByName(targetPropertyName);

                    if (srcSubtypeProp != null && targetSubtypeProp != null)
                    {
                        if (targetSubtypeProp.CoreProperty.TermSet != null
                            && srcSubtypeProp.CoreProperty.TermSet != null)
                        {
                            if (targetSubtypeProp.CoreProperty.IsMultivalued)
                            {
                                // Get some subset of changes to a user profile since last 24h hours
                                var startDate = DateTime.UtcNow.Subtract(TimeSpan.FromDays(1));
                                var changeQuery = new UserProfileChangeQuery(false, true);
                                var changeToken = new UserProfileChangeToken(startDate);
                                changeQuery.ChangeTokenStart = changeToken;
                                changeQuery.SingleValueProperty = true;
                                changeQuery.MultiValueProperty = true;
                                changeQuery.Update = true;
                                changeQuery.Add = true;
                                changeQuery.Delete = true;
                                changeQuery.UpdateMetadata = true;

                                var changes = userProfileManager.GetChanges(changeQuery);
                                foreach (
                                    var profile in
                                        changes.OfType<UserProfilePropertyValueChange>()
                                            .Select(change => (Microsoft.Office.Server.UserProfiles.UserProfile)change.ChangedProfile))
                                {
                                    this.SyncTaxonomyFields(
                                        site,
                                        profile,
                                        mapping,
                                        targetSubtypeProp.CoreProperty.TermSet.TermStore.Id,
                                        targetSubtypeProp.CoreProperty.TermSet.Id);
                                }
                            }
                            else
                            {
                                this.logger.Error(
                                    string.Format(
                                        CultureInfo.InvariantCulture,
                                        @"UserProfileTargetingService.SyncTaxonomyFieldsForChangedUsers: The target property {0} is not set as multi valued. Please set this target property as multi valued",
                                        targetPropertyName));
                            }
                        }
                        else
                        {
                            this.logger.Error(
                                @"UserProfileTargetingService.SyncTaxonomyFieldsForChangedUsers:
                            Some properties have wrong TermSet configuration. Please review user properties taxonomy settings.");
                        }
                    }
                    else
                    {
                        this.logger.Error(
                            @"UserProfileTargetingService.SyncTaxonomyFieldsForChangedUsers:
                        One or more user properties specified in the configuration list doesn't exists in the user profile property schema!");
                    }
                }
            }
        }
Пример #57
0
        public static Employee GetEmployeeByDisplayName(string displayName)
        {
            Employee employee = null;
            try
            {
                //从SSP里面取得当前用户所在的部门名称
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                    {
                        ServerContext context = ServerContext.GetContext(site);
                        UserProfileManager profileManager = new UserProfileManager(context);

                        foreach (UserProfile profile in profileManager)
                        {
                            if ((profile[PropertyConstants.UserName].Value.ToString().ToLower() == displayName.ToLower())
                                ||(profile[PropertyConstants.PreferredName].Value.ToString().ToLower()==displayName.ToLower()))
                            {
                                employee = InstanceEmployee(profile, site);
                                break;
                            }
                        }
                    }
                }
                );
            }
            catch (Exception e)
            {
                throw new Exception("获取当前的用户信息出错:" + e.Message);
            }

            return employee;
        }
        /// <summary>
        /// Synchronizes the taxonomy fields from specified mappings for users with empty target fields.
        /// The source property will build the destination property taxonomy tree.
        /// </summary>
        /// <param name="site">The site.</param>
        /// <param name="mappings">The mappings.</param>
        public void SyncTaxonomyFieldsForEmptyTargetFields(SPSite site, IDictionary<string, string> mappings)
        {
            using (new SPMonitoredScope(string.Format(CultureInfo.InvariantCulture, "{0}::{1}", MonitoredScopePrefix, "SyncTaxonomyFieldsForChangedUsers")))
            {
                // Get user profile objects
                var context = SPServiceContext.GetContext(site);
                var userProfileManager = new UserProfileManager(context);
                var profileSubtypeManager = ProfileSubtypeManager.Get(context);
                var profileSubtype =
                    profileSubtypeManager.GetProfileSubtype(
                        ProfileSubtypeManager.GetDefaultProfileName(ProfileType.User));
                var profileSubtypeProperties = profileSubtype.Properties;

                // For each property, update mapping
                foreach (var mapping in mappings)
                {
                    var sourcePropertyName = mapping.Key;
                    var targetPropertyName = mapping.Value;

                    var srcSubtypeProp = profileSubtypeProperties.GetPropertyByName(sourcePropertyName);
                    var targetSubtypeProp = profileSubtypeProperties.GetPropertyByName(targetPropertyName);

                    if (srcSubtypeProp != null && targetSubtypeProp != null)
                    {
                        if (targetSubtypeProp.CoreProperty.TermSet != null
                            && srcSubtypeProp.CoreProperty.TermSet != null)
                        {
                            if (targetSubtypeProp.CoreProperty.IsMultivalued)
                            {
                                // Get the profiles with empty target fields and sync them
                                var profilesToModifyEnumerator = userProfileManager.GetEnumerator();
                                while (profilesToModifyEnumerator.MoveNext())
                                {
                                    var profile = profilesToModifyEnumerator.Current as Microsoft.Office.Server.UserProfiles.UserProfile;

                                    if (profile != null && profile[mapping.Value].Value == null)
                                    {
                                        this.SyncTaxonomyFields(
                                        site,
                                        profile,
                                        mapping,
                                        targetSubtypeProp.CoreProperty.TermSet.TermStore.Id,
                                        targetSubtypeProp.CoreProperty.TermSet.Id);
                                    }
                                }
                            }
                            else
                            {
                                this.logger.Error(
                                    string.Format(
                                        CultureInfo.InvariantCulture,
                                        @"UserProfileTargetingService.SyncTaxonomyFieldsForChangedUsers: The target property {0} is not set as multi valued. Please set this target property as multi valued",
                                        targetPropertyName));
                            }
                        }
                        else
                        {
                            this.logger.Error(
                                @"UserProfileTargetingService.SyncTaxonomyFieldsForChangedUsers:
                            Some properties have wrong TermSet configuration. Please review user properties taxonomy settings.");
                        }
                    }
                    else
                    {
                        this.logger.Error(
                            @"UserProfileTargetingService.SyncTaxonomyFieldsForChangedUsers:
                        One or more user properties specified in the configuration list doesn't exists in the user profile property schema!");
                    }
                }
            }
        }
Пример #59
0
 public AssigmentController(ApplicationDbContext context)
 {
     _context            = new WorkContext(context);
     _userProfileManager = new UserProfileManager <UserProfile>(_context);
     _assigmentsManager  = new AssigmentsManager <Assigment>(_context);
 }
Пример #60
0
        string GetUserFullName(string siteURL, int id, string loginName)
        {
            string strFullName = string.Empty;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
              using (SPSite site = new SPSite(siteURL))
              {
                  try
                  {
                      ServerContext serverContext = ServerContext.GetContext(SPContext.Current.Site);
                      UserProfileManager profileManager = new UserProfileManager(serverContext);
                      SPUser spUser = site.RootWeb.Users.GetByID(id);
                      UserProfile profile = profileManager.GetUserProfile(spUser.LoginName);
                      string firstName = profile["FirstName"].Value.ToString();
                      string LastName = profile["LastName"].Value.ToString();
                      strFullName = firstName + " " + LastName;
                  }
                  catch (Exception) {
                      string[] nameparts = loginName.Split('|');
                      strFullName = nameparts[nameparts.Length - 1];

                  }
              }
            });
            return strFullName;
        }