Wednesday, August 5, 2009

How to get the last element that was added to a SharePoint list

This is so simple yet I could not find anything on the net .... but lucky for you i'm smart like that ... J

So my scenario:

I needed to get the last item added a list which doesn't seem like a hard thing to do but the way in which I was doing it was not the most efficient. So what I was doing was running through the list with a FOR LOOP and finding the last element. Only problem with this is that the list will eventually get very big and this can affect performance.

So the other more efficient solution is converting the list to a data table and then just pulling the last element in the table ... doesn't that sound a whole lot simpler... so here is the code =>

SPList targetList = web.Lists["SomeList"];

DataTable dt = targetList.Items.GetDataTable();

string lastID = (dt.Rows[dt.Rows.Count-1]["ID"]).ToString();

ok so once you get the ID you can find the item in the list by=>

SPListItem item = l.Items.GetItemById(Convert.ToInt32(lastID));

I hope people find this useful

Till the next problem...

 

Tuesday, August 4, 2009

Bypassing the login.aspx (FBA) when a search result is clicked in Moss 2007

Problem statement

We had to create an intranet blog as well as an internet facing blog, both would have the same data. It would be treated like an "authoring" paradigm. Without going into too many details the FBA (Forms Based Authentication) was setup for the external site and windows authentication setup for the internal site compliments of Bramley.

Everything was cool until a problem popped up when the ANON user does a search and one of the search results is clicked. This then takes the user to the FBA login screen and wants the ANON user to log in before it will display the page. This becomes a major pain if users are asked every time they click on a search result to authenticate themselves.

It's such a simple change but took us a whole day and a half to figure out .... J

Go to your login.aspx page on the file server which can be found under the "layouts" folder in the 12 hive.

Add this code to the login.aspx

<script runat="server">

protected override void OnLoad(EventArgs e)

{

//returnWebUrl is the url of the search result that was clicked

string returnWebUrl= Server.UrlDecode(Request.QueryString["ReturnUrl"]);

//set the auth cookie and the redirect

FormsAuthentication.SetAuthCookie("anonymoususer", true);

Response.Redirect("http://sharepoint/"+returnWebUrl);

base.OnLoad(e);

}


</script>


And this should solve the problem of bypassing the FBA login.aspx screen when a search result item is clicked.