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);
                }
            }
        }
예제 #2
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);
                }
            }
        }
예제 #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);
        }
예제 #4
0
 internal string[] GetMultipleProfileProperties(ClientContext clientContext, string UserName, string[] PropertyNames)
 {
     try
     {
         var peopleManager = new PeopleManager(clientContext);
         UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(clientContext, UserName, PropertyNames);
         IEnumerable <string>         profilePropertyValues    = peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);
         clientContext.Load(profilePropertiesForUser);
         clientContext.ExecuteQuery();
         return(profilePropertyValues.ToArray());
     }
     catch (Exception ex)
     {
         LogMessage("Exception trying to get profile properties for user " + UserName + "\n" + ex.Message, EventLogEntryType.Error, ServiceEventID.SharePointOnlineError);
         return(null);
     }
 }
예제 #5
0
        protected string GetOthersUserEmail(User user)
        {
            string email = string.Empty;

            try
            {
                ClientContext clientContext                        = GetContext(TenantAdminUrl);
                PeopleManager peopleManager                        = new PeopleManager(clientContext);
                string[]      profilePropertyNames                 = new string[] { "WorkEmail" };
                UserProfilePropertiesForUser userForUser           = new UserProfilePropertiesForUser(clientContext, user.LoginName, profilePropertyNames);
                IEnumerable <string>         userProfileProperties = peopleManager.GetUserProfilePropertiesFor(userForUser);
                clientContext.Load(userForUser);
                clientContext.ExecuteQuery();
                email = userProfileProperties.ElementAt(0);
            }
            catch (Exception)
            {
            }
            return(email);
        }
예제 #6
0
        protected string GetOthersUserName(User user)
        {
            string fullName = string.Empty;

            try
            {
                ClientContext clientContext                        = GetContext(TenantAdminUrl);
                PeopleManager peopleManager                        = new PeopleManager(clientContext);
                string[]      profilePropertyNames                 = new string[] { "LastName", "FirstName" };
                UserProfilePropertiesForUser userForUser           = new UserProfilePropertiesForUser(clientContext, user.LoginName, profilePropertyNames);
                IEnumerable <string>         userProfileProperties = peopleManager.GetUserProfilePropertiesFor(userForUser);
                clientContext.Load(userForUser);
                clientContext.ExecuteQuery();
                fullName = userProfileProperties.ElementAt(0) + ", " + userProfileProperties.ElementAt(1);
            }
            catch (Exception)
            {
            }
            return(fullName);
        }
예제 #7
0
        /// <summary>
        /// Get current user's Email.  User.Email may not have the correct values in all the cases hence making a call to user profile to get accurate values
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>

        private string GetOthersUserEmail(User user)
        {
            string email = string.Empty;

            try
            {
                ClientContext clientContext                        = GetContext(TenantAdminUrl);
                PeopleManager peopleManager                        = new PeopleManager(clientContext);
                string[]      profilePropertyNames                 = new string[] { "WorkEmail" };
                UserProfilePropertiesForUser userForUser           = new UserProfilePropertiesForUser(clientContext, user.LoginName, profilePropertyNames);
                IEnumerable <string>         userProfileProperties = peopleManager.GetUserProfilePropertiesFor(userForUser);
                clientContext.Load(userForUser);
                clientContext.ExecuteQuery();
                email = userProfileProperties.ElementAt(0);
            }
            catch (Exception ex)
            {
                Log.LogFileSystem(string.Format("Error happened in getting User's Email - {0}", ex.Message) + DateTime.Now.ToString());
            }
            return(email);
        }
