Exemple #1
0
        private User bindCurrentUser(Microsoft.SharePoint.Client.User currentUser)
        {
            if (currentUser == null)
            {
                return(null);
            }

            var user = new User()
            {
                Id    = currentUser.Id.ToString(),
                Name  = currentUser.Title,
                Login = currentUser.LoginName
            };

            var list = new List <UserGroup>();

            foreach (var group in currentUser.Groups)
            {
                list.Add(new UserGroup
                {
                    Id   = group.Id.ToString(),
                    Name = group.Title
                });
            }

            user.Groups = list;

            return(user);
        }
Exemple #2
0
 protected void btnRemoveReadPermissionLevelFromCurrentUser_Click(object sender, EventArgs e)
 {
     cc.Load(cc.Web, web => web.CurrentUser);
     cc.ExecuteQuery();
     Microsoft.SharePoint.Client.User currentUser = cc.Web.CurrentUser;
     cc.Web.RemovePermissionLevelFromUser(currentUser.LoginName, RoleType.Reader);
 }
 public static string ToUserEmailValue(this Microsoft.SharePoint.Client.User fieldItemValue)
 {
     if (fieldItemValue != null)
     {
         return(fieldItemValue.Email);
     }
     return(string.Empty);
 }
Exemple #4
0
        public ActionResult SendPDF(string formXml, string xsnName, string viewName, string toEmail, string emailBody)
        {
            var spContext = SharePointContextProvider.Current.GetSharePointContext(System.Web.HttpContext.Current);

            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                SP.User spUser = GetSharePointUser(clientContext);

                string internalUserID = null;

                // Store data for processing
                string            tenantID = TokenHelper.GetRealmFromTargetUrl(new Uri(clientContext.Url));
                RequestIdentifier rid      = RequestUtil.AddRequestEntity(PdfRequestType.SendPDF, PdfRequestStatus.InProgress, tenantID, internalUserID);

                PDFRequest response = new PDFRequest();
                response.RequestID   = rid.ID;
                response.RequestType = PdfRequestType.SendPDF;
                response.Status      = PdfRequestStatus.InProgress;
                response.Message     = "";

                BlobUtil bu = null;
                try
                {
                    bu = new BlobUtil();

                    ParameterCollection plist = new ParameterCollection();
                    plist.Add(Parameters.Api, "SendPDF");
                    plist.Add(Parameters.ViewName, viewName ?? "");
                    plist.Add(Parameters.UserID, internalUserID);
                    plist.Add(Parameters.XsnName, xsnName ?? "");
                    plist.Add(Parameters.FromEmail, spUser.Email ?? "");
                    plist.Add(Parameters.ToEmail, toEmail ?? "");
                    plist.Add(Parameters.EmailBody, emailBody ?? "");

                    BlobCollection bc = new BlobCollection();
                    bc.Add("xml", formXml);
                    bc.Add("parameters", plist);
                    bu.StoreRequestArguments(rid.ID, bc);

                    // post to queue
                    PdfServiceQueues.XmlToHtmlClient.AddMessage(rid.ID, internalUserID);
                }
                catch (Exception ex)
                {
                    // Update request status
                    response.Status  = PdfRequestStatus.Error;
                    response.Message = ex.Message;
                    RequestUtil.UpdateRequestStatus(rid.ID, PdfRequestStatus.Error, ex.Message);
                    //PdfServiceQueues.EmailSendClient.AddErrorMessage(requestID, internalUserID.Value, ex.Message);
                }
                finally
                {
                }
                return(new ObjectResult <PDFRequest>(response));
            }
        }
Exemple #5
0
        public void bindmyrequests()
        {
            string login          = "******"; //give your username here
            string password       = "******";                 //give your password
            var    securePassword = new SecureString();

            foreach (char c in password)
            {
                securePassword.AppendChar(c);
            }
            string        siteUrl           = "https://ectacae.sharepoint.com/sites/ECTPortal/eservices/studentservices";
            ClientContext clientContext     = new ClientContext(siteUrl);
            var           onlineCredentials = new SharePointOnlineCredentials(login, securePassword);

            clientContext.Credentials = onlineCredentials;
            List      list  = clientContext.Web.Lists.GetByTitle("Students_Requests");
            CamlQuery query = new CamlQuery();
            string    mail  = Session["sEmail"].ToString();

            Microsoft.SharePoint.Client.User user = clientContext.Web.EnsureUser(mail);
            clientContext.Load(user, x => x.Id);
            clientContext.ExecuteQuery();
            //string thisWillBeUsersLoginName = user.Id;
            int userid = user.Id;

            //clientContext.Web.EnsureUser(mail)
            query.ViewXml = "<View><Query><Where><Eq><FieldRef Name='Requester' LookupId='TRUE'/><Value Type='User'>" + userid + "</Value></Eq></Where></Query><RowLimit>100</RowLimit></View>";
            //query.ViewXml = "<View></View>";
            Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(query);
            clientContext.Load(list);
            clientContext.Load(items);
            clientContext.ExecuteQuery();

            // create a data table
            DataTable LDT = new DataTable();

            LDT.Columns.Add("Title");
            LDT.Columns.Add("Status");
            LDT.Columns.Add("ServiceID");
            LDT.Columns.Add("Requester");
            LDT.Columns.Add("Created", System.Type.GetType("System.DateTime"));
            //fill datatatable
            foreach (Microsoft.SharePoint.Client.ListItem item in items)
            {
                //var userValue = (FieldUserValue)item["Requester"];
                //var user = clientContext.Web.GetUserById(userValue.LookupId);
                //clientContext.Load(user, x => x.LoginName);
                //clientContext.ExecuteQuery();
                //string thisWillBeUsersLoginName = user.LoginName;
                //string request = item["Request"].ToString();
                LDT.Rows.Add(item["Title"], item["Status"], item["Request"], item["Requester"], Convert.ToDateTime(item["Created"]));
            }
            LDT.DefaultView.Sort = "Created DESC";
            Repeater1.DataSource = LDT;
            Repeater1.DataBind();
        }
Exemple #6
0
        protected void btnCreateGroupAndAddUsers_Click(object sender, EventArgs e)
        {
            cc.Load(cc.Web, web => web.CurrentUser);
            cc.ExecuteQuery();
            Microsoft.SharePoint.Client.User currentUser = cc.Web.CurrentUser;

            if (!cc.Web.GroupExists("Test"))
            {
                Group group = cc.Web.AddGroup("Test", "Test group", true);
                cc.Web.AddUserToGroup("Test", currentUser.LoginName);
            }
        }
Exemple #7
0
 public SPDocumentInfo(List spList, File spFile, User spUser)
     : this(spList, spFile)
 {
     try
     {
         CheckedOutByUser = new SPUserPrincipal(spUser);
     }
     catch (Exception ex)
     {
         CheckedOutByUser = new SPUserPrincipal(new[] { new Error(ex.GetType().ToString(), ex.Message) });
     }
 }
Exemple #8
0
 protected void btnRemoveUserFromGroup_Click(object sender, EventArgs e)
 {
     cc.Load(cc.Web, web => web.CurrentUser);
     cc.ExecuteQuery();
     Microsoft.SharePoint.Client.User currentUser = cc.Web.CurrentUser;
     if (cc.Web.GroupExists("Test"))
     {
         if (cc.Web.IsUserInGroup("Test", currentUser.LoginName))
         {
             cc.Web.RemoveUserFromGroup("Test", currentUser.LoginName);
         }
     }
 }
Exemple #9
0
        public void GetUserIdByEmailTest()
        {
            var            email          = "*****@*****.**";
            UserCollection userCollection = _clientContext.Web.SiteUsers;

            _clientContext.Load(userCollection);
            _clientContext.ExecuteQuery();

            Microsoft.SharePoint.Client.User user = userCollection.GetByEmail(email);
            _clientContext.Load(user);
            _clientContext.ExecuteQuery();

            Assert.AreEqual(user.Id, 419);
        }
Exemple #10
0
        public void GetUserIdByLoginNameTest()
        {
            var            loginName      = "i:0#.w|ncdmz\\moma";
            UserCollection userCollection = _clientContext.Web.SiteUsers;

            _clientContext.Load(userCollection);
            _clientContext.ExecuteQuery();

            Microsoft.SharePoint.Client.User user = userCollection.GetByLoginName(loginName);
            _clientContext.Load(user);
            _clientContext.ExecuteQuery();

            Assert.AreEqual(user.Id, 419);
        }
