Пример #1
0
        private void HandleItemUpdated(SPRemoteEventProperties properties)
        {
            using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
            {
                if (clientContext != null)
                {
                    List     requestList = clientContext.Web.Lists.GetById(properties.ItemEventProperties.ListId);
                    ListItem item        = requestList.GetItemById(properties.ItemEventProperties.ListItemId);
                    clientContext.Load(item);
                    clientContext.ExecuteQuery();

                    if (String.Compare(item[SiteRequestFields.State].ToString(), "Approved", true) == 0)
                    {
                        try
                        {
                            string         site_title       = item[SiteRequestFields.Title].ToString();
                            string         site_description = item[SiteRequestFields.Description].ToString();
                            string         site_template    = item[SiteRequestFields.Template].ToString();
                            string         site_url         = item[SiteRequestFields.Url].ToString();
                            SharePointUser site_owner       = LabHelper.BaseSetUser(clientContext, item, SiteRequestFields.Owner);
                            LabHelper.CreateSiteCollection(clientContext, site_url, site_template, site_title, site_description, site_owner.Email);
                            item[SiteRequestFields.State] = "COMPLETED";
                        }
                        catch (Exception ex)
                        {
                            item[SiteRequestFields.State]         = "ERROR";
                            item[SiteRequestFields.StatusMessage] = ex.Message;
                        }
                        item.Update();
                        clientContext.ExecuteQuery();
                    }
                }
            }
        }
 /// <summary>
 /// Determines if a user the can modify a clause.
 /// </summary>
 public bool UserCanModify(string userEmail, SharePointUser owner, List <SharePointUser> designees,
                           bool isUserAdmin, bool isLocked)
 {
     return(isUserAdmin || (!isLocked && (IsUserOwner(owner, userEmail) ||
                                          (designees != null && designees.Any() &&
                                           designees.Select(d => d.EMail == userEmail).Any()))));
 }
Пример #3
0
        public SharePointUser BuildExisting(int?id = null)
        {
            SharePointUser sharePointUser = Build();

            sharePointUser.Id = id.GetValueOrDefault(_uniqueId++);
            return(sharePointUser);
        }
Пример #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SharePointAccessInfo"/> class.
 /// </summary>
 /// <param name="webUrl">The web URL.</param>
 /// <param name="authenticationResult">The authentication result.</param>
 public SharePointAccessInfo(string webUrl, AuthenticationResult authenticationResult) : this(webUrl)
 {
     // Dont expose the refresh token on the client side!
     AccessToken  = authenticationResult.AccessToken;
     ExpiresOn    = authenticationResult.ExpiresOn;
     TenantId     = authenticationResult.TenantId;
     UserId       = authenticationResult.UserInfo.UniqueId;
     RefreshToken = authenticationResult.RefreshToken;
     UserEmail    = authenticationResult.UserInfo.DisplayableId;
     User         = new SharePointUser();
 }
Пример #5
0
        /// <summary>
        /// Used to create a User Object to SharePointUser
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public static SharePointUser BaseSetUser(ClientContext ctx, ListItem item, string field)
        {
            SharePointUser _owner     = new SharePointUser();
            var            _fieldUser = ((FieldUserValue)(item[field]));
            User           _user      = ctx.Web.EnsureUser(_fieldUser.LookupValue);

            ctx.Load(_user, u => u.LoginName, u => u.Email, u => u.PrincipalType, u => u.Title);
            ctx.ExecuteQuery();

            _owner.Email = _user.Email;
            _owner.Login = _user.LoginName;
            _owner.Name  = _user.Title;

            return(_owner);
        }
Пример #6
0
        protected void btnCreate_Click(object sender, EventArgs e)
        {
            var    spContext = SharePointContextProvider.Current.GetSharePointContext(Context);
            string newWebUrl = string.Empty;

            using (ClientContext ctx = spContext.CreateUserClientContextForSPHost())
            {
                SharePointUser currentUser;
                ctx.Load(ctx.Web.CurrentUser);
                ctx.ExecuteQuery();

                var user = ctx.Web.CurrentUser;
                currentUser = new SharePointUser()
                {
                    Email = user.Email,
                    Login = user.LoginName,
                    Name  = user.Title
                };


                var siteRequestInfo = new SiteRequestInformation()
                {
                    Title       = this.txtTitle.Text,
                    Description = this.txtDescription.Text,
                    EnumStatus  = SiteRequestStatus.New,
                    Template    = "STS#0",
                    SiteOwner   = currentUser,
                };

                siteRequestInfo.Url = string.Format(@"{0}{1}", this.lblBasePath.Text, siteRequestInfo.Title);
                LabHelper _helper = new LabHelper();
                _helper.AddRequest(siteRequestInfo, ctx);
            }


            Response.Redirect(Page.Request["SPHostUrl"]);
        }
