private static bool UpdateProfileProperties(string userAccount, string userName, string subDepartment
                                                    , string Anniversarydate, string birthday, DateTime lastUpdated)
        {
            try
            {
                var SubDepartmentAttribute = ConfigurationManager.AppSettings["SubDepartmentAttribute"];
                var AnniversaryAttribute   = ConfigurationManager.AppSettings["AnniversaryAttribute"];
                var BirthdayAttribute      = ConfigurationManager.AppSettings["BirthdayAttribute"];

                var userAccountName = "i:0#.f|membership|" + AuthHelper.userName;

                var tenantCtx     = AuthHelper.GetTenantContext();
                var peopleManager = new PeopleManager(tenantCtx);

                peopleManager.SetSingleValueProfileProperty(userAccountName, SubDepartmentAttribute, subDepartment);
                peopleManager.SetSingleValueProfileProperty(userAccountName, AnniversaryAttribute, Anniversarydate);
                peopleManager.SetSingleValueProfileProperty(userAccountName, BirthdayAttribute, birthday);

                tenantCtx.ExecuteQuery();
                LogManager.WriteToFile("INFO : " + DateTime.Now + " --> " + userName + " --> " + userAccount + " --> " + lastUpdated + " --> Updated.");

                Console.WriteLine();
                return(true);
            }
            catch (Exception ex)
            {
                LogManager.WriteToFile("ERROR : " + DateTime.Now + " --> " + userName + " --> " + ex.Message);
                return(false);
            }
        }