Exemple #11
0
 private SP.User GetSharePointUser(SP.ClientContext clientContext)
 {
     SP.User spUser = null;
     if (clientContext != null)
     {
         spUser = clientContext.Web.CurrentUser;
         clientContext.Load(spUser, user => user.Title,
                            user => user.Email,
                            user => user.IsSiteAdmin,
                            user => user.LoginName);
         clientContext.ExecuteQuery();
     }
     return(spUser);
 }
Exemple #12
0
        /// <summary>
        /// Gets the tree node icon.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        public static string GetTreeNodeIcon(this SPClient.User user)
        {
            string image      = string.Empty;
            bool   isExternal = false;

#if CLIENTSDKV161UP
            isExternal = user.IsShareByEmailGuestUser;
#endif

            if (isExternal)
            {
                image = Constants.IMAGE_EXTERNAL_USERS;
            }
            else
            {
                switch (user.PrincipalType)
                {
                case Microsoft.SharePoint.Client.Utilities.PrincipalType.All:
                    image = Constants.IMAGE_SITE_USER_EXCLAMATION;
                    break;

                case Microsoft.SharePoint.Client.Utilities.PrincipalType.DistributionList:
                    image = Constants.IMAGE_SITE_GROUP_DISTRIBUTION;
                    break;

                case Microsoft.SharePoint.Client.Utilities.PrincipalType.None:
                    image = Constants.IMAGE_SITE_USER_EXCLAMATION;
                    break;

                case Microsoft.SharePoint.Client.Utilities.PrincipalType.SecurityGroup:
                    image = Constants.IMAGE_SITE_GROUP_SECURITY;
                    break;

                case Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup:
                    image = Constants.IMAGE_SITE_GROUP;
                    break;

                case Microsoft.SharePoint.Client.Utilities.PrincipalType.User:
                    image = Constants.IMAGE_SITE_USER;
                    break;

                default:
                    break;
                }
            }

            return(image);
        }
Exemple #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // define initial script, needed to render the chrome control
            string script = @"
            function chromeLoaded() {
                $('body').show();
            }

            //function callback to render chrome after SP.UI.Controls.js loads
            function renderSPChrome() {
                //Set the chrome options for launching Help, Account, and Contact pages
                var options = {
                    'appTitle': document.title,
                    'onCssLoaded': 'chromeLoaded()'
                };

                //Load the Chrome Control in the divSPChrome element of the page
                var chromeNavigation = new SP.UI.Controls.Navigation('divSPChrome', options);
                chromeNavigation.setVisible(true);
            }";

            //register script in page
            Page.ClientScript.RegisterClientScriptBlock(typeof(Default), "BasePageScript", script, true);

            if (!this.IsPostBack)
            {
                // The following code gets the client context and Title property by using TokenHelper.
                // To access other properties, the app may need to request permissions on the host web.
                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                {
                    clientContext.Load(clientContext.Web, web => web.Title
                                       , web => web.CurrentUser);
                    clientContext.ExecuteQuery();

                    Microsoft.SharePoint.Client.User currentUser       = clientContext.Web.CurrentUser;
                    List <SharePointUser>            peoplePickerUsers = new List <SharePointUser>(1);
                    peoplePickerUsers.Add(new SharePointUser()
                    {
                        Name = currentUser.Title, Email = currentUser.Email, Login = currentUser.LoginName
                    });
                    hdnAdministrators.Value = JsonUtility.Serialize <List <SharePointUser> >(peoplePickerUsers);
                }
            }
        }
        public static void AddItemsToEmployeelist(ClientContext ctx)
        {
            List list = ctx.Web.GetListByTitle("Employee");

            ctx.Load(list);


            Microsoft.SharePoint.Client.User users = ctx.Site.RootWeb.EnsureUser("*****@*****.**");
            ctx.Load(users, u => u.Id);
            ctx.ExecuteQuery();


            ListItem item1 = list.AddItem(new ListItemCreationInformation());

            item1["Title"]         = "Manager";
            item1["TIM_Employee"]  = users;
            item1["TIM_Picture"]   = "http://www.catster.com/wp-content/uploads/2017/06/small-kitten-meowing.jpg";
            item1["TIM_Linkedin"]  = "https://www.linkedin.com/feed/";
            item1["TIM_Age"]       = 30;
            item1["TIM_Education"] = "Basic";
            item1.Update();


            ListItem item2 = list.AddItem(new ListItemCreationInformation());

            item2["Title"]         = "Staff";
            item2["TIM_Employee"]  = users;
            item2["TIM_Picture"]   = "https://d2btg9txypwkc4.cloudfront.net/media/catalog/category/Kampanjer.jpg";
            item2["TIM_Linkedin"]  = "https://www.linkedin.com/feed/";
            item2["TIM_Age"]       = 20;
            item2["TIM_Education"] = "Highschool";
            item2.Update();


            ListItem item3 = list.AddItem(new ListItemCreationInformation());

            item3["Title"]         = "Staff";
            item3["TIM_Employee"]  = users;
            item3["TIM_Picture"]   = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/27/Tim_Studio2104.jpg/1200px-Tim_Studio2104.jpg";
            item3["TIM_Linkedin"]  = "https://www.linkedin.com/feed/";
            item3["TIM_Age"]       = 55;
            item3["TIM_Education"] = "University";
            item3.Update();
            ctx.ExecuteQuery();
        }
Exemple #15
0
        public void AddEventListItem(string Id, EventListItem item)
        {
            var eventData = item;

            using (ClientContext context = _sharepointContextProvider.GetSharepointContextFromUrl(APIResource.SHAREPOINT_CONTEXT + "/sites/FOS/"))
            {
                Web web       = context.Web;
                var loginName = item.eventHost;
                //var loginName = "i:0#.f|membership|" + item.eventHost;
                //string email = eventData.eventHost;
                //PeopleManager peopleManager = new PeopleManager(context);
                //ClientResult<PrincipalInfo> principal = Utility.ResolvePrincipal(context, web, email, PrincipalType.User, PrincipalSource.All, web.SiteUsers, true);
                //context.ExecuteQuery();

                Microsoft.SharePoint.Client.User newUser = context.Web.EnsureUser(loginName);
                context.Load(newUser);
                context.ExecuteQuery();

                FieldUserValue userValue = new FieldUserValue();
                userValue.LookupId = newUser.Id;

                List members = context.Web.Lists.GetByTitle("Event List");
                Microsoft.SharePoint.Client.ListItem listItem = members.AddItem(new ListItemCreationInformation());
                listItem["EventHost"]           = userValue;
                listItem["EventTitle"]          = eventData.eventTitle;
                listItem["EventId"]             = 1;
                listItem["EventRestaurant"]     = eventData.eventRestaurant;
                listItem["EventMaximumBudget"]  = eventData.eventMaximumBudget;
                listItem["EventTimeToClose"]    = eventData.eventTimeToClose;
                listItem["EventTimeToReminder"] = eventData.eventTimeToReminder;
                listItem["EventParticipants"]   = eventData.eventParticipants;
                listItem["EventCategory"]       = eventData.eventCategory;

                listItem["EventRestaurantId"]  = eventData.eventRestaurantId;
                listItem["EventServiceId"]     = eventData.eventServiceId;
                listItem["EventDeliveryId"]    = eventData.eventDeliveryId;
                listItem["EventCreatedUserId"] = eventData.eventCreatedUserId;
                listItem["EventHostId"]        = eventData.eventHostId;
                listItem.Update();
                context.ExecuteQuery();
            }
        }
        public static bool ParseUser(this SPClient.Web web, string username, out SPClient.User user)
        {
            user = null;

            if (string.IsNullOrEmpty(username))
            {
                return(false);
            }

            try
            {
                user = web.EnsureUser(username);

                if (!user.IsPropertyAvailable("LoginName"))
                {
                    web.Context.Load(user);
                    web.Context.ExecuteQuery();
                }
            }
            catch { return(false); }

            return(true);
        }