예제 #8
0
        //gavdcodeend 25

        //gavdcodebegin 26
        static void SpCsCsomGetPropertiesUserProfile(ClientContext spCtx)
        {
            string myUser = "******" +
                            ConfigurationManager.AppSettings["spUserName"];
            PeopleManager myPeopleManager = new PeopleManager(spCtx);

            string[] myProfPropertyNames = new string[]
            { "Manager", "Department", "Title" };
            UserProfilePropertiesForUser myProfProperties =
                new UserProfilePropertiesForUser(spCtx, myUser, myProfPropertyNames);
            IEnumerable <string> myProfPropertyValues =
                myPeopleManager.GetUserProfilePropertiesFor(myProfProperties);

            spCtx.Load(myProfProperties);
            spCtx.ExecuteQuery();

            foreach (string oneValue in myProfPropertyValues)
            {
                Console.WriteLine(oneValue);
            }
        }
        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));
        }
        //TODO: Get Web Permissions
        private void GetWebPermissions(ClientContext cc)
        {
            var roleAssignments = cc.LoadQuery(cc.Web.RoleAssignments.Include(r => r.Member, r => r.Member.PrincipalType,
                                                                              r => r.RoleDefinitionBindings.Include(b => b.Name)));

            foreach (var roleAssignment in roleAssignments)
            {
                if (roleAssignment.Member.PrincipalType == Microsoft.SharePoint.Client.Utilities.PrincipalType.User)
                {
                    //Get the Display Name of the user and/or other properties
                    PeopleManager peopleManager        = new PeopleManager(cc);
                    string[]      profilePropertyNames = new string[] { "PreferredName", "Department", "Title" };
                    UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(
                        cc, roleAssignment.Member.LoginName, profilePropertyNames);
                    IEnumerable <string> profilePropertyValues = peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

                    //Get the permissions
                    Console.Write(roleAssignment.Member.LoginName, roleAssignment.Member.Title);
                }
            }
            cc.ExecuteQuery();
        }
예제 #11
0
        static void Main(string[] args)
        {
            string siteUrl    = "https://xxx.sharepoint.com";
            string username   = "******";
            string passwords  = "xxx";
            string targetUser = "******";

            ClientContext ctx = new ClientContext(siteUrl);

            var securepassword = new SecureString();

            foreach (char c in passwords)
            {
                securepassword.AppendChar(c);
            }

            ctx.Credentials = new SharePointOnlineCredentials(username, securepassword);

            // Get the PeopleManager object.
            PeopleManager peopleManager = new PeopleManager(ctx);

            // Retrieve specific properties by using the GetUserProfilePropertiesFor method.
            // The returned collection contains only property values.
            string[] profilePropertyNames = new string[] { "PreferredName", "Department", "Title" };
            UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(ctx, targetUser, profilePropertyNames);
            IEnumerable <string>         profilePropertyValues    = peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

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

            // Iterate through the property values.
            foreach (var value in profilePropertyValues)
            {
                Console.Write(value + "\\n");
            }
            Console.ReadKey(false);
        }
예제 #12
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);
            }
        }
예제 #13
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;
            }
            
        }
        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);
        }
예제 #15
0
        /// <summary>
        /// Get current user's Email.  User.Email may not have the correct values in all the cases hence making a call to user profile to get accurate values
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>

        private string GetOthersUserEmail(User user)
        {
            string email = string.Empty;
            try
            {
                ClientContext clientContext = GetContext(TenantAdminUrl);
                PeopleManager peopleManager = new PeopleManager(clientContext);
                string[] profilePropertyNames = new string[] { "WorkEmail" };
                UserProfilePropertiesForUser userForUser = new UserProfilePropertiesForUser(clientContext, user.LoginName, profilePropertyNames);
                IEnumerable<string> userProfileProperties = peopleManager.GetUserProfilePropertiesFor(userForUser);
                clientContext.Load(userForUser);
                clientContext.ExecuteQuery();
                email = userProfileProperties.ElementAt(0);
            }
            catch (Exception ex)
            {
                Log.LogFileSystem(string.Format("Error happened in getting User's Email - {0}", ex.Message) + DateTime.Now.ToString());
            }
            return email;
        }
예제 #16
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;
 }
