public bool RemoverPermissao(string urlSite, string nomeGrupo) { var retorno = false; SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb web = new SPSite(SPContext.Current.Site.ID).OpenWeb(String.Concat(@"/", urlSite))) { var anterior = web.AllowUnsafeUpdates; web.AllowUnsafeUpdates = true; try { web.RoleAssignments.Remove(web.SiteGroups[nomeGrupo]); } catch (Exception) { web.RoleAssignments.Remove(web.EnsureUser(nomeGrupo)); } web.Update(); web.AllowUnsafeUpdates = !anterior; retorno = true; } }); return(retorno); }
private void CheckItems(XmlNode siteNode, string url) { using (SPWeb web = new SPSite(url).OpenWeb()) { XmlNodeList alertNodes = siteNode.SelectNodes("alert[@type='Item']"); foreach (XmlNode alertNode in alertNodes) { string alertTitle = alertNode.Attributes["title"].Value; string listTitle = alertNode.Attributes["list"].Value; string loginName = alertNode.Attributes["user"].Value; int itemId = Int32.Parse(alertNode.Attributes["id"].Value); string itemUrl = alertNode.Attributes["url"].Value; string objectType = alertNode.Attributes["object"].Value; output.Append(string.Format("user: {0,20}...", loginName)); try { SPList list = web.Lists[listTitle]; SPClaimProviderManager cpm = SPClaimProviderManager.Local; SPClaim userClaim = cpm.ConvertIdentifierToClaim(loginName, SPIdentifierTypes.WindowsSamAccountName); SPUser user = web.EnsureUser(userClaim.ToEncodedString()); string eventType = alertNode.Attributes["event"].Value; SPEventType spEventType = (SPEventType)Enum.Parse(typeof(SPEventType), eventType); string eventFrequency = alertNode.Attributes["frequency"].Value; SPAlertFrequency spAlertFrequency = (SPAlertFrequency)Enum.Parse(typeof(SPAlertFrequency), eventFrequency); string type = alertNode.Attributes["type"].Value; SPAlertType spAlertType = (SPAlertType)Enum.Parse(typeof(SPAlertType), type); SPListItem item = null; if (list.BaseType == SPBaseType.DocumentLibrary) { SPFile file = web.GetFile(itemUrl); item = file.Item; } else { item = list.GetItemById(itemId); } SPAlert newAlert = user.Alerts.Add(); newAlert.Title = alertTitle; newAlert.AlertType = spAlertType; newAlert.Item = item; newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email; newAlert.EventType = spEventType; newAlert.AlertFrequency = spAlertFrequency; newAlert.Status = SPAlertStatus.On; newAlert.Update(false); output.Append(string.Format("Complete" + Environment.NewLine)); } catch (Exception ex) { output.Append(string.Format("error: {0,20}" + Environment.NewLine, ex.Message)); } } } }
public void generateInitialTasks(Matter matter, string taskListLocation) { StringBuilder tasksCreated = new StringBuilder(); // Grab the tasks created for log output. // read LitigationTasks.config (custom XML file) to dataset for value retrieval. DataSet ds = new DataSet(); try { ds.ReadXml("LitigationTasks.config"); } catch (Exception ex) { log.addError(ex.ToString()); } #region Get the litigation manager user as SPFieldUserValue // This strange articulation must be done because the task list is located in a different web, and therefore the user object has a different key/id // While SharePoint could perform an internal cast of SPUser.ToString(), it seems retrival from the hashtable using the addListItem method prevents this. SPFieldUserValue taskAssignedTo = null; try { using (SPWeb tasksWeb = new SPSite(taskListLocation).OpenWeb()) { // Ensure the Litigation Manager has access to the web containing tasks, or SharePoint might kibby and die. SPUser user = tasksWeb.EnsureUser(matter.LitigationManagerSPUser.ToString()); taskAssignedTo = new SPFieldUserValue(tasksWeb, user.ID, user.LoginName); } } catch (Exception ex) { log.addWarning("Unable to determine an appropriate user to assign tasks to for matter " + matter.LMNumber + ", so they will need to be assigned manually." + " The Exception was: " + ex.ToString()); } #endregion foreach (DataRow task in ds.Tables[0].Rows) { var description = task["description"]; var associatedURL = task["url"]; var daysUntilDue = Convert.ToInt32(task["daysuntildue"]); Hashtable taskFields = new Hashtable(); taskFields.SetProperty("Due Date", DateTime.Now.AddDays(daysUntilDue)); taskFields.SetProperty("Matter Name", matter.MatterName); taskFields.SetProperty("Task Description", description); taskFields.SetProperty("Assigned To", taskAssignedTo); taskFields.SetProperty("Allow Manual Completion", true); taskFields.SetProperty("Related URL", associatedURL); taskFields.SetProperty("Associated Site ID", matter.LMNumber); taskFields.SetProperty("Data Source", "LitMatterSyncService"); taskFields.SetProperty("Additional Source Information", "Provisioned with Site"); addListItem(taskListLocation, taskFields); tasksCreated.AppendLine(description.ToString() + "(Due in " + daysUntilDue.ToString() + " days)"); } log.addInformation("Generated the following initial tasks for matter " + matter.LMNumber + "\n" + tasksCreated); }
private void CheckLists(XmlNode siteNode, string url) { using (SPWeb web = new SPSite(url).OpenWeb()) { XmlNodeList alertNodes = siteNode.SelectNodes("alert[@type='List']"); foreach (XmlNode alertNode in alertNodes) { string alertTitle = alertNode.Attributes["title"].Value; string listTitle = alertNode.Attributes["list"].Value; string loginName = alertNode.Attributes["user"].Value; string objectType = alertNode.Attributes["object"].Value; bool isFolder = objectType.ToLower().Equals("folder"); if (!isFolder) { output.Append(string.Format("user: {0,20}...", loginName)); try { SPList list = web.Lists[listTitle]; SPClaimProviderManager cpm = SPClaimProviderManager.Local; SPClaim userClaim = cpm.ConvertIdentifierToClaim(loginName, SPIdentifierTypes.WindowsSamAccountName); SPUser user = web.EnsureUser(userClaim.ToEncodedString()); string eventType = alertNode.Attributes["event"].Value; SPEventType spEventType = (SPEventType)Enum.Parse(typeof(SPEventType), eventType); string eventFrequency = alertNode.Attributes["frequency"].Value; SPAlertFrequency spAlertFrequency = (SPAlertFrequency)Enum.Parse(typeof(SPAlertFrequency), eventFrequency); string type = alertNode.Attributes["type"].Value; SPAlertType spAlertType = (SPAlertType)Enum.Parse(typeof(SPAlertType), type); SPAlert newAlert = user.Alerts.Add(); newAlert.Title = alertTitle; newAlert.AlertType = spAlertType; newAlert.List = list; newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email; newAlert.EventType = spEventType; newAlert.AlertFrequency = spAlertFrequency; newAlert.Status = SPAlertStatus.On; newAlert.Update(false); output.Append(string.Format("Complete" + Environment.NewLine)); } catch (Exception ex) { output.Append(string.Format("error: {0,20}" + Environment.NewLine, ex.Message)); } } } } }
private void RemoveAlerts(XmlNode siteNode, string url) { using (SPWeb web = new SPSite(url).OpenWeb()) { SPClaimProviderManager cpm = SPClaimProviderManager.Local; SPClaim userClaim = cpm.ConvertIdentifierToClaim("emirates\\s717981", SPIdentifierTypes.WindowsSamAccountName); SPUser tempUser = web.EnsureUser(userClaim.ToEncodedString()); web.AllowUnsafeUpdates = true; try { SPAlertCollection allAlerts = web.Alerts; List <Guid> alertsToDelete = new List <Guid>(); foreach (SPAlert spAlert in allAlerts) { alertsToDelete.Add(spAlert.ID); } Guid [] alerts = alertsToDelete.ToArray(); for (int i = 0; i < alerts.Length; i++) { SPAlert alert = allAlerts[alerts[i]]; alert.User = tempUser; alert.Status = SPAlertStatus.Off; alert.Update(); } foreach (Guid alertGuid in alertsToDelete) { allAlerts.Delete(alertGuid); } web.Update(); } catch (Exception ex) { Console.WriteLine(ex.Message); } web.AllowUnsafeUpdates = false; } }
//internal async Task EnsureVisitor(GenericXmlSecurityToken xmlToken) internal void EnsureVisitor(GenericXmlSecurityToken xmlToken) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xmlToken.TokenXml.OuterXml); XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("saml", "urn:oasis:names:tc:SAML:1.0:assertion"); XmlNodeList names = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='name']/saml:AttributeValue", nsmgr); XmlNodeList userlogonnames = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userlogonname']/saml:AttributeValue", nsmgr); XmlNodeList userids = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userid']/saml:AttributeValue", nsmgr); //string namefirst = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='name']/saml:AttributeValue", nsmgr)[1].InnerText; //string userlogonname = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userlogonname']/saml:AttributeValue", nsmgr)[1].InnerText; //string userid = xmlDoc.SelectNodes("//saml:Assertion/saml:AttributeStatement/saml:Attribute[@AttributeName='userid']/saml:AttributeValue", nsmgr)[1].InnerText; Guid id = SPContext.Current.Site.ID; //await Task.Run(() => SPSecurity.RunWithElevatedPrivileges(delegate() SPSecurity.RunWithElevatedPrivileges(delegate() { using (SPWeb elevatedWeb = new SPSite(id).OpenWeb()) { elevatedWeb.AllowUnsafeUpdates = true; List <SPUser> spUsers = new List <SPUser>(); foreach (XmlNode node in names) { try { SPUser spUserbyname = elevatedWeb.EnsureUser(node.InnerText); if (!spUsers.Any <SPUser>(u => u.ID == spUserbyname.ID)) { spUsers.Add(spUserbyname); } //break; } catch (Exception ex) { ProviderLogging.LogError(ex); } } foreach (XmlNode node in userlogonnames) { try { SPUser spUserbyname = elevatedWeb.EnsureUser(node.InnerText); if (!spUsers.Any <SPUser>(u => u.ID == spUserbyname.ID)) { spUsers.Add(spUserbyname); } //break; } catch (Exception ex) { ProviderLogging.LogError(ex); } } foreach (XmlNode node in userids) { try { SPUser spUserbyname = elevatedWeb.EnsureUser(node.InnerText); if (!spUsers.Any <SPUser>(u => u.ID == spUserbyname.ID)) { spUsers.Add(spUserbyname); } //break; } catch (Exception ex) { ProviderLogging.LogError(ex); } } elevatedWeb.Update(); try { if (spUsers != null && spUsers.Count > 0) { SPGroup usersGroup = elevatedWeb.SiteGroups.GetByID(7); SPGroup visitorGroup = elevatedWeb.AssociatedVisitorGroup; foreach (SPUser user in spUsers) { usersGroup.AddUser(user); visitorGroup.AddUser(user); } /* * if(usersGroup != null) * { * * usersGroup.AddUser(spUser); * } * * //.SiteGroups.Web.AssociatedVisitorGroup; * if (visitorGroup != null) * { * visitorGroup.AddUser(spUser); * } */ } } catch (Exception ex) { ProviderLogging.LogError(ex); } finally { elevatedWeb.Update(); } elevatedWeb.AllowUnsafeUpdates = false; } }); //})); }
/// <summary> /// OnSubmitFile method for the content organizer /// </summary> /// <param name="contentOrganizerWeb">The web.</param> /// <param name="recordSeries">Record series.</param> /// <param name="userName">Submitting user name.</param> /// <param name="fileContent">File content.</param> /// <param name="properties">File properties.</param> /// <param name="finalFolder">The final folder.</param> /// <param name="resultDetails">Result processing details.</param> /// <returns>The CustomRouterResult.</returns> public override CustomRouterResult OnSubmitFile(EcmDocumentRoutingWeb contentOrganizerWeb, string recordSeries, string userName, Stream fileContent, RecordsRepositoryProperty[] properties, SPFolder finalFolder, ref string resultDetails) { this.ResolveDependencies(); var web = new SPSite(contentOrganizerWeb.DropOffZoneUrl).OpenWeb(); // Get routed document properties var documentProperties = EcmDocumentRouter.GetHashtableForRecordsRepositoryProperties( properties, recordSeries); // Example: Get a conventional field (8553196d-ec8d-4564-9861-3dbe931050c8 = FileLeafRef) string originalFileName = documentProperties["8553196d-ec8d-4564-9861-3dbe931050c8"].ToString(); // EncodedAbsUrl field string originalFileUrl = documentProperties["7177cfc7-f399-4d4d-905d-37dd51bc90bf"].ToString(); // Example: Get the SharePoint user who perform the action var user = web.EnsureUser(userName); // Example: Deal with errors if (originalFileName.ToLower().Contains("error")) { // Display error message SPUtility.TransferToErrorPage( string.Format(CultureInfo.InvariantCulture, "This is an error message")); // Save the error file in the Drop Off Library this.SaveDocumentToDropOffLibrary( fileContent, documentProperties, contentOrganizerWeb.DropOffZone, originalFileName, contentOrganizerWeb, user); return CustomRouterResult.SuccessCancelFurtherProcessing; } // Here is the business logic // Example: get a taxonomy field from document properties string confidentialityTaxValue = documentProperties[MyFields.MyTaxField.InternalName].ToString(); string confidentiality = new TaxonomyFieldValue(confidentialityTaxValue).Label; // Example: Set a new field to the item var indexDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime( DateHelper.GetSharePointDateUtc(web, DateTime.Now)); // Be careful, if you want to add or modify some properties, use internal GUID instead of InternalName if (!documentProperties.ContainsKey(MyFields.MyIndexDate.ID.ToString())) { documentProperties.Add(MyFields.MyIndexDate.ID.ToString(), indexDate); } else { documentProperties[MyFields.MyIndexDate.ID.ToString()] = indexDate; } // Save the file in the final destination. You can get the newly created file here and apply further actions. var file = EcmDocumentRouter.SaveFileToFinalLocation( contentOrganizerWeb, finalFolder, fileContent, originalFileName, originalFileUrl, documentProperties, user, true, string.Empty); web.Dispose(); return CustomRouterResult.SuccessContinueProcessing; }