コード例 #1
0
        /// <summary>
        /// Invokes SharePoint REST call
        /// </summary>
        /// <param name="restUrlSuffix">REST url query</param>
        /// <param name="fileName">(optional) Name of the file where the json output will be dumped.</param>
        /// <returns>returns the json output</returns>
        private async Task <string> Connect(string restUrlSuffix, string fileName)
        {
            using (var handler = new HttpClientHandler()
            {
                Credentials = credential
            })
            {
                //Getting authentication cookies
                Uri uri = new Uri(webUrl);
                handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));

                //Invoking REST API
                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await client.GetAsync(string.Format(restUrlSuffix, webUrl)).ConfigureAwait(false);

                    response.EnsureSuccessStatusCode();

                    string jsonData = await response.Content.ReadAsStringAsync();

                    if (!String.IsNullOrWhiteSpace(fileName))
                    {
                        //Debug.Write(jsonData);
                        File.WriteAllText(fileName, jsonData);
                    }

                    return(jsonData);
                }
            }
        }
コード例 #2
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            var models = new List <SPUserAlertDefinition>();

            try
            {
                var creds      = SPIaCConnection.CurrentConnection.GetActiveCredentials();
                var newcreds   = new System.Net.NetworkCredential(creds.UserName, creds.Password);
                var spourl     = new Uri(this.ClientContext.Url);
                var spocreds   = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password);
                var spocookies = spocreds.GetAuthenticationCookie(spourl);

                var spocontainer = new System.Net.CookieContainer();
                spocontainer.SetCookies(spourl, spocookies);

                var ws = new InfrastructureAsCode.Core.com.sharepoint.useralerts.Alerts();
                ws.Url             = string.Format("{0}/_vti_bin/Alerts.asmx", spourl.AbsoluteUri);
                ws.Credentials     = newcreds;
                ws.CookieContainer = spocontainer;
                var alerts = ws.GetAlerts();

                LogVerbose("User {0} webId:{1} has {2} alerts configured", alerts.CurrentUser, alerts.AlertWebId, alerts.Alerts.Count());
                foreach (var alertItem in alerts.Alerts)
                {
                    var model = new SPUserAlertDefinition()
                    {
                        CurrentUser   = alerts.CurrentUser,
                        WebId         = alerts.AlertWebId,
                        WebTitle      = alerts.AlertWebTitle,
                        AlertForTitle = alertItem.AlertForTitle,
                        AlertForUrl   = alertItem.AlertForUrl,
                        EventType     = alertItem.EventType,
                        Id            = alertItem.Id
                    };
                    models.Add(model);
                    LogVerbose("Alert {0} Active:{1} EventType:{2} Id:{3}", alertItem.AlertForUrl, alertItem.Active, alertItem.EventType, alertItem.Id);
                }


                models.ForEach(alert => WriteObject(alert));
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed in GetListItemCount for Library {0}", ListTitle);
            }
        }
        /// <summary>
        /// Process the request
        /// </summary>
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            if (this.ClientContext == null)
            {
                LogWarning("Invalid client context, configure the service to run again");
                return;
            }



            // obtain CSOM object for host web
            var vweb = this.ClientContext.Web;

            this.ClientContext.Load(vweb, hw => hw.SiteGroups, hw => hw.Title, hw => hw.ContentTypes);
            this.ClientContext.ExecuteQuery();


            GroupCollection groups = vweb.SiteGroups;

            this.ClientContext.Load(groups, g => g.Include(inc => inc.Id, inc => inc.Title, igg => igg.Users));
            this.ClientContext.ExecuteQuery();


            var creds      = SPIaCConnection.CurrentConnection.GetActiveCredentials();
            var newcreds   = new System.Net.NetworkCredential(creds.UserName, creds.Password);
            var spourl     = new Uri(this.ClientContext.Url);
            var spocreds   = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password);
            var spocookies = spocreds.GetAuthenticationCookie(spourl);

            var spocontainer = new System.Net.CookieContainer();

            spocontainer.SetCookies(spourl, spocookies);

            var ows = new OfficeDevPnP.Core.UPAWebService.UserProfileService();

            ows.Url             = string.Format("{0}/_vti_bin/userprofileservice.asmx", spourl.AbsoluteUri);
            ows.Credentials     = newcreds;
            ows.CookieContainer = spocontainer;

            var siteGroupUsers = new List <SPUserDefinitionModel>();

            var filteredGroups = groups.Where(w => SiteGroups.Any(a => w.Title.Equals(a, StringComparison.CurrentCultureIgnoreCase)));

            foreach (var group in filteredGroups)
            {
                foreach (var user in group.Users)
                {
                    if (!siteGroupUsers.Any(a => a.UserName == user.LoginName))
                    {
                        var userProfile = ows.GetUserProfileByName(user.LoginName);
                        //var userOrgs = ows.GetUserOrganizations(user.LoginName);
                        var UserName = userProfile.RetrieveUserProperty("UserName");
                        var office   = userProfile.RetrieveUserProperty("Department");
                        if (string.IsNullOrEmpty(office))
                        {
                            office = userProfile.RetrieveUserProperty("SPS-Department");
                        }

                        var userManager = userProfile.RetrieveUserProperty("Manager");

                        office = office.Replace(new char[] { '/', '\\', '-' }, ",");
                        office = office.Replace(" ", "");
                        var officeSplit   = office.Split(new string[] { "," }, StringSplitOptions.None);
                        var officeAcronym = (officeSplit.Length > 0) ? officeSplit[0] : string.Empty;

                        siteGroupUsers.Add(new SPUserDefinitionModel()
                        {
                            Manager             = userManager,
                            Organization        = office,
                            OrganizationAcronym = officeAcronym,
                            UserName            = user.LoginName,
                            UserEmail           = user.Email,
                            UserDisplay         = user.Title
                        });
                    }
                }



                WriteObject(siteGroupUsers);
            }
        }
