Wednesday, 25 December 2013

Application Server Role, Web Server (IIS) Role: configuration error


I’m installing SharePoint 2013 on Windows 2012 ‘offline’ – the server has no Internet access.  Within minutes of starting the Preparation Tool to install the prerequisites it has failed to install the Web Server (IIS) Role.
Error_During_Installation
The process failed because additional files are required and the server does not have access to Windows Update.  I’ve got around this by installing the role manually using a few PowerShell commands, namely Add-WindowsFeature, specifying the Windows 2012 DVD as the installation source (the server is virtual so I have mounted the ISO image).  The commands are as follows:
Import-Module ServerManager
Add-WindowsFeature NET-WCF-HTTP-Activation45,NET-WCF-TCP-Activation45,NET-WCF-Pipe-Activation45
Add-WindowsFeature Net-Framework-Features,Web-Server,Web-WebServer,Web-Common-Http,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-App-Dev,Web-Asp-Net,Web-Net-Ext,Web-ISAPI-Ext,Web-ISAPI-Filter,Web-Health,Web-Http-Logging,Web-Log-Libraries,Web-Request-Monitor,Web-Http-Tracing,Web-Security,Web-Basic-Auth,Web-Windows-Auth,Web-Filtering,Web-Digest-Auth,Web-Performance,Web-Stat-Compression,Web-Dyn-Compression,Web-Mgmt-Tools,Web-Mgmt-Console,Web-Mgmt-Compat,Web-Metabase,Application-Server,AS-Web-Support,AS-TCP-Port-Sharing,AS-WAS-Support, AS-HTTP-Activation,AS-TCP-Activation,AS-Named-Pipes,AS-Net-Framework,WAS,WAS-Process-Model,WAS-NET-Environment,WAS-Config-APIs,Web-Lgcy-Scripting,Windows-Identity-Foundation,Server-Media-Foundation,Xps-Viewer -Source D:\Sources\sxs
 
PowerShell_Commands
This process took no more than a few minutes to complete.  After a quick reboot the configuration is completed.  After logging on I restarted the Preparation Tool and it completed without error.

Monday, 25 November 2013

Recently I have changed my SharePoint site Administrator password

 

Recently I have changed my SharePoint site Administrator password. After that whenever I try to create web application it is giving error that Administrator password is wrong.
In this post we will see a quick fix how to resolve this issue

Password Error

Following is the error which I am getting while creating a new web application


Password InCorrect Error

Fixing the problem

Update the farm credentials so that SharePoint will update the new password where ever required

 
stsadm -o updatefarmcredentials -userlogin <domain\username> -password <newpassword>

Add, Update and Delete list items using ECMAScript

Add, Update and Delete list items using ECMAScript

 

Introduction

In this post we will see how to Add, Update and Delete SharePoint list items with ECMAScript (aka javascript client object model)
  • Add item to SharePoint list
  • Update item of SharePoint list
  • Delete item from SharePoint list

Add item to SharePoint list

 
To add an item to the list, use the ListItemCreationInformation object,set the properties using set_item, call the update and ExecuteQueryAsync methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    function AddListItem(){
    var ListName = "MyList";
    var context = new SP.ClientContext.get_current(); // the current context is taken by default here
    //you can also create a particular site context as follows
    //var context = new SP.ClientContext('/Sites/site1');
    var lstObject = context.get_web().get_lists().getByTitle(ListName);
    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = lstObject.addItem(listItemCreationInfo);
    newItem.set_item('Title', 'This is new item');
    // set values to other columns of the list here
    newItem.update();
    context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
        Function.createDelegate(this, this.onFailure));
 
     function onSuccess() {
 
        alert('Item created: ' + newItem.get_id());
    }
 
    function onFailure(sender, args) {
 
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
}

Update Item of SharePoint list

