Thursday, February 9, 2012

SharePoint2010: Create Unique FileName when adding an item in document library programatically using Lambda expression.

public static string CheckFileNameIsUnique(string FileName)
{
string UniqueName = string.Empty;
try
{
SPList splCurrentList = SPContext.Current.Web.Lists["MYLIST"];
bool IsNotUnique = true;
int UniqueIndex = 0;
while (IsNotUnique)
{
UniqueIndex++;
UniqueName = FileName + "_" + String.Format("{0:000}", UniqueIndex);
var listEnumeration = splCurrentList.Items.OfType();
//If any matching record found, IsNotUnique returns "True", else returns 'False".
IsNotUnique = listEnumeration.Any(p => Convert.ToString(p["FILENAME"]).Trim() == UniqueName.Trim());
}
}
catch (Exception ex)
{
}
return UniqueName;
}

Tuesday, February 7, 2012

Check whether the current user exists in any SharePoint security groups

public static Boolean isUserInGroup(string groupName)
{
using (SPWeb spwebCurrentWeb = Functions.GetCurrentWeb())
{
SPGroup spGroup = spwebCurrentWeb.Groups[groupName];
if (spGroup!= null)
return spwebCurrentWeb.IsCurrentUserMemberOfGroup(spGroup.ID);
else
return false;
}
}

Monday, February 6, 2012

Copy data between SPListItems for matching fields in SharePoint.

1. Below code snippet will copy all the matching field data from spListItem2 to spListItem1 without hardcoding the field names.

SPListItem spListItem1 = spListItemCollection1[0];
SPListItem spListItem2 = spListItemCollection2[0];
SPFieldCollection spCollContentTypeFields = spListItem1.ContentType.Fields;
foreach (SPField field in spCollContentTypeFields)
{
if (spListItem2.Fields.Contains(field.Id))
{
if (string.Compare(Convert.ToString(spListItem1[field.StaticName]).Trim(), Convert.ToString(spListItem2[field.StaticName]).Trim(), true) != 0)
{
spListItem1[field.Id] = spListItem2[field.Id];
}
}
}
spListItem1.Web.AllowUnsafeUpdates = true;
spListItem1.Update();

Hope this helps, happy coding...

Friday, February 3, 2012

Welcome

Welcome to MyCodeResearch blogspot, here you will get usefull code snippets that will save your efforts and valuable time in Developement phase.