Exemple #17
0
        /// <summary>
        /// Gets the tree node icon.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <returns></returns>
        public static string GetTreeNodeIcon(this SPClient.User user)
        {
            string image = string.Empty;

            switch (user.PrincipalType)
            {
            case Microsoft.SharePoint.Client.Utilities.PrincipalType.All:
                image = Constants.IMAGE_SITE_USER_EXCLAMATION;
                break;

            case Microsoft.SharePoint.Client.Utilities.PrincipalType.DistributionList:
                image = Constants.IMAGE_SITE_GROUP_DISTRIBUTION;
                break;

            case Microsoft.SharePoint.Client.Utilities.PrincipalType.None:
                image = Constants.IMAGE_SITE_USER_EXCLAMATION;
                break;

            case Microsoft.SharePoint.Client.Utilities.PrincipalType.SecurityGroup:
                image = Constants.IMAGE_SITE_GROUP_SECURITY;
                break;

            case Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup:
                image = Constants.IMAGE_SITE_GROUP;
                break;

            case Microsoft.SharePoint.Client.Utilities.PrincipalType.User:
                image = Constants.IMAGE_SITE_USER;
                break;

            default:
                break;
            }

            return(image);
        }
        public ProvisioningJobInformation[] GetProvisioningJobs(ProvisioningJobStatus status, String jobType = null, Boolean includeStream = false, string owner = null)
        {
            List <ProvisioningJobInformation> result = new List <ProvisioningJobInformation>();

            // Connect to the Infrastructural Site Collection
            using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(PnPPartnerPackSettings.InfrastructureSiteUrl))
            {
                // Get a reference to the target library
                Web  web  = context.Web;
                List list = web.Lists.GetByTitle(PnPPartnerPackConstants.PnPProvisioningJobs);

                StringBuilder sbCamlWhere = new StringBuilder();

                // Generate the CAML query filter accordingly to the requested statuses
                Boolean openCamlOr       = true;
                Int32   conditionCounter = 0;
                foreach (var statusFlagName in Enum.GetNames(typeof(ProvisioningJobStatus)))
                {
                    var statusFlag = (ProvisioningJobStatus)Enum.Parse(typeof(ProvisioningJobStatus), statusFlagName);
                    if ((statusFlag & status) == statusFlag)
                    {
                        conditionCounter++;
                        if (openCamlOr)
                        {
                            // Add the first <Or /> CAML statement
                            sbCamlWhere.Insert(0, "<Or>");
                            openCamlOr = false;
                        }
                        sbCamlWhere.AppendFormat(
                            @"<Eq>
                                <FieldRef Name='PnPProvisioningJobStatus' />
                                <Value Type='Text'>" + statusFlagName + @"</Value>
                            </Eq>");

                        if (conditionCounter >= 2)
                        {
                            // Close the current <Or /> CAML statement
                            sbCamlWhere.Append("</Or>");
                            openCamlOr = true;
                        }
                    }
                }
                // Remove the first <Or> CAML statement if it is useless
                if (conditionCounter == 1)
                {
                    sbCamlWhere.Remove(0, 4);
                }

                // Add the jobType filter, if any
                if (!String.IsNullOrEmpty(jobType))
                {
                    sbCamlWhere.Insert(0, "<And>");
                    sbCamlWhere.AppendFormat(
                        @"<Eq>
                        <FieldRef Name='PnPProvisioningJobType' />
                        <Value Type='Text'>" + jobType + @"</Value>
                    </Eq>");
                    sbCamlWhere.Append("</And>");
                }

                // Add the owner filter, if any
                if (!String.IsNullOrEmpty(owner))
                {
                    Microsoft.SharePoint.Client.User ownerUser = web.EnsureUser(owner);
                    context.Load(ownerUser, u => u.Id, u => u.Email, u => u.Title);
                    context.ExecuteQueryRetry();

                    sbCamlWhere.Insert(0, "<And>");
                    sbCamlWhere.AppendFormat(
                        @"<Eq>
                        <FieldRef Name='PnPProvisioningJobOwner' />
                        <Value Type='User'>" + ownerUser.Title + @"</Value>
                    </Eq>");
                    sbCamlWhere.Append("</And>");
                }

                CamlQuery query = new CamlQuery();
                query.ViewXml =
                    @"<View>
                        <Query>
                            <Where>" + sbCamlWhere.ToString() + @"
                            </Where>
                        </Query>
                    </View>";

                ListItemCollection items = list.GetItems(query);
                context.Load(items);
                context.ExecuteQueryRetry();

                foreach (var jobItem in items)
                {
                    result.Add(PrepareJobInformationFromSharePoint(context, jobItem, includeStream));
                }
            }
            return(result.ToArray());
        }
        public Guid EnqueueProvisioningJob(ProvisioningJob job)
        {
            // Prepare the Job ID
            Guid jobId = Guid.NewGuid();

            // Connect to the Infrastructural Site Collection
            using (var context = PnPPartnerPackContextProvider.GetAppOnlyClientContext(PnPPartnerPackSettings.InfrastructureSiteUrl))
            {
                // Set the initial status of the Job
                job.JobId  = jobId;
                job.Status = ProvisioningJobStatus.Pending;

                // Convert the current Provisioning Job into a Stream
                Stream stream = job.ToJsonStream();

                // Get a reference to the target library
                Web  web  = context.Web;
                List list = web.Lists.GetByTitle(PnPPartnerPackConstants.PnPProvisioningJobs);
                Microsoft.SharePoint.Client.File file = list.RootFolder.UploadFile(String.Format("{0}.job", jobId), stream, false);

                Microsoft.SharePoint.Client.User ownerUser = web.EnsureUser(job.Owner);
                context.Load(ownerUser);
                context.ExecuteQueryRetry();

                ListItem item = file.ListItemAllFields;

                item[PnPPartnerPackConstants.ContentTypeIdField]       = PnPPartnerPackConstants.PnPProvisioningJobContentTypeId;
                item[PnPPartnerPackConstants.TitleField]               = job.Title;
                item[PnPPartnerPackConstants.PnPProvisioningJobStatus] = ProvisioningJobStatus.Pending.ToString();
                item[PnPPartnerPackConstants.PnPProvisioningJobError]  = String.Empty;
                item[PnPPartnerPackConstants.PnPProvisioningJobType]   = job.GetType().FullName;

                FieldUserValue ownerUserValue = new FieldUserValue();
                ownerUserValue.LookupId = ownerUser.Id;
                item[PnPPartnerPackConstants.PnPProvisioningJobOwner] = ownerUserValue;

                item.Update();

                context.ExecuteQueryRetry();

                // Check if we need to enqueue a message in the Azure Storage Queue, as well
                // This happens when the Provisioning Job has to be executed in Continous mode
                if (PnPPartnerPackSettings.ContinousJobHandlers.ContainsKey(job.GetType()))
                {
                    // Get the storage account for Azure Storage Queue
                    CloudStorageAccount storageAccount =
                        CloudStorageAccount.Parse(PnPPartnerPackSettings.StorageQueueConnectionString);

                    // Get queue ... and create if it does not exist
                    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
                    CloudQueue       queue       = queueClient.GetQueueReference(PnPPartnerPackSettings.StorageQueueName);
                    queue.CreateIfNotExists();

                    // Add entry to queue
                    ContinousJobItem content = new ContinousJobItem {
                        JobId = job.JobId
                    };
                    queue.AddMessage(new CloudQueueMessage(JsonConvert.SerializeObject(content)));
                }
            }

            return(jobId);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                #region HighTrust Version
                ////get the access token and host so that we can use it for other requests on the site
                //var hostWeb = Page.Request["SPHostUrl"];

                ////passing null as the Windows identity so we can use it as an AppOnly request
                //using (var ctx = TokenHelper.GetS2SClientContextWithWindowsIdentity(new Uri(hostWeb), null))
                //{
                //    ctx.Load(ctx.Web, web => web.Title, user => user.CurrentUser);
                //    ctx.ExecuteQuery();
                //    Microsoft.SharePoint.Client.User curUser = ctx.Web.CurrentUser;

                //    //if the current user is me, then show the link to the clean up page
                //    if (curUser.IsSiteAdmin)
                //    {
                //        string link = "<a href='cleanapp.aspx'>Clean Up App</a>";
                //        CleanUpLit.Text = link;
                //    }

                //    //now query the list and get all the social events
                //    Response.Write(ctx.Web.Title);
                //}

                #endregion

                #region LowTrust Version

                if (!IsPostBack)
                {
                    //get the context token and host web
                    var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
                    var hostWeb      = Page.Request["SPHostUrl"];

                    //create the tokenContent from it so we can get an AccessToken to use for AppOnly cals
                    SharePointContextToken tokenContent = TokenHelper.ReadAndValidateContextToken(contextToken, Request.Url.Authority);

                    //get the Access tokenj
                    string accessToken = TokenHelper.GetAccessToken(tokenContent.RefreshToken, TokenHelper.SharePointPrincipal,
                                                                    new Uri(hostWeb).Authority, TokenHelper.GetRealmFromTargetUrl(new Uri(hostWeb))).AccessToken;

                    //now store it in view state so we can call out to other pages in our app with it
                    ViewState[HDN_HOST_WEB]  = hostWeb;
                    ViewState[HDN_ACC_TOKEN] = accessToken;

                    //write it out to hidden so that it can be used by client code
                    //Url encode the hostWeb so it can be passed to REST endpoint and successfully parsed (otherwise the ":" in the URL blocks it)
                    hiddenLit.Text = GetHiddenHtml(HDN_HOST_WEB, HttpUtility.UrlEncode(hostWeb)) + GetHiddenHtml(HDN_ACC_TOKEN, accessToken);

                    // The following code gets the client context and Title property by using TokenHelper.
                    // To access other properties, the app may need to request permissions on the host web.
                    var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

                    using (var clientContext = spContext.CreateUserClientContextForSPHost())
                    //using (var clientContext = TokenHelper.GetClientContextWithAccessToken(hostWeb, accessToken))
                    {
                        clientContext.Load(clientContext.Web, web => web.Title, user => user.CurrentUser);
                        clientContext.ExecuteQuery();
                        Microsoft.SharePoint.Client.User curUser = clientContext.Web.CurrentUser;

                        //if the current user is me, then show the link to the clean up page
                        if (curUser.IsSiteAdmin)
                        {
                            CleanUpPnl.Visible = true;
                        }

                        ////now query the list and get all the social events
                        //Response.Write(clientContext.Web.Title);

                        #region SQL data test
                        ////TEST TO CHECK OUT DATABASE CONNECTIVITY
                        //SqlConnection cn = new SqlConnection(conStr);
                        //SqlCommand cm = new SqlCommand("tblObjectGraph");
                        //cm.Connection = cn;
                        //cm.CommandText = "select * from tblObjectGraph";
                        //SqlDataAdapter da = new SqlDataAdapter(cm);

                        //DataSet ds = new DataSet();
                        //da.Fill(ds);

                        //string data = string.Empty;
                        //foreach(DataRow dr in ds.Tables[0].Rows)
                        //{
                        //    data += "ID = " + ((double)dr["ObjectGraphID"]).ToString() + "; Url = " + (string)dr["ObjectGraphUrl"] + "; TwitterTags = " + (string)dr["TwitterTags"] + "<br/>";
                        //}

                        //Response.Write("Database data:<p>" + data + "</p>");
                        #endregion

                        #region IIS Info
                        //Response.Write("<p>PhysicalPath = " + Request.PhysicalPath + "<br/>" +
                        //    "PhysicalApplicationPath = " + Request.PhysicalApplicationPath + "<br/></p>");

                        //string vars = string.Empty;
                        //foreach (string key in Request.ServerVariables.Keys)
                        //{
                        //    vars += key + " = " + Request.ServerVariables[key] + "<br/>";
                        //}

                        //Response.Write("<p>Server Variables:</p><p>" + vars + "</p>");
                        #endregion
                    }
                }
                #endregion

                #region LowTrust VS 2012 Version
                // The following code gets the client context and Title property by using TokenHelper.
                // To access other properties, you may need to request permissions on the host web.

                //var contextToken = TokenHelper.GetContextTokenFromRequest(Page.Request);
                //var hostWeb = Page.Request["SPHostUrl"];

                //using (var clientContext = TokenHelper.GetClientContextWithContextToken(hostWeb, contextToken, Request.Url.Authority))
                //{
                //    clientContext.Load(clientContext.Web, web => web.Title, user => user.CurrentUser);
                //    clientContext.ExecuteQuery();
                //    Response.Write(clientContext.Web.Title);
                //}
                #endregion
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Response.Write("ERROR: " + ex.Message);
            }
        }
        public static void FillPeoplePickerValue(HiddenField peoplePickerHiddenField, Microsoft.SharePoint.Client.User user)
        {
            List <O365User> O365Users = new List <O365User>(1);

            O365Users.Add(new O365User()
            {
                Name = user.Title, Email = user.Email, Login = user.LoginName
            });
            peoplePickerHiddenField.Value = JsonConvert.SerializeObject(O365Users);
        }
Exemple #22
0
        public static void LoadSiteUsers(TreeNode parentNode, SPClient.List siteUserInfoList, MainBrowser form)
        {
            try
            {
                SPClient.CamlQuery query = new SPClient.CamlQuery();
                query.ViewXml = "<View><RowLimit>1000</RowLimit></View>";

                SPClient.ClientContext      ctx       = GetClientContext(parentNode);
                SPClient.ListItemCollection userItems = siteUserInfoList.GetItems(query);
                ctx.Load(userItems);
                ctx.ExecuteQuery();

                int total   = userItems.Count;
                int current = 0;

                foreach (SPClient.ListItem userListItem in userItems)
                {
                    SPClient.User principle = null;

                    if (userListItem.FieldValues.ContainsKey("Name") && siteUserInfoList.ParentWeb.ParseUser(userListItem["Name"].ToString(), out principle))
                    {
                        TreeNode node = parentNode.Nodes.Add(principle.LoginName);
                        node.Tag = principle;
                        node.ContextMenuStrip = form.mnContextItem;

                        switch (principle.PrincipalType)
                        {
                        case Microsoft.SharePoint.Client.Utilities.PrincipalType.All:
                            node.ImageKey         = Constants.IMAGE_SITE_USER_EXCLAMATION;
                            node.SelectedImageKey = Constants.IMAGE_SITE_USER_EXCLAMATION;
                            break;

                        case Microsoft.SharePoint.Client.Utilities.PrincipalType.DistributionList:
                            node.ImageKey         = Constants.IMAGE_SITE_GROUP_DISTRIBUTION;
                            node.SelectedImageKey = Constants.IMAGE_SITE_GROUP_DISTRIBUTION;
                            break;

                        case Microsoft.SharePoint.Client.Utilities.PrincipalType.None:
                            node.ImageKey         = Constants.IMAGE_SITE_USER_EXCLAMATION;
                            node.SelectedImageKey = Constants.IMAGE_SITE_USER_EXCLAMATION;
                            break;

                        case Microsoft.SharePoint.Client.Utilities.PrincipalType.SecurityGroup:
                            node.ImageKey         = Constants.IMAGE_SITE_GROUP_SECURITY;
                            node.SelectedImageKey = Constants.IMAGE_SITE_GROUP_SECURITY;
                            break;

                        case Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup:
                            node.ImageKey         = Constants.IMAGE_SITE_GROUP;
                            node.SelectedImageKey = Constants.IMAGE_SITE_GROUP;
                            break;

                        case Microsoft.SharePoint.Client.Utilities.PrincipalType.User:
                            node.ImageKey         = Constants.IMAGE_SITE_USER;
                            node.SelectedImageKey = Constants.IMAGE_SITE_USER;
                            break;

                        default:
                            break;
                        }
                    }

                    // Update progress
                    current++;
                    ItemLoaded(null, new ItemLoadedEventArgs()
                    {
                        TotalItem = total, CurrentItem = current
                    });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, form.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);

                AddLoadingNode(parentNode, LoadType.WebUsers);
            }
        }
Exemple #23
0
        protected void rdbList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!rdbList.Items[1].Enabled)
            {
                rdbList.Items[1].Attributes.Add("style", "color:grey");
            }

            if (!rdbList.Items[0].Enabled)
            {
                rdbList.Items[0].Attributes.Add("style", "color:grey");
            }

            ddlistSCA.Enabled = true;
            btnCreate.Enabled = true;
            ScriptManager.RegisterStartupScript(this, GetType(), "NoSCADefault", "document.getElementById('spanChangeOwnerOption').style.display = 'none';", true);

            siteURL = Page.Request["SPHostUrl"];

            if (rdbList.SelectedItem.Value == "myself")
            {
                ddlistSCA.Visible  = false;
                txtboxUser.Visible = true;


                var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
                using (var clientContext = spContext.CreateUserClientContextForSPHost())
                //var clientContext = GetContext(siteURL);
                //using (clientContext)
                {
                    clientContext.Load(clientContext.Web, web => web.Title, user => user.CurrentUser);
                    clientContext.ExecuteQuery();
                    Microsoft.SharePoint.Client.User currentUser = clientContext.Web.CurrentUser;

                    //txtboxUser.Text = currentUser.Title;
                    txtboxUser.Text = GetOthersUserName(currentUser);

                    ddSelectedUser.Text    = GetOthersUserEmail(currentUser);
                    ddSelectedUser.Enabled = false;
                }
            }

            if (rdbList.SelectedItem.Value == "manager")
            {
                ddlistSCA.Visible  = false;
                txtboxUser.Visible = true;

                var currentUserManager = GetCurrentUserManager();
                var clientContext      = GetContext(siteURL);
                using (clientContext)
                {
                    var manager = clientContext.Web.EnsureUser(currentUserManager);
                    clientContext.Load(manager);
                    clientContext.ExecuteQuery();
                    txtboxUser.Text = GetOthersUserName(manager);         //manager.Title;
                    //txtboxUser.Text = item.Value;
                    ddSelectedUser.Text    = GetOthersUserEmail(manager); //manager.Email;
                    ddSelectedUser.Enabled = false;
                }
            }

            if (rdbList.SelectedItem.Value == "sca")
            {
                try
                {
                    ddlistSCA.Visible  = true;
                    txtboxUser.Visible = false;
                    //var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
                    if (ddlistSCA.Items.Count <= 0)
                    {
                        var clientContext = GetContext(siteURL);
                        using (clientContext)
                        {
                            clientContext.Load(clientContext.Web);
                            clientContext.ExecuteQuery();
                            lblsitename.Text = clientContext.Web.Url;

                            clientContext.Load(clientContext.Site, user => user.Owner);
                            clientContext.ExecuteQuery();
                            User siteOwner = clientContext.Site.Owner;

                            List <PeoplePickerUser> peoplePickerSecondaryUsers = new List <PeoplePickerUser>(10);
                            UserCollection          userCollection             = clientContext.Web.SiteUsers;
                            clientContext.Load(userCollection);
                            clientContext.ExecuteQuery();
                            foreach (User user in userCollection)
                            {
                                if (user.IsSiteAdmin && !user.Title.Contains("Global Admin") && !user.Title.Contains("Company Administrator") && !user.Title.Contains("Service Account") && !user.Title.Contains("spositeadmins") && supportedDomain.Any(user.Email.ToLower().Contains) && !user.Title.Contains("SharePoint Service") && user.Email != siteOwner.Email)
                                {
                                    ddlistSCA.Items.Add(new System.Web.UI.WebControls.ListItem(GetOthersUserName(user), GetOthersUserEmail(user)));
                                }
                            }
                            if (ddlistSCA.Items.Count < 1)
                            {
                                ddlistSCA.Enabled = false;
                                btnCreate.Enabled = false;
                                ScriptManager.RegisterStartupScript(this, GetType(), "btnbg", "$('#btnCreate').css('background-color', '#0096D6');", true);
                                ScriptManager.RegisterStartupScript(this, GetType(), "btnfg", "$('#btnCreate').css('foreground-color', '#0096D6');", true);
                                ScriptManager.RegisterStartupScript(this, GetType(), "NoSCA", "document.getElementById('spanChangeOwnerOption').style.display = 'block';", true);
                            }
                            else
                            {
                                User owner = null;
                                owner = clientContext.Web.EnsureUser(ddlistSCA.SelectedValue);
                                var userSelectedSCA = clientContext.Web.EnsureUser(ddlistSCA.SelectedValue);
                                clientContext.Load(userSelectedSCA);
                                clientContext.ExecuteQuery();
                                ddSelectedUser.Text    = userSelectedSCA.Email;
                                ddSelectedUser.Enabled = false;
                            }
                        }
                    }
                    else
                    {
                        var clientContext = GetContext(siteURL);
                        using (clientContext)
                        {
                            User owner = null;
                            owner = clientContext.Web.EnsureUser(ddlistSCA.SelectedValue);
                            var userSelectedSCA = clientContext.Web.EnsureUser(ddlistSCA.SelectedValue);
                            clientContext.Load(userSelectedSCA);
                            clientContext.ExecuteQuery();
                            ddSelectedUser.Text    = userSelectedSCA.Email;
                            ddSelectedUser.Enabled = false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "exceptionMessage", "alert('" + ex.Message + "');", true);
                }
            }

            if (rdbList.SelectedItem.Value == "other")
            {
                txtboxUser.Visible          = false;
                ddlistSCA.Visible           = false;
                inputAdministrators.Visible = true;
            }

            // Hide loading gif
            img_ScaLoading.Visible = false;
        }
