Sharepoint - Delete item from recycle - sharepoint

Recently i came across with the following scenario:
Create a list item in custom list
Delete it using the batch deletion procedure (before delete it keep the UniqueId somewhere)
The item goes to the recycle bin
I have tried the web.RecycleBin.Delete(ids) (i used the UniqueId from step 2) and the error System.ArgumentException: ids at Microsoft.SharePoint.SPRecycleBinItemCollection.GetSortedIds(Guid[] ids, SPRecycleBinItemType[]& itemTypes) occurred
I tried to iterate through the recycle bin items and none of the deleted items had the UniqueId from step 2. Also i tried the SPRecycleBinItemCollection.GetItemById without any luck
my question is what guid expects the web.RecycleBin.Delete? I used the item.UniqueId but i think i'm wrong

Based on my test, you can try the following code. You can store the guid in a temp Array.
using (SPSite site = new SPSite(strSiteUrl))//SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
// Allow Unsafe Updates to prevent the cross site scripting
web.AllowUnsafeUpdates = true;
//// Get The SPList
SPList list = web.Lists["123"];
// Get the list items
SPListItem item = list.Items[0];
Guid strGuid = item.UniqueId;
item.Delete();
Guid[] guids = { strGuid };
web.RecycleBin.Delete(guids);
}
}
But I suggest you to use the CSOM to do it.

Related

SPWeb.lists[] List does not exist

I am running my code under administrative rights that iterates over different site->spweb to check the existance of a list. Strangely and for some site the code returns me that list does not exists(exception : List does not exists) Yet i can totally browse the list from browser on the same web
what am i missing here ?
EDIT:Adding Code
foreach (SPSite s in webApp.Sites)
{
foreach (SPWeb w in s.AllWebs)
{
try{
SPList sourceList = w.Lists["Ticks and Cross"];
}catch(exception ex){ ..... }
}
s.Dispose();
}
All sites has same templates, so there is no chance that list is not ther. For some site i get the sourceList, for other its exception, its really wired
I guess you pass incorrect parameter to Lists[]. You should specify valid guid, title or index of the list. Can you post your code?

How to programmatically add target lists to the what's new web part in Sharepoint (or how to handle undocumented namespaces)