예제 #17
0
        private void Init()
        {
            _log.Info("Início do processo: SharepointSyncJob");
            var listItemListaTelefonicaProperties = new List <ItemListaTelefonicaProperties>();

            using (ClientContext tenantContext = new ClientContext(_configuration.TenantUrl))
            {
                SecureString passWord = new SecureString();
                foreach (char c in _configuration.Password.ToCharArray())
                {
                    passWord.AppendChar(c);
                }
                tenantContext.Credentials = new SharePointOnlineCredentials(_configuration.EmailAccount, passWord);
                PeopleManager peopleManager = new PeopleManager(tenantContext);

                UserCollection users = tenantContext.Web.SiteUsers;
                tenantContext.Load(users);
                tenantContext.ExecuteQuery();
                StringBuilder items = new StringBuilder();
                string[]      userProfileProperties =
                {
                    UserProfileProperties.FirstName,
                    UserProfileProperties.LastName,
                    UserProfileProperties.PreferredName,
                    UserProfileProperties.WorkEmail,
                    UserProfileProperties.Pager,
                    UserProfileProperties.Department,
                    UserProfileProperties.CellPhone,
                    UserProfileProperties.PictureURL,
                    UserProfileProperties.Office,
                    UserProfileProperties.IpPhone,
                    UserProfileProperties.WorkPhone,
                    UserProfileProperties.IpPhone,
                    UserProfileProperties.AboutMe,
                    UserProfileProperties.StreetAddress,
                    UserProfileProperties.CityAddress,
                    UserProfileProperties.StateAddress,
                    UserProfileProperties.ZIPAddress,
                    UserProfileProperties.CountryAddress,
                    UserProfileProperties.SPS_Location,
                    UserProfileProperties.Title,
                    UserProfileProperties.Fax,
                    UserProfileProperties.AccountName,
                };

                foreach (string propertyKey in userProfileProperties)
                {
                    items.Append(propertyKey);
                    items.Append(",");
                }
                items.AppendLine();
                _log.Info("A ler os Users profile: SharepointSyncJob");
                foreach (User user in users)
                {
                    try
                    {
                        if (user.PrincipalType != Microsoft.SharePoint.Client.Utilities.PrincipalType.User)
                        {
                            continue;
                        }

                        UserProfilePropertiesForUser userProfilePropertiesForUser = new UserProfilePropertiesForUser(tenantContext, user.LoginName, userProfileProperties);
                        var profileProperties = peopleManager.GetUserProfilePropertiesFor(userProfilePropertiesForUser);
                        tenantContext.Load(userProfilePropertiesForUser);
                        tenantContext.ExecuteQuery();
                        var listProfileProperties = profileProperties.ToList();
                        if (listProfileProperties.Any())
                        {
                            ItemListaTelefonicaProperties itemListaTelefonicaProperties = new ItemListaTelefonicaProperties();

                            itemListaTelefonicaProperties.FirstName     = listProfileProperties[0];
                            itemListaTelefonicaProperties.LastName      = listProfileProperties[1];
                            itemListaTelefonicaProperties.PreferredName = listProfileProperties[2];
                            itemListaTelefonicaProperties.Email         = user.Email;
                            itemListaTelefonicaProperties.Pager         = listProfileProperties[4];
                            itemListaTelefonicaProperties.Department    = listProfileProperties[5];
                            itemListaTelefonicaProperties.CellPhone     = listProfileProperties[6];
                            itemListaTelefonicaProperties.Office        = listProfileProperties[8];
                            itemListaTelefonicaProperties.WorkFax       = listProfileProperties[9];
                            itemListaTelefonicaProperties.WorkPhone     = listProfileProperties[10];
                            itemListaTelefonicaProperties.IpPhone       = listProfileProperties[11];
                            itemListaTelefonicaProperties.AboutMe       = listProfileProperties[12];
                            itemListaTelefonicaProperties.WorkAddress   = listProfileProperties[13];
                            itemListaTelefonicaProperties.WorkCity      = listProfileProperties[14];
                            itemListaTelefonicaProperties.WorkState     = listProfileProperties[15];
                            itemListaTelefonicaProperties.WorkZip       = listProfileProperties[16];
                            itemListaTelefonicaProperties.WorkCountry   = listProfileProperties[17];
                            itemListaTelefonicaProperties.Company       = listProfileProperties[18];
                            itemListaTelefonicaProperties.JobTitle      = listProfileProperties[19];
                            itemListaTelefonicaProperties.WorkFax       = listProfileProperties[20];
                            itemListaTelefonicaProperties.PictureURL    = $"{this._configuration.TenantUrl}{PICTURE_URL}{ user.Email}";

                            listItemListaTelefonicaProperties.Add(itemListaTelefonicaProperties);
                        }
                    }
                    catch (Exception ex)
                    {
                        _log.Error($"-> users no processo: SharepointSyncJob: {ex}", ex);
                    }
                }

                InsertOrUpdateContactoToListContactos(listItemListaTelefonicaProperties);
            }
            _log.Info("Fim do processo: SharepointSyncJob");
        }
        private TipsModel GetTipForCurrentUser()
        {

            ClientContext clientContext = new ClientContext(ConfigurationManager.AppSettings["SiteCollectionUrl"])
            {
                RequestTimeout = 1000000,
                Credentials =
                    new SharePointOnlineCredentials(ConfigurationManager.AppSettings["UserName"],
                        ConvertToSecureString(ConfigurationManager.AppSettings["Password"]))
            };


            //get user info
            var spUser = clientContext.Web.CurrentUser;
            clientContext.Load(spUser, user => user.LoginName);
            clientContext.ExecuteQuery();

            

            //Get tip items
            Web web = clientContext.Web;
            List newsList = web.GetList("sites/Portal/Lists/Tips");
            clientContext.Load(newsList);
            var items = newsList.GetItems(CamlQuery.CreateAllItemsQuery());
            clientContext.Load(items,
                includes =>
                    includes.Include(y => y["Device"], y => y["Department"], y => y.Client_Title, y => y["Content"]));
            clientContext.ExecuteQuery();

            //get user profile property
            PeopleManager peopleManager = new PeopleManager(clientContext);

            var profilePropertyNames = new string[] { "Device", "SPS-Department", "Title" };
            UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(
                clientContext, spUser.LoginName, profilePropertyNames);
            IEnumerable<string> profilePropertyValues =
                peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

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

            var devices = profilePropertyValues.ToList()[0];
            var department = profilePropertyValues.ToList()[1];
            var tip = new TipsModel();

            foreach (var item in items)
            {
                TaxonomyFieldValueCollection col = item["Device"] as TaxonomyFieldValueCollection;

                foreach (var taxItem in col)
                {
                    if (devices.Contains(taxItem.Label))
                    {
                       
                      tip = new TipsModel(item.Client_Title, item["Content"].ToString());
                    }
                }
            }
         

            return tip;
        }
        public ActionResult Index()
        {
            var sw = Stopwatch.StartNew();
            var ai = new TelemetryClient();
            var startTime = DateTime.UtcNow;
            var newsViewModel = new List<NewsModel>();
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext == null) return View(newsViewModel);

                //get user info
                var spUser = clientContext.Web.CurrentUser;
                clientContext.Load(spUser, user => user.LoginName);
                clientContext.ExecuteQuery();

                IDatabase cache = RedisHelper.Connection.GetDatabase();
                var cacheKey = $"news_{spUser.LoginName}";

                if (cache.KeyExists(cacheKey))
                {
                    newsViewModel = JsonConvert.DeserializeObject<List<NewsModel>>(cache.StringGet(cacheKey));
                    sw.Stop();
                    var timespanCache = sw.Elapsed;
                    ViewBag.Time = $"{timespanCache.Minutes:00}m:{timespanCache.Seconds:00}s:{timespanCache.Milliseconds / 10:00}ms";
                    ai.TrackDependency("Redis", cacheKey, startTime, sw.Elapsed, true);
                    return View(newsViewModel);
                }

                //Get news items
                Web web = clientContext.Web;
                List newsList = web.GetList("sites/Portal/Lists/News");
                clientContext.Load(newsList);
                var items = newsList.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(items,
                    includes =>
                        includes.Include(y => y["Device"], y => y["Department"], y => y.Client_Title,
                            y => y["NewsContent"]));
                clientContext.ExecuteQuery();



                //get user profile property
                PeopleManager peopleManager = new PeopleManager(clientContext);

                var profilePropertyNames = new[] { "Device", "SPS-Department", "Title" };
                UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(
                    clientContext, spUser.LoginName, profilePropertyNames);
                IEnumerable<string> profilePropertyValues =
                    peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

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

                var propertyValues = profilePropertyValues as IList<string> ?? profilePropertyValues.ToList();
                var devices = propertyValues.ToList()[0];
                var department = propertyValues.ToList()[1];

                foreach (var item in items)
                {
                    TaxonomyFieldValueCollection col = item["Device"] as TaxonomyFieldValueCollection;

                    foreach (var taxItem in col)
                    {
                        if (devices.Contains(taxItem.Label))
                        {
                            int index = newsViewModel.FindIndex(i => i.Title == item.Client_Title);
                            if (index != 0)
                            {
                                newsViewModel.Add(new NewsModel(item.Client_Title, item["NewsContent"].ToString()));
                            }
                        }
                    }
                }
                cache.StringSet(cacheKey, JsonConvert.SerializeObject(newsViewModel), new TimeSpan(0, 0, 1, 0));
            }


            sw.Stop();
            var timespan = sw.Elapsed;
            ViewBag.Time = $"{timespan.Minutes:00}m:{timespan.Seconds:00}s:{timespan.Milliseconds / 10:00}ms";
            ai.TrackDependency("SharePoint", "GetNews", startTime, sw.Elapsed, true);
            return View(newsViewModel);
        }