Beispiel #2
0
        private void GetUserDetails()
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    PeopleManager peopleManager = new PeopleManager(clientContext);
                    PersonProperties properties = peopleManager.GetMyProperties();
                    clientContext.Load(properties);
                    clientContext.ExecuteQuery();

                    UserInfo userInfo = new UserInfo()
                    {
                        DisplayName = properties.DisplayName,
                        PhotoUrl = spContext.SPHostUrl + "/_layouts/userphoto.aspx?accountname=" + properties.Email,
                        LastPing = DateTime.Now
                    };


                    HttpRuntime.Cache.Add(properties.AccountName, userInfo, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 3, 0), CacheItemPriority.Normal, new CacheItemRemovedCallback(CacheRemovalCallback));

                    Session["UserAccountName"] = properties.AccountName;
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Get email address - Check if the user is not a service account, search, or any admin account - These account won't have valid email address
        /// </summary>
        /// <param name="user">user</param>
        /// <returns></returns>
        private bool IsRealUser(User user, ClientContext ctxTenant)
        {
            bool isRealUser = false;

            try
            {
                //ClientContext ctxTenant = GetContext(WebConfigurationManager.AppSettings.Get("TenantAdminUrl"));
                using (ctxTenant)
                {
                    PeopleManager peopleManager                        = new PeopleManager(ctxTenant);
                    string[]      profilePropertyNames                 = new string[] { "WorkEmail" };
                    UserProfilePropertiesForUser userForUser           = new UserProfilePropertiesForUser(ctxTenant, user.LoginName, profilePropertyNames);
                    IEnumerable <string>         userProfileProperties = peopleManager.GetUserProfilePropertiesFor(userForUser);
                    ctxTenant.Load(userForUser);
                    ctxTenant.ExecuteQuery();
                    if (userProfileProperties.Count() == 1)
                    {
                        if (userProfileProperties.ElementAt(0) != "") //app@sharepoint, search crawl account..
                        {
                            if (IsUserInSupportedDomain(userProfileProperties.ElementAt(0)))
                            {
                                isRealUser = true;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.LogFileSystem(string.Format("Error happened in validating if the user is real - {0}", ex.Message) + DateTime.Now.ToString());
            }
            return(isRealUser);
        }
Beispiel #4
0
        public ActionResult GetAll()
        {
            PeopleManager        mgr = new PeopleManager(Properties.Settings.Default.ConStr);
            IEnumerable <Person> ppl = mgr.GetAllPeople();

            return(Json(ppl));
        }
Beispiel #5
0
        static void PP(ClientContext clientContext, string targetUser)
        {
            PeopleManager    peopleManager    = new PeopleManager(clientContext);
            PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);


            // Load the request and run it on the server.
            // This example requests only the AccountName and UserProfileProperties
            // properties of the personProperties object.
            clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
            clientContext.ExecuteQuery();

            try
            {
                foreach (var property in personProperties.UserProfileProperties)
                {
                    if (property.Key.ToString().ToLower().Contains("personalspace"))
                    {
                        Console.WriteLine(string.Format("{0}: {1}",
                                                        property.Key.ToString(), property.Value.ToString()));
                        Console.WriteLine(targetUser);
                        //Download(property.Value.ToString().Replace("MThumb","Lthumb"), targetUser);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception");
            }
            //Console.ReadKey(false);
        }
        public ActionResult Create()
        {
            var disp = new vmCourse();

            using (DeptManager)
            {
                using (InstManager)
                {
                    using (PeopleManager)
                    {
                        using (TBManager)
                        {
                            disp.Departments = DeptManager.GetAllDepartments().ToList();
                            var inst   = InstManager.GetAllInstructors();
                            var people = PeopleManager.GetAllPeople();

                            var instr = from instructor in inst
                                        join person in people on instructor.PersonID equals person.ID
                                        select new KeyValuePair <int, string>(instructor.ID, string.Format("{0}, {1}", person.LastName, person.FirstMidName));
                            disp.Instructors = instr.ToDictionary(t => t.Key, t => t.Value);
                            disp.Textbooks   = TBManager.GetAllTextbooks().ToList();
                            return(View(disp));
                        }
                    }
                }
            }
        }
        public void TryAddBuilders_AddsBuildersIfThereIsEnoughFreePeople()
        {
            // arrange
            var buildings = new[, ]
            {
                {
                    Mock.Of <Building>(
                        b =>
                        b.Finished == false &&
                        b.Builders == 0 && b.FreePeople == 10 &&
                        b.Prototype == Mock.Of <IncomeBuilding>(
                            p => p.Workers == 0 && p.Builders == 1))
                }
            };

            buildings[0, 0].Owner = Mock.Of <Player>(p => p.Area == Mock.Of <Area>(a => a.Buildings == buildings));

            var manager = new PeopleManager();

            // act
            manager.TryAddBuilders(buildings[0, 0], 1);

            // assert
            Assert.AreEqual(1, buildings[0, 0].Builders);
        }
        protected void btnGetManager_Click(object sender, EventArgs e)
        {
            using (var clientContext = GetClientContext())
            {
                string[] propertyNames = { "FirstName", "LastName", "Manager" };
                string accountName = txtUserID.Text;

                PeopleManager peopleManager = new PeopleManager(clientContext);
                UserProfilePropertiesForUser prop = new UserProfilePropertiesForUser(clientContext, accountName, propertyNames);
                IEnumerable<string> profileProperty = peopleManager.GetUserProfilePropertiesFor(prop);
                clientContext.Load(prop);
                clientContext.ExecuteQuery();

                if (profileProperty != null && profileProperty.Count() > 0)
                {
                    txtName.Text = string.Format("{0} {1}", profileProperty.ElementAt(0), profileProperty.ElementAt(1));
                    txtManager.Text = profileProperty.ElementAt(2);
                }
                else
                {
                    string noProfileData = string.Format("No data found for user id: {0}", accountName.Replace(@"\",@"\\"));
                    ClientScript.RegisterStartupScript(this.GetType(), "errorMessage", "alert('" + noProfileData + "');", true);
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// Get current user's manager
        /// </summary>
        /// <returns></returns>
        private string GetCurrentUserManager()
        {
            var ownerEmail = string.Empty;

            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    PeopleManager    peopleManager    = new PeopleManager(clientContext);
                    PersonProperties personProperties = peopleManager.GetMyProperties();
                    clientContext.Load(personProperties);
                    clientContext.ExecuteQuery();
                    foreach (var item in personProperties.UserProfileProperties)
                    {
                        if (item.Key == "Manager")
                        {
                            ownerEmail = item.Value;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log.LogFileSystem(string.Format("Error happened in getting Current User Manager - {0}", ex.Message) + DateTime.Now.ToString());
            }
            return(ownerEmail);
        }
Beispiel #10
0
        private static void UpdateProperty(PeopleManager peopleManager, GraphApi.User user, Property prop)
        {
            var propertyNewValue = typeof(GraphApi.User).GetProperty(prop.ADAttributeName).GetValue(user);

            if (propertyNewValue != null || prop.WriteIfBlank)
            {
                if (prop.IsMulti)
                {
                    peopleManager.SetMultiValuedProfileProperty(UserProfilePrefix + user.UserPrincipalName,
                                                                prop.UserProfileAttributeName, new List <string>()
                    {
                    });
                }
                else
                {
                    peopleManager.SetSingleValueProfileProperty(UserProfilePrefix + user.UserPrincipalName,
                                                                prop.UserProfileAttributeName,
                                                                propertyNewValue == null ? string.Empty : propertyNewValue.ToString());
                }

                Console.WriteLine("Updated User: {0} Property: {1} New Value: {2}",
                                  user.DisplayName, prop.UserProfileAttributeName, propertyNewValue);
            }

            //logic to write only if different
        }
        private bool CanUseAcceptLanguageHeaderForLocalization(Web web)
        {
            if (web.Context.IsAppOnly())
            {
                return(true);
            }

#if SP2019
            if (web.Context.IsAppOnlyWithDelegation())
            {
                return(true);
            }
#endif

            var           currentUser      = web.EnsureProperty(w => w.CurrentUser);
            PeopleManager peopleManager    = new PeopleManager(web.Context);
            var           languageSettings = peopleManager.GetUserProfilePropertyFor(web.CurrentUser.LoginName, "SPS-MUILanguages");
            web.Context.ExecuteQueryRetry();

            if (languageSettings == null || String.IsNullOrEmpty(languageSettings.Value))
            {
                return(true);
            }

            return(false);
        }
        private void btn_peopleManager_Click(object sender, EventArgs e)
        {
            PeopleManager peopleManag = new PeopleManager();

            peopleManag.onRefresh += new PeopleManager.refreshHander(loadPeople);
            peopleManag.ShowDialog();
        }
Beispiel #13
0
 public ActionResult Edit(int id)
 {
     using (DeptManager)
     {
         using (InstManager)
         {
             using (PeopleManager)
             {
                 var item = InstManager.GetInstructorbyID(id);
                 var disp = Mapper.Map <vmInstructor>(item);
                 if (disp != null)
                 {
                     disp.Person      = Mapper.Map <vmPerson>(PeopleManager.GetPersonbyID(item.PersonID));
                     disp.Departments = DeptManager.GetAllDepartments().OrderBy(d => d.Name).ToList();
                 }
                 else
                 {
                     disp = new vmInstructor();
                     ModelState.AddModelError("", "Failed to load details fo requested item.");
                 }
                 return(View(disp));
             }
         }
     }
 }
Beispiel #14
0
 public void SetPeopleManager()
 {
     if (PeopleManager == null)
     {
         PeopleManager = PeopleManager.GetInstance(Session);
     }
 }
        private List <PersonProperties> GetProfilesForUsers(IList <User> users)
        {
            var ctx           = GetSpoClientContextForSite(SpoSite.Admin);
            var peopleManager = new PeopleManager(ctx);
            var userProfiles  = new List <PersonProperties>();

            Logger?.Debug($"[O365] Getting profiles for {users.Count} users");

            try
            {
                foreach (var user in users)
                {
                    var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
                    ctx.Load(userProfile);
                    userProfiles.Add(userProfile);
                }

                ctx.ExecuteQueryWithIncrementalRetry(SpoRetries, SpoBackoff, Logger);
            }
            catch (MaximumRetryAttemptedException ex)
            {
                // Exception handling for the Maximum Retry Attempted
                Logger?.Error($"[O365] Max retries / throttle for SPO reached getting profiles. Message {ex.Message}");
                throw new O365Exception($"Max retries / throttle for SPO reached. Message {ex.Message}", ex);
            }
            catch (Exception ex)
            {
                Logger?.Error($"[O365] Propblem getting profiles for users. Message: {ex.Message}");
            }

            return(userProfiles);
        }
 //
 // GET: /Textbook/Details/5
 public ActionResult Details(int id)
 {
     using (InstManager)
     {
         using (PublishersManager)
         {
             using (AuthorsManager)
             {
                 using (PeopleManager)
                 {
                     var tb   = TBManager.GetTextbookbyID(id);
                     var disp = Mapper.Map <vmTextbook>(tb);
                     if (disp != null)
                     {
                         disp.Publisher     = Mapper.Map <vmPublisher>(PublishersManager.GetPublisherbyID(tb.PublisherID));
                         disp.Author        = Mapper.Map <vmAuthor>(AuthorsManager.GetAuthorbyID(tb.AuthorID));
                         disp.Author.Person = Mapper.Map <vmPerson>(PeopleManager.GetPersonbyID(disp.Author.PersonID));
                     }
                     else
                     {
                         disp = new vmTextbook();
                         ModelState.AddModelError("", "Failed to load details for requested item.");
                     }
                     return(View(disp));
                 }
             }
         }
     }
 }
Beispiel #17
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string hostweburl = Request["SPHostUrl"];
                string appweburl = Request["SPAppWebUrl"];

                //get context token for 
                var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);

                string userAcctName = string.Empty;
                using (var clientContext = TokenHelper.GetClientContextWithContextToken(appweburl, contextToken, Request.Url.Authority))
                {
                    //// PeopleManager class provides the methods for operations related to people
                    PeopleManager peopleManager = new PeopleManager(clientContext);

                    //// PersonProperties class is used to represent the user properties
                    //// GetMyProperties method is used to get the current user's properties 
                    PersonProperties personProperties = peopleManager.GetMyProperties();
                    clientContext.Load(personProperties, p => p.AccountName);
                    clientContext.ExecuteQuery();

                    userAcctName = personProperties.AccountName;
                    //userLogin.Text = userAcctName;
                    //lblUserLogin.Text = userAcctName;                   
                    
                } 
            }
        }
Beispiel #18
0
        private static void SetMultiValueProfileProperty()
        {
            //Tenant Admin Details
            string tenantAdministrationUrl = "https://yourtenant-admin.sharepoint.com/";
            string tenantAdminLoginName = "*****@*****.**";
            string tenantAdminPassword = "******";

            //AccountName of the user whos property you want to update.
            //If you want to update properties of multiple users, you can fetch the accountnames through search.
            string UserAccountName = "i:0#.f|membership|[email protected]";

            using (ClientContext clientContext = new ClientContext(tenantAdministrationUrl))
            {
                SecureString passWord = new SecureString();

                foreach (char c in tenantAdminPassword.ToCharArray()) passWord.AppendChar(c);

                clientContext.Credentials = new SharePointOnlineCredentials(tenantAdminLoginName, passWord);

                // List Multiple values
                List<string> skills = new List<string>() { "SharePoint", "Office 365", "C#", "JavaScript" };

                // Get the people manager instance for tenant context
                PeopleManager peopleManager = new PeopleManager(clientContext);

                // Update the SPS-Skills property for the user using account name from profile.
                peopleManager.SetMultiValuedProfileProperty(UserAccountName, "SPS-Skills", skills);

                clientContext.ExecuteQuery();
            }
        }
Beispiel #19
0
        public ActionResult Create()
        {
            using (EnrollmentsManager)
            {
                using (CoursesManager)
                {
                    using (StudManager)
                    {
                        using (PeopleManager)
                        {
                            using (SemestersManager)
                            {
                                var disp = new vmEnrollment();
                                disp.Courses   = CoursesManager.GetAllCourses().ToList();
                                disp.Semesters = SemestersManager.GetAllSemesters().ToList();
                                var students = StudManager.GetAllStudents();
                                var people   = PeopleManager.GetAllPeople();

                                var studs = from student in students
                                            join person in people on student.PersonID equals person.ID
                                            select new KeyValuePair <int, string>(student.ID, string.Format("{0}, {1}", person.LastName, person.FirstMidName));
                                disp.Students = studs.ToDictionary(t => t.Key, t => t.Value);
                                return(View(disp));
                            }
                        }
                    }
                }
            }
        }
Beispiel #20
0
        protected void btnGetManager_Click(object sender, EventArgs e)
        {
            using (var clientContext = GetClientContext())
            {
                string[] propertyNames = { "FirstName", "LastName", "Manager" };
                string   accountName   = txtUserID.Text;

                PeopleManager peopleManager                  = new PeopleManager(clientContext);
                UserProfilePropertiesForUser prop            = new UserProfilePropertiesForUser(clientContext, accountName, propertyNames);
                IEnumerable <string>         profileProperty = peopleManager.GetUserProfilePropertiesFor(prop);
                clientContext.Load(prop);
                clientContext.ExecuteQuery();

                if (profileProperty != null && profileProperty.Count() > 0)
                {
                    txtName.Text    = string.Format("{0} {1}", profileProperty.ElementAt(0), profileProperty.ElementAt(1));
                    txtManager.Text = profileProperty.ElementAt(2);
                }
                else
                {
                    string noProfileData = string.Format("No data found for user id: {0}", accountName.Replace(@"\", @"\\"));
                    ClientScript.RegisterStartupScript(this.GetType(), "errorMessage", "alert('" + noProfileData + "');", true);
                }
            }
        }
Beispiel #21
0
 public ActionResult Index()
 {
     using (EnrollmentsManager)
     {
         using (CoursesManager)
         {
             using (StudManager)
             {
                 using (PeopleManager)
                 {
                     using (SemestersManager)
                     {
                         var disp = Mapper.Map <IEnumerable <vmEnrollment> >(EnrollmentsManager.GetAllEnrollments());
                         foreach (var d in disp)
                         {
                             d.Course         = Mapper.Map <vmCourse>(CoursesManager.GetCoursebyID(d.CourseID));
                             d.Student        = Mapper.Map <vmStudent>(StudManager.GetStudentbyID(d.StudentID));
                             d.Student.Person = Mapper.Map <vmPerson>(PeopleManager.GetPersonbyID(d.Student.PersonID));
                             d.Semester       = Mapper.Map <vmSemester>(SemestersManager.GetSemesterbyID(d.SemesterID));
                         }
                         return(View(disp));
                     }
                 }
             }
         }
     }
 }
Beispiel #22
0
 public ActionResult Details(int id)
 {
     using (EnrollmentsManager)
     {
         using (StudManager)
         {
             using (PeopleManager)
             {
                 using (CoursesManager)
                 {
                     using (SemestersManager)
                     {
                         var disp = Mapper.Map <vmEnrollment>(EnrollmentsManager.GetEnrollmentbyID(id));
                         if (disp != null)
                         {
                             disp.Student        = Mapper.Map <vmStudent>(StudManager.GetStudentbyID(disp.StudentID));
                             disp.Student.Person = Mapper.Map <vmPerson>(PeopleManager.GetPersonbyID(disp.Student.PersonID));
                             disp.Course         = Mapper.Map <vmCourse>(CoursesManager.GetCoursebyID(disp.CourseID));
                             disp.Semester       = Mapper.Map <vmSemester>(SemestersManager.GetSemesterbyID(disp.SemesterID));
                         }
                         else
                         {
                             disp = new vmEnrollment();
                             ModelState.AddModelError("", "Failed to load details for requested object");
                         }
                         return(View(disp));
                     }
                 }
             }
         }
     }
 }
        public static void GetUserProfiles(ClientContext clientContext)
        {
            // Replace the following placeholder values with the target SharePoint site and
            // target user.
            //   const string serverUrl = "http://serverName/";
            const string targetUser = "******";

            // Connect to the client context.
            //  ClientContext clientContext = new ClientContext(serverUrl);

            // Get the PeopleManager object and then get the target user's properties.
            PeopleManager    peopleManager    = new PeopleManager(clientContext);
            PersonProperties personProperties = peopleManager.GetPropertiesFor(targetUser);

            // Load the request and run it on the server.
            // This example requests only the AccountName and UserProfileProperties
            // properties of the personProperties object.
            clientContext.Load(personProperties, p => p.AccountName, p => p.UserProfileProperties);
            clientContext.ExecuteQuery();

            foreach (var property in personProperties.UserProfileProperties)
            {
                Console.WriteLine(string.Format("{0}: {1}",
                                                property.Key.ToString(), property.Value.ToString()));
            }
        }
Beispiel #24
0
 public PeopleModelTest()
 {
     peopleService     = new Mock <IPeopleService>();
     documentsDataBase = new Mock <IDocumentsDataBase>();
     HttpClientService = new Mock <IHttpClientService>();
     model             = new PeopleManager(peopleService.Object, documentsDataBase.Object);
 }
 public AccountController(IConfiguration config, IStringLocalizer <Resource> Resource, PeopleManager manager, HelperWorkWithData helperWork)
 {
     this.helperWork = helperWork;
     this.manager    = manager;
     this.config     = config;
     this.Resource   = Resource;
 }
Beispiel #26
0
        public static Contact GetUser(Uri requestUri, int Id)
        {
            ClientContext context;
            if (ClientContextUtilities.TryResolveClientContext(requestUri, out context, null))
            {
                using (context)
                {
                    var web = context.Web;
                    context.Load(web);
                    var user = web.GetUserById(Id);
                    context.Load(user, u => u.LoginName);
                    context.ExecuteQuery();

                    var peopleManager = new PeopleManager(context);

                    var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
                    context.Load(userProfile);
                    context.ExecuteQuery();

                    var contact = new Contact() { ExternalId = user.Id.ToString(), FullName = user.Title, EmailAddress = user.Email };
                    if (userProfile.IsPropertyAvailable("Title"))
                        contact.Position = userProfile.Title;
                    if (userProfile.IsPropertyAvailable("UserProfileProperties") && userProfile.UserProfileProperties.ContainsKey("WorkPhone"))
                        contact.PhoneNumber = userProfile.UserProfileProperties["WorkPhone"];
                    return contact;
                }
            }
            throw new InvalidOperationException(string.Format("Unable to find user '{0}' at '{1}'", Id, requestUri.AbsoluteUri));
        }
Beispiel #27
0
        public void ThreathenPed(Ped ped)
        {
            bool threathen = false;

            if (!Helpers.HasPedClearLineOfSighOfPed(ped, Game.Player.Character))
            {
                if (Game.IsControlJustPressed(Control.Talk))
                {
                    Interval  = 0;
                    threathen = true;
                    Function.Call(Hash.CLEAR_ALL_HELP_MESSAGES);
                }
                else
                {
                    Helpers.ShowHelpMessageThisFrame("Press ~INPUT_TALK~ to threathen.", Main.configRobPeople.Help_Message_Beep_Sound);
                }
            }
            else
            {
                threathen = true;
            }

            if (threathen)
            {
                Helpers.PedSpeakThreathen(Game.Player.Character);
                RobPedSequence sequence = InstantiateScript <RobPedSequence>();
                sequence.SetTargetPed(ped);
                PeopleManager.AddThreatenedPed(ped);
            }
        }
        private void UpdateBasicSpoAttribute(ClientContext clientContext, UpnIdentifier upn, string attributeName, string value)
        {
            var           targetUser    = O365Settings.SpoProfilePrefix + upn.Upn;
            PeopleManager peopleManager = new PeopleManager(clientContext);

            peopleManager.SetSingleValueProfileProperty(targetUser, attributeName, value.ToString());
        }
Beispiel #29
0
        public void Start()
        {
            PeopleManager manager = new PeopleManager();
            var           loop    = true;

            while (loop)
            {
                Console.Clear();
                UI.PrintMainMenu();
                var choice = Console.ReadKey(true).Key;

                switch (choice)
                {
                case ConsoleKey.D1:
                    manager.AddPerson();
                    break;

                case ConsoleKey.D2:
                    manager.PrintAll();
                    break;

                case ConsoleKey.D3:
                    var filter = GetFilter();
                    Console.Clear();
                    manager.PrintWhere(filter);
                    Console.ReadKey(true);
                    break;

                default:
                    InvalidInput.Invoke();
                    Console.ReadKey(true);
                    break;
                }
            }
        }
Beispiel #30
0
        public ActionResult Add(Person person)
        {
            PeopleManager mgr = new PeopleManager(Properties.Settings.Default.PeopleConStr);

            mgr.AddPerson(person);
            return(Redirect("/people/index"));
        }
Beispiel #31
0
        /// <summary>
        /// Used to fetch user profile property from SPO.
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="PropertyName"></param>
        /// <returns></returns>
        static string GetSingleProfileProperty(string UserName, string PropertyName)
        {
            try
            {
                var peopleManager = new PeopleManager(_clientContext);

                ClientResult <string> profileProperty = peopleManager.GetUserProfilePropertyFor(UserName, PropertyName);
                _clientContext.ExecuteQuery();

                //this is the web service way of retrieving the same thing as client API. Note: valye of propertyname is not case sensitive when using web service, but does seem to be with client API
                //UPSvc.PropertyData propertyData = userProfileService.GetUserPropertyByAccountName(UserName, PropertyName);

                if (profileProperty.Value.Length > 0)
                {
                    return(profileProperty.Value);
                }
                else
                {
                    LogMessage("Cannot find a value for property " + PropertyName + " for user " + UserName, LogLevel.Information);
                    return(string.Empty);
                }
            }
            catch (Exception ex)
            {
                LogMessage("User Error: Exception trying to get profile property " + PropertyName + " for user " + UserName + "\n" + ex.Message, LogLevel.Error);
                return(string.Empty);
            }
        }
Beispiel #32
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                string hostweburl = Request["SPHostUrl"];
                string appweburl  = Request["SPAppWebUrl"];

                //get context token for
                var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);

                string userAcctName = string.Empty;
                using (var clientContext = TokenHelper.GetClientContextWithContextToken(appweburl, contextToken, Request.Url.Authority))
                {
                    //// PeopleManager class provides the methods for operations related to people
                    PeopleManager peopleManager = new PeopleManager(clientContext);

                    //// PersonProperties class is used to represent the user properties
                    //// GetMyProperties method is used to get the current user's properties
                    PersonProperties personProperties = peopleManager.GetMyProperties();
                    clientContext.Load(personProperties, p => p.AccountName);
                    clientContext.ExecuteQuery();

                    userAcctName = personProperties.AccountName;
                    //userLogin.Text = userAcctName;
                    //lblUserLogin.Text = userAcctName;
                }
            }
        }
Beispiel #33
0
        public ActionResult Skills(List <string> skills)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    //Write the values to the Skills property of the current user.

                    PeopleManager peopleManager = new PeopleManager(clientContext);

                    var properties = peopleManager.GetMyProperties();

                    clientContext.Load(properties, props => props.AccountName);

                    clientContext.ExecuteQuery();

                    peopleManager.SetMultiValuedProfileProperty(properties.AccountName, "SPS-Skills", skills);

                    clientContext.ExecuteQuery();

                    return(Json("success"));
                }
            }

            return(Json("error"));
        }
Beispiel #34
0
        protected string GetCurrentUserEmail()
        {
            var ownerEmail = string.Empty;

            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    PeopleManager    peopleManager    = new PeopleManager(clientContext);
                    PersonProperties personProperties = peopleManager.GetMyProperties();
                    clientContext.Load(personProperties);
                    clientContext.ExecuteQuery();
                    foreach (var item in personProperties.UserProfileProperties)
                    {
                        if (item.Key == "WorkEmail")
                        {
                            ownerEmail = item.Value;
                            break;
                        }
                    }
                }
            }
            catch (Exception)
            {
            }
            return(ownerEmail);
        }
Beispiel #35
0
        //
        // GET: /Instructor/Delete/5

        public ActionResult Delete(int id)
        {
            using (DeptManager)
            {
                using (InstManager)
                {
                    using (PeopleManager)
                    {
                        var item = InstManager.GetInstructorbyID(id);
                        var disp = Mapper.Map <vmInstructor>(item);
                        if (disp != null)
                        {
                            disp.Person     = Mapper.Map <vmPerson>(PeopleManager.GetPersonbyID(item.PersonID));
                            disp.Department = Mapper.Map <vmDepartment>(DeptManager.GetDepartmentbyID(item.DepartmentID));
                        }
                        else
                        {
                            disp = new vmInstructor();
                            ModelState.AddModelError("", "Failed to load details for requested object");
                        }
                        return(View(disp));
                    }
                }
            }
        }
        public StatusManager(Session session)
        {
            _userId = session.UserId;
            _peopleManager = PeopleManager.GetInstance(session);
            _userStatusList = new UserStatusList(_peopleManager);
            _userStatusList.StartWatching(new[] { _userId });

            _statusMessageList = new StatusMessageList(_peopleManager);
            _statusMessageList.StartWatching();
        }
Beispiel #37
0
    // Use this for initialization
    void Start()
    {
        peopleManager = FindObjectOfType<PeopleManager>();

        head = transform.FindChild("Head").gameObject;
        person = GetComponent<Person>();
        controller = GetComponent<DDPlayerController>();
        spriteRenderer = GetComponent<SpriteRenderer>();

        RandomiseInternalSpriteColours();
        StartCoroutine(MoveAroundArea());
    }
        protected override void ExecuteCmdlet()
        {
            PeopleManager peopleManager = new PeopleManager(ClientContext);

            foreach (var acc in Account)
            {
                ClientResult<string> result = Tenant.EncodeClaim(acc);
                ClientContext.ExecuteQuery();
                var properties = peopleManager.GetPropertiesFor(result.Value);
                ClientContext.Load(properties);
                ClientContext.ExecuteQuery();
                WriteObject(properties);
            }
        }
        static void Main(string[] args)
        {
            try
            {
                //Get the tenant admin information needed to read and update user profile data
                string tenantAdminUrl = GetString("Enter your tenant admin url (https://tenantname-admin.sharepoint.com): ");

                string tenantAdminUser = GetString("Enter your tenant admin user ([email protected]): ");
                SecureString tenantAdminPassword = GetPassword();

                //Provide the user profile Account name property value of the user profile to read/update
                string userToUpdate = "i:0#.f|membership|" + tenantAdminUser;


                using (ClientContext clientContext = new ClientContext(tenantAdminUrl))
                {
                    clientContext.Credentials = new SharePointOnlineCredentials(tenantAdminUser, tenantAdminPassword);

                    // Get the people manager instance for tenant context
                    PeopleManager peopleManager = new PeopleManager(clientContext);

                    //Read a user profile property 
                    Console.ForegroundColor = ConsoleColor.Green;
                    string userProfileProperty = "AboutMe";
                    Console.WriteLine("Current value of the {0} property for user {1}:", userProfileProperty, userToUpdate);

                    //Update a user profile property
                    string newAboutMeValue = GetString(String.Format("Enter a new value to be set for property {0}:", userProfileProperty));

                    Console.WriteLine("Setting new value...");

                    // Update the AboutMe property for the user using account name.
                    peopleManager.SetSingleValueProfileProperty(userToUpdate, userProfileProperty, newAboutMeValue);

                    clientContext.ExecuteQuery();
                }
                Console.WriteLine("Press any key to continue.");
                Console.Read();

            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(string.Format("Exception!"), ex.ToString());
                Console.WriteLine("Press any key to continue.");
                Console.Read();
                throw;
            }

        }
Beispiel #40
0
        public CicStatusService(Session session, ITraceContext traceContext)
        {
            _userId = session.UserId;
            _traceContext = traceContext;
            _peopleManager = PeopleManager.GetInstance(session);
            _userStatusList = new UserStatusList(_peopleManager);
            _userStatusList.StartWatching(new[] { _userId });
            _userStatusList.WatchedObjectsChanged += OnUserStatusChanged;

            _statusMessageList = new StatusMessageList(_peopleManager);
            _statusMessageList.StartWatching();

            _filteredStatusList = new FilteredStatusMessageList(_peopleManager);
            _filteredStatusList.StartWatching(new[] { _userId });
        }
Beispiel #41
0
        protected void RefreshUIValues()
        {

            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Get the people manager instance and load current properties
                PeopleManager peopleManager = new PeopleManager(clientContext);
                PersonProperties personProperties = peopleManager.GetMyProperties();
                clientContext.Load(personProperties);
                clientContext.ExecuteQuery();

                // Just to output what we have now for about me
                aboutMeValue.Text = personProperties.UserProfileProperties["AboutMe"];
            }

        }
        protected override void ExecuteCmdlet()
        {
            var peopleManager = new PeopleManager(ClientContext);

            var result = Tenant.EncodeClaim(Account);
            ClientContext.ExecuteQueryRetry();

            if (ParameterSetName == "Single")
            {
                peopleManager.SetSingleValueProfileProperty(result.Value, PropertyName, Value);
            }
            else
            {
                peopleManager.SetMultiValuedProfileProperty(result.Value, PropertyName, Values.ToList());
            }

            ClientContext.ExecuteQueryRetry();
        }
        private string GetCurrentUserInformation()
        {
            var siteUri = "https://rdoyle.sharepoint.com";

            using (var context = this.contextFactory.GetContext(siteUri))
            {
                var user = context.Web.CurrentUser;
                context.Load(user, u => u.LoginName);
                context.ExecuteQuery();

                var peopleManager = new PeopleManager(context);
                var personProperties = peopleManager.GetPropertiesFor(user.LoginName);

                context.Load(personProperties, p => p.PictureUrl);
                context.ExecuteQuery();

                return personProperties.PictureUrl;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterChromeControlScript();

            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                var user = clientContext.Web.CurrentUser;
                clientContext.Load(user);
                clientContext.ExecuteQuery();

                var peopleManager = new PeopleManager(clientContext);
                var userProperties = peopleManager.GetUserProfilePropertyFor(user.LoginName, "SPS-MUILanguages");
                clientContext.ExecuteQuery();

                currentLanguages.Text = userProperties.Value;
            }
        }
        /// <summary>
        /// Checks if replacing the "Accept-Language" header is allowed. This approach does not work when the user that's
        /// making the call has set one or more languages in their user profile
        /// </summary>
        /// <param name="web">Current site</param>
        /// <returns>True if the "Accept-Language" header approach can be used</returns>
        private static bool CanUseAcceptLanguageHeaderForLocalization(Web web)
        {
            if (web.Context.IsAppOnly())
            {
                return true;
            }

            var currentUser = web.EnsureProperty(w => w.CurrentUser);
            PeopleManager peopleManager = new PeopleManager(web.Context);
            var languageSettings = peopleManager.GetUserProfilePropertyFor(web.CurrentUser.LoginName, "SPS-MUILanguages");
            web.Context.ExecuteQueryRetry();

            if (languageSettings == null || String.IsNullOrEmpty(languageSettings.Value))
            {
                return true;
            }

            return false;
        }
        protected void btnPersonalizedSearch_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Load user profile properties
                PeopleManager peopleManager = new PeopleManager(clientContext);
                PersonProperties personProperties = peopleManager.GetMyProperties();
                clientContext.Load(personProperties);
                clientContext.ExecuteQuery();
                // Check teh value for About Me to investigate current values
                string aboutMeValue = personProperties.UserProfileProperties["AboutMe"];
                string templateFilter = ResolveAdditionalFilter(aboutMeValue);
                // Let's build the query
                string query = "contentclass:\"STS_Site\" " + templateFilter;
                ClientResult<ResultTableCollection> results = ProcessQuery(clientContext, query);
                lblStatus2.Text = FormatResults(results);
            }
        }