Пример #7
0
 public FluentClauseBuilder WithEditorCalled(string title)
 {
     _editor = new FluentSharePointUserBuilder().WithTitle(title).BuildExisting();
     return(this);
 }
Пример #8
0
 public FluentClauseBuilder WithEditor(SharePointUser editor)
 {
     _editor = editor;
     return(this);
 }
Пример #9
0
 public FluentClauseBuilder WithAuthor(SharePointUser author)
 {
     _author = author;
     return(this);
 }
 private bool IsUserOwner(SharePointUser owner, string userEmail)
 {
     return(userEmail == owner.EMail);
 }
Пример #11
0
 public FluentGroupBuilder WithAuthorCalled(string title)
 {
     _author = new FluentSharePointUserBuilder().WithTitle(title).BuildExisting();
     return(this);
 }
Пример #12
0
        static void Main(string[] args)
        {
            // Determine the system connectivity mode based on the command line
            // arguments: -http, -tcp or -auto  (defaults to auto)
            ServiceBusEnvironment.SystemConnectivity.Mode = GetConnectivityMode(args);

            string serviceNamespace = ConfigurationManager.AppSettings["General.SBServiceNameSpace"];
            string issuerName       = ConfigurationManager.AppSettings["General.SBIssuerName"];
            string issuerSecret     = EncryptionUtility.Decrypt(ConfigurationManager.AppSettings["SBIssuerSecret"], ConfigurationManager.AppSettings["General.EncryptionThumbPrint"]);

            // create the service URI based on the service namespace
            Uri serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, "SharePointProvisioning");

            // create the credentials object for the endpoint
            TransportClientEndpointBehavior sharedSecretServiceBusCredential = new TransportClientEndpointBehavior();

            sharedSecretServiceBusCredential.TokenProvider = TokenProvider.CreateSharedSecretTokenProvider(issuerName, issuerSecret);

            // create the channel factory loading the configuration
            ChannelFactory <ISharePointProvisioningChannel> channelFactory = new ChannelFactory <ISharePointProvisioningChannel>("RelayEndpoint", new EndpointAddress(serviceUri));

            // apply the Service Bus credentials
            channelFactory.Endpoint.Behaviors.Add(sharedSecretServiceBusCredential);

            // create and open the client channel
            ISharePointProvisioningChannel channel = channelFactory.CreateChannel();

            channel.Open();

            SharePointProvisioningData sharePointProvisioningData = new SharePointProvisioningData();

            sharePointProvisioningData.Title              = "Test site on-premises";
            sharePointProvisioningData.Url                = String.Format("{0}{1}", "https://bertonline.sharepoint.com/sites/", Guid.NewGuid().ToString());
            sharePointProvisioningData.Template           = "ContosoCollaboration";
            sharePointProvisioningData.Name               = "";
            sharePointProvisioningData.DataClassification = "HBI";

            SharePointUser[] owners = new SharePointUser[1];
            SharePointUser   owner  = new SharePointUser();

            owner.Login = "******";
            owner.Name  = "Kevin Cook";
            owner.Email = "*****@*****.**";
            owners[0]   = owner;
            sharePointProvisioningData.Owners = owners;

            channel.ProvisionSiteCollection(sharePointProvisioningData);

            //Console.WriteLine("Enter text to echo (or [Enter] to exit):");
            //string input = Console.ReadLine();
            //while (input != String.Empty)
            //{
            //    try
            //    {
            //        Console.WriteLine("Server echoed: {0}", channel.Echo(input));
            //    }
            //    catch (Exception e)
            //    {
            //        Console.WriteLine("Error: " + e.Message);
            //    }
            //    input = Console.ReadLine();
            //}
            Console.ReadLine();
            channel.Close();
            channelFactory.Close();
        }
Пример #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SharePointAccessInfo"/> class.
 /// </summary>
 public SharePointAccessInfo(string webUrl)
 {
     SPTenantUrl = webUrl;
     HostWebUrl  = webUrl;
     User        = new SharePointUser();
 }