예제 #20
0
        static void Main()
        {
            var newsViewModel = new List<NewsModel>();

            ClientContext clientContext = new ClientContext("https://mod738287.sharepoint.com/sites/Portal")
            {
                RequestTimeout = 1000000,
                Credentials =
                    new SharePointOnlineCredentials("*****@*****.**",
                        ConvertToSecureString("pass@word1"))
            };

            //get user info
            var spUser = clientContext.Web.CurrentUser;
            clientContext.Load(spUser, user => user.LoginName);
            clientContext.ExecuteQuery();

            IDatabase cache = RedisHelper.Connection.GetDatabase();
            var cacheKey = $"news_{spUser.LoginName}";

            //Get news items
            Web web = clientContext.Web;
            List newsList = web.GetList("sites/Portal/Lists/News");
            clientContext.Load(newsList);
            var items = newsList.GetItems(CamlQuery.CreateAllItemsQuery());
            clientContext.Load(items,
                includes =>
                    includes.Include(y => y["Device"], y => y["Department"], y => y.Client_Title, y => y["NewsContent"]));
            clientContext.ExecuteQuery();

            //get user profile property
            PeopleManager peopleManager = new PeopleManager(clientContext);

            var profilePropertyNames = new string[] { "Device", "SPS-Department", "Title" };
            UserProfilePropertiesForUser profilePropertiesForUser = new UserProfilePropertiesForUser(
                clientContext, spUser.LoginName, profilePropertyNames);
            IEnumerable<string> profilePropertyValues =
                peopleManager.GetUserProfilePropertiesFor(profilePropertiesForUser);

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

            var devices = profilePropertyValues.ToList()[0];
            var department = profilePropertyValues.ToList()[1];

            foreach (var item in items)
            {
                TaxonomyFieldValueCollection col = item["Device"] as TaxonomyFieldValueCollection;

                foreach (var taxItem in col)
                {
                    if (devices.Contains(taxItem.Label))
                    {
                        int index = newsViewModel.FindIndex(i => i.Title == item.Client_Title);
                        if (index != 0)
                        {
                            newsViewModel.Add(new NewsModel(item.Client_Title, item["NewsContent"].ToString()));
                        }
                    }
                }
            }
            cache.StringSet(cacheKey, JsonConvert.SerializeObject(newsViewModel), new TimeSpan(0, 0, 1, 0));
        }