Exemple #24
0
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl);

            // Define the full Site Collection URL
            String siteUrl = String.Format("{0}{1}",
                                           PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14),
                                           job.RelativeUrl);

            using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext())
            {
                adminContext.RequestTimeout = Timeout.Infinite;

                // Configure the Site Collection properties
                SiteEntity newSite = new SiteEntity();
                newSite.Description          = job.Description;
                newSite.Lcid                 = (uint)job.Language;
                newSite.Title                = job.SiteTitle;
                newSite.Url                  = siteUrl;
                newSite.SiteOwnerLogin       = job.PrimarySiteCollectionAdmin;
                newSite.StorageMaximumLevel  = job.StorageMaximumLevel;
                newSite.StorageWarningLevel  = job.StorageWarningLevel;
                newSite.Template             = PnPPartnerPackSettings.DefaultSiteTemplate;
                newSite.TimeZoneId           = job.TimeZone;
                newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel;
                newSite.UserCodeWarningLevel = job.UserCodeWarningLevel;

                // Create the Site Collection and wait for its creation (we're asynchronous)
                var tenant = new Tenant(adminContext);
                tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin?

                Site site = tenant.GetSiteByUrl(siteUrl);
                Web  web  = site.RootWeb;

                adminContext.Load(site, s => s.Url);
                adminContext.Load(web, w => w.Url);
                adminContext.ExecuteQueryRetry();

                // Enable Secondary Site Collection Administrator
                if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin))
                {
                    Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin);
                    secondaryOwner.IsSiteAdmin = true;
                    secondaryOwner.Update();

                    web.SiteUsers.AddUser(secondaryOwner);
                    adminContext.ExecuteQueryRetry();
                }

                Console.WriteLine("Site \"{0}\" created.", site.Url);

                // Check if external sharing has to be enabled
                if (job.ExternalSharingEnabled)
                {
                    EnableExternalSharing(tenant, site);

                    // Enable External Sharing
                    Console.WriteLine("Enabled External Sharing for site \"{0}\".",
                                      site.Url);
                }
            }

            // Move to the context of the created Site Collection
            using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
            {
                Site site = clientContext.Site;
                Web  web  = site.RootWeb;

                clientContext.Load(site, s => s.Url);
                clientContext.Load(web, w => w.Url);
                clientContext.ExecuteQueryRetry();

                // Check if we need to enable PnP Partner Pack overrides
                if (job.PartnerPackExtensionsEnabled)
                {
                    // Enable Responsive Design
                    PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url);

                    Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".",
                                      site.Url);
                }

                // Check if the site has to be responsive
                if (job.ResponsiveDesignEnabled)
                {
                    // Enable Responsive Design
                    PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url);

                    Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".",
                                      site.Url);
                }

                // Apply the Provisioning Template
                Console.WriteLine("Applying Provisioning Template \"{0}\" to site.",
                                  job.ProvisioningTemplateUrl);

                // Determine the reference URLs and file names
                String templatesSiteUrl = PnPPartnerPackUtilities.GetSiteCollectionRootUrl(job.ProvisioningTemplateUrl);
                String templateFileName = job.ProvisioningTemplateUrl.Substring(job.ProvisioningTemplateUrl.LastIndexOf("/") + 1);

                using (ClientContext repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(templatesSiteUrl))
                {
                    // Configure the XML file system provider
                    XMLTemplateProvider provider =
                        new XMLSharePointTemplateProvider(
                            repositoryContext,
                            templatesSiteUrl,
                            PnPPartnerPackConstants.PnPProvisioningTemplates);

                    // Load the template from the XML stored copy
                    ProvisioningTemplate template = provider.GetTemplate(templateFileName);
                    template.Connector = provider.Connector;

                    // We do intentionally remove taxonomies, which are not supported
                    // in the AppOnly Authorization model
                    // For further details, see the PnP Partner Pack documentation
                    ProvisioningTemplateApplyingInformation ptai =
                        new ProvisioningTemplateApplyingInformation();

                    // Write provisioning steps on console log
                    ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType) {
                        Console.WriteLine("{0} - {1}", messageType, messageType);
                    };
                    ptai.ProgressDelegate += delegate(string message, int step, int total) {
                        Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message);
                    };

                    ptai.HandlersToProcess ^=
                        OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups;

                    // Configure template parameters
                    if (job.TemplateParameters != null)
                    {
                        foreach (var key in job.TemplateParameters.Keys)
                        {
                            if (job.TemplateParameters.ContainsKey(key))
                            {
                                template.Parameters[key] = job.TemplateParameters[key];
                            }
                        }
                    }

                    web.ApplyProvisioningTemplate(template, ptai);
                }

                Console.WriteLine("Applyed Provisioning Template \"{0}\" to site.",
                                  job.ProvisioningTemplateUrl);
            }
        }
        private void CreateSiteCollection(SiteCollectionProvisioningJob job)
        {
            Console.WriteLine("Creating Site Collection \"{0}\".", job.RelativeUrl);

            // Define the full Site Collection URL
            String siteUrl = String.Format("{0}{1}",
                                           PnPPartnerPackSettings.InfrastructureSiteUrl.Substring(0, PnPPartnerPackSettings.InfrastructureSiteUrl.IndexOf("sharepoint.com/") + 14),
                                           job.RelativeUrl);

            // Load the template from the source Templates Provider
            if (!String.IsNullOrEmpty(job.TemplatesProviderTypeName))
            {
                ProvisioningTemplate template = null;

                var templatesProvider = PnPPartnerPackSettings.TemplatesProviders[job.TemplatesProviderTypeName];
                if (templatesProvider != null)
                {
                    template = templatesProvider.GetProvisioningTemplate(job.ProvisioningTemplateUrl);
                }

                if (template != null)
                {
                    using (var adminContext = PnPPartnerPackContextProvider.GetAppOnlyTenantLevelClientContext())
                    {
                        adminContext.RequestTimeout = Timeout.Infinite;

                        // Configure the Site Collection properties
                        SiteEntity newSite = new SiteEntity();
                        newSite.Description         = job.Description;
                        newSite.Lcid                = (uint)job.Language;
                        newSite.Title               = job.SiteTitle;
                        newSite.Url                 = siteUrl;
                        newSite.SiteOwnerLogin      = job.PrimarySiteCollectionAdmin;
                        newSite.StorageMaximumLevel = job.StorageMaximumLevel;
                        newSite.StorageWarningLevel = job.StorageWarningLevel;

                        // Use the BaseSiteTemplate of the template, if any, otherwise
                        // fallback to the pre-configured site template (i.e. STS#0)
                        newSite.Template = !String.IsNullOrEmpty(template.BaseSiteTemplate) ?
                                           template.BaseSiteTemplate :
                                           PnPPartnerPackSettings.DefaultSiteTemplate;

                        newSite.TimeZoneId           = job.TimeZone;
                        newSite.UserCodeMaximumLevel = job.UserCodeMaximumLevel;
                        newSite.UserCodeWarningLevel = job.UserCodeWarningLevel;

                        // Create the Site Collection and wait for its creation (we're asynchronous)
                        var tenant = new Tenant(adminContext);
                        tenant.CreateSiteCollection(newSite, true, true); // TODO: Do we want to empty Recycle Bin?

                        Site site = tenant.GetSiteByUrl(siteUrl);
                        Web  web  = site.RootWeb;

                        adminContext.Load(site, s => s.Url);
                        adminContext.Load(web, w => w.Url);
                        adminContext.ExecuteQueryRetry();

                        // Enable Secondary Site Collection Administrator
                        if (!String.IsNullOrEmpty(job.SecondarySiteCollectionAdmin))
                        {
                            Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(job.SecondarySiteCollectionAdmin);
                            secondaryOwner.IsSiteAdmin = true;
                            secondaryOwner.Update();

                            web.SiteUsers.AddUser(secondaryOwner);
                            adminContext.ExecuteQueryRetry();
                        }

                        Console.WriteLine("Site \"{0}\" created.", site.Url);

                        // Check if external sharing has to be enabled
                        if (job.ExternalSharingEnabled)
                        {
                            EnableExternalSharing(tenant, site);

                            // Enable External Sharing
                            Console.WriteLine("Enabled External Sharing for site \"{0}\".",
                                              site.Url);
                        }
                    }

                    // Move to the context of the created Site Collection
                    using (ClientContext clientContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(siteUrl))
                    {
                        clientContext.RequestTimeout = Timeout.Infinite;

                        Site site = clientContext.Site;
                        Web  web  = site.RootWeb;

                        clientContext.Load(site, s => s.Url);
                        clientContext.Load(web, w => w.Url);
                        clientContext.ExecuteQueryRetry();

                        // Check if we need to enable PnP Partner Pack overrides
                        if (job.PartnerPackExtensionsEnabled)
                        {
                            // Enable Responsive Design
                            PnPPartnerPackUtilities.EnablePartnerPackOnSite(site.Url);

                            Console.WriteLine("Enabled PnP Partner Pack Overrides on site \"{0}\".",
                                              site.Url);
                        }

                        // Check if the site has to be responsive
                        if (job.ResponsiveDesignEnabled)
                        {
                            // Enable Responsive Design
                            PnPPartnerPackUtilities.EnableResponsiveDesignOnSite(site.Url);

                            Console.WriteLine("Enabled Responsive Design Template to site \"{0}\".",
                                              site.Url);
                        }

                        // Apply the Provisioning Template
                        Console.WriteLine("Applying Provisioning Template \"{0}\" to site.",
                                          job.ProvisioningTemplateUrl);

                        // We do intentionally remove taxonomies, which are not supported
                        // in the AppOnly Authorization model
                        // For further details, see the PnP Partner Pack documentation
                        ProvisioningTemplateApplyingInformation ptai =
                            new ProvisioningTemplateApplyingInformation();

                        // Write provisioning steps on console log
                        ptai.MessagesDelegate += delegate(string message, ProvisioningMessageType messageType)
                        {
                            Console.WriteLine("{0} - {1}", messageType, messageType);
                        };
                        ptai.ProgressDelegate += delegate(string message, int step, int total)
                        {
                            Console.WriteLine("{0:00}/{1:00} - {2}", step, total, message);
                        };

                        // Exclude handlers not supported in App-Only
                        ptai.HandlersToProcess ^=
                            OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.TermGroups;
                        ptai.HandlersToProcess ^=
                            OfficeDevPnP.Core.Framework.Provisioning.Model.Handlers.SearchSettings;

                        // Configure template parameters
                        if (job.TemplateParameters != null)
                        {
                            foreach (var key in job.TemplateParameters.Keys)
                            {
                                if (job.TemplateParameters.ContainsKey(key))
                                {
                                    template.Parameters[key] = job.TemplateParameters[key];
                                }
                            }
                        }

                        // Fixup Title and Description
                        if (template.WebSettings != null)
                        {
                            template.WebSettings.Title       = job.SiteTitle;
                            template.WebSettings.Description = job.Description;
                        }

                        // Apply the template to the target site
                        web.ApplyProvisioningTemplate(template, ptai);

                        // Save the template information in the target site
                        var info = new SiteTemplateInfo()
                        {
                            TemplateProviderType = job.TemplatesProviderTypeName,
                            TemplateUri          = job.ProvisioningTemplateUrl,
                            TemplateParameters   = template.Parameters,
                            AppliedOn            = DateTime.Now,
                        };
                        var jsonInfo = JsonConvert.SerializeObject(info);
                        web.SetPropertyBagValue(PnPPartnerPackConstants.PropertyBag_TemplateInfo, jsonInfo);

                        // Set site policy template
                        if (!String.IsNullOrEmpty(job.SitePolicy))
                        {
                            web.ApplySitePolicy(job.SitePolicy);
                        }

                        // Apply Tenant Branding, if requested
                        if (job.ApplyTenantBranding)
                        {
                            var brandingSettings = PnPPartnerPackUtilities.GetTenantBrandingSettings();

                            using (var repositoryContext = PnPPartnerPackContextProvider.GetAppOnlyClientContext(
                                       PnPPartnerPackSettings.InfrastructureSiteUrl))
                            {
                                var brandingTemplate = BrandingJobHandler.PrepareBrandingTemplate(repositoryContext, brandingSettings);

                                // Fixup Title and Description
                                if (brandingTemplate != null)
                                {
                                    if (brandingTemplate.WebSettings != null)
                                    {
                                        brandingTemplate.WebSettings.Title       = job.SiteTitle;
                                        brandingTemplate.WebSettings.Description = job.Description;
                                    }

                                    // TO-DO: Need to handle exception here as there are multiple webs inside this where
                                    BrandingJobHandler.ApplyBrandingOnWeb(web, brandingSettings, brandingTemplate);
                                }
                            }
                        }


                        Console.WriteLine("Applied Provisioning Template \"{0}\" to site.",
                                          job.ProvisioningTemplateUrl);
                    }
                }
            }
        }