Beispiel #47
0
        protected void btnScenario2_Click(object sender, EventArgs e)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Get the people manager instance for current context to get account name
                PeopleManager peopleManager = new PeopleManager(clientContext);
                PersonProperties personProperties = peopleManager.GetMyProperties();
                clientContext.Load(personProperties, p => p.AccountName);
                clientContext.ExecuteQuery();

                // Convert entry to html
                string updatedValue = (txtAboutMe.Text).Replace(Environment.NewLine, "<br />");

                // Update the AboutMe property for the user using account name from profile
                peopleManager.SetSingleValueProfileProperty(personProperties.AccountName, "AboutMe", updatedValue);
                clientContext.ExecuteQuery();

            }
        }
Beispiel #48
0
        protected void btnScenario1_Click(object sender, EventArgs e)
        {

            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Get the people manager instance and load current properties
                PeopleManager peopleManager = new PeopleManager(clientContext);
                PersonProperties personProperties = peopleManager.GetMyProperties();
                clientContext.Load(personProperties);
                clientContext.ExecuteQuery();

                // just to output what we have now to text box
                txtProperties.Text = "";
                foreach (var item in personProperties.UserProfileProperties)
                {
                    txtProperties.Text += string.Format("{0} - {1}{2}", item.Key, item.Value, Environment.NewLine);
                }
            }
        }