コード例 #4
0
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();
            var models = new List <SPUserDefinitionModel>();

            try
            {
                var creds      = SPIaCConnection.CurrentConnection.GetActiveCredentials();
                var newcreds   = new System.Net.NetworkCredential(creds.UserName, creds.Password);
                var spourl     = new Uri(this.ClientContext.Url);
                var spocreds   = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password);
                var spocookies = spocreds.GetAuthenticationCookie(spourl);

                var spocontainer = new System.Net.CookieContainer();
                spocontainer.SetCookies(spourl, spocookies);

                var ows = new OfficeDevPnP.Core.UPAWebService.UserProfileService();
                ows.Url             = string.Format("{0}/_vti_bin/userprofileservice.asmx", spourl.AbsoluteUri);
                ows.Credentials     = newcreds;
                ows.CookieContainer = spocontainer;
                var UserProfileResult = ows.GetUserProfileByIndex(-1);
                var NumProfiles       = ows.GetUserProfileCount();
                var i              = 1;
                var tmpCount       = 0;
                var nextValue      = UserProfileResult.NextValue;
                var nextValueIndex = int.Parse(nextValue);

                // As long as the next User profile is NOT the one we started with (at -1)...
                while (nextValueIndex != -1)
                {
                    LogVerbose("Examining profile {0} of {1}", i, NumProfiles);

                    // Look for the Personal Space object in the User Profile and retrieve it
                    // (PersonalSpace is the name of the path to a user's OneDrive for Business site. Users who have not yet created a
                    // OneDrive for Business site might not have this property set.)

                    tmpCount++;

                    var PersonalSpaceUrl = UserProfileResult.RetrieveUserProperty("PersonalSpace");
                    var UserName         = UserProfileResult.RetrieveUserProperty("UserName");
                    if (!string.IsNullOrEmpty(UserName))
                    {
                        UserName = UserName.ToString().Replace(";", ",");
                    }

                    var userObject = new SPUserDefinitionModel()
                    {
                        UserName  = UserName,
                        OD4BUrl   = PersonalSpaceUrl,
                        UserIndex = nextValueIndex
                    };
                    models.Add(userObject);

                    // And now we check the next profile the same way...
                    UserProfileResult = ows.GetUserProfileByIndex(nextValueIndex);
                    nextValue         = UserProfileResult.NextValue;
                    nextValueIndex    = int.Parse(nextValue);
                    i++;
                }

                models.ForEach(user => WriteObject(user));
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed to retreive user profiles");
            }
        }
