Only Remove SPGroups that Contain a specific Character - c#

I need to remove groups from a SharePoint site that contain an underscore in the name. I need something like the below code, but I am unable to use .Contains on the collGroups.
Any idea how I can do this?
using (SPSite oSite = new SPSite(spsite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
SPGroupCollection collGroups = oWeb.SiteGroups;
if(collGroups.Contains("_")) //this doens't work, but I need something like this
{
group.Delete();
}
}
}

For future reference: here is what I ended up writing, thanks to gunr2171 for pointing me in the right direction!
using (SPSite oSite = new SPSite(spsite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
var result = (from g in oWeb.Groups.OfType<SPGroup>()
where g.Name.Contains("_")
select g).ToList();
foreach (SPGroup group in result)
{
SPGroupCollection collGroups = oWeb.SiteGroups;
collGroups.Remove(group.Name);
Console.WriteLine("Removed " + group.Name);
}
Console.WriteLine("Process Complete!");
}

Related

caml query not working properly in sharepoint online

I need to get list items which is older than say 7 days and delete them. I tried using caml query and it worked well in sharepoint 2010 but when I tried to use the same in Sharepoint Online, its getting all list items and deleting it regardless of the condition.
public static bool removeOldEntries(string listName, int offset)
{
bool successFlag = true;
try
{
using (var context = new ClientContext(siteURL))
{
SecureString password = ToSecureString(pwd);
context.Credentials = new SharePointOnlineCredentials(userName, password);
Web web = context.Web;
var list = context.Web.Lists.GetByTitle(listName);
if (list != null)
{
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = "<Where><Leq><FieldRef Name='Modified'/><Value Type='DateTime'><Today OffsetDays='-" + offset + "'/></Value></Leq></Where>";
ListItemCollection collListItem = list.GetItems(camlQuery);
context.Load(collListItem, items => items.Include(
item => item["ID"]));
context.ExecuteQuery();
if (collListItem.Count > 0)
{
foreach (ListItem oListItem in collListItem)
{
ListItem itemToDelete = list.GetItemById(int.Parse(oListItem["ID"].ToString()));
itemToDelete.DeleteObject();
context.ExecuteQuery();
}
}
}
}
}
catch (Exception ex)
{
successFlag = false;
}
return successFlag;
}
Thanks in advance for any help.
First try adding a Tag in your view xml
So it should look like
camlQuery.ViewXml = "<Query><Where><Leq><FieldRef Name='Modified'/><Value Type='DateTime'><Today OffsetDays='-" + offset + "'/></Value></Leq></Where></Query>";
If it doesn't help try adding a view tag
camlQuery.ViewXml = "<View><Query><Where><Leq><FieldRef Name='Modified'/><Value Type='DateTime'><Today OffsetDays='-" + offset + "'/></Value></Leq></Where></Query></View>";
you can make use of the PNP.PowerShell Module.
$CreationDate = Get-Date "16.06.2021 20:04" -Format s
Get-PnPListItem -List "Opportunities" -Query "<View><Query><Where><Eq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>$CreationDate</Value></Eq></Where></Query></View>"
For more check out the reference:
https://sposcripts.com/sharepoint/sharepointonline/filtering-for-sharepoint-items-with-caml-queries/#If_DateTime_should_exactly_match_a_specific_date

Updating SPFile properties using SPFile.Update()

I'm trying to update SPFile properties.
Here is my code:
using (SPSite oSite = new SPSite(sFileURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
oFile = oWeb.GetFile(sFileURL);
foreach (XmlNode xNode in oXmlDoc.FirstChild.ChildNodes)
{
oFile.Item.Properties[xNode.Name] = xNode.InnerText;
string itemmm =oFile.Item.Properties[xNode.Name].ToString();
}
oFile.Update();
oWeb.AllowUnsafeUpdates = false;
}
}
The problem is that when I check the file properties in SharePoint I don't see the changes I have made.
I was trying to add AllowUnsafeUpdates = true but it didn't solve the problem.
What else can I do?
In fact, you don't modify SPFile instance, but the associated SPItem. Hence calling SPFile.Update() does nothing. It's better to work with the SPItem instance directly:
SPItem item = oFile.Item;
item.Properties[xNode.Name] = xNode.InnerText;
item.Update();
Also, AllowUnsafeUpdates property is not relevant to your situation. Do not alter it.
Your code is lacking all checks which is to be done before actual update.
using (SPSite oSite = new SPSite(sFileURL))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
oWeb.AllowUnsafeUpdates = true;
SPFile oFile = oWeb.GetFile(sFileURL);
if (oFile == null)
{
return false;
}
SPListItem item = oFile.GetListItem();
if (item.File.Level == SPFileLevel.Checkout)
{
item.File.UndoCheckOut();
}
if (item.File.Level != SPFileLevel.Checkout)
{
item.File.CheckOut();
}
item["Your Column name"] = "Value";
item.SystemUpdate(false);
item.File.CheckIn("SystemCheckedin");
item.File.Publish("SystemPublished");
oWeb.AllowUnsafeUpdates = false;
}
}

