/// <summary>Validates a macro.</summary> /// <param name="macroName">The macro to validate.</param> public static void ValidateMacro(string macroName) { string name = macroName; int index = name.IndexOf(":"); if (index > 0) { name = name.Substring(0, index); } switch (name) { case "SPWebScope": case "CurrentUserKey": case "Now": case "StartOfToday": case "StartOfTomorrow": case "StartOfThisWeek": case "StartOfNextWeek": case "StartOfWeekAfterNext": break; default: SlkCulture culture = new SlkCulture(); throw new SlkSettingsException(culture.Format(culture.Resources.InvalidMacro, macroName)); } }
void UpdateCachedDropBox() { StringBuilder errors = new StringBuilder(); dropBoxManager = new DropBoxManager(properties); foreach (DropBoxUpdate update in cachedDropBoxUpdates) { try { UpdateDropBoxPermissionsNow(update.State, update.User); } catch (Exception e) { properties.Store.LogException(e); errors.AppendFormat(SlkCulture.GetResources().ErrorSavingDropBoxPermissions, update.State, update.User.LoginName); } } if (errors.Length > 0) { throw new SafeToDisplayException(errors.ToString()); } dropBoxManager = null; }
/// <summary>Saves the assignment.</summary> /// <remarks> /// <para> /// When creating a self-assigned assignment, take care to ensure that /// <r>AssignmentProperties.AutoReturn</r> is <n>true</n>, otherwise the learner assignments /// will never reach /// <a href="Microsoft.SharePointLearningKit.LearnerAssignmentState.Enumeration.htm">LearnerAssignmentState.Final</a> /// state. /// </para> /// <para> /// <b>Security:</b>  If <pr>slkRole</pr> is /// <a href="Microsoft.SharePointLearningKit.SlkRole.Enumeration.htm">SlkRole.Instructor</a>, /// this operation fails if the <a href="SlkApi.htm#AccessingSlkStore">current user</a> doesn't /// have SLK /// <a href="Microsoft.SharePointLearningKit.SlkSPSiteMapping.InstructorPermission.Property.htm">instructor</a> /// permissions on <pr>destinationSPWeb</pr>. Also fails if the current user doesn't have access to the /// package/file. /// </para> /// </remarks> /// <param name="web">The <c>SPWeb</c> to create the assignment in.</param> /// <param name="slkRole">The <c>SlkRole</c> to use when creating the assignment. Use /// <c>SlkRole.Learner</c> to create a self-assigned assignment, i.e. an assignment with /// no instructors for which the current learner is the only learner. Otherwise, use /// <c>SlkRole.Instructor</c>.</param> public void Save(SPWeb web, SlkRole slkRole) { // Verify that the web is in the site if (web.Site.ID != Store.SPSiteGuid) { throw new InvalidOperationException(SlkCulture.GetResources().SPWebDoesNotMatchSlkSPSite); } if (Id == null) { SaveNewAssignment(web, slkRole); } else { UpdateAssignment(web); } if (customPropertiesItem != null) { customPropertiesItem["Title"] = Id.GetKey().ToString(); foreach (AssignmentProperty property in Properties) { customPropertiesItem[property.Name] = property.Value; } customPropertiesItem.ParentList.ParentWeb.AllowUnsafeUpdates = true; customPropertiesItem.Update(); } }
/// <summary> /// Gets the localized string representation in text format of a LearnerAssignmentState value. /// </summary> /// <param name="learnerAssignmentState">The <c>LearnerAssignmentState</c> value.</param> public static string GetLearnerAssignmentState(LearnerAssignmentState?learnerAssignmentState) { SlkCulture culture = new SlkCulture(); if (learnerAssignmentState == null) { return(culture.Resources.LearnerAssignmentStatusNotStarted); } else { switch (learnerAssignmentState.Value) { case LearnerAssignmentState.NotStarted: return(culture.Resources.LearnerAssignmentStatusNotStarted); case LearnerAssignmentState.Active: return(culture.Resources.LearnerAssignmentStatusActive); case LearnerAssignmentState.Completed: return(culture.Resources.LearnerAssignmentStatusCompleted); case LearnerAssignmentState.Final: return(culture.Resources.LearnerAssignmentStatusFinal); default: return(learnerAssignmentState.ToString()); } } }
void CheckUserIsLearner() { if (Assignment.Store.CurrentUserId != LearnerId) { throw new SafeToDisplayException(SlkCulture.GetResources().SubmitAssignmentNotLearner); } }
Exception InvalidTransitionException(LearnerAssignmentState oldStatus, LearnerAssignmentState newStatus) { SlkCulture culture = new SlkCulture(); string message = culture.Format(culture.Resources.LearnerAssignmentTransitionNotSupported, oldStatus, newStatus); return(new InvalidOperationException(message)); }
static void CreateDatabase(SlkSPSiteMapping mapping, string databaseName, string appPoolAccountName, string databaseSchema) { // restrict the characters in <databaseName> if (!Regex.Match(databaseName, @"^\w+$").Success) { throw new SafeToDisplayException(SlkCulture.GetResources().InvalidDatabaseName, databaseName); } // if <appPoolAccountName> is null, set it to the name of the application pool account // (e.g. "NT AUTHORITY\NETWORK SERVICE"); set <appPoolSid> to its SID byte[] appPoolSid = null; if (appPoolAccountName == null) { using (SPSite site = new SPSite(mapping.SPSiteGuid)) { appPoolAccountName = site.WebApplication.ApplicationPool.Username; } } NTAccount appPoolAccount = new NTAccount(appPoolAccountName); SecurityIdentifier securityId = (SecurityIdentifier)appPoolAccount.Translate(typeof(SecurityIdentifier)); appPoolSid = new byte[securityId.BinaryLength]; securityId.GetBinaryForm(appPoolSid, 0); SlkUtilities.ImpersonateAppPool(delegate() { CreateDatabase(mapping.DatabaseServerConnectionString, databaseName, mapping.DatabaseConnectionString, appPoolAccountName, appPoolSid, databaseSchema); }); }
/// <summary>Initializes a new instance of <see cref="DropBoxManager"/>.</summary> public DropBoxManager(AssignmentProperties assignmentProperties) { this.assignmentProperties = assignmentProperties; store = assignmentProperties.Store; this.settings = assignmentProperties.Store.Settings.DropBoxSettings; culture = new SlkCulture(); }
/// <summary>Initializes a new instance of <see cref="DomainGroupUtilities"/>.</summary> ///<param name="timeout">An exception is thrown if enumeration takes longer than approximately this amount of time.</param> ///<param name="hideDisabledUsers">Whether to retrieve disabled users or not.</param> public DomainGroupUtilities(TimeSpan timeout, bool hideDisabledUsers) { timeoutTime = DateTime.Now + timeout; this.timeout = timeout; this.hideDisabledUsers = hideDisabledUsers; culture = new SlkCulture(); }
/// <summary> /// Initializes an instance of this class, by formatting an error message. /// </summary> /// /// <param name="format">A <c>String.Format</c>-style format string. If /// <paramref name="args"/> is zero-length, <paramref name="format"/> is /// returned without formatting.</param> /// /// <param name="args">Formatting arguments.</param> /// public SafeToDisplayException(string format, params object[] args) : base( (args != null && args.Length == 0) ? format : String.Format(SlkCulture.GetCulture(), format, args) ) { }
/// <summary>Initializes a new instance of <see cref="DropBox"/>.</summary> /// <param name="store">The ISlkStore to use.</param> /// <param name="web">The web to create the drop box in.</param> public DropBoxCreator(ISlkStore store, SPWeb web) { this.site = new SPSite(web.Url); this.web = site.OpenWeb(); web.AllowUnsafeUpdates = true; this.store = store; culture = new SlkCulture(web); }
/// <summary> /// Returns an <c>AssignmentProperties</c> object populated with default information for /// a new assignment based on a given e-learning package or non-e-learning document. /// This method doesn't actually create the assignment -- it just returns information that /// can be used as defaults for a form that a user would fill in to create a new assignment. /// </summary> /// <remarks> /// <para> /// If <paramref name="slkRole"/> is <c>SlkRole.Learner</c>, default properties for a /// self-assigned assignment are returned. In this case, the returned /// <c>AssignmentProperties</c> will contain no users in /// <c>AssignmentProperties.Instructors</c>, and <c>AssignmentProperties.Learners</c> will /// contain only the current user. /// </para> /// <para> /// <b>Security:</b>  If <pr>slkRole</pr> is /// <a href="Microsoft.SharePointLearningKit.SlkRole.Enumeration.htm">SlkRole.Instructor</a>, /// this operation fails if the <a href="SlkApi.htm#AccessingSlkStore">current user</a> doesn't /// have SLK /// <a href="Microsoft.SharePointLearningKit.SlkSPSiteMapping.InstructorPermission.Property.htm">instructor</a> /// permissions on <pr>destinationSPWeb</pr>. Also fails if the current user doesn't have access to the /// package/file. /// </para> /// </remarks> /// <param name="store"></param> /// <param name="destinationSPWeb">The <c>SPWeb</c> that the assignment would be assigned in.</param> /// <param name="slkRole">The <c>SlkRole</c> for which information is to be retrieved. /// Use <c>SlkRole.Learner</c> to get default information for a self-assigned assignment, /// i.e. an assignment with no instructors for which the current learner is the only /// learner. Otherwise, use <c>SlkRole.Instructor</c>.</param> /// <returns></returns> public static AssignmentProperties CreateNewAssignmentObject(ISlkStore store, SPWeb destinationSPWeb, SlkRole slkRole) { // Security checks: Fails if the user isn't an instructor on the web if SlkRole=Instructor // (verified by EnsureInstructor). Fails if the user doesn't have access to the // package (verified by calling RegisterPackage or by accessing // the properties of the non-elearning file). // Check parameters if (destinationSPWeb == null) { throw new ArgumentNullException("destinationSPWeb"); } // Verify that the web is in the site if (destinationSPWeb.Site.ID != store.SPSiteGuid) { throw new InvalidOperationException(SlkCulture.GetResources().SPWebDoesNotMatchSlkSPSite); } UserItemIdentifier currentUserId = store.CurrentUserId; AssignmentProperties assignment = new AssignmentProperties(null, store); assignment.StartDate = DateTime.Today; // midnight today assignment.DueDate = null; assignment.EmailChanges = store.Settings.EmailSettings.DefaultEmailingOn; assignment.CreatedById = currentUserId; store.AddCustomProperties(assignment, destinationSPWeb); // Role checking and determine if self assigned bool isSelfAssigned; if (slkRole == SlkRole.Instructor) { store.EnsureInstructor(destinationSPWeb); isSelfAssigned = false; } else if (slkRole == SlkRole.Learner) { isSelfAssigned = true; } else { throw new ArgumentException(SlkCulture.GetResources().InvalidSlkRole, "slkRole"); } assignment.ShowAnswersToLearners = isSelfAssigned; assignment.AutoReturn = isSelfAssigned; if (isSelfAssigned) { assignment.Learners.Add(new SlkUser(currentUserId, destinationSPWeb.CurrentUser)); } else { assignment.Instructors.Add(new SlkUser(currentUserId, destinationSPWeb.CurrentUser)); } return(assignment); }
/// <summary>Loads SLK configuration information from WSS and LearningStore, in a form that's /// suitable for copying to Configure.aspx form fields. </summary> /// /// <param name="spSiteGuid">The GUID of the SPSite to retrieve configuration information /// from.</param> /// /// <returns>An AdministrationConfiguration.</returns> /// /// <remarks> /// This method is static so it can used outside the context of IIS. Only SharePoint /// administrators can perform this function. /// </remarks> /// /// <exception cref="SafeToDisplayException"> /// An error occurred that can be displayed to a browser user. /// </exception> /// public static AdministrationConfiguration LoadConfiguration(Guid spSiteGuid) { AdministrationConfiguration configuration = new AdministrationConfiguration(spSiteGuid); // only SharePoint administrators can perform this action CheckPermissions(); // set <mapping> to the mapping between <spSiteGuid> and the LearningStore connection // information for that SPSite SlkSPSiteMapping mapping = SlkSPSiteMapping.GetMapping(spSiteGuid); // set "out" parameters based on <mappingExists> and <mapping> if (mapping != null) { // the mapping exists -- set "out" parameters based on <mapping> configuration.DatabaseServer = mapping.DatabaseServer; configuration.DatabaseName = mapping.DatabaseName; configuration.InstructorPermission = mapping.InstructorPermission; configuration.LearnerPermission = mapping.LearnerPermission; // The below given condition will be true only during the migration of SLK from // 'SLK without Observer role' to 'SLK with Observer role' implementation if (mapping.ObserverPermission == null) { mapping.ObserverPermission = LoadCulture(spSiteGuid).Resources.DefaultSlkObserverPermissionName; } configuration.ObserverPermission = mapping.ObserverPermission; } else { SlkCulture siteCulture = LoadCulture(spSiteGuid); AppResourcesLocal adminResources = SlkCulture.GetResources(); configuration.IsNewConfiguration = true; mapping = SlkSPSiteMapping.CreateMapping(spSiteGuid); // the mapping doesn't exist -- set "out" parameters to default values SPWebService adminWebService = SlkAdministration.GetAdminWebService(); configuration.DatabaseServer = adminWebService.DefaultDatabaseInstance.Server.Address; configuration.DatabaseName = adminResources.DefaultSlkDatabaseName; mapping.DatabaseServer = configuration.DatabaseServer; mapping.DatabaseName = configuration.DatabaseName; configuration.InstructorPermission = siteCulture.Resources.DefaultSlkInstructorPermissionName; configuration.LearnerPermission = siteCulture.Resources.DefaultSlkLearnerPermissionName; configuration.ObserverPermission = siteCulture.Resources.DefaultSlkObserverPermissionName; } // set "out" parameters that need to be computed bool createDatabaseResult = false; SlkUtilities.ImpersonateAppPool(delegate() { createDatabaseResult = !DatabaseExists(mapping.DatabaseServerConnectionString, mapping.DatabaseName); }); configuration.CreateDatabase = createDatabaseResult; return(configuration); }
private void InitializeEmailSender(IEmailSender emailSender) { culture = new SlkCulture(web); if (emailSender == null) { this.emailSender = new SharePointEmailer(web); } else { this.emailSender = emailSender; } }
/// <summary>Throws an exception if this computer isn't part of a SharePoint farm, or the caller doesn't /// have the necessary permissions to access instances of this class.</summary> static internal void CheckPermissions() { SPFarm farm = SPFarm.Local; if (farm == null) { throw new InvalidOperationException(SlkCulture.GetResources().SharePointFarmNotFound); } else if (!farm.CurrentUserIsAdministrator()) { throw new SafeToDisplayException(SlkCulture.GetResources().NotSharePointAdmin); } }
/// <summary> /// Returns <c>true</c> if all SharePoint permissions specified by a given set of permission /// names exist in the root web site of a given SPSite, <c>false</c> if not. /// </summary> bool PermissionsExist() { bool returnValue = true; SlkUtilities.ImpersonateAppPool(delegate() { bool catchAccessDenied = SPSecurity.CatchAccessDeniedException; try { SPSecurity.CatchAccessDeniedException = false; // populate <existingPermissions> with the existing permissions on the root SPWeb of the // site with GUID <spSiteGuid> Dictionary <string, bool> existingPermissions = new Dictionary <string, bool>(20); using (SPSite spSite = new SPSite(siteId)) { using (SPWeb rootWeb = spSite.RootWeb) { foreach (SPRoleDefinition roleDef in rootWeb.RoleDefinitions) { existingPermissions[roleDef.Name] = true; } } } if (existingPermissions.ContainsKey(LearnerPermission) == false) { returnValue = false; } else if (existingPermissions.ContainsKey(InstructorPermission) == false) { returnValue = false; } else if (existingPermissions.ContainsKey(ObserverPermission) == false) { returnValue = false; } } catch (UnauthorizedAccessException) { SlkCulture culture = new SlkCulture(); throw new SafeToDisplayException(culture.Resources.NoAccessToSite); } finally { SPSecurity.CatchAccessDeniedException = catchAccessDenied; } }); return(returnValue); }
/// <summary>Changes the folder's name.</summary> /// <param name="oldAssignmentFolderName">The old folder name.</param> /// <param name="newAssignmentFolderName">The new folder name.</param> public void ChangeName(string oldAssignmentFolderName, string newAssignmentFolderName) { string newUrl = assignmentFolder.Url.Replace(oldAssignmentFolderName, newAssignmentFolderName); if (!web.GetFolder(newUrl).Exists) { assignmentFolder.Folder.MoveTo(newUrl); } else { SlkCulture culture = new SlkCulture(); throw new SafeToDisplayException(culture.Resources.AssignmentNameAlreadyUsed); } }
void CheckUserIsInstructor() { UserItemIdentifier current = Assignment.Store.CurrentUserId; foreach (SlkUser instructor in Assignment.Instructors) { if (instructor.UserId == current) { return; } } throw new SafeToDisplayException(SlkCulture.GetResources().ChangeLearnerAssignmentNotInstructor); }
public static string LocalizedValue(string value) { if (string.IsNullOrEmpty(value)) { return(value); } try { if (value.Length > 11 && value.Substring(0, 11) == "$Resources:") { SlkCulture culture; string cultureValue = System.Web.HttpContext.Current.Request.QueryString["culture"]; if (string.IsNullOrEmpty(cultureValue)) { culture = new SlkCulture(); } else { culture = new SlkCulture(new CultureInfo(cultureValue)); } if (value.Length > 18 && value.Substring(0, 18) == "$Resources:SlkDll,") { // Resource string from Slk dll resource string key = value.Substring(18); return(culture.Resources.ResourceManager.GetString(key, culture.Culture)); } else { // Generic resource string int index = value.IndexOf(","); if (index > -1) { string source = value.Substring(11, index - 11); string key = value.Substring(index + 1); return(Microsoft.SharePoint.Utilities.SPUtility.GetLocalizedString("$Resources:" + key, source, (uint)culture.Culture.LCID)); } } } // Not a valid resource string return(value); } catch (Exception e) { return(e.ToString()); } }
/// <summary> /// Saves SLK configuration information. This method accepts information in a form that's /// compatible with Configure.aspx form fields. /// </summary> /// /// <param name="spSiteGuid">The GUID of the SPSite being configured.</param> /// /// <param name="databaseServer">The name of the database server to associate with the /// specified SPSite. By default, integrated authentication is used to connect to the /// database; to use a SQL Server user ID and password instead, append the appropriate /// connection string information to the database server name -- for example, instead of /// "MyServer", use "MyServer;user id=myacct;password=mypassword". For security reasons, /// integrated authentication is strongly recommended.</param> /// /// <param name="databaseName">The name of the database to associate with the specified /// SPSite. This database must exist if <paramref name="schemaToCreateDatabase"/> is /// <c>null</c>, and must not exist if <paramref name="schemaToCreateDatabase"/> is /// non-<c>null</c>, otherwise an error message is returned.</param> /// /// <param name="schemaToCreateDatabase">If non-<c>null</c>, this is the SlkSchema.sql file /// containing the schema of the database, and an SLK database named /// <paramref name="databaseName"/> is created using this schema. If <c>null</c>, /// <paramref name="databaseName"/> specifies an existing database.</param> /// /// <param name="instructorPermission">The name of the SharePoint permission that /// identifies instructors.</param> /// /// <param name="learnerPermission">The name of the SharePoint permission that /// identifies learners.</param> /// /// <param name="observerPermission">The name of the SharePoint permission that /// identifies observers.</param> /// /// <param name="createPermissions">If <c>true</c>, the permissions specified by /// <paramref name="instructorPermission"/> and <paramref name="learnerPermission"/> /// are added to the root SPWeb of the specified SPSite (if they don't already /// exist).</param> /// /// <param name="settingsFileContents">If not <c>null</c>, this is the contents of a SLK /// Settings file to associate with this SPSite. If <c>null</c>, the previous SLK /// Settings file is used if one exists, or the default SLK settings file is used if a /// database is being created.</param> /// /// <param name="defaultSettingsFileContents">The contents of the default SLK Settings file. /// Must not be <n>null</n>.</param> /// /// <param name="appPoolAccountName">The name of the application pool account; for example, /// "NT AUTHORITY\NETWORK SERVICE". If <n>null</n>, then the current Windows identity is /// used, or, if the current identity is impersonated, the original Windows identity is /// used.</param> /// /// <remarks> /// This method is static so it can used outside the context of IIS. Only SharePoint /// administrators can perform this function. /// </remarks> /// /// <exception cref="SafeToDisplayException"> /// An error occurred that can be displayed to a browser user. /// </exception> /// public static void SaveConfiguration(Guid spSiteGuid, string databaseServer, string databaseName, string schemaToCreateDatabase, string instructorPermission, string learnerPermission, string observerPermission, bool createPermissions, string settingsFileContents, string defaultSettingsFileContents, string appPoolAccountName) { CheckParameters(databaseServer, databaseName, instructorPermission, learnerPermission, observerPermission, defaultSettingsFileContents); // only SharePoint administrators can perform this action CheckPermissions(); // set <mapping> to the mapping between <spSiteGuid> and the LearningStore connection information for that SPSite SlkSPSiteMapping mapping = SlkSPSiteMapping.GetMapping(spSiteGuid); if (mapping == null) { mapping = SlkSPSiteMapping.CreateMapping(spSiteGuid); } mapping.DatabaseServer = databaseServer; mapping.DatabaseName = databaseName; mapping.InstructorPermission = instructorPermission; mapping.LearnerPermission = learnerPermission; mapping.ObserverPermission = observerPermission; if (mapping.IsDirty) { mapping.Update(); } // create the database if specified if (schemaToCreateDatabase != null) { CreateDatabase(mapping, databaseName, appPoolAccountName, schemaToCreateDatabase); } // create permissions if specified if (createPermissions) { SlkCulture culture = LoadCulture(spSiteGuid); // create the permissions if they don't exist yet CreatePermission(spSiteGuid, instructorPermission, culture.Resources.SlkInstructorPermissionDescription, 0); CreatePermission(spSiteGuid, learnerPermission, culture.Resources.SlkLearnerPermissionDescription, 0); CreatePermission(spSiteGuid, observerPermission, culture.Resources.SlkObserverPermissionDescription, 0); } UpdateSlkSettings(mapping.DatabaseConnectionString, spSiteGuid, settingsFileContents, defaultSettingsFileContents); }
/// <summary> /// Returns the SPSite-to-LearningStore mapping represented by a given SPSite GUID. If no /// such mapping exists, an exception is thrown. /// </summary> /// /// <param name="site">The SPSite to retrieve a mapping for.</param> /// /// <exception cref="SlkNotConfiguredException"> /// SLK is not configured for SharePoint site collection. /// (This configuration is performed in SharePoint Central Administration.) /// </exception> /// public static SlkSPSiteMapping GetRequiredMapping(SPSite site) { SlkSPSiteMapping mapping = GetMapping(site.ID); if (mapping == null) { mapping = GetMapping(site.WebApplication.Id); } if (mapping == null) { throw new SlkNotConfiguredException(SlkCulture.GetResources().SlkNotEnabled); } else { return(mapping); } }
void VerifyIsValidSelfAssigned() { // set <currentUserId> to the UserItemIdentifier of the current user; note that this // requires a round trip to the database UserItemIdentifier currentUserId = Store.CurrentUserId; // verify that <properties> specify no instructors and that the current user is the // only learner if (Instructors.Count != 0) { throw new UnauthorizedAccessException(SlkCulture.GetResources().InvalidSelfAssignment); } if ((Learners.Count != 1) || (Learners[0].UserId != currentUserId)) { throw new UnauthorizedAccessException(SlkCulture.GetResources().InvalidSelfAssignment); } }
/// <summary>Unlocks a file.</summary> /// <param name="file">The file to unlock.</param> /// <param name="currentUser">The current user id.</param> public static void UnlockFile(SPFile file, int currentUser) { try { if (file.LockedByUser != null && file.LockedByUser.ID != currentUser) { using (new AllowUnsafeUpdates(file.Web)) { file.ReleaseLock(file.LockId); } } } catch (SPException e) { SlkCulture culture = new SlkCulture(); string message = string.Format(CultureInfo.CurrentUICulture, culture.Resources.FailUnlockFile, file.Item.Url); SlkStore.GetStore(file.Web).LogException(e); throw new SafeToDisplayException(message); } }
void SetUpDropBox(Guid id) { // Library is created, now need to set it up dropBoxList = web.Lists[id]; bool okToContinue = false; try { AddFields(); // Set up versioning dropBoxList.EnableVersioning = true; dropBoxList.Update(); // Reached point at which list is usable, so any errors from now, just log but continue. okToContinue = true; ChangeToInternationalNames(); ClearPermissions(); CreateNoPermissionsFolder(dropBoxList); ModifyDefaultView(); } catch (SPException e) { store.LogError(culture.Resources.DropBoxListCreateFailure, e); if (okToContinue == false) { // Error creating list - delete it dropBoxList.Delete(); web.AllProperties[DropBox.PropertyKey] = null; dropBoxList = null; throw new SafeToDisplayException(string.Format(SlkCulture.GetCulture(), culture.Resources.DropBoxListCreateFailure, e.Message)); } } catch (Exception e) { store.LogError(culture.Resources.DropBoxListCreateFailure, e); throw; } }
void SaveNewAssignment(SPWeb web, SlkRole slkRole) { // Security checks: If assigning as an instructor, fails if user isn't an instructor on // the web (implemented by calling EnsureInstructor). Fails if the user doesn't have access to the package/file if (web == null) { throw new ArgumentNullException("web"); } if (PackageFormat == null && Location == null) { throw new InvalidOperationException(SlkCulture.GetResources().InvalidNewAssignment); } SPSiteGuid = web.Site.ID; SPWebGuid = web.ID; VerifyRole(web, slkRole); Id = Store.CreateAssignment(this); if (isSelfAssigned == false) { //Update the MRU list Store.AddToUserWebList(web); } if (IsNonELearning) { DropBoxManager dropBoxMgr = new DropBoxManager(this); Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest(); dropBoxMgr.CreateAssignmentFolder(); } if (EmailChanges) { using (AssignmentEmailer emailer = new AssignmentEmailer(this, Store.Settings.EmailSettings, web)) { emailer.SendNewEmail(Learners); } } }
/// <summary>Makes the assignment be a no package assignemnt.</summary> public void MakeNoPackageAssignment(string title) { Location = Package.NoPackageLocation.ToString(); if (String.IsNullOrEmpty(Title)) { if (string.IsNullOrEmpty(title)) { Title = SlkCulture.GetResources().NoPackageTitle; } else { Title = title; } } if (Description == null) { Description = String.Empty; } return; }
private static SlkSettings LoadSettings(SlkSPSiteMapping mapping, SPSite site, XmlSchema xmlSchema) { // create a LearningStore. Read is in privileged scope so irrelevant what key is. // Cannot use current user as may be be called in a page PreInit event when it's not necessarily valid string learningStoreKey = "SHAREPOINT\\System"; LearningStore learningStore = new LearningStore(mapping.DatabaseConnectionString, learningStoreKey, ImpersonationBehavior.UseOriginalIdentity); // read the SLK Settings file from the database into <settings> SlkSettings settings; using (LearningStorePrivilegedScope privilegedScope = new LearningStorePrivilegedScope()) { LearningStoreJob job = learningStore.CreateJob(); LearningStoreQuery query = learningStore.CreateQuery(Schema.SiteSettingsItem.ItemTypeName); query.AddColumn(Schema.SiteSettingsItem.SettingsXml); query.AddColumn(Schema.SiteSettingsItem.SettingsXmlLastModified); query.AddCondition(Schema.SiteSettingsItem.SiteGuid, LearningStoreConditionOperator.Equal, mapping.SPSiteGuid); job.PerformQuery(query); DataRowCollection dataRows = job.Execute <DataTable>().Rows; if (dataRows.Count != 1) { throw new SafeToDisplayException(SlkCulture.GetResources().SlkSettingsNotFound, site.Url); } DataRow dataRow = dataRows[0]; string settingsXml = (string)dataRow[0]; DateTime settingsXmlLastModified = ((DateTime)dataRow[1]); using (StringReader stringReader = new StringReader(settingsXml)) { XmlReaderSettings xmlSettings = new XmlReaderSettings(); xmlSettings.Schemas.Add(xmlSchema); xmlSettings.ValidationType = ValidationType.Schema; using (XmlReader xmlReader = XmlReader.Create(stringReader, xmlSettings)) { settings = new SlkSettings(xmlReader, settingsXmlLastModified); } } } return(settings); }
/// <summary>Enumerates a domain group.</summary> public override DomainGroupEnumeratorResults EnumerateGroup(SPUser domainGroup, SPWeb web, TimeSpan timeRemaining, bool hideDisabledUsers) { DomainGroupEnumeratorResults results = new DomainGroupEnumeratorResults(); ICollection <SPUserInfo> spUserInfos = new List <SPUserInfo>(); try { DomainGroupUtilities enumerateDomainGroups = new DomainGroupUtilities(timeRemaining, hideDisabledUsers); spUserInfos = enumerateDomainGroups.EnumerateDomainGroup(domainGroup); foreach (string error in enumerateDomainGroups.Errors) { results.Errors.Add(error); } } catch (DomainGroupEnumerationException exception) { results.Errors.Add(exception.Message); if (exception.InnerException != null) { results.DetailedExceptions.Add(exception.InnerException); } } foreach (SPUserInfo spUserInfo in spUserInfos) { try { SPUser spUserInGroup = web.EnsureUser(spUserInfo.LoginName); results.Users.Add(spUserInGroup); } catch (SPException exception) { SlkCulture culture = new SlkCulture(); results.Errors.Add(string.Format(culture.Culture, culture.Resources.ErrorCreatingSPSiteUser, web.Site.Url, exception)); } } return(results); }
private Guid CreateLibrary(int recursiveNumber) { string name = dropBoxName; if (recursiveNumber > 0) { name = name + recursiveNumber.ToString(CultureInfo.InvariantCulture); } try { return(web.Lists.Add(name, dropBoxName, SPListTemplateType.DocumentLibrary)); } catch (SPException e) { // Library already exists, add a number to make it unique Guid id = CheckIfCreatedInMeantime(); if (id == Guid.Empty) { if (recursiveNumber < 2) { return(CreateLibrary(recursiveNumber + 1)); } else { throw new SafeToDisplayException(string.Format(SlkCulture.GetCulture(), culture.Resources.DropBoxListCreateFailure, e.Message)); } } else { // The reload in objects should have given the other process time to complete setting up the list - at least adding the fields alreadyCreated = true;; return(id); } } }
/// <summary>Get the anonymous store.</summary> /// <param name="site">The site to get the settings for.</param> /// <returns></returns> public static AnonymousSlkStore GetStore(SPSite site) { Guid siteId = site.ID; // set <httpContext> to the current HttpContext (null if none) HttpContext httpContext = HttpContext.Current; // if an AnonymousSlkStore corresponding to <spSiteGuid> is cached, retrieve it, otherwise // create one string cacheItemName = null; AnonymousSlkStore anonymousSlkStore; if (httpContext != null) { cacheItemName = String.Format(CultureInfo.InvariantCulture, "SlkStore_{0}", siteId); anonymousSlkStore = (AnonymousSlkStore)httpContext.Cache.Get(cacheItemName); if (anonymousSlkStore != null) { return(anonymousSlkStore); } } // set <mapping> to the SlkSPSiteMapping corresponding to <siteId>; if no such // mapping, exists, a SafeToDisplayException is thrown SlkSPSiteMapping mapping = SlkSPSiteMapping.GetRequiredMapping(site); // load "SlkSettings.xsd" from a resource into <xmlSchema> XmlSchema xmlSchema; using (StringReader schemaStringReader = new StringReader(SlkCulture.GetDefaultResources().SlkSettingsSchema)) { xmlSchema = XmlSchema.Read(schemaStringReader, delegate(object sender2, ValidationEventArgs e2) { // ignore warnings (already displayed when SLK Settings file was uploaded) }); } SlkSettings settings = null; try { settings = LoadSettings(mapping, site, xmlSchema); } catch (SqlException) { // Try again in case temporary error try { settings = LoadSettings(mapping, site, xmlSchema); } catch (SqlException e) { SlkCulture culture = new SlkCulture(CultureInfo.InvariantCulture); SlkStore.LogError(culture.Resources.SlkSettingsSqlErrorLoad + " {0}", culture, e); throw new SafeToDisplayException(culture.Resources.SlkSettingsSqlErrorLoad); } } // create and (if possible) cache the new AnonymousSlkStore object anonymousSlkStore = new AnonymousSlkStore(siteId, mapping, settings); DateTime cacheExpirationTime = DateTime.Now.AddSeconds(HttpContextCacheTime); if (httpContext != null) { httpContext.Cache.Add(cacheItemName, anonymousSlkStore, null, cacheExpirationTime, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } return(anonymousSlkStore); }