コード例 #5
0
        /// <summary>
        /// Execute the REST API querying the list with paging
        /// </summary>
        public override void ExecuteCmdlet()
        {
            base.ExecuteCmdlet();

            Collection <SPListItemDefinition> results = new Collection <SPListItemDefinition>();

            try
            {
                var creds        = SPIaCConnection.CurrentConnection.GetActiveCredentials();
                var spourl       = new Uri(this.ClientContext.Url);
                var spocreds     = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(creds.UserName, creds.Password);
                var spocookies   = spocreds.GetAuthenticationCookie(spourl);
                var spocontainer = new System.Net.CookieContainer();
                spocontainer.SetCookies(spourl, spocookies);

                // region Consume the web service
                var ListService = string.Format("{0}/_api/web/lists/getByTitle('{1}')/ItemCount", this.ClientContext.Url, this.ListTitle);
                var webRequest  = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ListService);
                webRequest.Credentials     = new System.Net.NetworkCredential(creds.UserName, creds.Password);
                webRequest.Method          = "GET";
                webRequest.Accept          = "application/json;odata=verbose";
                webRequest.CookieContainer = spocontainer;

                var webResponse = webRequest.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream())
                {
                    using (StreamReader responseReader = new StreamReader(webStream))
                    {
                        string response  = responseReader.ReadToEnd();
                        var    jobj      = JObject.Parse(response);
                        var    itemCount = jobj["d"]["ItemCount"];
                        LogVerbose("ItemCount:{0}", itemCount);
                    }
                }

                var successFlag = true;
                ListService = string.Format("{0}/_api/web/lists/getByTitle('{1}')/items?$top={2}", this.ClientContext.Url, this.ListTitle, this.Throttle);
                while (successFlag)
                {
                    LogVerbose("Paging:{0}", ListService);
                    successFlag                = false;
                    webRequest                 = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(ListService);
                    webRequest.Credentials     = new System.Net.NetworkCredential(creds.UserName, creds.Password);
                    webRequest.Method          = "GET";
                    webRequest.Accept          = "application/json;odata=verbose";
                    webRequest.CookieContainer = spocontainer;

                    webResponse = webRequest.GetResponse();
                    using (Stream webStream = webResponse.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(webStream))
                        {
                            string response  = responseReader.ReadToEnd();
                            var    jobj      = JObject.Parse(response);
                            var    jarr      = (JArray)jobj["d"]["results"];
                            var    jnextpage = jobj["d"]["__next"];

                            foreach (JObject j in jarr)
                            {
                                LogVerbose("ItemID:{0}", j["Id"]);
                                var newitem = new SPListItemDefinition()
                                {
                                    Title = j["Title"].ToObject <string>(),
                                    Id    = j["Id"].ToObject <int>()
                                };
                                results.Add(newitem);
                            }

                            if (jnextpage != null && !String.IsNullOrEmpty(jnextpage.ToString()))
                            {
                                successFlag = true;
                                ListService = jnextpage.ToString();
                            }
                        }
                    }
                }

                WriteObject(results, true);
            }
            catch (Exception ex)
            {
                LogError(ex, "Failed in GetListItemCount for Library {0}", ListTitle);
            }
        }