SharePoint Kings,Technosavvy guys hunting SharePoint Challenges... SharePoint 2013, SharePoint 2010, MOSS 2007, Windows Workflow Foundation, Project Server and Other Related Technologies.
Wednesday, August 31, 2011
Calculating Age in SharePoint calculated field
In this post, we are going to discuss how to calculate age based on birthdate in SharePoint list field. Now you must be wondering, what is the big deal about this post? It is so easy to calculate age as calculated field.
Well, it’s not that easy. Try it out yourself. First you might think that what we can do is we can create one field with the name age and have it as a calculated field and write a formula which will calculate difference between today and the birthdate with using YEAR function and you are done. However this is not going to help. The reason behind this is we cannot use Today in the calculated field. If you try to do so, you will get an error. So below calculation will not work.
We cannot use Today in calculated field. This is the major drawback as of now. There are many instances where we need to calculate many things based on Today’s date. However when now it’s not possible directly, we need to play a trick here.
And the trick is to confuse SharePoint. Now how can we confuse SharePoint? Well answer is very simple. We all know that we can use fields in the calculated fields. It allows us to select the fields from the list which we already have like shown in above image.
So we are going to create a field called Today as single line of text. So go ahead and create a field called Today. Remember, that the name should be Today. Now create field called Age and then use the same formula.
So here what we have done is we have confused SharePoint. Because SharePoint thinks that you will use this as part of a field formula which we will not.
Now go ahead and delete the Today field that we’ve created. We are done. Enter the data, enter birthdate and see the Age field populating.
Do remember one thing. If you need by any chance to change the field settings of Age or any field that you may or may not encounter error again. In that case, you again need to create a field called Today. Work on your modifications and then delete Today column. It’s a trick. Well to my opinion, this can vary. Because when I tested this on one server, it gave me error when I clicked on Ok button of Age field after removing Today column. And on the other server, it went fine. So still not sure why is this.
However at least I have showed you how to calculate Age. Wasn’t that a nice trick that we played with SharePoint? Do let us know.
Monday, August 29, 2011
Client Object Model – Part 12
In this post, we are going to discuss on one very important aspect of client object model. But before that if you have not gone through Part 1 to Part 11, I would recommend reading them first and then continue reading from here.
You must have thought that in none of the series we talked about authentication. How does a client object model connects with the respective objects on the server like lists, sites, libraries, workflows etc.?
There are three methods.
1) Default authentication
2) Forms authentication
3) Anonymous authentication
And we have managed client object model, Silverlight client object model and ECMA script object model.
Managed COM – Windows authentication is default authentication.
So we do not need to explicitly specify anything. When we do not specify anything, it connects with our windows credentials and then checks our access on objects that we access through object model.
So we need to be very careful while writing a code that when the code runs, user should have a sufficient privilege on objects.
We can use anonymous or forms authentication with managed COM.
Silverlight COM – Same as Managed COM.
ECMA COM - Do not need any authentication. It runs inside the browser page and hence by default it has passed the parent authentication method.
Setting the Forms bases authentication on COM
If we use Forms authentication, then we need to set one more property which is AuthenticationMode on clientcontext object.
Plus we also need to make an instance of FormsAuthenticationLoginInfo class and assign the username and password before accessing or performing any operation on any SharePoint object and then set that authentication object to client context object.
FormsAuthenticationLoginInfo("UserName", "Password");
clientContext.FormsAuthenticationLoginInfo = objformsAuth;
Setting the Anonymous authentication on COM
ClientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
Do remember that when using this method, object which you are trying to access in code should have anonymous permission assigned.
Thursday, August 25, 2011
Client Object Model – Part 11
If you have not gone through Part 1 to Part 10, I would recommend you reading them first and then continue exploring from here. There is a lot of stuff to learn in those parts.
1) Break Role Inheritance
If you want to break role inheritance for a list or any list item or library or document or a sub site, we can use BreakRoleInheritance(Boolean, Boolean) method to break it. Breaking inheritance means stopping permission inheriting from its parent and then assigning unique permissions for specific object.
If first Boolean parameter which is CopyRoleAssignments is false then it even does not copy any permission from parent and user becomes an owner of that object under whom the code is running. Second parameter which is clearSubScopes means that do we need to clear the unique permission on child object and then subsequently inherit permission from its parent or not.
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
BreakInheritance();
}
private void BreakInheritance()
{
context = ClientContext.Current;
web = context.Web;
List lstEmployee = web.Lists.GetByTitle("Employees");
lstEmployee.BreakRoleInheritance(true, true);
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
lblOutputLabel.Text = "Inheritance has been broken successfully from its parent site";
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
2) Custom User Actions
Custom user actions mean any action that is added to the default options given in the SharePoint. We can add edit control block as custom action which reflects an option while we select the list item or document item in list or library. We can define custom action to be in the menu options of site actions menu. We can also define custom actions options for modify all site settings sub menu options.
UserCustomActions returns the collection of all custom actions defined in an object. If your object is list, then it returns all custom actions defined in that list. If your object is site, then it returns all custom actions defined at site level.
We can add, remove and update custom actions through client object model. Whatever we can do with one client object model method can be achieved with other client object model methods.
Adding custom user actions to a list edit control block
context = ClientContext.Current;
web = context.Web;
List lstEmployee = web.Lists.GetByTitle("Employees");
UserCustomActionCollection collCustomAction = lstEmployee.UserCustomActions;
UserCustomAction UserCustomAction = collCustomAction.Add();
UserCustomAction.Location = "EditControlBlock";
UserCustomAction.Sequence = 100;
UserCustomAction.Title = "SPKings User Custom Action";
UserCustomAction.Url = context.Url + @"/_layouts/SPKingsPage.aspx";
UserCustomAction.Update();
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
Update custom user actions to a list edit control block
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
UserCustomActionCollection collCustomAction;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
AddCustomAction();
}
private void AddCustomAction()
{
context = ClientContext.Current;
web = context.Web;
List lstEmployee = web.Lists.GetByTitle("Employees");
collCustomAction = lstEmployee.UserCustomActions;
context.Load(collCustomAction,
userCustomActions => userCustomActions.Include(
userCustomAction => userCustomAction.Title));
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
foreach (UserCustomAction oUserCustomAction in collCustomAction)
{
if (oUserCustomAction.Title == "SPKings User Custom Action")
{
oUserCustomAction.ImageUrl = context.Url + "/_layouts/images/SomeImage.jpeg";
oUserCustomAction.Update();
context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);
}
}
}
private void DisplayMessage()
{
lblOutputLabel.Text = "Custom Action - ECB has been update successfully";
}
private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUIAfterUpdate = DisplayMessage;
this.Dispatcher.BeginInvoke(updateUIAfterUpdate);
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
3) Working with Web Parts on a page
We can get all the web parts residing on a page with the help of client object model and re arrange them as well as change their properties like title. We can also remove them or add new one as well.
Change title of the web part
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
LimitedWebPartManager limitedWebPartManager = null;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
AddCustomAction();
}
private void AddCustomAction()
{
context = ClientContext.Current;
string URL = ClientContext.Current.Url;
web = context.Web;
File HomePage = web.GetFileByServerRelativeUrl("/sites/SP2010/Shared%20Documents/Default.aspx");
limitedWebPartManager = HomePage.GetLimitedWebPartManager(PersonalizationScope.Shared);
context.Load(limitedWebPartManager.WebParts,
webparts => webparts.Include(
webpart => webpart.WebPart.Title));
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
WebPartDefinition oWebPartDefinition = limitedWebPartManager.WebParts[1];
WebPart oWebPart = oWebPartDefinition.WebPart;
oWebPart.Title = "SPKings Title Changed again";
oWebPartDefinition.SaveWebPartChanges();
context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);
}
private void DisplayMessage()
{
lblOutputLabel.Text = "WebPart title has been changed successfully";
}
private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUIAfterUpdate = DisplayMessage;
this.Dispatcher.BeginInvoke(updateUIAfterUpdate);
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
Deleting a web part
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
LimitedWebPartManager limitedWebPartManager = null;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
AddCustomAction();
}
private void AddCustomAction()
{
context = ClientContext.Current;
string URL = ClientContext.Current.Url;
web = context.Web;
File HomePage = web.GetFileByServerRelativeUrl("/sites/SP2010/Shared%20Documents/Default.aspx");
limitedWebPartManager = HomePage.GetLimitedWebPartManager(PersonalizationScope.Shared);
context.Load(limitedWebPartManager.WebParts);
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
WebPartDefinition webPartDefinition = limitedWebPartManager.WebParts[1];
webPartDefinition.DeleteWebPart();
context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);
}
private void DisplayMessage()
{
lblOutputLabel.Text = "WebPart has been deleted successfully";
}
private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUIAfterUpdate = DisplayMessage;
this.Dispatcher.BeginInvoke(updateUIAfterUpdate);
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
//MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
lblOutputLabel.Text = "Request Failed: " + e.Message; // +"Stack Trace:" + e.StackTrace;
}
}
}
Read more in Part-12
Tuesday, August 23, 2011
Client Object Model – Part 10
Some more examples of Silverlight Client object model
1) Iterating through groups and users
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
GroupCollection collGroup;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
collGroup = context.Web.SiteGroups;
context.Load(collGroup);
context.Load(collGroup,
groups => groups.Include(
group => group.Users));
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
foreach (Group groupItem in collGroup)
{
lblOutputLabel.Text += "Group Name: " + groupItem.Title + Environment.NewLine + "________________" + Environment.NewLine;
UserCollection userColl = groupItem.Users;
foreach (User user in userColl)
{
lblOutputLabel.Text += " User Name : " + user.Title + Environment.NewLine;
}
}
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
2) Iterating through groups and users by including only specific properties
Same as above example, only thing to change is instead of
context.Load(collGroup);
context.Load(collGroup,
groups => groups.Include(
group => group.Users));
We can write something like this:
context.Load(collGroup,
groups => groups.Include(
group => group.Title,
group => group.Id,
group => group.Users.Include(
user => user.Title )));
Here what we have done is we have only included groups ID and Title as well as users Title only. It becomes faster than the previous example due to less network traffic.
3) Creating Group
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
GroupCollection collGroup;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
GroupCreationInformation FinanceGroup = new GroupCreationInformation();
FinanceGroup.Title = "Finance Group";
FinanceGroup.Description = "This group has been added through SCOM";
web.SiteGroups.Add(FinanceGroup);
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
lblOutputLabel.Text = "Group has been created successfully";
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
4) Adding users to a group
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
GroupCollection collGroup;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
GroupCollection collGroup = context.Web.SiteGroups;
Group FinanceGroup = collGroup.GetById(3);
UserCreationInformation userCreationInfo = new UserCreationInformation();
userCreationInfo.Email = "name@domain.com";
userCreationInfo.LoginName = @"DOMAIN\name";
userCreationInfo.Title = "Michael";
User User = FinanceGroup.Users.Add(userCreationInfo);
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
lblOutputLabel.Text = "Group has been created successfully";
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
Keep reading Part 11 to explore Client Object Model more.
Monday, August 22, 2011
Result is out
Thursday, August 18, 2011
Client Object Model – Part 9
If you have not gone through Part 1 to Part 8, I would recommend you reading them first and then continue reading.
Let’s explore more examples
1) Querying a list and return selected fields only. Here I am retrieving only three fields that I want to show.
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
ListItemCollection listItems ;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
List lstEmployees = web.Lists.GetByTitle("Employees");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Title'/>
<Value Type='Text'>Andre Pal</Value>
</Eq>
</Where>
</Query>
<RowLimit>100</RowLimit>
</View>";
listItems = lstEmployees.GetItems(camlQuery);
context.Load(
listItems,
items => items
.Include(
item => item["Title"],
item => item["Last_x0020_Name"],
item => item["EmployeeID"]));
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
foreach (ListItem listItem in listItems)
{
lblOutputLabel.Text += "Title:" + listItem["Title"] + " Last Name : " + listItem["Last_x0020_Name"] + " Employee ID : " + listItem["EmployeeID"] + Environment.NewLine;
}
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
2) Update items in a list. Here I have used the same above code. We need to take care what when we are dealing with Silverlight, we cannot block UI and hence for every operation that we perform, we need to pass on asynchronous callback functions. Hence when we are updating the record, we have passed on another function which updates and then call appropriate method once succeeded or failed.
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
ListItemCollection listItems ;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
List lstEmployees = web.Lists.GetByTitle("Employees");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Title'/>
<Value Type='Text'>Andre Pal</Value>
</Eq>
</Where>
</Query>
<RowLimit>100</RowLimit>
</View>";
listItems = lstEmployees.GetItems(camlQuery);
context.Load(
listItems,
items => items
.Include(
item => item["Title"],
item => item["Last_x0020_Name"],
item => item["EmployeeID"]));
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
foreach (ListItem listItem in listItems)
{
listItem["Title"] = listItem["Title"] + " Updated From Code";
listItem.Update();
}
context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);
}
private void UpdateSuccess()
{
MessageBox.Show("All records updated");
}
private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUISuccess = UpdateSuccess;
this.Dispatcher.BeginInvoke(updateUISuccess);
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
3) Delete items from list
Deleting list items is pretty easy stuff. However there is one very important thing that we need to take care of. When we get the list items object and when we loop through items to delete them one by one, then collection keep losing one element from it and then we end up having exception thrown from it or finishes without removing certain items. Hence we need to change list items collection with the help of ToList method like shown below.
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
ListItemCollection listItems ;
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
List lstEmployees = web.Lists.GetByTitle("Employees");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Title'/>
<Value Type='Text'>Andre Pal</Value>
</Eq>
</Where>
</Query>
<RowLimit>100</RowLimit>
</View>";
listItems = lstEmployees.GetItems(camlQuery);
context.Load(
listItems,
items => items
.Include(
item => item["Title"],
item => item["Last_x0020_Name"],
item => item["EmployeeID"]));
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
foreach (ListItem listItem in listItems.ToList())
{
listItem.DeleteObject();
}
context.ExecuteQueryAsync(LoadSuccesAfterUpdate, LoadFailed);
}
private void UpdateSuccess()
{
MessageBox.Show("All records deleted");
}
private void LoadSuccesAfterUpdate(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUISuccess = UpdateSuccess;
this.Dispatcher.BeginInvoke(updateUISuccess);
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
Keep reading Part 10 to explore more on Silverlight client object model.
Tuesday, August 16, 2011
Client Object Model – Part 8
1) Iterating through list items
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
ListItemCollection listItems;
private delegate void UpdateUIMethod();
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
List lstEmployees = web.Lists.GetByTitle("Employees");
CamlQuery Query = new CamlQuery();
Query.ViewXml = "<View/>";
listItems = lstEmployees.GetItems(Query);
context.Load(lstEmployees);
context.Load(listItems);
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
foreach (ListItem listItem in listItems)
{
lblOutputLabel.Text += Environment.NewLine + "\n" +
"ID: " + listItem.Id + " Title:" + listItem["Title"] + " First Name : " + listItem["First_x0020_Name"]
+ " Last Name" + listItem["Last_x0020_Name"];
}
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
2) Getting only specific properties
Instead of getting all properties of any specific object, if we want to get only specific properties that we are interested in, we can use lambda expression in query. This will result in less network traffic.
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
ListItemCollection listItems;
private delegate void UpdateUIMethod();
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
context.Load(web,
s => s.Title,
s => s.Description);
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
lblOutputLabel.Text += "Web Title : " + web.Title + Environment.NewLine + "\n" + " Description:" + web.Description ;
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
3) Create a list and list items
namespace SilverlightSPCOM
{
public partial class MainPage : UserControl
{
private ClientContext context = null;
private Web web = null;
private delegate void UpdateUIMethod();
public MainPage()
{
InitializeComponent();
}
private void btnRetrive_Click(object sender, RoutedEventArgs e)
{
LoadData();
}
private void LoadData()
{
context = ClientContext.Current;
web = context.Web;
ListCreationInformation lstCreationListFromSL =
new ListCreationInformation();
lstCreationListFromSL.Title = "List created from silverlight";
lstCreationListFromSL.TemplateType = (int)ListTemplateType.GenericList;
List lstFromSL = web.Lists.Add(lstCreationListFromSL);
Field fldFirstName = lstFromSL.Fields.AddFieldAsXml(@"<Field Type='Text' DisplayName='First Name'/>", true, AddFieldOptions.DefaultValue);
Field fldLastName = lstFromSL.Fields.AddFieldAsXml(@"<Field Type='Text' DisplayName='Last Name'/>", true, AddFieldOptions.DefaultValue);
Field fldAge = lstFromSL.Fields.AddFieldAsXml(@"<Field Type='Number' DisplayName='Age'/>", true, AddFieldOptions.DefaultValue);
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem listItem = lstFromSL.AddItem(itemCreateInfo);
listItem["Title"] = "1 Item created From SL";
listItem["First_x0020_Name"] = "John";
listItem["Last_x0020_Name"] = "Desilva";
listItem["Age"] = "25";
listItem.Update();
listItem = lstFromSL.AddItem(itemCreateInfo);
listItem["Title"] = "2 Item created From SL";
listItem["First_x0020_Name"] = "Michelle";
listItem["Last_x0020_Name"] = "Alberto";
listItem["Age"] = "24";
listItem.Update();
context.ExecuteQueryAsync(LoadSucces, LoadFailed);
}
private void DisplayData()
{
lblOutputLabel.Text += "List Created successfully and items are also created successfully";
}
private void LoadSucces(object sender, ClientRequestSucceededEventArgs e)
{
UpdateUIMethod updateUI = DisplayData;
this.Dispatcher.BeginInvoke(updateUI);
}
private void LoadFailed(object sender, ClientRequestFailedEventArgs e)
{
MessageBox.Show("Request Failed: " + e.Message + ", Stack Trace:" + e.StackTrace);
}
}
}
Many more examples to come. Keep reading Part-9 of this series.
Friday, August 12, 2011
Client Object Model – Part 7
1) Query List
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(QueryListData, "sp.js");
function QueryListData()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle("Employees");
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="First_x0020_Name"/><Value Type="Text">Andre</Value></Eq></Where></Query><ViewFields><FieldRef Name="Title" /></ViewFields></View>');
this.listItems = this.list.getItems(camlQuery);
currentcontext.load(listItems);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
var listEnumerator = this.listItems.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();
var title = item.get_item('Title');
alert(title);
}
}
function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>
2) Getting version and other info from list item. Also check out how to get lookup field value in case of created by and modified by.
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(QueryListData, "sp.js");
function QueryListData()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle("Employees");
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name="First_x0020_Name"/><Value Type="Text">Andre</Value></Eq></Where></Query></View>');
this.listItems = this.list.getItems(camlQuery);
currentcontext.load(listItems);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
var listEnumerator = this.listItems.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();
var title = item.get_item('Title');
var vInformation = item.get_item('_UIVersionString');
var Created = item.get_item('Created');
var Modified = item.get_item('Modified');
var CreatedBy = item.get_item('Author').get_lookupValue();
var ModifiedBy = item.get_item('Editor').get_lookupValue();
var totalsctring = "Title:" + title + "\n" + "Version:" + vInformation + "\n" + "Created:" + Created +"\n" +
"Modified:" + Modified +"\n" +
"CreatedBy:" + CreatedBy +"\n" +
"ModifiedBy :" + ModifiedBy +"\n" ;
alert(totalsctring);
}
}
function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>
3) Iterate through Site Groups
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(IteratethroughGroup, "sp.js");
function IteratethroughGroup()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.groupCollection = currentweb.get_siteGroups();
currentcontext.load(this.groupCollection);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
var listEnumerator = this.groupCollection.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();
groupName = item.get_title();
alert(groupName);
}
}
function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>
4) Iterate through recycle bin
Remember, this is for the site collection recycle bin because we have taken site as a reference. If you want to take individual web recycle bin into consideration then use ge_web istead of get_site option. Rest everything need not to be changed.
<script type="text/javascript">
var currentcontext = null;
var currentsite = null;
ExecuteOrDelayUntilScriptLoaded(IteratethroughRecycleBin, "sp.js");
function IteratethroughRecycleBin()
{
currentcontext = new SP.ClientContext.get_current();
currentsite = currentcontext.get_site();
this.rbincoll = currentsite.get_recycleBin();
currentcontext.load(this.rbincoll);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
if(this.rbincoll.get_count() > 0)
{
var listEnumerator = this.rbincoll.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();
var title = item.get_title();
var id = item.get_id();
alert("ID: " + id+ "\nTitle:" + title);
}
}
else
{
alert('There is no item in recycle bin');
}
}
function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>
Keep reading Part 8 of this series.
Wednesday, August 10, 2011
Client Object Model – Part 6
We are going to see more examples of ECMA script here.
1) Create Site
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(CreateSite, "sp.js");
function CreateSite()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
var webCreateInfo = new SP.WebCreationInformation();
webCreateInfo.set_description("This site created from ECMA script");
webCreateInfo.set_language(1033);
webCreateInfo.set_title("ECMA Script created site");
webCreateInfo.set_url("ECMAScriptSite");
webCreateInfo.set_useSamePermissionsAsParentSite(true);
webCreateInfo.set_webTemplate("STS#0");
this.NewWebsite = this.currentweb.get_webs().add(webCreateInfo);
currentcontext.load(this.NewWebsite, 'ServerRelativeUrl', 'Created');
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert("Web site url : " + this.NewWebsite.get_serverRelativeUrl());
}
function ExecuteOnFailure(sender, args) {
alert('Site cannot be created');
}
</script>
2) Iterate through sub sites
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(EnumerateThroughSite, "sp.js");
function EnumerateThroughSite()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.subsites = currentweb.get_webs();
//this.sitecoll = currentcontext.get_site(); //to get top level site - just for information
currentcontext.load(this.subsites);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
var subsites = '';
var groupEnumerator = this.subsites.getEnumerator();
while (groupEnumerator.moveNext()) {
var Site = groupEnumerator.get_current();
subsites += '\nID: ' + Site.get_id() +
'\nTitle: ' + Site.get_title();
}
alert(subsites);
}
function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>
3) Load List properties
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(LoadListProp, "sp.js");
function LoadListProp()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle("Employees");
currentcontext.load(list, 'Title', 'Id');
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert('List title : ' + this.list.get_title() + '; List ID : '+ this.list.get_id());
//alert('success');
}
function ExecuteOnFailure(sender, args) {
alert("Cannot enumerate");
}
</script>
4) Load List Data
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(LoadListData, "sp.js");
function LoadListData()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle("Employees");
var camlQuery = new SP.CamlQuery();
var query = '<View><RowLimit>3</RowLimit></View>';
camlQuery.set_viewXml(query);
this.listItems = list.getItems(camlQuery);
currentcontext.load(listItems, 'Include(DisplayName,Id)');
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
var listEnumerator = this.listItems.getEnumerator();
//iterate though all of the items
while (listEnumerator.moveNext()) {
var item = listEnumerator.get_current();
var title = item.get_displayName();
var id = item.get_id();
alert("Item title : " + title + "; Item ID : "+ id);
}
}
function ExecuteOnFailure(sender, args) {
alert("Cannot load list data");
}
</script>
Keep reading Part 7 for further exploring ECMA script.
Monday, August 8, 2011
Client Object Model – Part 5
various operations sing ECMA script.
If you have not gone through Part 1 to Part 4, I would recommend reading them first before continue this.
Let’s expand our example and explore how we can create lists, list items, delete list etc. These operations are easy to perform. Once you get to know how to call list and list items, then it’s really easy to play around with them.
1) Create List
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(CreateList, "sp.js");
function CreateList()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext .get_web();
var ListInfo = new SP.ListCreationInformation();
var ItemInfo = new SP.ListItemCreationInformation();
ListInfo.set_title('List Created From ECMA Script');
ListInfo.set_templateType(SP.ListTemplateType.genericList);
this.createdList = currentweb.get_lists().add(ListInfo);
currentcontext.load(createdList, 'Title','Id');
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert('list title:' + createdList .get_title() + '\n ID' + createdList .get_id());
}
function ExecuteOnFailure(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
2) Delete List
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(DeleteList, "sp.js");
function DeleteList()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
this.list.deleteObject();
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert('list deleted successfully');
}
function ExecuteOnFailure(sender, args) {
alert('list could not be deleted');
}
</script>
3) Update List
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(UpdateList, "sp.js");
function UpdateList()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
this.list.set_description('Description set from ECMA script');
list.update();
currentcontext.load(list, 'Description');
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert('list description :' + this.list.get_description());
}
function ExecuteOnFailure(sender, args) {
alert('Description cannot be set');
}
</script>
4) Create List Item
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(CreateListItem, "sp.js");
function CreateListItem ()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
var ItemInfo = new SP.ListItemCreationInformation();
this.ListItem = list.addItem(ItemInfo);
ListItem.set_item('Title', 'Item created from ECMA script');
ListItem.update();
currentcontext.load(ListItem);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert('list item id:' + this.ListItem.get_id());
}
function ExecuteOnFailure(sender, args) {
alert('List Item cannot be created');
}
</script>
5) Update List Item
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(UpdateListItem, "sp.js");
function UpdateListItem()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
this.ListItem = list.getItemById(1);
ListItem.set_item('Title', 'Item ID 1 update using ECMA script');
ListItem.update();
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert('list item updated successfully');
}
function ExecuteOnFailure(sender, args) {
alert('List Item cannot be updated');
}
</script>
6) Delete List Item
<script type="text/javascript">
var currentcontext = null;
var currentweb = null;
ExecuteOrDelayUntilScriptLoaded(DeleteListItem, "sp.js");
function DeleteListItem()
{
currentcontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
this.list = currentweb.get_lists().getByTitle('List Created From ECMA Script');
this.ListItem = list.getItemById(1);
ListItem.deleteObject();
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}
function ExecuteOnSuccess(sender, args) {
alert('list item deleted successfully');
}
function ExecuteOnFailure(sender, args) {
alert('List Item cannot be deleted');
}
</script>
There are more examples to come in series. Read Part-6
Wednesday, August 3, 2011
Result is out
Tuesday, August 2, 2011
Login with different user – SharePoint designer
If you have used designer then you must know that there is no way to log in with the different user straight. You need to close designer and re open if you wish to test something with different user’s credentials.
In SharePoint Designer 2010, we have an option to do that. However not many people know this. This is because the icon which allows us to do this almost goes unnoticed.
When you click on that small user icon on down left side, it allows you to login with different user without closing SharePoint Designer.
This feature is not available in SharePoint Designer 2007.
Now that’s a handy tip. Isn’t it?
Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!
If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com