Пример #14
0
        private void ProcessSiteRequest()
        {
            try
            {
                string generalSiteDirectoryUrl              = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryUrl");
                string generalSiteDirectoryListName         = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryListName");
                string generalSiteDirectoryProvisioningPage = RoleEnvironment.GetConfigurationSettingValue("General.SiteDirectoryProvisioningPage");
                string generalSiteCollectionUrl             = RoleEnvironment.GetConfigurationSettingValue("General.SiteCollectionUrl");
                string generalMailSMTPServer       = RoleEnvironment.GetConfigurationSettingValue("General.MailSMTPServer");
                string generalMailUser             = RoleEnvironment.GetConfigurationSettingValue("General.MailUser");
                string generalMailUserPassword     = RoleEnvironment.GetConfigurationSettingValue("General.MailUserPassword");
                string generalMailSiteRequested    = RoleEnvironment.GetConfigurationSettingValue("General.MailSiteRequested");
                string generalEncryptionThumbPrint = RoleEnvironment.GetConfigurationSettingValue("General.EncryptionThumbPrint");

                //Manager initiation
                SiteDirectoryManager siteDirectoryManager = new SiteDirectoryManager();

                //Decrypt mail password
                generalMailUserPassword = EncryptionUtility.Decrypt(generalMailUserPassword, generalEncryptionThumbPrint);

                // SharePoint context for the host web
                var           spContext            = SharePointContextProvider.Current.GetSharePointContext(Context);
                ClientContext hostWebClientContext = spContext.CreateAppOnlyClientContextForSPHost();

                // Object that contains data about the site collection we're gonna provision
                SharePointProvisioningData siteData = new SharePointProvisioningData();

                siteData.Url = String.Format("{0}{1}", generalSiteCollectionUrl, Guid.NewGuid().ToString());

                // Deal with the Title
                siteData.Title = txtTitle.Text;

                // Deal with the template
                siteData.Template = drlTemplate.SelectedItem.Value;

                // Deal with the data classification
                siteData.DataClassification = drlClassification.SelectedItem.Value;

                // Deal with the site name (empty for root)
                siteData.Name = "";

                // Deal with the site owners
                List <SharePointUser> ownersList = JsonUtility.Deserialize <List <SharePointUser> >(hdnAdministrators.Value);
                SharePointUser[]      owners     = new SharePointUser[ownersList.Count];
                List <String>         mailTo     = new List <string>(ownersList.Count);
                string ownerNames    = "";
                string ownerAccounts = "";

                int i = 0;
                foreach (SharePointUser owner in ownersList)
                {
                    owner.Login = StripUPN(owner.Login);
                    owners[i]   = owner;

                    mailTo.Add(owner.Email);

                    if (ownerNames.Length > 0)
                    {
                        ownerNames    = ownerNames + ", ";
                        ownerAccounts = ownerAccounts + ", ";
                    }
                    ownerNames    = ownerNames + owner.Name;
                    ownerAccounts = ownerAccounts + owner.Login;

                    i++;
                }
                siteData.Owners = owners;

#if (DEBUG)
                //In debug mode have the WCF call ignore certificate errors
                System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
                {
                    return(true);
                };
#endif
                // Provision site collection on the
                using (SharePointProvisioning.SharePointProvisioningServiceClient service = new SharePointProvisioning.SharePointProvisioningServiceClient())
                {
                    if (service.ProvisionSiteCollection(siteData))
                    {
                        string[] ownerLogins = new string[owners.Length];
                        int      j           = 0;
                        foreach (SharePointUser owner in owners)
                        {
                            ownerLogins[j] = owner.Login;
                            j++;
                        }

                        siteDirectoryManager.AddSiteDirectoryEntry(hostWebClientContext, hostWebClientContext.Web, generalSiteDirectoryUrl, generalSiteDirectoryProvisioningPage, generalSiteDirectoryListName, siteData.Title, siteData.Url, siteData.Template, ownerLogins);

                        string mailBody = String.Format(generalMailSiteRequested, siteData.Title, ownerNames, ownerAccounts);
                        MailUtility.SendEmail(generalMailSMTPServer, generalMailUser, generalMailUserPassword, mailTo, null, "Your SharePoint site request has been registered", mailBody);
                    }
                }

                if (Page.Request["IsDlg"].Equals("0", StringComparison.InvariantCultureIgnoreCase))
                {
                    // redirect to host web home page
                    Response.Redirect(Page.Request["SPHostUrl"]);
                }
                else
                {
                    // refresh the page from which the dialog was opened. Normally this is always the SPHostUrl
                    ClientScript.RegisterStartupScript(typeof(Default), "RedirectToSite", "navigateParent('" + Page.Request["SPHostUrl"] + "');", true);
                }
            }
            catch (Exception ex)
            {
                lblErrors.Text = String.Format("Error: {0} \n\r Stacktrace: {1}", ex.Message, ex.StackTrace);
            }
        }