From code I've automatically created a lot of similar sites (SPWeb) in my site collection from a site template (in Sharepoint Foundation). Every site has a home page on which I've added the "what's new" web part (found under "Social collaboration").
Even though the web part has several "target lists" (I'd have called it "source lists") added to it on the template site, this connection is lost on the sites created from the template. So I need to programmatically find all these web parts and add the target lists to them. Looping the web parts is not an issue - I've done that before - but I can't seem to find a word on the net on how to go about modifying this particular web part. All I have is a brief intellisense.
I've found out that it recides in the
Microsoft.SharePoint.Applications.GroupBoard.WebPartPages
namespace, but on the lists provided on MSDN this is one of very few namespaces that doesn't have a link to a reference documentation.
Does anyone have any experience of modifying this web part from code? If not, how would you go about to find out? I can't seem to figure out a method for this..
Here is how I did it. It worked really well. I had a feature that created several list instances and provisioned the What's New web part. In the Feature Receiver, I looped through all of the list instances, indexed the Modified field, and then added the list to the web part:
private void ConfigureLists(SPWeb web, SPFeatureReceiverProperties properties)
{
List<Guid> ids = new List<Guid>();
SPElementDefinitionCollection elements =
properties.Feature.Definition.GetElementDefinitions(new CultureInfo((int)web.Language, false));
foreach (SPElementDefinition element in elements)
{
if ("ListInstance" == element.ElementType)
{
XmlNode node = element.XmlDefinition;
SPList list = web.Lists[node.Attributes["Title"].Value];
SPField field = list.Fields[SPBuiltInFieldId.Modified];
if (!field.Indexed)
{
field.Indexed = true;
field.Update();
}
ids.Add(list.ID);
}
}
string targetConfig = string.Empty;
foreach (Guid id in ids)
{
targetConfig += string.Format("'{0}',''\n", id);
}
SPFile file = web.GetFile("Pages/default.aspx");
file.CheckOut();
using (SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
WhatsNewWebPart webpart = null;
foreach (System.Web.UI.WebControls.WebParts.WebPart eachWebPart in manager.WebParts)
{
webpart = eachWebPart as WhatsNewWebPart;
if (null != webpart)
{
break;
}
}
if (null != webpart)
{
webpart.TargetConfig = targetConfig;
manager.SaveChanges(webpart);
}
}
file.CheckIn("ConfigureWebParts");
file.Publish("ConfigureWebParts");
file.Approve("ConfigureWebParts");
}
If you are unsure about the property, export the web part from the browser, then open the .webpart/.dwp file with a text editor. Somewhere in the xml will be a reference to the source list.
*.webparts are usually easier to modify, just set the property.
*.dwps are harder because you sometimes have to get the property (eg ViewXML), then load it into an XmlDocument, then replace the property, and write the xml document string value back to ViewXML.

Is there any log of login attempts to sharepoint 2007?

Where can I find a log of login attempts to share point 2007?
Thanks.
PS: I have another question too, I 'd be really grateful if anybody helps me on it:
Sharepoint users are logged out
I haven't been able to find much without a third party tool. Our group is looking into acquiring DocAve by AvePoint.
In the mean time you can at least get an idea in your site analytics area of your site settings dashboard to see how many people have encountered the /_layouts/accessdenied.aspx page. It wont tell you much, but perhaps you can find a way to customize and add a snippet of code that will take a user's ID when they hit that page. Its not perfect, so I'd suggest a 3rd party tool unless you can scan all of your web front ends etc.
We had a similar requirement once, where we needed to log the last visited time of all the users on the site. So after some period of time, say 90 days, if a particular user had not logged into the site, the admin could delete his profile.
We overcame this problem with a very simple approach. You can follow the sample code for your reference.
You would need to create a list in your site by the name "UserLoginDetails" and create a column "LastLogIn" in that. Code is self explanatory.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Xml.Serialization;
using Microsoft.SharePoint;
namespace Ubaid.WebParts
{
[Guid("883a77d6-271d-4b88-9ca2-d5150a00520b")]
[DefaultProperty("Text"), ToolboxData("<{0}:UserLastVisited runat=server></{0}:UserLastVisited>"), XmlRoot(Namespace = "Ubaid.WebParts")]
public class UserLastVisited : System.Web.UI.WebControls.WebParts.WebPart
{
protected override void CreateChildControls()
{
base.CreateChildControls();
string siteName = SPContext.Current.Web.Url;
using (SPSite site = new SPSite(siteName))
{
SPWeb web = site.OpenWeb();
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
SPList UserLoginDetailsList = web.Lists["UserLoginDetails"];
SPQuery query = new SPQuery();
string uname = SPContext.Current.Web.CurrentUser.LoginName;
query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + uname + "</Value></Eq></Where>";
SPListItemCollection listItemColl = UserLoginDetailsList.GetItems(query);
if (listItemColl.Count > 0)
{
SPListItem item = listItemColl[0];
item["LastLogIn"] = DateTime.Now.ToLocalTime();
item.Update();
}
else
{
SPListItem item = UserLoginDetailsList.Items.Add();
item["Title"] = uname;
item["LastLogIn"] = DateTime.Now.ToLocalTime();
item.Update();
}
}
}
}
}
You can insert this webpart in your masterpage, as the data in this list needs to be updated on every page load.
Not sure which is the best way to do it / performance issues, but since ours was a small site we could manage with this pretty well.

SharePoint 2007 : Get all list items in a list regardless of view from web service?

I need to check for duplicates. Currently I have items stored in sub folders in a list.
How can I retrieve all items in the list from a web service, so I can check for duplicates?
Here is code from object model: I want to do exactly this, but from a web service
private static void PrintItemTitles()
{
string strUrl = "http://localhost:8099/";
using (SPSite site = new SPSite(strUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["MyList"];
SPListItemCollection items = list.Items;
foreach (SPListItem item in items)
if (item != null)
Console.WriteLine(item.Title);
}
}
}
Use SPList.Items doesn't return all items? Well, then try SPList.GetItems(SPQuery).
Have a following SPQuery:
SPQuery query = new SPQuery();
query.ViewFields = "<FieldRef Name='ID'/><FieldRef Name='Title'/>";
query.Query = String.Format("<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>{0}</Value></Eq></Where>", someItemTitle)
query.MeetingInstanceId = -1; //In case if you query recurring meeting workspace - get items from all meetings
query.RowLimit = 10; //Will you have more than 10 duplicates? Increase this value
query.ViewAttributes = "Scope='RecursiveAll'"; //Also return items from folders subfolders
Note: There could be some mistakes in code, because i`m writing from top of my head
By executing this query and if it returns more than one item, then you have a duplicate!
Edit: Ahh, sorry, you are talking about Web Services.
Then this code won't help. There are 2 options then:
Option 1: You CAN create a view that
does include items even from folders
(flat view). See here for
instructions.
Option 2: According to Lists Web Service's GetListItems method, you can pass QueryOptions parameter. Pass in
<QueryOptions>
<MeetingInstanceID>-1</MeetingInstanceID> <!-- Again, if you query recurring meeting, you want ALL items -->
<ViewAttributes Scope='RecursiveAll' /> <!-- or Recursive if that does not work -->
</QueryOptions>
Good luck!
You can use the Lists.asmx web service, but that is quite hard to do as it returns quite a lot of information. I would deploy a custom web service on my SharePoint environment that contains that code and returns the list items.

Add items to list programmatically

I am using form base authentication in my Sharepoint site. On my login page there are custom fields to be filled by unauthenticated user. These fields i want to add in to my list. I am using following code to insert record in list.
protected void AddVendor(object sender, EventArgs e)
{
string strList = "http://comp01:5353/Lists/Vendors/";
using (SPSite site = new SPSite(strList))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPUser user = web.AllUsers["demouser"];
SPList list = web.Lists["Vendors"];
SPListItem Item = list.Items.Add();
Item["First Name"] = txtVendorName.Text;
Item["Last Name"] = txtVLastName.Text;
Item["business"] = txtDescription.Text;
Item["Description"] = txtDescription.Text;
Item["Mobile No"] = txtMobileNumber.Text;
Item["Approved"] = "No";
Item["Created By"] = "demoadmin";
Item["Modified By"] = "demoadmin";
Item.Update();
}
}
}
but is is giving me an error saying that Thread was being aborted. I don't know what exactly missing. but is it because I am performing add action and user is not authenticated...?
I donĀ“t know if it will help you but the code that says (f.e.) Item["Modified By"] will not work since that is the internal name which is Modified_x0020_By. This goes for all the fields with "spaces" in them.
This might be one of your issues...
Where have you written this code, is it inside some event ? Login Control Provides two events that will help you to solve this
OnLoginError="OnLoginError" OnLoggedIn="OnLoggedIn"
I did similar functionality where I wanted to capture the user name loggin to the site and log it to the DB Table. And with respect to the ThreadAbort Exception, it happens when you use Response.Redirect while a code is being executed. In you case I doubt that its being thrown because you are trying to do the above code but the FBA system tries to redirect the user to the default.aspx . Try out above said Event of the Login Control it should help you.

Resources