Exemple #26
0
        public static void FillPeoplePickerValue(HiddenField peoplePickerHiddenField, Microsoft.SharePoint.Client.User user)
        {
            List <PeoplePickerUser> peoplePickerUsers = new List <PeoplePickerUser>(1);

            peoplePickerUsers.Add(new PeoplePickerUser()
            {
                Name = user.Title, Email = user.Email, Login = user.LoginName
            });
            peoplePickerHiddenField.Value = JsonHelper.Serialize <List <PeoplePickerUser> >(peoplePickerUsers);
        }
Exemple #27
0
        //public static string GetUserUrl(this SPClient.User user)
        //{
        //    return null;
        //}

        public static string GetSettingsUrl(this SPClient.User user)
        {
            // <sitecollection|web>/_layouts/userdisp.aspx?ID=10
            return(string.Format("{0}/_layouts/userdisp.aspx?ID={1}&Force=True", user.Context.Url, user.Id));
        }
        protected override async Task ActivateAsync()
        {
            var contactListName  = "Contact List";
            var taskListName     = "Onboarding Tasks";
            var documentListName = "Documents";

            var contacts = new List <string> {
                "Thomas,Mod,[email protected],112, Admin",
                "David,De Gea,[email protected],113, Goal Keeper",
                "Luke,Shaw,[email protected],114, Left Back"
            };

            var tasks = new List <string> {
                $"Greeting to everyone;[email protected]; {DateTime.Now.ToString()};{DateTime.Now.AddHours(4).ToString()}"
            };

            var spUrl  = AppInstance.Properties.ContextParams.EnsureContextParamStringValue(Omnia.Fx.SharePoint.Constants.Parameters.SPUrl);
            var ctx    = SharePointClientContextProvider.CreateClientContext(spUrl);
            var spSite = ctx.Site;

            var contactList     = ctx.Web.Lists.GetByTitle(contactListName);
            var taskList        = ctx.Web.Lists.GetByTitle(taskListName);
            var documentList    = ctx.Web.Lists.GetByTitle(documentListName);
            var documentFolders = documentList.RootFolder.Folders;
            var web             = ctx.Web;

            ctx.Load(contactList);
            ctx.Load(taskList);
            ctx.Load(documentList);
            ctx.Load(documentFolders);
            ctx.Load(web);

            await ctx.ExecuteQueryAsync();

            //Add data to contact list
            foreach (var contact in contacts)
            {
                var itemCreation = new ListItemCreationInformation();
                var oContact1    = contactList.AddItem(itemCreation);

                oContact1["First_x0020_Name"]   = contact.Split(',')[0];
                oContact1["Last_x0020_Name"]    = contact.Split(',')[1];
                oContact1["Email"]              = contact.Split(',')[2];
                oContact1["Phone_x0020_number"] = contact.Split(',')[3];
                oContact1["Job_x0020_Title"]    = contact.Split(',')[3];
                oContact1.Update();
                await ctx.ExecuteQueryAsync();
            }

            //Add data to task list
            foreach (var task in tasks)
            {
                Microsoft.SharePoint.Client.User user = ctx.Web.EnsureUser(task.Split(';')[1]);
                ctx.Load(user);
                await ctx.ExecuteQueryAsync();

                var toBeAddUser = new FieldUserValue()
                {
                    LookupId = user.Id
                };

                var itemCreation = new ListItemCreationInformation();
                var oTask        = taskList.AddItem(itemCreation);

                oTask["Title"]     = task.Split(';')[0];
                oTask["Contact"]   = toBeAddUser;
                oTask["StartDate"] = task.Split(';')[2];
                oTask["DueDate"]   = task.Split(';')[3];
                oTask.Update();
                await ctx.ExecuteQueryAsync();
            }

            /// Documents list
            var srcUrl    = spUrl.Substring(0, spUrl.LastIndexOf("/sites"));
            var srcCtx    = SharePointClientContextProvider.CreateClientContext($"{srcUrl}/sites/onboarding-source");
            var camlQuery = CamlQuery.CreateAllItemsQuery();
            var srcList   = srcCtx.Web.Lists.GetByTitle("Documents");
            var srcItems  = srcList.GetItems(camlQuery);

            srcCtx.Load(srcList, l => l.RootFolder, l => l.RootFolder.Folders);
            srcCtx.Load(srcItems, items => items.Include(i => i.File));
            await srcCtx.ExecuteQueryAsync();

            foreach (var folder in srcList.RootFolder.Folders)
            {
                var existedFolder = documentFolders.FirstOrDefault(f => f.Name == folder.Name);
                var folderUrl     = "";
                if (existedFolder == null)
                {
                    documentList.EnableFolderCreation = true;
                    documentList.Update();
                    await ctx.ExecuteQueryAsync();

                    ListItemCreationInformation folderCreationInfo = new ListItemCreationInformation();
                    folderCreationInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
                    folderCreationInfo.LeafName             = folder.Name;

                    var newItem = documentList.AddItem(folderCreationInfo);
                    newItem["Title"] = folder.Name;
                    newItem.Update();
                    await ctx.ExecuteQueryAsync();

                    ctx.Load(newItem);
                    await ctx.ExecuteQueryAsync();

                    folderUrl = newItem.FieldValues["FileRef"].ToString();
                }
                else
                {
                    folderUrl = existedFolder.ServerRelativeUrl;
                }
                //var srcItem = srcItems.FirstOrDefault(item => item.FieldValues["FileLeafRef"])
                var folderItems = folder.Files;
                srcCtx.Load(folderItems);
                await srcCtx.ExecuteQueryAsync();

                foreach (var file in folderItems)
                {
                    var fileStream = file.OpenBinaryStream();
                    await srcCtx.ExecuteQueryAsync();

                    var fileCreationInfo = new FileCreationInformation();
                    fileCreationInfo.ContentStream = fileStream.Value;
                    fileCreationInfo.Overwrite     = true;
                    Uri result = null;
                    if (Uri.TryCreate(new Uri(ctx.Web.Url), folderUrl, out result))
                    {
                        fileCreationInfo.Url = result.ToString() + "/" + file.Name;
                    }
                    Microsoft.SharePoint.Client.File uploadFile = documentList.RootFolder.Files.Add(fileCreationInfo);
                    uploadFile.Update();

                    await ctx.ExecuteQueryAsync();

                    if (file.Title != "" && file.Title != null)
                    {
                        uploadFile.ListItemAllFields["Title"] = file.Title;
                        uploadFile.Update();
                        await ctx.ExecuteQueryAsync();
                    }
                }
            }
        }
