Sunday, December 7, 2008

Preserving/Updating CreatedBy and ModifiedBy

You might have a scenario where by you want to migrate the list data from one site another site list manually instead of .STP file
Or you use Run With Elevated Privileges ( with delegate()) to insert a record into library where by normal user don't have contribute rights but only READ access Or you need to update one or more fields in a library and you want to preserve Created By and Modified By data.

Here is the Pseudocode:
If Current User is Super user OR Preserver user details is false
Normal Insert
Else
Run the Code With Elevated Privileges to Insert
Then Restore User Details
End If

Code for Restore User Details (C#):

private void RestoreUserDetails(string sitename, string libname, int itemId, int sharePointUserID, string UserLoginName)
{
using (SPSite siteColl = new SPSite(sitename))
{
using (SPWeb web = siteColl.OpenWeb())
{
SPList Legal = web.Lists[libname];
SPListItem LegalItem = Legal.GetItemById(itemId);

//SPFieldUserValue oUser = new SPFieldUserValue(web, web.CurrentUser.ID, web.CurrentUser.LoginName);
SPFieldUserValue oUser = new SPFieldUserValue(web, sharePointUserID, UserLoginName);

LegalItem["Author"] = oUser.User.ID;
LegalItem["Editor"] = oUser.User.ID;
LegalItem.Update();

}
}
}

Tuesday, December 2, 2008

Deactivating the Multiple Documents Option for Upload

We had a business requirement to block the "Upload Multiple Documents" Option for the document library. So add "Content Editor Web Part" check the "Hide" under layouts section.
Then add below code under Source Editor and you are done!.

<script type="text/javascript">
function GetElementByText(tagName, title)
{
var a = document.getElementsByTagName(tagName);

for (var i=0; i < a.length; i++)
{
if (a[i].text)
{
if (a[i].text === title)
{
return a[i];
}
}
}
return null;
}

if (window.onload)
{
var oLoad = window.onload;
window.onload = function bodyLoad()
{
oLoad();
var oMenu = GetElementByText("ie:menuitem","Upload Multiple Documents");
if (oMenu )
{
oMenu .disabled = true;
}
}
}

</script>

Note: If you want to deactivate the Upload Document change the var oMenu ;
var oMenu = GetElementByText("ie:menuitem","Upload Documents");