c# iterate through object members

The context here is that I want to see the permissions an object in a sharepoint list has.
But the question has got to do with C#
Sharepoint has an object called SPListItem and you can view various details about the object by iterating over it's index.
I am able to iterate through the index of SPListItem by using integer numbers (splistitem[i]). But, the problem is that I don't know what property/detail is my program printing out.
How do I print out the name of the index and the index value as well ?
here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System;
using Microsoft.SharePoint;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("-----");
using (SPSite site = new SPSite("http://c4968397007/sites/anupamsworkspace/"))
{
using (SPWeb web = site.OpenWeb())
{
SPList oSPList = web.Lists["Check2"];
SPListItem oSPListItem = oSPList.Items[0];
for (int i = 0; i < 100;i++ )
//printing out the index value using int index, how do I print the name of the value it's printing out ?
Console.WriteLine(oSPListItem[i]);
}
}
Console.ReadLine();
}
}
}
This should do the trick:
using (SPSite site = new SPSite("http://c4968397007/sites/anupamsworkspace/"))
{
using (SPWeb web = site.OpenWeb())
{
var list = web.Lists["Check2"];
var item = list.Items[0];
foreach (var field in list.Fields)
{
Console.WriteLine("Key: {0} Value: {1}", field.StaticName, item[field.StaticName])
}
}
}
Regards,
Martin
You can use below approach
using (SPWeb web = site.OpenWeb())
{
SPList list = web.GetList("Check2");
if (list.ItemCount > 0)
{
SPListItem item = list.Items[0];
Hashtable ht = item.Properties;
foreach (DictionaryEntry de in ht)
Console.WriteLine("Key: {0} Value: {1}", de.Key, de.Value);
}
}
}

How to get Sharepoint List using c#

How to get fields values from a particular list item.In my case i want to get all form fileds of Workplan list.Actually i want to get Workplan all list item and insert to sharepoint 2013 associated database.
I try the following code.
string strUrl = "http://example.com/default.aspx";
using (SPSite site = new SPSite(strUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[52];
SPQuery myquery = new SPQuery();
myquery.Query = "";
SPListItemCollection items = list.GetItems(myquery);
foreach (SPListItem item in items)
{
if (item != null)
{
var Name = item.ListItems.Fields.List;
Console.WriteLine("Name is :" + Name);
}
}
}
}
This is the easiest way I can think of using Server Object Model:
string strUrl = "http://example.com";
using(SPSite oSite = new SPSite(strUrl))
{
using(SPWeb oWeb = oSite.OpenWeb())
{
SPList list = oWeb.Lists["Workplan"];
foreach(SPField field in list.Fields)
{
Console.WriteLine(field.Title);
}
}
}
Btw, as for your site-URL "http://example.com/default.aspx" it is enough to do it like "http://example.com".
For more information on Sharepoint I recommend using this site in the future.
using (SPSite site = new SPSite("URL")
{
using (SPWeb web = site.OpenWeb("sitecollection/subsite"))
{
//to get specific list type
string listUrl = "/sites/sitecollection/subsite/Lists/Announcements";
SPList list = web.GetList(listUrl);
Console.WriteLine("List URL: {0}", list.RootFolder.ServerRelativeUrl);
}
}
//To get all lists from spweb use this:
SPSite oSiteCollection = SPContext.Current.Site;
using(SPWebCollection collWebs = oSiteCollection.AllWebs)
{
foreach (SPWeb oWebsite in collWebs)
{
SPListCollection collSiteLists = oWebsite.Lists;
foreach (SPList oList in collSiteLists)
{
//get your each list here
}
oWebsite.Dispose();
}
}

How to get site's URL using ServerManager object

I am trying to get site's URL here but not able to figure out how to get it,
using (var mgr = new ServerManager())
{
foreach (var site in mgr.Sites)
{
var siteURL = site. ??
Here's class I am using
http://msdn.microsoft.com/en-us/library/microsoft.web.administration.application.virtualdirectories(v=vs.90).aspx
Umm..I guess this might help..
ServerManager serverMgr = new ServerManager();
Site site = serverMgr.Sites["YourSiteName"];
List<string[]> urls = new List<string[]>();
foreach (Binding binding in site.Bindings)
{
string bindingInfo = binding.BindingInformation;
string subString = bindingInfo.Substring(2, bindingInfo.Length - 2);
string[] adrs = subString.Split(':');
adrs[0] = "localhost:" + adrs[0];
urls.Add(adrs);
}
Sites is a Sitecollection and you can get sites by looping through its items.
If you are just looking for website's url why dont you use Request object.

Categories