Exemple #29
0
        private void AddUsers(string siteName, string siteUrl, frm_Data_User userForm)
        {
            ClientContext clientContext = SharePoint.GetClient(siteUrl, frm_Main_Menu.username, frm_Main_Menu.password);

            Web web = clientContext.Web;

            // Instantiates the User Information List
            SP.List userList = web.SiteUserInfoList;

            // Get the current user
            SP.User user = web.CurrentUser;

            // Initialise row counter
            int rowNum = 0;

            // Create a new Caml Query
            CamlQuery camlQuery = new CamlQuery();

            // Set the XML
            camlQuery.ViewXml = "<View><Query>{0}</Query></View>";

            // Define a collection to store the list items in
            ListItemCollection collListItem = userList.GetItems(camlQuery);


            // Load in the items
            clientContext.Load(collListItem, icol => icol.Include(i => i.ContentType));
            clientContext.Load(collListItem);

            // Attempt to retreive the List Items
            try
            {
                clientContext.ExecuteQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }

            foreach (SP.ListItem oListItem in collListItem)
            {
                // Increment counter
                rowNum++;

                int id = (int)oListItem.FieldValues["ID"];

                object firstName  = oListItem.FieldValues["FirstName"];
                object lastName   = oListItem.FieldValues["LastName"];
                object fullName   = oListItem.FieldValues["Title"];
                object userName   = oListItem.FieldValues["UserName"];
                object email      = oListItem.FieldValues["EMail"];
                object sipAddress = oListItem.FieldValues["SipAddress"];

                object isSiteAdmin = oListItem.FieldValues["IsSiteAdmin"];
                object deleted     = oListItem.FieldValues["Deleted"];
                object hidden      = oListItem.FieldValues["UserInfoHidden"];
                object isActive    = oListItem.FieldValues["IsActive"];

                string ContentTypeName = oListItem.ContentType.Name;
                object guid            = oListItem.FieldValues["GUID"];

                DateTime          createDate = Convert.ToDateTime(oListItem.FieldValues["Created"]);
                SP.FieldUserValue author     = (SP.FieldUserValue)oListItem.FieldValues["Author"];
                string            createUser = author.LookupValue.ToString();

                DateTime          modifyDate = Convert.ToDateTime(oListItem.FieldValues["Modified"]);
                SP.FieldUserValue editor     = (SP.FieldUserValue)oListItem.FieldValues["Editor"];
                string            modifyUser = editor.LookupValue.ToString();

                if (firstName != null)
                {
                    //System.Diagnostics.Debugger.Break();
                }

                userForm.AddRow
                (
                    rowNum,
                    id,
                    firstName,
                    lastName,
                    fullName,
                    userName,
                    email,
                    sipAddress,
                    isSiteAdmin,
                    deleted,
                    hidden,
                    isActive,
                    ContentTypeName,
                    guid,
                    createDate,
                    createUser,
                    modifyDate,
                    modifyUser
                );

                lbl_Row_Count.Text = rowNum.ToString() + " record(s) found";
                lbl_Row_Count.Refresh();

                if (rowNum >= nud_Row_Limit.Value && nud_Row_Limit.Value != 0)
                {
                    break;
                }
            }
        }
        private async static Task CreateInfrastructuralSiteCollectionAsync(SetupInformation info)
        {
            Uri infrastructureSiteUri = new Uri(info.InfrastructuralSiteUrl);
            Uri tenantAdminUri        = new Uri(infrastructureSiteUri.Scheme + "://" +
                                                infrastructureSiteUri.Host.Replace(".sharepoint.com", "-admin.sharepoint.com"));
            Uri sharepointUri = new Uri(infrastructureSiteUri.Scheme + "://" +
                                        infrastructureSiteUri.Host + "/");
            var siteUrl           = info.InfrastructuralSiteUrl.Substring(info.InfrastructuralSiteUrl.IndexOf("sharepoint.com/") + 14);
            var siteCreated       = false;
            var siteAlreadyExists = false;

            var accessToken = await AzureManagementUtility.GetAccessTokenSilentAsync(
                tenantAdminUri.ToString(), ConfigurationManager.AppSettings["O365:ClientId"]);

            AuthenticationManager am = new AuthenticationManager();

            using (var adminContext = am.GetAzureADAccessTokenAuthenticatedContext(
                       tenantAdminUri.ToString(), accessToken))
            {
                adminContext.RequestTimeout = Timeout.Infinite;

                var tenant = new Tenant(adminContext);

                // Check if the site already exists, and eventually removes it from the Recycle Bin
                if (tenant.CheckIfSiteExists(info.InfrastructuralSiteUrl, "Recycled"))
                {
                    tenant.DeleteSiteCollectionFromRecycleBin(info.InfrastructuralSiteUrl);
                }

                siteAlreadyExists = tenant.SiteExists(info.InfrastructuralSiteUrl);
                if (!siteAlreadyExists)
                {
                    // Configure the Site Collection properties
                    SiteEntity newSite = new SiteEntity();
                    newSite.Description          = "PnP Partner Pack - Infrastructural Site Collection";
                    newSite.Lcid                 = (uint)info.InfrastructuralSiteLCID;
                    newSite.Title                = newSite.Description;
                    newSite.Url                  = info.InfrastructuralSiteUrl;
                    newSite.SiteOwnerLogin       = info.InfrastructuralSitePrimaryAdmin;
                    newSite.StorageMaximumLevel  = 1000;
                    newSite.StorageWarningLevel  = 900;
                    newSite.Template             = "STS#0";
                    newSite.TimeZoneId           = info.InfrastructuralSiteTimeZone;
                    newSite.UserCodeMaximumLevel = 0;
                    newSite.UserCodeWarningLevel = 0;

                    // Create the Site Collection and wait for its creation (we're asynchronous)
                    tenant.CreateSiteCollection(newSite, true, true, (top) =>
                    {
                        if (top == TenantOperationMessage.CreatingSiteCollection)
                        {
                            var maxProgress = (100 / (Int32)SetupStep.Completed);
                            info.ViewModel.SetupProgress += 1;
                            if (info.ViewModel.SetupProgress >= maxProgress)
                            {
                                info.ViewModel.SetupProgress = maxProgress;
                            }
                        }
                        return(false);
                    });
                }
            }

            await Task.Delay(5000);

            using (var adminContext = am.GetAzureADAccessTokenAuthenticatedContext(
                       tenantAdminUri.ToString(), accessToken))
            {
                adminContext.RequestTimeout = Timeout.Infinite;

                var  tenant = new Tenant(adminContext);
                Site site   = tenant.GetSiteByUrl(info.InfrastructuralSiteUrl);
                Web  web    = site.RootWeb;

                adminContext.Load(site, s => s.Url);
                adminContext.Load(web, w => w.Url);
                adminContext.ExecuteQueryRetry();

                // Enable Secondary Site Collection Administrator
                if (!String.IsNullOrEmpty(info.InfrastructuralSiteSecondaryAdmin))
                {
                    Microsoft.SharePoint.Client.User secondaryOwner = web.EnsureUser(info.InfrastructuralSiteSecondaryAdmin);
                    secondaryOwner.IsSiteAdmin = true;
                    secondaryOwner.Update();

                    web.SiteUsers.AddUser(secondaryOwner);
                    adminContext.ExecuteQueryRetry();
                }
                siteCreated = true;
            }

            if (siteAlreadyExists || siteCreated)
            {
                accessToken = await AzureManagementUtility.GetAccessTokenSilentAsync(
                    sharepointUri.ToString(), ConfigurationManager.AppSettings["O365:ClientId"]);

                using (ClientContext clientContext = am.GetAzureADAccessTokenAuthenticatedContext(
                           info.InfrastructuralSiteUrl, accessToken))
                {
                    clientContext.RequestTimeout = Timeout.Infinite;

                    Site site = clientContext.Site;
                    Web  web  = site.RootWeb;

                    clientContext.Load(site, s => s.Url);
                    clientContext.Load(web, w => w.Url);
                    clientContext.ExecuteQueryRetry();

                    // Override settings within templates, before uploading them
                    UpdateProvisioningTemplateParameter("Responsive", "SPO-Responsive.xml",
                                                        "AzureWebSiteUrl", info.AzureWebAppUrl);
                    UpdateProvisioningTemplateParameter("Overrides", "PnP-Partner-Pack-Overrides.xml",
                                                        "AzureWebSiteUrl", info.AzureWebAppUrl);

                    // Apply the templates to the target site
                    ApplyProvisioningTemplate(web, "Infrastructure", "PnP-Partner-Pack-Infrastructure-Jobs.xml");
                    ApplyProvisioningTemplate(web, "Infrastructure", "PnP-Partner-Pack-Infrastructure-Templates.xml");
                    ApplyProvisioningTemplate(web, "", "PnP-Partner-Pack-Infrastructure-Contents.xml");

                    // We to it twice to force the content types, due to a small bug in the provisioning engine
                    ApplyProvisioningTemplate(web, "", "PnP-Partner-Pack-Infrastructure-Contents.xml");
                }
            }
            else
            {
                // TODO: Handle some kind of exception ...
            }
        }