function UpdateListItem()
{
var ListName = "MyList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');
 
var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(1);
lstObjectItem.set_item('Title', 'This is updated item');
lstObjectItem.update();
lstObject.set_description("Updated description using ECMAScript");
lstObject.update();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
 
function onSuccess() {
alert('Item udated');
}
 
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
 
 

Delete Item from SharePoint list

function DeleteListItem()
{
var ListName = "MyList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');
 
var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(1);
lstObjectItem.deleteObject();
 
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
 
function onSuccess() {
alert('Item Deleted');
}
 
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
 
 

Move Files of SharePoint Document Library using Object Model

Move Files of SharePoint Document Library using Object Model

 

Introduction

In this post we will see how to move files of SharePoint document library to one location to another using object model.
We will also see how to keep same file Version, Modified and Modified By values after moving
The post includes
  • Generic method to move file to destination
  • Keeping the file version, Modified and Modified By without any change.

Move file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
string siteUrl = "http://sharepoint-devsite.com/DevSite";
string fileName = "ProjectPlan.docx";
string sourceDirectory = "/DevSite/Shared Documents";
string destinationDirectory  = "/DevSite/ProjectDocs/ProjTeam/DevTeam/TechLead";
using (SPSite currSite = new SPSite(siteUrl))
{
    using (SPWeb currWeb = currSite.OpenWeb())
    {
        MoveFile(currWeb, destinationDirectory, sourceDirectory, fileName);
    }
}
 
public void MoveFile(SPWeb sourceWeb, string sourceDirectory, string destinationDirectory, string fileName)
{
    SPFile sourcefile = sourceWeb.GetFile(sourceDirectory + "/" + fileName);
    if (sourcefile.Exists)
    {
        object modifiedOn = sourcefile.Item["Modified"];
        object modifiedBy = sourcefile.Item["Modified By"];
 
        //true - replace if file exists
        sourcefile.MoveTo(destinationDirectory + "/" + fileName, true);  
 
        SPFile dstFile = sourceWeb.GetFile(destinationDirectory + "/" + fileName);
        SPListItem dstItem = (SPListItem)dstFile.Item;
        dstItem.ParentList.Fields["Modified"].ReadOnlyField = false;
        dstItem.ParentList.Fields["Modified By"].ReadOnlyField = false;
        dstItem["Modified"] = modifiedOn;
        dstItem["Modified By"] = modifiedBy;
        //updates the item without creating another version of the item
        dstItem.UpdateOverwriteVersion();
        dstItem.ParentList.Fields["Modified"].ReadOnlyField = true;
        dstItem.ParentList.Fields["Modified By"].ReadOnlyField = true;
    }
 
}
 
 
 
 
MoveFile is the method which moves the file to destination without changing ‘Modified’ and ‘Modified By’ values.

Move Folders of SharePoint Document Library using object model

Move Folders of SharePoint Document Library using object model


Introduction

SharePoint does not support moving folders directly but in this post we will see how we can achieve move folders of SharePoint document library to one location to another using object model.
We will also see how to keep same folder Version, Modified and Modified By values after moving
The post includes.
  • Moving folder along with subfolders from source to destination
  • Moving folder along with its items
  • Creation of folder
  • Deleting of folder

Skill Level – Medium


Move folder

Object model has MoveTo option on Folder object but that will not move the folder. From UI if we check Content and structure we will get move option on the file but
move option will be in disabled state on the folder.



Below code uses ‘MoveFolder’ method to move folder from source to destination. The method uses internally other methods to move all the subfolders and items.
Source folder ‘DevTeam’ is located in ‘Shared Documents’ Documents Libary
‘DevTeam’ folder should be moved to ‘ProjTeam’ folder under ‘ProjectDocs’ Documents Library. ‘ProjTeam’ is our destination folder.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
string siteUrl = "http://sharepoint-devsite.com/DevSiteA";
string sourceDirectory = "/DevSiteA/Shared Documents/DevTeam";
string destinationDirectory = "/DevSiteA/ProjectDocs/ProjTeam";
 
using (SPSite currSite = new SPSite(siteUrl))
{
    using (SPWeb currWeb = currSite.OpenWeb())
    {
        MoveFolder(currWeb, sourceDirectory, destinationDirectory);
    }
}
 
//Move all folders and subfolder
public void MoveFolder(SPWeb sourceWeb, string sourceDirectory, string destinationDirectory)
{
    SPFolder srcFolder  = sourceWeb.GetFolder(sourceDirectory);
    if (srcFolder.Exists)
    {
        SPDocumentLibrary docLib = srcFolder.DocumentLibrary;
        SPFolderCollection oFolder = srcFolder.SubFolders;
        SPQuery oQuery = new SPQuery();
        oQuery.Query = "<Where><Eq><FieldRef Name='FSObjType'/><Value Type='Lookup'>1</Value></Eq></Where>";
        oQuery.Folder = oFolder.Folder;
        oQuery.ViewAttributes = "Scope='RecursiveAll'";
        SPListItemCollection collListItems = docLib.GetItems(oQuery);
        string newdestinationFolderPath = destinationDirectory;
        //Move the root folder with files
        MoveSingleFolder(sourceWeb, sourceDirectory, newdestinationFolderPath);
 
        newdestinationFolderPath = destinationDirectory + "/" + srcFolder.Name;
        //Move the subfolders with files
        foreach (SPListItem item in collListItems)
        {
            MoveSingleFolder(sourceWeb, item.Url, newdestinationFolderPath);
        }
        // Delete the root folder
        DeleteSourceFolder(sourceWeb, sourceDirectory);
    }
 
}
 
//Move single folder
private void MoveSingleFolder(SPWeb srcWeb, string sourceFolderPath, string destinationFolderPath)
{
    SPFolder srcFolder = srcWeb.GetFolder(sourceFolderPath);
    if (srcFolder.Exists)
    {
        string srcFolderName = srcFolder.Name;
        SPFolder dstFolder = srcWeb.GetFolder(destinationFolderPath);
        if (dstFolder.Exists)
        {
            //create the folder
            SPFolder newFolder = dstFolder.SubFolders.Add(srcFolderName);
                SPListItem newFolderItem = (SPListItem)newFolder.Item;
                newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = false;
                newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified_x0020_By].ReadOnlyField = false;
                newFolderItem[SPBuiltInFieldId.Modified] = srcFolder.Item["Modified"];
                newFolderItem["Modified By"] = srcFolder.Item["Modified By"];
                newFolderItem.UpdateOverwriteVersion();
                newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified].ReadOnlyField = true;
                newFolderItem.ParentList.Fields[SPBuiltInFieldId.Modified_x0020_By].ReadOnlyField = true;
 
        }
        MoveFolderItems(srcWeb, sourceFolderPath, destinationFolderPath + "/" + srcFolderName);
    }
}
 
