/// <summary> /// Sends a Notification that the Site was created /// </summary> /// <param name="info"></param> protected void SendSuccessEmail(SiteInformation info) { //TODO CLEAN UP EMAILS try { StringBuilder _admins = new StringBuilder(); SuccessEmailMessage _message = new SuccessEmailMessage(); _message.SiteUrl = info.Url; _message.SiteOwner = info.SiteOwner.Name; _message.Subject = "Notification: Your new SharePoint site is ready"; _message.To.Add(info.SiteOwner.Name); foreach (var admin in info.AdditionalAdministrators) { _message.Cc.Add(admin.Name); _admins.Append(admin.Name); _admins.Append(" "); } _message.SiteAdmin = _admins.ToString(); EmailHelper.SendNewSiteSuccessEmail(_message); } catch (Exception ex) { Log.Error("Provisioning.Job.SiteProvisioningJob.SendSuccessEmail", "There was an error sending email. The Error Message: {0}, Exception: {1}", ex.Message, ex); } }
public string GetEmailSubject(SiteInformation site) { if (site == null) { throw new ArgumentNullException("site"); } var subject = string.Empty; //If already sent delete email, then will not send any email. if (site.ComplianceState.DeleteNotificationSent) { return(subject); } if (!site.ComplianceState.FirstLockNotificationSent) { subject = string.Format(SitePolicyResources.MailSubjectFirstLock, site.Url); } else if (!site.ComplianceState.SecondLockNotificationSent) { subject = string.Format(SitePolicyResources.MailSubjectSecondLock, site.Url); } else if (!site.ComplianceState.DeleteNotificationSent) { subject = string.Format(SitePolicyResources.MailSubjectDelete, site.Url); } return(subject); }
protected string CheckReservedNamespaces(SiteInformation siteRequest) { string returnValue = string.Empty; string siteUri = siteRequest.Url; // string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); // string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; siteUri = siteUri.Replace("https://cocacola.sharepoint.com/teams", "https://teams.coca-cola.com/sites"); siteUri = siteUri.Replace("https://cocacola.sharepoint.com/sites", "https://partner.coca-cola.com/sites"); using (var ctx = new ClientContext("https://teams.coca-cola.com/sites/MTMigration")) { ctx.AuthenticationMode = ClientAuthenticationMode.Default; System.Net.NetworkCredential cred = new System.Net.NetworkCredential("na\\X30965", "Friday$123456789"); ctx.Credentials = cred; List oList = ctx.Web.Lists.GetByTitle("SiteInventory"); CamlQuery camlQuery = new CamlQuery(); camlQuery.ViewXml = "<View><Query><Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + siteUri.Trim() + "</Value></Eq><Eq><FieldRef Name='MigrateSite' /><Value Type='Boolean'>1</Value></Eq></And></Where></Query><RowLimit>1</RowLimit></View>"; ListItemCollection collListItem = oList.GetItems(camlQuery); ctx.Load(collListItem); ctx.Load(oList); ctx.ExecuteQuery(); if (collListItem.Count > 0) { returnValue = siteUri; } } return(returnValue); }
protected void Notifiy(SiteInformation site, ClientContext clientContext, bool supressEmail) { if (site == null) { throw new ArgumentNullException("site"); } if (site.Administrators == null || site.Administrators.Count == 0) { return; } var mailSendTo = site.Administrators.Select(admin => admin.Email).ToList(); //Get Email Subject var subject = GetEmailSubject(site); if (string.IsNullOrEmpty(subject)) { return; } var body = GetEmailBody(site); //Sent Email if (mailSendTo.Count > 0 && !supressEmail) { MailUtility.SendEmail(clientContext, mailSendTo, null, subject, body); } SetNotifyFlag(site); }
protected void Page_Load(object sender, EventArgs e) { string[] siteInformation = new string[] {}; SiteInformation si = new SiteInformation(); siteInformation = si.getInformation(); //Page Title Page.Title = siteInformation[0] + " : معرفی سایت و خدمات"; if (Request.QueryString["Show"].ToString() != null) { switch (Request.QueryString["Show"].ToString()) { case "Gift800": ImageImage.ImageUrl = "~/images/about/Gift800.png"; break; default: Response.Redirect("~/Error.aspx?Code=NotFound"); break; } } else { Response.Redirect("~/Error.aspx?Code=NotFound"); } }
private void HandleSitePolicy(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { if(!string.IsNullOrWhiteSpace(siteRequest.SitePolicy)) { provisioningTemplate.SitePolicy = siteRequest.SitePolicy; } }
/// <summary> /// Member to handle the Url of custom actions /// </summary> /// <param name="provisioningTemplate"></param> /// <param name="siteRequest"></param> private void HandleCustomActions(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { if (provisioningTemplate.CustomActions != null) { //handle site custom actions foreach (var _siteCustomActions in provisioningTemplate.CustomActions.SiteCustomActions) { //IF ITS A SCRIPT SRC WE DO NOT WANT TO MODIFY if (!string.IsNullOrEmpty(_siteCustomActions.Url)) { var _escapedURI = Uri.EscapeUriString(siteRequest.Url); _siteCustomActions.Url = string.Format(_siteCustomActions.Url, _escapedURI); } } //handle web custom actions foreach( var _webActions in provisioningTemplate.CustomActions.WebCustomActions) { //IF ITS A SCRIPT SRC WE DO NOT WANT TO MODIFY if (!string.IsNullOrEmpty(_webActions.Url)) { var _escapedURI = Uri.EscapeUriString(siteRequest.Url); _webActions.Url = string.Format(_webActions.Url, _escapedURI); } } } }
/// <summary> /// Member to handle the Url of custom actions /// </summary> /// <param name="provisioningTemplate"></param> /// <param name="siteRequest"></param> private void HandleCustomActions(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { if (provisioningTemplate.CustomActions != null) { //handle site custom actions foreach (var _siteCustomActions in provisioningTemplate.CustomActions.SiteCustomActions) { //IF ITS A SCRIPT SRC WE DO NOT WANT TO MODIFY if (!string.IsNullOrEmpty(_siteCustomActions.Url)) { var _escapedURI = Uri.EscapeUriString(siteRequest.Url); _siteCustomActions.Url = string.Format(_siteCustomActions.Url, _escapedURI); } } //handle web custom actions foreach (var _webActions in provisioningTemplate.CustomActions.WebCustomActions) { //IF ITS A SCRIPT SRC WE DO NOT WANT TO MODIFY if (!string.IsNullOrEmpty(_webActions.Url)) { var _escapedURI = Uri.EscapeUriString(siteRequest.Url); _webActions.Url = string.Format(_webActions.Url, _escapedURI); } } } }
private void HandleSitePolicy(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { if (!string.IsNullOrWhiteSpace(siteRequest.SitePolicy)) { provisioningTemplate.SitePolicy = siteRequest.SitePolicy; } }
protected void Page_Load(object sender, EventArgs e) { string[] siteInformation = new string[]{}; SiteInformation si = new SiteInformation(); siteInformation = si.getInformation(); //Page Title Page.Title = siteInformation[0] + " : معرفی سایت و خدمات"; if (Request.QueryString["Show"].ToString() != null) { switch (Request.QueryString["Show"].ToString()) { case "Gift800": ImageImage.ImageUrl = "~/images/about/Gift800.png"; break; default: Response.Redirect("~/Error.aspx?Code=NotFound"); break; } } else { Response.Redirect("~/Error.aspx?Code=NotFound"); } }
public SiteInformation Get() { var result = new SiteInformation(); var siteUrl = Request.GetQueryNameValuePairs().FirstOrDefault(p => p.Key == "siteUrl").Value; DbRepository.UsingContext(dbContext => { var site = dbContext.GetSite(siteUrl); if (site == null) { result.IsSuccess = false; result.Message = string.Format(UxResources.SiteRecordNotFound, siteUrl); } else { ILifeCycleHelper helper = new LifeCyclePolicy(); result.AudienceScope = site.AudienceScope; result.ExpireDate = site.ComplianceState.ExpireDate; result.NeedExtend = GovernanceWorkflowHelper.NeedExtend( helper.GetExpiredDate(site)); result.CanDecommission = site.ComplianceState.IsCompliant && !result.NeedExtend; DateTime tmp = site.ComplianceState.ExpireDate; site.ComplianceState.ExpireDate = DateTime.MinValue; var extendDate = helper.GetExpiredDate(site); site.ComplianceState.ExpireDate = tmp; result.IsSuccess = true; } }); return(result); }
private SiteInformation GetSiteInformation(string path) { var siteInfo = new SiteInformation(); var site = _siteManager.GetSiteByName(path); var applicationRoot = site.Applications.SingleOrDefault(a => a.Path == "/"); var virtualRoot = applicationRoot.VirtualDirectories.SingleOrDefault(v => v.Path == "/"); siteInfo.Name = site.Name; siteInfo.ApplicationPoolName = applicationRoot.ApplicationPoolName; siteInfo.PhysicalPath = virtualRoot.PhysicalPath; foreach (var siteBinding in site.Bindings) { siteInfo.BindingInformation.Add(new BindingInfo { BindingInformation = siteBinding.BindingInformation, Host = siteBinding.Host, Protocol = siteBinding.Protocol }); } return(siteInfo); }
public void ChangeComplianceStateToDefault(SiteInformation site) { if (site == null) { throw new ArgumentNullException("site"); } var status = site.ComplianceState; status.DeleteNotificationSentDate = DateTime.MinValue; status.DeleteNotificationSent = false; status.DeleteDate = DateTime.MinValue; status.LockedDate = DateTime.MinValue; status.FirstLockNotificationSentDate = DateTime.MinValue; status.FirstLockNotificationSent = false; status.IsLocked = false; status.IsReadonly = false; status.SecondLockNotificationSent = false; status.SecondLockNotificationSentDate = DateTime.MinValue; status.IsCompliant = true; }
protected void Page_Load(object sender, EventArgs e) { //check premissions AdminPremissions ap = new AdminPremissions(); bool AdminPremission = ap.getAdminPremissions(Convert.ToInt32(Session["UserId"]), "Admins"); if (!AdminPremission) { Response.Redirect("~/Error.aspx?Code=404"); } //Page Title string[] siteInformation = new string[] { }; SiteInformation si = new SiteInformation(); siteInformation = si.getInformation(); Page.Title = siteInformation[0] + " : مدیریت ادمین ها"; //insert log if (!IsPostBack) { AdminLogInsert ali = new AdminLogInsert(); ali.insertAdminLog(Convert.ToInt32(Session["UserId"]), 1100, 0, "0"); } }
public SiteInformation GetSiteRequestMock() { var _owner = new SiteUser() { Name = "*****@*****.**" }; //Add addtional Users List <SiteUser> _additionalAdmins = new List <SiteUser>(); SiteUser _admin1 = new SiteUser(); _admin1.Name = "*****@*****.**"; SiteUser _admin2 = new SiteUser(); _admin2.Name = "*****@*****.**"; _additionalAdmins.Add(_admin1); _additionalAdmins.Add(_admin2); var _siteInfo = new SiteInformation() { Title = "Test Title", Description = "Test Description", Template = "CT2", Url = "https://spsites.contoso.com/sites/B3", SitePolicy = "HBI", SiteOwner = _owner, AdditionalAdministrators = _additionalAdmins, EnableExternalSharing = true, SharePointOnPremises = true }; return(_siteInfo); }
public string GetEmailBody(SiteInformation site) { if (site == null) { throw new ArgumentNullException("site"); } var content = string.Empty; string deadline; var specifiedZone = TimeZoneInfo.FindSystemTimeZoneById(GovernanceWorkflowHelper.TimeZoneId); var timezone = "{0} (" + specifiedZone.StandardName + ")"; //eg: (Pacific Standard Time). if (!site.ComplianceState.FirstLockNotificationSent) { deadline = string.Format(CultureInfo.CurrentCulture, timezone, site.ComplianceState.LockedDate.ToShortDateString()); content = string.Format(SitePolicyResources.MailBodyFirstLock, deadline); } else if (!site.ComplianceState.SecondLockNotificationSent) { deadline = string.Format(CultureInfo.CurrentCulture, timezone, site.ComplianceState.LockedDate.ToShortDateString()); content = string.Format(SitePolicyResources.MailBodySecondLock, deadline); } else if (!site.ComplianceState.DeleteNotificationSent) { deadline = string.Format(CultureInfo.CurrentCulture, timezone, site.ComplianceState.DeleteDate.ToShortDateString()); content = string.Format(SitePolicyResources.MailBodyDelete, deadline); } return(content); }
//LockedDate will be displayed in first&second notification email //Extend LockedDate to no earlier than the email sent date if needed to avoid confusion private void ExtendOutdatedLockedDate(SiteInformation site) { var now = GovernanceWorkflowHelper.GetCurrentBusinessTime(); if (site.ComplianceState.LockedDate < now) { var lockDate = DateTime.MinValue; if (!site.ComplianceState.FirstLockNotificationSent) { lockDate = now.AddDays(GovernanceWorkflowHelper.FirstLockNotificationDays); } else if (!site.ComplianceState.SecondLockNotificationSent) { lockDate = now.AddDays(GovernanceWorkflowHelper.SecondLockNotificationDays); } if (lockDate == DateTime.MinValue) { return; } site.ComplianceState.LockedDate = lockDate; if (site.ComplianceState.ExpireDate < lockDate) { site.ComplianceState.ExpireDate = lockDate; } } }
public virtual GovernancePlan GetGovernancePlan(SiteInformation site) { // Add GetGovernnance Plan Logic Here var plan = site.IsExternalSharingEnabled ? extSharedTeamsPlan : extSharingOffTeamsPlan; return(plan); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); if (Environment.GetEnvironmentVariable("DB_CONNECTION") == "SQL") { services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer( Configuration.GetConnectionString("DefaultConnection"))); } else { services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite( Configuration.GetConnectionString("LocalConnection"))); } services.AddIdentity <IdentityUser, IdentityRole>() .AddDefaultUI(UIFramework.Bootstrap4) .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); var site = new SiteInformation( new AzureBlobSetings(Configuration.GetSection("AzureBlobSetings")["AccountName"], Configuration.GetSection("AzureBlobSetings")["AccountKey"], Configuration.GetSection("AzureBlobSetings")["ContainerName"])); services.AddSingleton <ISiteInformation>(site); services.AddSingleton <IAzureIoT>(new AzureIoT(site)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddLocalization(options => options.ResourcesPath = nameof(Resources)); services.AddMvc() .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix) .AddDataAnnotationsLocalization(); services.Configure <RequestLocalizationOptions>(options => { var supportedCultures = new List <CultureInfo> { new CultureInfo("en-US"), new CultureInfo("fr") }; options.DefaultRequestCulture = new RequestCulture("en-US"); options.SupportedCultures = supportedCultures; options.SupportedUICultures = supportedCultures; }); CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(Culture.FromLanguageToCulture(site.Settings.Language)); CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(Culture.FromLanguageToCulture(site.Settings.Language)); }
protected void Page_Load(object sender, EventArgs e) { //Page Title string[] siteInformation = new string[]{}; SiteInformation si = new SiteInformation(); siteInformation = si.getInformation(); Page.Title = siteInformation[0] + " : " + siteInformation[2]; }
public override IEnumerable <NoncomplianceType> GetNoncompliances(SiteInformation site) { if (IsCompliant(site)) { yield break; } yield return(NoncomplianceType.NoAdditionalSiteAdmin); }
public override IEnumerable <NoncomplianceType> GetNoncompliances(SiteInformation site) { if (IsCompliant(site)) { yield break; } yield return(NoncomplianceType.MissClassification); }
public override IEnumerable <NoncomplianceType> GetNoncompliances(SiteInformation site) { if (IsCompliant(site)) { yield break; } yield return(NoncomplianceType.MembershipReviewDelay); }
internal ProvisioningTemplate HandleProvisioningTemplate(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { this.HandleExternalSharing(provisioningTemplate, siteRequest); this.HandleSitePolicy(provisioningTemplate, siteRequest); this.HandleAdditionalAdministrators(provisioningTemplate, siteRequest); this.HandlePropertyBagEntries(provisioningTemplate, siteRequest); this.HandleCustomActions(provisioningTemplate, siteRequest); return provisioningTemplate; }
protected void Page_Load(object sender, EventArgs e) { //Page Title string[] siteInformation = new string[] {}; SiteInformation si = new SiteInformation(); siteInformation = si.getInformation(); Page.Title = siteInformation[0] + " : " + siteInformation[2]; }
private void HandleAdditionalAdministrators(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { foreach(var _Admin in siteRequest.AdditionalAdministrators) { User _user = new User(); _user.Name = _Admin.Name; provisioningTemplate.Security.AdditionalOwners.Add(_user); } }
public SiteEditMetadata SetExternalSharing(SiteEditMetadata metadata) { try { if (!metadata.SharePointOnPremises) { string _sharingStatus = string.Empty; ConfigManager _manager = new ConfigManager(); var _tenantAdminUrl = _manager.GetAppSettingsKey("TenantAdminUrl"); AbstractSiteProvisioningService _siteService = new Office365SiteProvisioningService(); _siteService.Authentication = new AppOnlyAuthenticationTenant(); _siteService.Authentication.TenantAdminUrl = _tenantAdminUrl; SiteInformation _srInfo = new SiteInformation(); _srInfo.Url = metadata.Url; if (metadata.EnableExternalSharing) { _srInfo.EnableExternalSharing = true; _sharingStatus = "true"; } else { _srInfo.EnableExternalSharing = false; _sharingStatus = "false"; } _siteService.SetExternalSharing(_srInfo); Uri siteUri = new Uri(metadata.Url); string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(metadata.Url, accessToken)) { var _web = clientContext.Web; clientContext.Load(_web); //Update property bag as well _web.SetPropertyBagValue(SITE_PROPERTY_EXTERNAL_SHARING, _sharingStatus); metadata.Success = true; }; } } catch (Exception _ex) { var _message = string.Format("There was an error processing the request. {0}", _ex.Message); Log.Error("MetadataController.SetSiteExternalSharingStatus", "There was an error processing the request. Exception: {0}", _ex); metadata.ErrorMessage = _ex.Message; return(metadata); } return(metadata); }
public override bool IsCompliant(SiteInformation site) { var expiredDate = GetExpiredDate(site); var now = GovernanceWorkflowHelper.GetCurrentBusinessTime(); if ((expiredDate - now).TotalDays <= GovernanceWorkflowHelper.FirstLockNotificationDays) { return(false); } return(true); }
public MailSender(SiteInformation siteInformation) { _smtpServer = siteInformation.SmtpServer; _smtpPort = siteInformation.SmtPort; _smtpPort = _smtpPort == 0 ? 25 : _smtpPort; _fromAddress = siteInformation.SmtpUserName; _fromAddressTitle = siteInformation.SmtpUserName; _username = siteInformation.SmtpUserName; _password = siteInformation.SmtpPassword; _enableSsl = siteInformation.SmtpEnableSsl; _useDefaultCredentials = true; }
public virtual void Process(SiteInformation site) { var state = site.ComplianceState; var lockDate = GovernanceWorkflowHelper.GetCurrentBusinessTime() .AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["DefaultFirstLockNotificationDays"])); if (state.LockedDate > lockDate || state.LockedDate == DateTime.MinValue) { state.LockedDate = lockDate; } }
private SiteInformation GetApplicationInformation(string path) { var siteInfo = new SiteInformation(); var app = _siteManager.GetApplicationByPath(path); var virtualRoot = app.VirtualDirectories.SingleOrDefault(v => v.Path == "/"); siteInfo.Name = app.Path.Split('/').FirstOrDefault(); siteInfo.ApplicationPoolName = app.ApplicationPoolName; siteInfo.PhysicalPath = virtualRoot.PhysicalPath; return(siteInfo); }
/// <summary> /// Check to see if site exists /// </summary> /// <param name="siteRequest"></param> protected void ActivatePublishingFeature(SiteInformation siteRequest) { Uri siteUri = new Uri(siteRequest.Url); string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(siteRequest.Url, accessToken)) { // Push notifications feature activation // This needs to be here until another approach is found where it is not needed clientContext.Web.ActivateFeature(new Guid("22a9ef51737b4ff29346694633fe4416")); } }
public virtual void Enforce(SiteInformation site, bool supressEmail) { var state = site.ComplianceState; //If site is locked, then will not send any lock notification email, instead of sending delete email. if (site.ComplianceState.IsLocked && !site.ComplianceState.DeleteNotificationSent) { SetNotifyDeleteState(site); } if (GovernanceWorkflowHelper.NeedNotifyLock(state.LockedDate, state)) { ExtendOutdatedLockedDate(site); //Extend the LockedDate if it is earlier than current date } else if (GovernanceWorkflowHelper.NeedNotifyDelete(state.LockedDate, state)) { ExtendOutdatedDeleteDate(site); //Extend the DeleteDate if it is earlier than current date } if (state.IsCompliant) { ChangeComplianceStateToDefault(site); } var tenant = new Tenant(TenentClientContext); if (GovernanceWorkflowHelper.NeedNotifyLock(state.LockedDate, state)) { Notifiy(site, TenentClientContext, supressEmail); Log.Info(GetType().Name, "Notify Lock for site {0}", site.Url); } else if (GovernanceWorkflowHelper.NeedLock(state.LockedDate, state)) { tenant.SetSiteLockState(site.Url, SiteLockState.NoAccess, true); site.ComplianceState.IsLocked = true; Log.Info(GetType().Name, "Site {0} was locked", site.Url); } else if (GovernanceWorkflowHelper.NeedNotifyDelete(state.LockedDate, state)) { Notifiy(site, TenentClientContext, supressEmail); Log.Info(GetType().Name, "Notify Delete for site {0}", site.Url); } else if (GovernanceWorkflowHelper.NeedDelete(state.LockedDate)) { //set a flag to let us know that the site is deleted by Governance Job //site.DeletedBy = AutoSiteDeleteBy.GovernanceJob; tenant.DeleteSiteCollection(site.Url, true); //Set a value to indicate that the site was just deleted site.ComplianceState.DeleteDate = DateTime.MaxValue; Log.Info(GetType().Name, "Site {0} was deleted", site.Url); } TenentClientContext.ExecuteQueryRetry(); }
public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } SiteInformation siteInformation = db.SiteInformation.Find(id); if (siteInformation == null) { return(HttpNotFound()); } return(View(siteInformation)); }
public virtual int GetDefaultLifeTimeInMonth(SiteInformation site) { switch (site.AudienceScope) { case "Team": case "Project": return(6); case "Enterprise": case "Organization": return(12); } return(6); }
public MdlzCommonCustomizations(SiteInformation _request, ProvisioningTemplate _provTemplate, Template template) { request = _request; provTemplate = _provTemplate; if (appSettings == null) { IConfigurationFactory _cf = ConfigurationFactory.GetInstance(); IAppSettingsManager _manager = _cf.GetAppSetingsManager(); appSettings = _manager.GetAppSettings(); } Authentication = new AppOnlyAuthenticationSite(); Authentication.SiteUrl = _request.Url; }
private void HandlePropertyBagEntries(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { Dictionary<string, string> _props = JsonConvert.DeserializeObject<Dictionary<string, string>>(siteRequest.SiteMetadataJson); if(_props != null) { foreach(var prop in _props) { PropertyBagEntry _pb = new PropertyBagEntry(); _pb.Key = prop.Key; _pb.Value = prop.Value; provisioningTemplate.PropertyBagEntries.Add(_pb); } } }
public OperationResult Post(SiteInformation data) { var result = new OperationResult(); try { var siteUrl = Request.GetQueryNameValuePairs().FirstOrDefault(p => p.Key == "siteUrl").Value; DbRepository.UsingContext(dbContext => { var site = dbContext.GetSite(siteUrl); if (site == null) { result.IsSuccess = false; result.Message = string.Format(UxResources.SiteRecordNotFound, siteUrl); } else { site.AudienceScope = data.AudienceScope; var status = site.ComplianceState; if (data.NeedExtend) { var now = GovernanceWorkflowHelper.GetCurrentBusinessTime(); var lockDate = now.AddDays(GovernanceWorkflowHelper.FirstLockNotificationDays); if (status.ExpireDate > lockDate || status.ExpireDate == DateTime.MinValue) { status.ExpireDate = lockDate; } if (status.LockedDate > lockDate || status.LockedDate == DateTime.MinValue) { status.LockedDate = lockDate; } } else if (data.IsExtend) { status.ExpireDate = data.ExtendDate; } dbContext.SaveChanges(); result.IsSuccess = true; } }); } catch (Exception e) { result.IsSuccess = false; result.Message = e.Message; } return(result); }
public string GenerateSiteUrl( SiteInformation siteRequest, Template template, bool avoidDuplicateUrls = false) { var url = template.HostPath; if(!url.EndsWith("/")) { url += "/"; } url += siteRequest.Title.UrlNameFromString(); return url; }
private void HandleExternalSharing(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { //EXTERNAL SHARING CUSTOM ACTION MUST BE DEFINED IN TEMPLATE. IF THE SITE REQUEST DOES NOT HAVE EXTERNAL SHARING ENABLE WE WILL REMOVE THE CUSTOM ACCTION if(!siteRequest.EnableExternalSharing) { if(provisioningTemplate.CustomActions != null) { //FIND THE CUSTOM ACTION CA_SITE_EXTERNALSHARING var _externalSharingCA = provisioningTemplate.CustomActions.SiteCustomActions.FirstOrDefault(t => t.Title == "CA_SITE_EXTERNALSHARING"); if(_externalSharingCA != null) { provisioningTemplate.CustomActions.SiteCustomActions.Remove(_externalSharingCA); } } } }
public void CreateNewSiteRequest(SiteInformation siteRequest) { siteRequest.EnumStatus = SiteRequestStatus.New; UsingContext(client => { try { Task<Task<Database>> _taskResult = Task.FromResult<Task<Database>>(this.GetOrCreateDatabaseAsync(client)); Database _db; if (!_taskResult.IsFaulted) { if (!_taskResult.Result.IsFaulted) { _db = _taskResult.Result.Result; var _dbCollectionTasks = Task.FromResult(this.GetOrCreateCollectionAsync(client, _db.SelfLink, DB_COLLECTION_ID)); if (!_dbCollectionTasks.Result.IsFaulted) { var _siteInfo = this.GetSiteRequestByUrl(client, _dbCollectionTasks.Result.Result.DocumentsLink, siteRequest.Url); if (_siteInfo == null) { var doc = this.SaveNewRequest(client, _dbCollectionTasks.Result.Result.SelfLink, siteRequest); } } } } } catch (DocumentClientException de) { Exception baseException = de.GetBaseException(); Log.Error("AzureDocDbRequestManager.CreateNewSiteRequest", "{0} error occurred: {1}, Message: {2}", de.StatusCode, de.Message, baseException.Message); } catch (Exception ex) { Exception baseException = ex.GetBaseException(); Log.Error("AzureDocDbRequestManager.CreateNewSiteRequest", "Error: {0}, Message: {1}", ex.Message, baseException.Message); } }); }
/// <summary> /// Internal Member to save a new site request /// </summary> /// <param name="client"></param> /// <param name="collectionLink"></param> /// <param name="info"></param> /// <returns></returns> private Document SaveNewRequest(DocumentClient client, string collectionLink, SiteInformation info ) { //If Settings are set to autoapprove then automatically approve the requests if (_manager.GetAppSettings().AutoApprove) { info.RequestStatus = SiteRequestStatus.Approved.ToString(); info.ApprovedDate = DateTime.Now; } else { info.RequestStatus = SiteRequestStatus.New.ToString(); } info.SubmitDate = DateTime.Now; var saveDocumentTask = Task.FromResult(client.CreateDocumentAsync(collectionLink, info)); Document document = null; if(!saveDocumentTask.IsFaulted) { document = saveDocumentTask.Result.Result; } return document; }
/// <summary> /// Internal Member to Update Request and Status properties Azure DocumentDB by url /// </summary> /// <param name="client"></param> /// <param name="selfLink"></param> /// <param name="request"></param> /// <param name="status"></param> /// <param name="message"></param> /// <returns></returns> private Document UpdateSiteRequestStatusByUrl(DocumentClient client, string selfLink, SiteInformation request, SiteRequestStatus status, string message) { dynamic _requestDocument = client.CreateDocumentQuery<Document>(selfLink).Where(d => d.Id == request.Id).AsEnumerable().FirstOrDefault(); Document _d = _requestDocument; //Cast to Document to get the Selflink property Document _dReturnResult = null; SiteInformation _requestToUpdate = _requestDocument; if(!string.IsNullOrEmpty(message)) { _requestToUpdate.RequestStatusMessage = message; } _requestToUpdate.EnumStatus = status; var savedRequestTask = Task.FromResult(client.ReplaceDocumentAsync(_d.SelfLink, _requestToUpdate)); if (!savedRequestTask.Result.IsFaulted) { _dReturnResult = savedRequestTask.Result.Result; } return _dReturnResult; }
public SiteEditMetadata SetExternalSharing(SiteEditMetadata metadata) { try { if (!metadata.SharePointOnPremises) { string _sharingStatus = string.Empty; ConfigManager _manager = new ConfigManager(); var _tenantAdminUrl = _manager.GetAppSettingsKey("TenantAdminUrl"); AbstractSiteProvisioningService _siteService = new Office365SiteProvisioningService(); _siteService.Authentication = new AppOnlyAuthenticationTenant(); _siteService.Authentication.TenantAdminUrl = _tenantAdminUrl; SiteInformation _srInfo = new SiteInformation(); _srInfo.Url = metadata.Url; if (metadata.EnableExternalSharing) { _srInfo.EnableExternalSharing = true; _sharingStatus = "true"; } else { _srInfo.EnableExternalSharing = false; _sharingStatus = "false"; } _siteService.SetExternalSharing(_srInfo); Uri siteUri = new Uri(metadata.Url); string realm = TokenHelper.GetRealmFromTargetUrl(siteUri); string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUri.Authority, realm).AccessToken; using (var clientContext = TokenHelper.GetClientContextWithAccessToken(metadata.Url, accessToken)) { var _web = clientContext.Web; clientContext.Load(_web); //Update property bag as well _web.SetPropertyBagValue(SITE_PROPERTY_EXTERNAL_SHARING, _sharingStatus); metadata.Success = true; }; } } catch (Exception _ex) { var _message = string.Format("There was an error processing the request. {0}", _ex.Message); Log.Error("MetadataController.SetSiteExternalSharingStatus", "There was an error processing the request. Exception: {0}", _ex); metadata.ErrorMessage = _ex.Message; return metadata; } return metadata; }
private void HandleParameters(ProvisioningTemplate provisioningTemplate, SiteInformation siteRequest) { if (siteRequest.SiteMetadataJson != null) { // Add dynamic properties Dictionary<string, string> _props = JsonConvert.DeserializeObject<Dictionary<string, string>>(siteRequest.SiteMetadataJson); if (_props != null) { foreach (var prop in _props) { provisioningTemplate.Parameters.Add("pnp_" + prop.Key, prop.Value); } } } // Add static properties provisioningTemplate.Parameters.Add("pnp_LCID", siteRequest.Lcid.ToString()); provisioningTemplate.Parameters.Add("pnp_Title", siteRequest.Title); provisioningTemplate.Parameters.Add("pnp_SafeTitle", siteRequest.Title.UrlNameFromString()); provisioningTemplate.Parameters.Add("pnp_Policy", siteRequest.SitePolicy); provisioningTemplate.Parameters.Add("pnp_ExternalSharing", siteRequest.EnableExternalSharing.ToString()); provisioningTemplate.Parameters.Add("pnp_TemplateName", siteRequest.Template); }
public void CreateNewSiteRequest(SiteInformation siteRequest) { Log.Info("SPSiteRequestManager.CreateNewSiteRequest", "Entering CreateNewSiteRequest requested url {0}", siteRequest.Url); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.CreateNewSiteRequest", _message); throw new DataStoreException(_message); } List list = _web.Lists.GetByTitle(SiteRequestList.TITLE); ListItemCreationInformation _listItemCreation = new ListItemCreationInformation(); ListItem _record = list.AddItem(_listItemCreation); _record[SiteRequestFields.TITLE] = siteRequest.Title; _record[SiteRequestFields.DESCRIPTION_NAME] = siteRequest.Description; _record[SiteRequestFields.TEMPLATE_NAME] = siteRequest.Template; _record[SiteRequestFields.URL_NAME] = siteRequest.Url; _record[SiteRequestFields.LCID_NAME] = siteRequest.Lcid; _record[SiteRequestFields.TIMEZONE_NAME] = siteRequest.TimeZoneId; _record[SiteRequestFields.POLICY_NAME] = siteRequest.SitePolicy; _record[SiteRequestFields.EXTERNALSHARING_NAME] = siteRequest.EnableExternalSharing; _record[SiteRequestFields.ONPREM_REQUEST_NAME] = siteRequest.SharePointOnPremises; _record[SiteRequestFields.BC_NAME] = siteRequest.BusinessCase; _record[SiteRequestFields.PROPS_NAME] = siteRequest.SiteMetadataJson; //If Settings are set to autoapprove then automatically approve the requests if(_manager.GetAppSettings().AutoApprove) { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.Approved.ToString(); _record[SiteRequestFields.APPROVEDDATE_NAME] = DateTime.Now; } else { _record[SiteRequestFields.PROVISIONING_STATUS_NAME] = SiteRequestStatus.New.ToString(); } FieldUserValue _siteOwner = FieldUserValue.FromUser(siteRequest.SiteOwner.Name); _record[SiteRequestFields.OWNER_NAME] = _siteOwner; //Additional Admins if(siteRequest.AdditionalAdministrators != null) { if (siteRequest.AdditionalAdministrators.Count > 0) { FieldUserValue[] _additionalAdmins = new FieldUserValue[siteRequest.AdditionalAdministrators.Count]; int _index = 0; foreach (SiteUser _user in siteRequest.AdditionalAdministrators) { FieldUserValue _adminFieldUser = FieldUserValue.FromUser(_user.Name); _additionalAdmins[_index] = _adminFieldUser; _index++; } _record[SiteRequestFields.ADD_ADMINS_NAME] = _additionalAdmins; } } _record.Update(); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "SPSiteRequestManager.CreateNewSiteRequest", _timespan.Elapsed); Log.Info("SPSiteRequestManager.CreateNewSiteRequest", PCResources.SiteRequestNew_Successful, siteRequest.Url); } ); }
/// <summary> /// Member to return SiteRequest from the SharePoint SiteRequest Repository /// </summary> /// <param name="camlQuery">Query Query to Execute</param> /// <returns></returns> private ICollection<SiteInformation> GetSiteRequestsByCaml(string camlQuery) { List<SiteInformation> _siteRequests = new List<SiteInformation>(); UsingContext(ctx => { Stopwatch _timespan = Stopwatch.StartNew(); var _camlQuery = new CamlQuery(); _camlQuery.ViewXml = camlQuery; Log.Info("SPSiteRequestManager.GetSiteRequestsByCaml", "Querying SharePoint Request Repository {0}, Caml Query {1}", SiteRequestList.LISTURL, _camlQuery.ViewXml); var _web = ctx.Web; ctx.Load(_web); if (!_web.ListExists(SiteRequestList.TITLE)) { var _message = String.Format("The List {0} does not exist in Site {1}", SiteRequestList.TITLE, _web.Url); Log.Fatal("SPSiteRequestManager.GetSiteRequestsByCaml", _message); throw new DataStoreException(_message); } var _list = ctx.Web.Lists.GetByTitle(SiteRequestList.TITLE); var _listItemCollection = _list.GetItems(_camlQuery); ctx.Load(_listItemCollection, eachItem => eachItem.Include( item => item, item => item[SiteRequestFields.TITLE], item => item[SiteRequestFields.DESCRIPTION_NAME], item => item[SiteRequestFields.TEMPLATE_NAME], item => item[SiteRequestFields.POLICY_NAME], item => item[SiteRequestFields.URL_NAME], item => item[SiteRequestFields.OWNER_NAME], item => item[SiteRequestFields.ADD_ADMINS_NAME], item => item[SiteRequestFields.LCID_NAME], item => item[SiteRequestFields.EXTERNALSHARING_NAME], item => item[SiteRequestFields.PROVISIONING_STATUS_NAME], item => item[SiteRequestFields.ONPREM_REQUEST_NAME], item => item[SiteRequestFields.LCID_NAME], item => item[SiteRequestFields.TIMEZONE_NAME], item => item[SiteRequestFields.BC_NAME], item => item[SiteRequestFields.PROPS_NAME], item => item[SiteRequestFields.STATUSMESSAGE_NAME])); ctx.ExecuteQuery(); _timespan.Stop(); Log.TraceApi("SharePoint", "SPSiteRequestManager.GetSiteRequestsByCaml", _timespan.Elapsed); foreach (ListItem _item in _listItemCollection) { var _site = new SiteInformation() { Title = _item.BaseGet(SiteRequestFields.TITLE), Description = _item.BaseGet(SiteRequestFields.DESCRIPTION_NAME), Template = _item.BaseGet(SiteRequestFields.TEMPLATE_NAME), SitePolicy = _item.BaseGet(SiteRequestFields.POLICY_NAME), Url = _item.BaseGet(SiteRequestFields.URL_NAME), SiteOwner = _item.BaseGetUser(SiteRequestFields.OWNER_NAME), AdditionalAdministrators = _item.BaseGetUsers(SiteRequestFields.ADD_ADMINS_NAME), EnableExternalSharing = _item.BaseGet<bool>(SiteRequestFields.EXTERNALSHARING_NAME), RequestStatus = _item.BaseGet(SiteRequestFields.PROVISIONING_STATUS_NAME), Lcid = _item.BaseGetUint(SiteRequestFields.LCID_NAME), TimeZoneId = _item.BaseGetInt(SiteRequestFields.TIMEZONE_NAME), SharePointOnPremises = _item.BaseGet<bool>(SiteRequestFields.ONPREM_REQUEST_NAME), BusinessCase = _item.BaseGet(SiteRequestFields.BC_NAME), SiteMetadataJson = _item.BaseGet(SiteRequestFields.PROPS_NAME), RequestStatusMessage = _item.BaseGet(SiteRequestFields.STATUSMESSAGE_NAME) }; _siteRequests.Add(_site); } }); return _siteRequests; }