c# iterate through object members - c#

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);
}
}
}

Related

System.Description not present in the dictionary

I'm writing a C# program that can get the fields of all the work items in an Azure DevOps organization. However, I'm having some problems with the Description field:
IList<WorkItem> workItems = new List<WorkItem>();
string uri = "https://dev.azure.com/(organization)";
var creds = new VssBasicCredential(string.Empty, "pat");
var wiql = new Wiql()
{
Query = "SELECT [Id] FROM WorkItems"
};
using (var httpClient = new WorkItemTrackingHttpClient(new Uri(uri), creds))
{
var result = httpClient.QueryByWiqlAsync(wiql).Result;
var ids = result.WorkItems.Select(item => item.Id).ToArray();
if (ids.Length == 0)
{
workItems = Array.Empty<WorkItem>();
return;
}
var fields = new[]
{
"System.Title",
"System.WorkItemType",
"System.State",
"System.TeamProject",
"System.Description"
};
workItems = httpClient.GetWorkItemsAsync(ids, fields, result.AsOf).Result;
}
Console.WriteLine("{0} Items Found: ", workItems.Count);
Console.WriteLine();
Console.WriteLine("ID\tTitle\tType\tState\tProject\tDescription");
foreach (WorkItem item in workItems)
{
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
item.Id,
item.Fields["System.Title"],
item.Fields["System.WorkItemType"],
item.Fields["System.State"],
item.Fields["System.TeamProject"],
item.Fields["System.Description"]);
}
Here is also the project references:
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
This code is supposed to return all the parameters, but it gives the following exception:
"The given key 'System.Description' was not present in the dictionary."
Is there any way to solve this?
I think I found a solution: you basically have to make sure that the WI description is not null and, if it is, you want to show a custom message saying that there is no description to the WI:
foreach (WorkItem item in workItems)
{
string desc = item.Fields["System.Description"].ToString();
if (desc == string.Empty) desc = "(missing description)";
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\t{5}",
item.Id,
item.Fields["System.Title"],
item.Fields["System.WorkItemType"],
item.Fields["System.State"],
item.Fields["System.TeamProject"],
desc);
}
This way it will show you the description.

How do I print a list of URLs to console from a webpage using Selenium chrome driver in C#?

The big picture is to print all URLs in a specific location on a website to console.
This can give me the text to all the links, but not the URLs. please help. sorry, I'm very new to coding. I've been told to use a different web driver, but for my current project, I want to stay in Selenium.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using OpenQA.Selenium.Support.UI;
namespace Test_Scraper_1
{
class Program
{
static void Main(string[] args)
{
//Initialize chrome driver
using (var driver = new ChromeDriver())
{
driver.Navigate().GoToUrl("https://www.tfrrs.org/");
//find elements
var Search_Field = driver.FindElementByXPath(#"/html/body/div[3]/div/div/div[4]/div/div[2]/form/div[1]/input");
var Search_Button = driver.FindElementByXPath(#"/html/body/div[3]/div/div/div[4]/div/div[2]/form/div[4]/button");
var Count = 1;
Search_Field.SendKeys("Ashley Smith");
Search_Button.Click();
var titles = driver.FindElementsByClassName("allRows");
foreach (var allRows in titles)
{
Console.WriteLine(allRows.Text + Count++);
}
Console.ReadLine();
}
}
}
}
Your allRows is tr element like below.
<tr class="filtered allRows ">
<td id="col0">
Ashley Smith
</td>
<td id="col1">
Youngstown St. (F)
</td>
</tr>
But you need href attribute of a element. So you need something like this, assuming you want first link:
var column0 = allRows.FindElement(By.Id("col0"));
var aElement = column0.FindElement(By.TagName("a"));
var link = aElement.GetAttribute("href");
Use allRows.getAttribute("href") instead of allRows.Text in your foreach loop to get the URL
namespace Test_Scraper_1
{
class Program
{
static void Main(string[] args)
{
//Initialize chrome driver
using (var driver = new ChromeDriver())
{
driver.Navigate().GoToUrl("https://www.tfrrs.org/");
//find elements
var Search_Field = driver.FindElementByXPath(#"/html/body/div[3]/div/div/div[4]/div/div[2]/form/div[1]/input");
var Search_Button = driver.FindElementByXPath(#"/html/body/div[3]/div/div/div[4]/div/div[2]/form/div[4]/button");
var Count = 1;
//Navigate to target page
Search_Field.SendKeys("Ashley Smith");
Search_Button.Click();
var titles =driver.FindElementsByClassName("allRows"); // driver.FindElementByLinkText("Ashley Smith");
foreach (var title in titles)
{
var Link_Name_TFRRS = title.FindElement(By.TagName("a")).GetAttribute("href"); ;
Console.WriteLine(Link_Name_TFRRS);
}
Console.ReadLine();
}
}
}
}

Only Remove SPGroups that Contain a specific Character

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!");
}

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 do I get the selected values in a list box in asp.net

foreach (ListItem item in ListBoxMembers.Items)
{
if (item.Selected)
{
countSelected += 1;
}
}
for (int counter = 0; counter < countSelected; counter++)
{
string firstName = ListBoxMembers.SelectedItems[counter].Value;
}
This isn't returning the selected value. Where am I going wrong?
the error it throws is
System.Web.UI.WebControls does not contain defenition for listboxmembers.selectedItems error
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.Web.Security;
using System.Data;
using System.Web.UI.WebControls;
These are the name spaces I am using.
This is what I am trying to do
for (int counter = 0; counter < countSelected; counter++)
{
//To get User ID
string firstName=ListBoxMembers.SelectedItems[counter].Value;
// string firstName = ListBoxMembers.Items[counter].Value;
string GUserIDQueryText = "SELECT UserID FROM tbl_user WHERE FirstName ";
int userID = Convert.ToInt32(server.performQuery(GUserIDQueryText, firstName, MySqlDbType.VarChar));
//Insert into tbl_userGroups
string insertIDText = "INSERT INTO tbl_usergroups
(tbl_group_GroupID,tbl_user_UserID) VALUES(#tbl_group_GroupID,#tbl_user_UserID)";
...
}
I want to add all the selected users to the table.
the error it throws is System.Web.UI.WebControls does not contain defenition for listboxmembers.selectedItems Are you missing a directory or assembly directive. Why i am not able to use selectedItems
countSelected = ListBoxMembers.Items.Cast<ListItem>().Where(i => i.Selected).Count();
if you are trying to get all selected items, you can do
var selectedNames = ListBoxMembers.Items.Cast<ListItem>()
.Where(i => i.Selected)
.Select(i => i.Value)
.ToList()
List<string> selectedFirstNames = new List<string>();
foreach (ListItem item in ListBoxMembers.Items)
{
if (item.Selected)
{
selectedFirstNames.Add(item.Value);
}
}
//selectedFirstNames has your list of selected first names
Are you checking for Postback and NOT rebinding when it's a postback? I bet you're blowing away your selected values because you're rebinding. The code in your foreach loop is right.

Categories