deleting sharepoint list item from listview? - c#

I have get all items of a share-point list. Requirement is to delete list items form listview. Plz guide me how it can be done ?
I have idea that it can be done by using checkbox in listview.
I am not getting how to get checked items in listview and how to delete checked items from share point list ?

You can just use the SPListItemCollection.Delete method (assuming you're using the api). If not then use can use Lists.asmx to delete. For example ssomething like the code below will work
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["List1"].Items;
SPListItem item = listItems[k];
listItems.Delete(k);

And if you are using SharePoint 2010 you can use client Object Model - here is howto for exactly your sceanrio: http://msdn.microsoft.com/en-us/library/ee539976.aspx
Johnv2020 answer shows 2 other ways of doing it:
if you can/need to use server side code use regular SahrePoint object model (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitemcollection.delete.aspx - for SharePoint 2010 version, page also contain link to same method in previous version - Windows SharePoint Service 3/MOSS 2007).
If you need to talk to older version of SharePoint from clinet (browser or client application) - use WebService - http://msdn.microsoft.com/en-us/library/cc824213(v=office.12).aspx

Related

How to find SharePoint documents by custom column value using Microsoft Graph API

In SharePoint Online site via my Office 365 account, I've added a column - "CustomerId" to my documents. I want to find all documents with CustomerId of 102 in C# (not in JavaScript).
So far, I'm able to get all files under a folder
var files = graphClient.Sites[siteId].Drive.Items[driveItemId]
.Children.Request().GetAsync().Result;
Or see the same result in Graph Explorer
https://graph.microsoft.com/v1.0/sites/{siteId}/drive/items/{driveItemId}/children
but I haven't figured out the correct syntax to get all documents (driveIems) using the custom column filter condition in C# or in Graph Explorer. Examples of things I've tried:
In C#
var files = graphClient.Sites[siteId].Drive.Items[driveItemId]
.Search("fields/CustomerId eq 102").Request().GetAsync().Result;
In Graph Explorer
https://graph.microsoft.com/v1.0/sites/{siteId}/drive/items/{driveItemId}/search(q='CustomerId eq 102')
Hope someone can help me out on this.
Update:
Previously I got the driveItemId from
var customerFolder = graphClient.Sites[siteId].Drive.Root
.ItemWithPath("CustomerGroup/IndustryGroup").Request().GetAsync().Result;
string driveItemId = customerFolder.Id;
I see I can get a ListItem
var customerFolder = graphClient.Sites[siteId].Drive.Root
.ItemWithPath("CustomerGroup/IndustryGroup").Request()
.Expand(d => d.ListItem).GetAsync().Result;
but I only found a list ID of "4" from customerFolder.ListItem.Id
How shall I get a list ID so that I can use it in graphClient.Sites[siteId].Lists[listId]?
I would suggest to utilize the following query:
https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items?filter=fields/CustomerId eq 123&expand=driveItem
Explanation:
filter items in a list via filter query option
return associated drive items for a list item via expand query option
Here is an example for msgraph-sdk-dotnet:
var request = await graphClient.Sites[siteId].Lists[listId].Items.Request().Filter("fields/CustomerId eq 123").Expand(item => item.DriveItem).GetAsync();
foreach (var item in request)
{
Console.WriteLine(item.DriveItem.WebUrl);
}
Update
The underlying document library list (along with its properties) for a drive could be retrieved like this:
var list = await graphClient.Sites[siteId].Drive.List.Request().GetAsync();
Console.WriteLine(list.Id); //gives SharePoint List Id
Note: https://graph.microsoft.com/beta/sites/{site-id}/drive
endpoint returns the default drive (document library) for this site
Reference
Working with SharePoint sites in Microsoft Graph

How can I add WebPart on Sharepoint WikiPage?

How can I add WebPart on Sharepoint WikiPage?
For example:
How can I add GettingStartedWebPart on Sharepoint 2013 home page (SitePages/Home.aspx)?
I used "Team Site" template for my Site Collection. And removed default
"Get started with your site" web part.
I am trying:
...
SPLimitedWebPartManager spLimitedWebPartManager = spFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
var gettingStartedWebPart = new GettingStartedWebPart();
....
spLimitedWebPartManager.AddWebPart(gettingStartedWebPart, "wpz", 0);
But it doesn't work. Do you have any idea how to do it? Thank you for your time :) and solutions.
Edit:
I found the solution. First of all, you can use standard method for "Wiki Page" WikiEditPage.InsertWebPartIntoWikiPage. But, this method doesn't work correctly... More of this and one of the possible fix you can find if you read this article about SharePoint 2010 (The realization of WikiEditPage.InsertWebPartIntoWikiPage in SharePoint 2013 is the same as in SharePoint 2010): http://habaneroconsulting.com/insights/programmatically-change-content-on-a-wiki-page-in-sharepoint-2010#.VgAEAfmqpBd.
Also: http://maxshulga.blogspot.com/2010/06/wikieditpageinsertwebpartintowikipage.html
I've done something like this in the past with
private void AddWebPartToPage(SPWeb web, string filepath, string zoneidname, int zoneIndex)
{
SPLimitedWebPartManager wpm = web.GetLimitedWebPartManager(filepath, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
wpm.AddWebPart(wp, zoneidname, zoneIndex);
}
AddWebPartToPage(web, web.Url + "SitePages/Home.aspx", "CentreLeft", 0);
You will need to test this though.
Hope this helps.
Cheers
Truez

Submitting Repeating InfoPath Table to Sharepoint list in Browser Enabled Form

Hopefully you can help. I am working on a Browser Enabled InfoPath 2010 form that lives in a Document Library on a SharePoint site (2007 and 2010). In this form there is a repeating table with data that needs to be captured for reporting purposes. The solution I have chosen is to use the built in SharePoint lists.asmx Web Service to write the lines in the repeating table to a separate list on the sane SharePoint site, in the same site collection. I used the steps here, http://msdn.microsoft.com/en-us/library/cc162745(v=office.12).aspx, as my baseline.
I have gotten everything set up and working when run directly from the InfoPath form client site. The form opens and, on submit, the rows in the repeating table are written to the SharePoint list without any problems. However, once I deploy the form through Central Admin and test, none of the rows in the repeating table are getting written to the list. There are no errors or anything to indicate a problem with the code, and a boolean field used to indicate whether or not a row has been uploaded is set to true.
My first thought is that there is a problem with the permissions somewhere. Maybe when the service is called from client side it passes my credentials but when run from the server through the Document Library it's using something different? Shouldn't it use the credentials that are used to gain access to the SharePoint (which are also my AD credentials)? Is there a way to specify the use of the current users AD credentials when calling the lists.asmx web service in the code?
Anyway, not really sure where else to go with this. Any searching I do comes up with the same how two documentation on submitting to a SharePoint list in general. Any help would be greatly appreciated. Below is the code I am using to accomplish this.
if (MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value != "")
{
// If Ship Date is not blank, upload items in Material used to SP List where ForQuote is False
// Quote Number, RMA Number, Ship Date, Unit S/N,
// Create a WebServiceConnection object for submitting
// to the Lists Web service data connection.
WebServiceConnection wsSubmit =
(WebServiceConnection)this.DataConnections["Material Web Service Submit"];
//Create XPathNodeIterator object for the new Material Lines
XPathNodeIterator MaterialLines = this.MainDataSource.CreateNavigator().Select("/my:myFields/my:RepairQuote/my:QuoteLines/my:QuoteLine", NamespaceManager);
int lineCount = 0;
foreach (XPathNavigator NewLines in MaterialLines)
{
lineCount += 1;
if (NewLines.SelectSingleNode(".//my:ForQuote", NamespaceManager).Value == "false" && NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).Value == "false")
{
// Set the values in the Add List Item Template
// XML file using the values in the new row.
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='Title']", NamespaceManager).SetValue(NewLines.SelectSingleNode(".//my:lineItem", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='RMANumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:RMANumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='UnitSerialNumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:serialNumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='ShipDate']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='OrderType']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:orderType", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='QuoteNumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:quoteNumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='LineQuantity']", NamespaceManager).SetValue(NewLines.SelectSingleNode(".//my:lineQuantity", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[#Name='LineNumber']", NamespaceManager).SetValue(lineCount.ToString());
// Set the value of Cmd attribute to "New".
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/#Cmd", NamespaceManager).SetValue("New");
// Submit the new row.
wsSubmit.Execute();
NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).SetValue("true");
}
}
}
I'm unsure why the code doesn't work when you deploy and call the lists web service in code. However I would suggest you to try debugging it to get to the root of the problem:
Step by Step – Debug InfoPath 2010 Forms Deployed on SharePoint 2010 Using Visual Studio 2010
Please try this out and step through it to see if it goes through the code as expected.
Well, I am not sure if it is the answer per se, but I believe the problem was related to security on the site. I got around this by using the SharePoint Object Model instead of the web service to create the list items (See http://www.bizsupportonline.net/browserforms/how-to-use-sharepoint-object-model-submit-data-infopath-browser-form-sharepoint-list.htm). With the SharePoint Object Model I am able to use AllowUnsafeUpdates. Also, where it took me quite a bit of time to get the web service set up, including the data connections, CAML file, etc. This way, however, only took a few minutes. Lesson learned, use the SharePoint Object Model if at all possible.
foreach (XPathNavigator NewLines in MaterialLines)
{
lineCount += 1;
if (NewLines.SelectSingleNode(".//my:ForQuote", NamespaceManager).Value == "false" && NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).Value == "false")
{
using (SPSite site = SPContext.Current.Site)
{
if (site != null)
{
using (SPWeb web = site.OpenWeb())
{
// Turn on AllowUnsafeUpdates on the site
web.AllowUnsafeUpdates = true;
// Update the SharePoint list based on the values
// from the InfoPath form
SPList list = web.GetList("/Lists/InfoPathRtpItems");
if (list != null)
{
SPListItem item = list.Items.Add();
item["Title"] = NewLines.SelectSingleNode(".//my:lineItem", NamespaceManager).Value;
item["RMANumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:RMANumber", NamespaceManager).Value;
item["UnitSerialNumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:serialNumber", NamespaceManager).Value;
item["ShipDate"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value;
item["OrderType"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:orderType", NamespaceManager).Value;
item["QuoteNumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:quoteNumber", NamespaceManager).Value;
item["LineQuantity"] = NewLines.SelectSingleNode(".//my:lineQuantity", NamespaceManager).Value;
item["LineNumber"] = lineCount.ToString();
item.Update();
}
// Turn off AllowUnsafeUpdates on the site
web.AllowUnsafeUpdates = false;
// Close the connection to the site
web.Close();
}
// Close the connection to the site collection
site.Close();
}
}
}

How Can I Add a New Column to All Document Library Lists in SharePoint 2010 Using Visual Studio 2010?

I can't figure out how to create a solution in Visual Studio 2010 that will allow me to alter existing lists in a SharePoint 2010 site. Specifically, I want to add a new column, which contains a small icon, to existing document library lists. I want to be able to take an action when someone clicks on one of the new icons. I also want this new column to become part of the default view for new document library lists. All of this needs to be easily deployed to a SharePoint 2010 site via a .wsp file.
Extensive searching on Google has shown how to create new lists and new column types, and how to programmatically add columns to one of the new lists, but not how to modify all existing lists.
I'm brand new to SharePoint, and any pointers towards a solution would be much appreciated. Thanks!
If you really want to change all Document Libraries in the site, you could try changing the Content Type:
using (SPSite site = new SPSite("http://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
SPContentType ct = web.ContentTypes[SPBuiltInContentTypeId.Document];
SPField fld = web.Fields.GetField(fldName);
SPFieldLink lnk = new SPFieldLink(fld);
ct.FieldLinks.Add(lnk);
ct.Update(true);
}
}
The above code is shortened and modified from the example of SPContentType.Update Method (Boolean). The MSDN article also has good general information on Updating Content Types.

how to add a WebPart to all pages in a SharePoint site?

I am using SharePiont Server 2007 Enterprise with Windows Server 2008 Enterprise, and I am using publishing portal template. I am developing using VSTS 2008 + C# + .Net 3.5. I want to know how to add a WebPart to all pages of a SharePoint Site? Any reference samples?
I want to use this WebPart to display some common information (but the information may change dynamically, and it is why I choose a WebPart) on all pages.
There are two ways to do this depending on your situation.
If the sites exist already, you need to iterate over the sites, adding the web part:
http://blogs.msdn.com/tconte/archive/2007/01/18/programmatically-adding-web-parts-to-a-page.aspx
If the sites do not exist then you can add the web part to the site template:
How to add a web part page to a site definition?
Here's the code from Shiraz's first link worked out a bit more:
(Note: This code is not optimized, for instance, looping through a List's Items collection is not something you should normally do, but seeing as this is probably a one time action there's no problem)
private void AddCustomWebPartToAllPages()
{
using(SPSite site = new SPSite("http://sharepoint"))
{
GetWebsRecursively(site.OpenWeb());
}
}
private void GetWebsRecursively(SPWeb web)
{
//loop through all pages in the SPWeb's Pages library
foreach(var item in web.Lists["Pages"].Items)
{
SPFile f = item.File;
SPLimitedWebPartManager wpm = f.GetLimitedWebPartManager(PersonalizationScope.Shared);
//ADD YOUR WEBPART
YourCustomWebPart wp = new YourCustomWebPart();
wp.YourCustomWebPartProperty = propertyValue;
wpm.AddWebPart(wp, "ZONEID", 1);
f.Publish("Added Web Part");
f.Approve("Web Part addition approved");
}
// now do this recursively
foreach(var subWeb in web.Webs)
{
GetWebsRecursively(subWeb);
}
web.Dispose();
}

Categories

Resources