Beispiel #49
0
 /// <summary>
 /// Gets a user profile property Value for the specified user.
 /// </summary>
 /// <param name="ctx">An Authenticated ClientContext</param>
 /// <param name="userName">The name of the target user.</param>
 /// <param name="propertyName">The value of the property to get.</param>
 /// <returns><see cref="System.String"/>The specified profile property for the specified user. Will return an Empty String if the property is not available.</returns>
 public static string GetProfilePropertyFor(ClientContext ctx, string userName, string propertyName)
 {
     string _result = string.Empty;
     if (ctx != null)
     {
         try
         {
             //// PeopleManager class provides the methods for operations related to people
             PeopleManager peopleManager = new PeopleManager(ctx);
             //// GetUserProfilePropertyFor method is used to get a specific user profile property for a user
             var _profileProperty = peopleManager.GetUserProfilePropertyFor(userName, propertyName);
             ctx.ExecuteQuery();
             _result = _profileProperty.Value;
         }
         catch
         {
             throw;
         }
     }
     return _result;
 }
Beispiel #50
0
        protected void RefreshUIValues()
        {

            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                // Get the people manager instance and load current properties
                PeopleManager peopleManager = new PeopleManager(clientContext);
                PersonProperties personProperties = peopleManager.GetMyProperties();
                clientContext.Load(personProperties);
                clientContext.ExecuteQuery();

                // Just to output what we have now for skills now
                string skills = personProperties.UserProfileProperties["SPS-Skills"];
                lblSkills.Text = skills;
                var skillArray = skills.Split(new Char[] { '|' });
                lstSkills.Items.Clear();
                foreach (var item in skillArray)
                {
                    lstSkills.Items.Add(item);
                }
            }

        }