//Move folder items
private void MoveFolderItems(SPWeb sourceWeb, string sourceFolderPath, string destinationFolderPath)
{
    SPFolder srcFolder = sourceWeb.GetFolder(sourceFolderPath);
    int fileCount = srcFolder.Files.Count;
    while (fileCount > 0)
    {
        SPFile sourceFile = sourceWeb.GetFile(srcFolder.Files[0].Url);
        object modifiedOn = sourceFile.Item["Modified"];
        object modifiedBy = sourceFile.Item["Modified By"];
 
        sourceFile.MoveTo(destinationFolderPath + "/" + sourceFile.Name, true);
 
        fileCount--;
 
        SPListItem dstItem = (SPListItem)sourceFile.Item;
        dstItem.ParentList.Fields["Modified"].ReadOnlyField = false;
        dstItem.ParentList.Fields["Modified By"].ReadOnlyField = false;
        dstItem["Modified"] = modifiedOn;
        dstItem["Modified By"] = modifiedBy;
        dstItem.UpdateOverwriteVersion(); //updates the item without creating another version of the item
        dstItem.ParentList.Fields["Modified"].ReadOnlyField = true;
        dstItem.ParentList.Fields["Modified By"].ReadOnlyField = true;
    }
}
 
//Delete the folder
private void DeleteSourceFolder(SPWeb srcWeb, string sourceFolderPath)
{
    SPFolder srcFolder = srcWeb.GetFolder(sourceFolderPath);
    if (srcFolder.Exists)
    {
        if (srcFolder.Files.Count == 0) //Delete only after moving
        {
            SPFolder srcRootFolder = srcFolder.ParentFolder;
            srcRootFolder.SubFolders.Delete(srcFolder.Url);
        }
    }
 
}

Move Folder creates folder, moves items to it. It will then creates all the subfolders and moves items to each subfolder from the source. After moving is done the source folder is deleted. Version along with ‘Modified’ and ‘Modified By’ values will be same as the source.

Before Moving

Source Folder


After Moving
Destination Folder

Conclusion

Moving folders along with subfolders is a requirement which cannot be done directly from UI or from object model. Hope this code helps when required.

 

Create an Event Receiver for a Specific List Instance

The following steps show how to modify a list item event receiver to respond only to events that occur in a custom announcements-list instance.

To modify an event receiver to respond to a specific list instance

  1. In a browser, open the SharePoint site.
  2. In the navigation pane, Lists link.
  3. In the All Site Content page, choose the Create link.
  4. In the Create dialog box, choose the Announcements type, name the announcement TestAnnouncements, and then choose the Create button.
  5. In Visual Studio, create an event receiver project.
  6. In the What type of event receiver do you want? list, choose List Item Events.
    You can also select any other kind of event receiver that scopes to a list definition, for example, List Email Events or List Workflow Events.
  7. In the What item should be the event source? list, choose Announcements.
  8. In the Handle the following events list, select the An item is being added check box, and then choose the Finish button.
  9. In Solution Explorer, under EventReceiver1, open Elements.xml.
    The event receiver currently references the Announcements list definition by using the following line:
The event receiver currently references the Announcements list definition by using the following line:

<Receivers ListTemplateId="104">
 
Change this line to the following text:

<Receivers ListUrl="Lists/TestAnnouncements">

  1. This directs the event receiver to respond only to events that occur in the new TestAnnouncements announcements list that you just created. You can change the ListURL attribute to reference any list instance on the SharePoint server.
  2. Open the code file for the event receiver and put a breakpoint in the ItemAdding method.
  3. Choose the F5 key to build and run the solution.
  4. In SharePoint, choose the TestAnnouncements link in the navigation pane.
  5. Choose the Add new announcement link.
  6. Enter a title for the announcement, and then choose the Save button.
  7. Notice that the breakpoint is hit when the new item is added to the custom announcements list.
  8. Choose the F5 key to resume.
  9. In the navigation pane, choose the Lists link, and then choose the Announcements link.
  10. Add a new announcement.
  11. Notice that the event receiver does not trigger on the new announcement because the receiver is configured to respond only to events in the custom announcement list instance, TestAnnouncements.

SharePoint Event Handlers – Asynchronous Vs Synchronous


There is a little puzzlement among Asynchronousand Synchronous events, however I believe after reading this article, there will be no place for confusion in your brain, the reason for that I go behind a childlike practice to memorize what is Asynchronous ? and what is Synchronous ?
The same babyish method, I want to share with you.
A for Applefor Asynchronous and for After events, so all Asynchronous events occur after the event, which does not stop the code to execute. All Asynchronous events end with ‘ed’ letters like SiteDeleted, FieldAdded, ItemAdded etc.
Now, let’s talk on the subject of Synchronous events, all Synchronous events  occur before the event, which stop the code to execute. All Synchronous events end with ‘ing’ letters like SiteDeleting, FieldAdding, ItemAdding etc.

SPWebEventReceiver Asynchronous Events
SiteDeletedOccurs after an existing site collection deleted.
WebDeletedOccurs after an existing web site is completely deleted.
WebMovedOccurs after an existing web site has been moved.