Beispiel #51
0
        private static void SetUserProfileDataWithUserContext(Uri sharePointAdminUri, SyncConfiguration configuration, List<GraphApi.IUser> users)
        {
            string tenantAdminLoginName = ConfigurationManager.AppSettings["TenantAdminLogin"];
            string tenantAdminPassword = ConfigurationManager.AppSettings["TenantAdminPassword"];

            using (ClientContext clientContext = new ClientContext(sharePointAdminUri.ToString()))
            {
                //authenticate with SPOCredentials
                SecureString password = new SecureString();
                foreach (char c in tenantAdminPassword.ToCharArray()) password.AppendChar(c);
                clientContext.Credentials = new SharePointOnlineCredentials(tenantAdminLoginName, password);
                clientContext.ExecuteQuery();

                // Get the people manager instance for tenant context
                PeopleManager peopleManager = new PeopleManager(clientContext);

                foreach (GraphApi.User user in users)
                {
                    foreach (Property prop in configuration.Properties)
                    {
                        try
                        {
                            UpdateProperty(peopleManager, user, prop);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    clientContext.ExecuteQueryWithExponentialRetry(10, 30000); //implemented with throttling
                }
            }
        }
 public void GetMyProperties(string propertyName)
 {
     PeopleManager peopleManager = new PeopleManager(ctx);
     PersonProperties personProperties = peopleManager.GetMyProperties();
     ctx.Load(personProperties);
     ctx.ExecuteQuery();
     foreach(var userProperty in personProperties.UserProfileProperties)
     {
         System.Reflection.PropertyInfo p = typeof(PersonProperties).GetProperty(userProperty.Key);
     }
 }
Beispiel #53
0
        private static void UpdateProperty(PeopleManager peopleManager, GraphApi.User user, Property prop)
        {
            var propertyNewValue = typeof(GraphApi.User).GetProperty(prop.ADAttributeName).GetValue(user);

            if (propertyNewValue != null || prop.WriteIfBlank)
            {
                if (prop.IsMulti)
                {
                    peopleManager.SetMultiValuedProfileProperty(UserProfilePrefix + user.UserPrincipalName,
                        prop.UserProfileAttributeName, new List<string>() { });
                }
                else
                {
                    peopleManager.SetSingleValueProfileProperty(UserProfilePrefix + user.UserPrincipalName,
                        prop.UserProfileAttributeName,
                        propertyNewValue == null ? string.Empty : propertyNewValue.ToString());
                }

                Console.WriteLine("Updated User: {0} Property: {1} New Value: {2}",
                    user.DisplayName, prop.UserProfileAttributeName, propertyNewValue);
            }

            //logic to write only if different
        }
Beispiel #54
0
        /// <summary>
        /// Get multiple properties from SPO in a single call to the service
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="PropertyNames"></param>
        /// <returns></returns>
        static string[] GetMultipleProfileProperties(string UserName, string[] PropertyNames)
        {
            try
            {

                var peopleManager = new PeopleManager(_clientContext);


                UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(_clientContext, UserName, PropertyNames);
                IEnumerable<string> profilePropertyValues = peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

                // Load the request and run it on the server.
                _clientContext.Load(profilePropertiesForUser);
                _clientContext.ExecuteQuery();

                //convert to array and return
                return profilePropertyValues.ToArray();


            }
            catch (Exception ex)
            {
                LogMessage("Exception trying to get profile properties for user " + UserName + "\n" + ex.Message, LogLevel.Error);
                return null;
            }
            
        }
Beispiel #55
0
        /// <summary>
        /// Used to fetch user profile property from SPO.
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="PropertyName"></param>
        /// <returns></returns>
        static string GetSingleProfileProperty(string UserName, string PropertyName)
        {
            try
            {

                var peopleManager = new PeopleManager(_clientContext);

                ClientResult<string> profileProperty = peopleManager.GetUserProfilePropertyFor(UserName, PropertyName);
                _clientContext.ExecuteQuery();

                //this is the web service way of retrieving the same thing as client API. Note: valye of propertyname is not case sensitive when using web service, but does seem to be with client API
                //UPSvc.PropertyData propertyData = userProfileService.GetUserPropertyByAccountName(UserName, PropertyName);

                if (profileProperty.Value.Length > 0)
                {
                    return profileProperty.Value;
                }
                else
                {
                    LogMessage("Cannot find a value for property " + PropertyName + " for user " + UserName, LogLevel.Information);
                    return string.Empty;
                }


            }
            catch (Exception ex)
            {
                LogMessage("User Error: Exception trying to get profile property " + PropertyName + " for user " + UserName + "\n" + ex.Message, LogLevel.Error);
                return string.Empty;
            }

        }
 public void SetUserProfileProperty(string userAccountName, string propertyName, IList<string> propertyValues)
 {
     try
     {
         PeopleManager peopleManager = new PeopleManager(ctx);
         peopleManager.SetMultiValuedProfileProperty(userAccountName, propertyName, propertyValues);
         ctx.ExecuteQuery();
     }
     catch (Exception e)
     {
         string exp = e.Message + ((e.InnerException == null) ? "" : e.InnerException.Message);
         AppEventLog.LogInfo("SharePointService SetMultiValuedProfileProperty Method Error ", exp);
     }
 }
Beispiel #57
0
        public static List<Contact> GetUsers(Uri requestUri, string Filter = "", ICredentials credentials = null)
        {
            ClientContext context;
            var users = new List<Contact>();
            if (ClientContextUtilities.TryResolveClientContext(requestUri, out context, credentials))
            {
                var userProfilesResult = new List<PersonProperties>();
                using (context)
                {
                    var web = context.Web;
                    var peopleManager = new PeopleManager(context);

                    var siteUsers = from user in web.SiteUsers
                                    where user.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User
                                    select user;
                    var usersResult = context.LoadQuery(siteUsers);
                    context.ExecuteQuery();

                    foreach (var user in usersResult)
                        if (user.Title.ToLower().Contains(Filter.ToLower()) && !users.Any(x => x.FullName == user.Title))
                        {
                            var userProfile = peopleManager.GetPropertiesFor(user.LoginName);
                            context.Load(userProfile);
                            userProfilesResult.Add(userProfile);
                        }
                    context.ExecuteQuery();

                    foreach (var user in usersResult)
                    {
                        var contact = new Contact() { ExternalId = user.Id.ToString(), FullName = user.Title, EmailAddress = user.Email };
                        var userProfile = userProfilesResult.FirstOrDefault(x => x.IsPropertyAvailable("DisplayName") && x.DisplayName == user.Title);
                        if (userProfile != null)
                        {
                            contact.Position = userProfile.IsPropertyAvailable("Title") ? userProfile.Title : string.Empty;
                            contact.PhoneNumber = userProfile.IsPropertyAvailable("UserProfileProperties") && userProfile.UserProfileProperties.ContainsKey("WorkPhone") ? userProfile.UserProfileProperties["WorkPhone"] : string.Empty;
                        }
                        users.Add(contact);
                    }
                }
            }
            return users;
        }
Beispiel #58
0
 /// <summary>
 /// Get current user's manager  
 /// </summary>
 /// <returns></returns>
 private string GetCurrentUserManager()
 {
     var ownerEmail = string.Empty;
     try
     {
         var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
         using (var clientContext = spContext.CreateUserClientContextForSPHost())
         {
             PeopleManager peopleManager = new PeopleManager(clientContext);
             PersonProperties personProperties = peopleManager.GetMyProperties();
             clientContext.Load(personProperties);
             clientContext.ExecuteQuery();
             foreach (var item in personProperties.UserProfileProperties)
             {
                 if (item.Key == "Manager")
                 {
                     ownerEmail = item.Value;
                     break;
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Log.LogFileSystem(string.Format("Error happened in getting Current User Manager - {0}", ex.Message) + DateTime.Now.ToString());
     }
     return ownerEmail;
 }
        public JsonResult GetNameAndManagerFromProfile(string userID)
        {
            string empName = string.Empty;
            string empManager = string.Empty;

            try
            {
                SharePointContext spContext = Session["Context"] as SharePointContext;
                if (spContext == null)
                {
                    spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);
                }

                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {
                        string[] propertyNames = { "FirstName", "LastName", "Manager" };

                        PeopleManager peopleManager = new PeopleManager(clientContext);
                        UserProfilePropertiesForUser prop = new UserProfilePropertiesForUser(clientContext, userID, propertyNames);
                        IEnumerable<string> profileProperty = peopleManager.GetUserProfilePropertiesFor(prop);
                        clientContext.Load(prop);
                        clientContext.ExecuteQuery();

                        if (profileProperty != null && profileProperty.Count() > 0)
                        {
                            empName = string.Format("{0} {1}", profileProperty.ElementAt(0), profileProperty.ElementAt(1));
                            empManager = profileProperty.ElementAt(2);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                empManager = ex.Message;
            }

            return Json(new { Name = empName, Manager = empManager }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult EmployeeForm()
        {
            Employee emp = new Employee();

            try
            {
                var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    if (clientContext != null)
                    {

                        SetupManager.Provision(clientContext);

                        var web = clientContext.Web;

                        List desgList = web.Lists.GetByTitle("EmpDesignation");
                        ListItemCollection desgItems = desgList.GetItems(CamlQuery.CreateAllItemsQuery());

                        List countryList = web.Lists.GetByTitle("EmpCountry");
                        ListItemCollection countryItems = countryList.GetItems(CamlQuery.CreateAllItemsQuery());

                        string itemID = Request.QueryString["itemId"];
                        ListItem emplistItem = null;

                        if (itemID != null)
                        {
                            List lstEmployee = web.Lists.GetByTitle("Employees");
                            emplistItem = lstEmployee.GetItemById(itemID);
                            clientContext.Load(emplistItem);
                            emp.Id = itemID;
                        }

                        clientContext.Load(desgItems);
                        clientContext.Load(countryItems);
                        clientContext.ExecuteQuery();

                        List<SelectListItem> empDesgList = new List<SelectListItem>();
                        foreach (var item in desgItems)
                        {
                            empDesgList.Add(new SelectListItem { Text = item["Title"].ToString() });
                        }
                        emp.Designations = new SelectList(empDesgList, "Text", "Text");

                        List<SelectListItem> cList = new List<SelectListItem>();
                        foreach (var item in countryItems)
                        {
                            cList.Add(new SelectListItem { Text = item["Title"].ToString(), Value = item["ID"].ToString() });
                        }
                        emp.Countries = new SelectList(cList, "Value", "Text");

                        string empDesignation = string.Empty;
                        int stateID = 0;
                        int countryId = 0;

                        if (emplistItem != null)
                        {
                            emp.EmpNumber = ConvertObjectToString(emplistItem["EmpNumber"]);
                            emp.Name = ConvertObjectToString(emplistItem["Title"]);
                            emp.UserID = ConvertObjectToString(emplistItem["UserID"]);
                            emp.EmpManager = ConvertObjectToString(emplistItem["EmpManager"]);
                            emp.Designation = ConvertObjectToString(emplistItem["Designation"]);

                            string cityVal = ConvertObjectToString(emplistItem["Location"]);
                            ViewBag.JsCity = "";
                            ViewBag.JsStateID = "";

                            if (cityVal != "")
                            {
                                ViewBag.JsCity = cityVal;
                                List lstCity = web.Lists.GetByTitle("EmpCity");
                                CamlQuery query = new CamlQuery();
                                query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='Title' /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", cityVal);
                                ListItemCollection cityItems = lstCity.GetItems(query);
                                clientContext.Load(cityItems);
                                clientContext.ExecuteQuery();
                                if (cityItems.Count > 0)
                                {
                                    stateID = (cityItems[0]["State"] as FieldLookupValue).LookupId;
                                }
                                ViewBag.JsStateID = stateID;

                                List lstSate = web.Lists.GetByTitle("EmpState");
                                query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>{0}</Value></Eq></Where></Query></View>", stateID);
                                ListItemCollection stateItems = lstSate.GetItems(query);
                                clientContext.Load(stateItems);
                                clientContext.ExecuteQuery();
                                if (stateItems.Count > 0)
                                {
                                    countryId = (stateItems[0]["Country"] as FieldLookupValue).LookupId;
                                }
                                emp.CountryID = countryId.ToString();
                            }

                            string skillsData = ConvertObjectToString(emplistItem["Skills"]);
                            string[] skills = skillsData.Split(';');
                            List<Skill> lsSkills = new List<Skill>();
                            foreach (string skillData in skills)
                            {
                                if (skillData != "")
                                {
                                    string[] skill = skillData.Split(',');
                                    lsSkills.Add(new Skill { Technology = skill[0], Experience = skill[1] });

                                }
                            }
                            emp.Skills = lsSkills;
                            emp.SkillsCount = lsSkills.Count;

                            string attachementID = ConvertObjectToString(emplistItem["AttachmentID"]);
                            if (attachementID != "")
                            {
                                List lstAttachments = web.Lists.GetByTitle("EmpAttachments");
                                CamlQuery queryAttachments = new CamlQuery();
                                queryAttachments.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name='AttachmentID' /><Value Type='Text'>{0}</Value></Eq></Where></Query></View>", attachementID);

                                ListItemCollection attachmentItems = lstAttachments.GetItems(queryAttachments);
                                clientContext.Load(attachmentItems);
                                clientContext.ExecuteQuery();

                                List<EmpAttachment> lsAttachments = new List<EmpAttachment>();
                                if (attachmentItems.Count > 0)
                                {
                                    foreach (ListItem item in attachmentItems)
                                    {
                                        lsAttachments.Add(new EmpAttachment
                                        {
                                            FileName = item["Title"].ToString(),
                                            FileUrl = Request.QueryString["SPHostUrl"] + "/Lists/EmpAttachments/" + item["FileLeafRef"].ToString(),
                                            FileRelativeUrl = item["FileRef"].ToString()
                                        });
                                    }
                                }
                                emp.AttachmentID = attachementID;
                                emp.Attachments = lsAttachments;
                                emp.AttachmentsCount = lsAttachments.Count;
                            }
                            else
                            {
                                emp.AttachmentID = Guid.NewGuid().ToString();
                            }

                            emp.ActionName = "UpdateEmployeeToSPList";
                            emp.SubmitButtonName = "Update Employee";
                        }
                        else
                        {
                            PeopleManager peopleManager = new PeopleManager(clientContext);
                            PersonProperties personProperties = peopleManager.GetMyProperties();
                            clientContext.Load(personProperties, p => p.AccountName);
                            clientContext.ExecuteQuery();

                            if (personProperties != null && personProperties.AccountName != null)
                            {
                                emp.UserID = personProperties.AccountName;
                            }

                            List<Skill> lsSkills = new List<Skill>();
                            lsSkills.Add(new Skill { Technology = "", Experience = "" });
                            emp.Skills = lsSkills;
                            emp.SkillsCount = lsSkills.Count;

                            emp.AttachmentID = Guid.NewGuid().ToString();
                            emp.isFileUploaded = false;

                            emp.ActionName = "AddEmployeeToSPList";
                            emp.SubmitButtonName = "Add Employee";
                        }

                        LoadUserSiteGroups(ref emp, clientContext);
                    } //  if (clientContext != null)
                } // using (var clientContext

                ViewBag.SPURL = Request.QueryString["SPHostUrl"];
            }
            catch (Exception ex)
            {
                ViewBag.Error = ex.Message + "\n" + ex.StackTrace;
            }

            return View(emp);
        }