SPWebEventReceiver Synchronous Events
SiteDeletingOccurs before an existing site collection is being deleted.
WebDeletingOccurs before an existing web site is deleted.
WebMovingOccurs before an existing web site has been renamed or moved


SPListEventReceiver Asynchronous Methods
FieldAddedOccurs after a field link is added.
FieldDeletedOccurs after a field has been removed from the list.
FieldUpdatedOccurs after a field link has been updated


SPListEventReceiver Synchronous Methods
FieldAddingOccurs before a field link is added to a content type.
FieldDeletingOccurs before a field is removed from the list.
FieldUpdatingOccurs before a field link is updated


SPItemEventReceiver Asynchronous Methods
ItemAddedOccurs after a new item has been added
ItemAttachmentAddedOccurs after an attachment added to an item.
ItemAttachmentDeletedOccurs after an attachment removed from an item.
ItemCheckedOutOccurs after an item is checked out.
ItemDeletedOccurs after an item is completely deleted.
ItemFileMovedOccurs after a file is moved.
ItemUpdatedOccurs after an item is modified/edited.


SPListItemEventReceiver Synchronous Methods
ItemAddingOccurs before a new item is added.
ItemAttachmentAddingOccurs before an attachment is added to an item.
ItemAttachmentDeletingOccurs before an attachment when a user removed from an item.
ItemCheckingInOccurs before a file is checking-in.
ItemCheckingOutOccurs before an item is checking-out.
ItemDeletingOccurs before an item is completely deleted.
ItemFileMovingOccurs before a file is moved.
ItemUncheckedOutOccurs before an item is unchecked out.
ItemUncheckingOutBefore event that occurs when an item is being unchecked out.
ItemUpdatingOccurs before an existing item is modified/edited.


SharePoint Foundation 2010 New Events
Microsoft added several new events to SharePoint Foundation 2010 on SiteList and Item level. These fresh events are intended to meet up the requirements and for better elasticity.
SPWebEventReceiver
WebAddingOccurs before a new web site is created.
WebProvisionedOccurs after the web is provisioned.


WebAdding: event arises prior to a fresh web site is created, we can control the website to create or not to create by WebAdding event, then no SharePoint site is created and the provisioning process is not started.
WebProvisioned: event arise after the web is totally provisioned and process has stopped up. WebProvisioned can be configured to control in any synchronous or asynchronous methods.
If user wants to add few webparts to the newly provisioned web we can use this event to meet up the necessity
SPListEventReceiver
ListAddingOccurs before a list is created.
ListAddedOccurs after a list is created.
ListDeletingOccurs before a list is deleted.
ListDeletedOccurs after a list is deleted.

Creating a simple Event Receiver in SharePoint 2013

Create an empty SharePoint 2013 project in Visual Studio 2012. In the project, select add new item and select Event Receiver

Select the type of event receiver you need to add, and select the events you need to handle.

 Here, I have created the Department library to add and maintain documents and also created DocumentLog list to log the changes happening to the library.



In the list I have three columns, Title, Action & DateAndTime in order to catalog the changes happening to the library.
 
Back to the SharePoint project. Now go to the event receiver .cs file and you'll get a bunch of methods base on your selection during event receiver creation. Edit the code as below to implement the logic. Note that the ItemAdded method is used instead of the ItemAdding method.
 
public override void ItemAdded(SPItemEventProperties properties)
        {
            //base.ItemAdded(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Added";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemUpdating(SPItemEventProperties properties)
        {
            //base.ItemUpdating(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Updated";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

public override void ItemDeleting(SPItemEventProperties properties)
        {
            //base.ItemDeleting(properties);
            using (SPWeb web = properties.OpenWeb())
            {
                try
                {
                    SPList list = web.Lists["DocumentLog"];
                    SPListItem newItem = list.Items.Add();
                    newItem["Title"] = properties.ListItem.Name;
                    newItem["DateAndTime"] = System.DateTime.Now;
                    newItem["Action"] = "Item Deleted";
                    newItem.Update();
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }