Wednesday, March 20, 2013

SharePoint 2013 configure People Search using PowerShell Scripts

Hi guys in this post I'm going to show how can we configure people search using PowerShell. There are some prerequisites for people search.

People search prerequisites:
  • Search Service Application should be running in the SharePoint farm. 
  • SharePoint farm also should have a Search Center. (Enterprise Search Center)
  • Managed Metadata Application should be running in the SharePoint farm. 
  • User Profile Service should be configured and running in the farm.
  • MySite Should be configured.
So check the above given prerequisites are working in your SharePoint farm.

These are the steps to configure people search:

  • Check whether your user account has administrator privileges on both Search Service Application and User Profile Service Application.
  • Create a new crawl rule 
          #Creating a crawl rule for MySite Web Application
          $Path = "sps3://<host name>"
          $UserName = Read-Host "Enter Username"
          $Password = Read-Host "Enter Password" -AsSecureString
          $SearchApp = Get-SPEnterpriseSearchServiceApplication
          $Rule = New-SPEnterpriseSearchCrawlRule -SearchApplication $SearchApp -Path $Path -Type    InclusionRule -AuthenticationType BasicAccountRuleAccess -AccountName $UserName -AccountPassword $Password 
          $Rule.Update()
          Write-Host -f Green "New Rule created"

Before you run this script specify the Url of the Web Application where MySite is deployed (Url format is: sps3://<host name>) for $Path variable. It'll prompt for user authentication give the correct user credentials which has the administrator privileges.

  • Remove the Url of the Web Application where MySite is deployed from the default Content Source (Local SharePoint Sites)
          #Removing the MySite Url from the default Content Source
          $search = Get-SPEnterpriseSearchServiceApplication "Search Service Application"
          $contentSource = Get-SPEnterpriseSearchCrawlContentSource -SearchApplication $search -Identity "Local SharePoint Sites"
          $addresses = $contentSource.StartAddresses
          $addresses.Remove($Path)
          $contentSource.Update()
          Write-Host -f Green "Web Application Url of MySite successfully removed from default content source"

Before you run this script specify the name of your Search Service Application for $search variable.

  • Now create a new Content Source with Url that you removed from the default Content Source.
          #Creating a new content source for MySite
          New-SPEnterpriseSearchCrawlContentSource -SearchApplication $search -Type SharePoint -name   "MySite" -StartAddresses $Path 
          Write-Host -f Green "New content source is successfully created for MySite"

After you run this script new Content Source will be created with the name "MySite". Go to manage content sources in Search Service Application, click on the newly created Content Source and click "Start Full Crawl".  

Now good to go people search is successfully configured.

Feel free to give your feed backs.
Cheers.

Luckshan Roy.

Friday, March 8, 2013

Sharepoint 2013 creating a new discussion on discussions list

Hi guys have you all ever tried creating a new discussion on discussions list programmatically?? I tried recently and got an issue. Like we all normally create and add an item  to a list I tried adding a discussion item on discussions list. Well it got created as the way I want but when I tried to reply to that discussion a message box popped and gave this following error message.

"Value does not fall within the expected range"

This is the C# code I used to create and add a new disussion on discussions list.


using (SPSite site = new SPSite("http://site-url"))
{
          using (SPWeb web = site.OpenWeb())
          {
                    SPList list = web.Lists["Discussions List"];
                    SPListItemCollection listItemCln = list.GetItems(list.Views["Management"]);

                    SPListItem item = list.Items.Add();
                    item["Title"] = "New Post";
                    item["Body"] = "Body of the post";
                    item.Update();
          }
}

This is the disussion got created



This is the error message box popped out when I tried to reply that discussion


So when I checked the log file it gave me this error message.

Failed to cache field with id "{1805e563-22cf-44ed-96f5-58ebb8a6cb80}", overwrite=0

SocialRESTExceptionProcessingHandler.DoServerExceptionProcessing - SharePoint Server Exception [System.ArgumentException: Value does not fall within the expected range. at Microsoft.SharePoint.Utilities.SPUtility.CreateNewDiscussionReply(SPListItem parent) at Microsoft.SharePoint.ServerStub.Utilities.SPUtilityServerStub.InvokeStaticMethod??(String methodName, XmlNodeList xmlargs, ProxyContext proxyContext, Boolean& isVoid) at Microsoft.SharePoint.Client.ServerStub.InvokeStaticMethodWithMonitoredScope(Stri??ng methodName, XmlNodeList args, ProxyContext proxyContext, Boolean& isVoid)] 

Answer

I did some research and got some online help from others and found the solution. Discussions list is a type of list but we can't add items to it like we add on other lists. So there is a different way of adding the discussions on discussions list. This is working code:

using (SPSite site = new SPSite("http://site-url"))
{
          using (SPWeb web = site.OpenWeb())
          {
                    SPList list = web.Lists["Discussions List"];
                    SPListItem listItem = SPUtility.CreateNewDiscussion(list, "New Post");
                    listItem["Body"] = "Body of the post";
                    listItem.Update();   
          }





Cheers :D
Luckshan Roy 

Tuesday, February 26, 2013

Sharepoint 2013 get user property values

Hi guys in this post im going to show how we can get the user profile property values programmatically. So here for example I have shown how to get the 'Ask Me About' tag values.

using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
          {
SPUserCollection userCollection = web.AllUsers;
SPSite mySite = new SPSite("http://MySite-Url");

//Define Server Context
SPServiceContext serverContext = SPServiceContext.GetContext(mySite);

//Create an instance of the User Profile Manager
UserProfileManager profileManager = new UserProfileManager(serverContext);

foreach (SPUser spUser in userCollection)
{
String loginName = spUser.LoginName.ToString();
//Get user profile
UserProfile user = profileManager.GetUserProfile(loginName);
String userProperty = "SPS-Responsibility"; //Ask me about user property

UserProfileValueCollection coll = user[userProperty];

foreach (String val in coll)
{
String myTag = val;
}
}
          }
}

So using this code you can loop through users list and check eachone's Ask Me About property value. When initializing userProperty variable give the interal name of it. You can check the internal name by going to Central Admin > Manage service applications > User Profile Service Application > Manage User Properties and select a user property (Ask Me About) and click edit. In the Name field you can check the interal name. Check below..



Comment and give your feedbacks
Cheers.

Luckshan Roy.

Getting the values from discussions list

Hi guys,

Im sharing this because I had some issues when I tried to access the discussions list values in community site (SharePoint 2013 Template). When I tried accessing the list values by specifying the list name it gave me only the values of the replies of the discussion. So what we have to do is when we initializing the list mention the view. After that you can get the discussion list's values.

If you have tried the community site you'll get an idea how discussions and the replies are stored in the same list. When you check the list in 'Management' view you'll get a better understanding. Main discussion and the related values will be stored in the top level and when you click one discussion it'll show the replies and the related value of it. So check the below code for more details.


using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
  using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Discussions List"];
SPListItemCollection listItemCln = list.GetItems(list.Views["Management"]);

foreach (SPListItem post in listItemCln)
{
//Access the discussions list values
String title = post["Title"];
}
}
}

Thank You.
Luckshan Roy.

Link files in sharepoint document library to list fields.

Hi guys here with this code you can link the files in the sharepoint document library to shapoint list fields. So in the list item, document will be diplayed as a hyperlink.

In this example I have linked a file to a discussions list in community site (Sharepoint 2013).


public void linkFile()
{
using (SPSite site = new SPSite("http://site-url"))
{
using (SPWeb web = site.OpenWeb())
{
SPFolder rootFolder =  web.Folders["SiteAssets"].SubFolders["SitePages"].SubFolders["NewFolder"];
SPFile file = rootFolder.Files["sharepoint-coding.pdf"];

SPList list = web.Lists["Discussions List"];
SPListItemCollection listItemCln = list.GetItems(list.Views["Management"]);

SPList Item item = list.Items.Add();
item["Title"] = "Testing post to link attachment";
item["Body"] = "<p><strong>Attachments</strong></p>" + "<p><a href=\"/" + file.Url + "\"><img src=\"/_layouts/15/images/" + file.IconUrl + "\"/>" + file.Name + "</a></p>";
item.Update();
}
}
}

This is how it looks in discussions list after adding the item.


Comment your questions and suggestions
Cheers Guys.

Luckshan Roy.



Sharepoint add terms to metadata store using c#

Hi guys here you can find C# code to add terms to sharepoint metadata store.


private void setTagsToDirectory()
{
using (SPSite site = new SPSite("http://site-url"))
          {
TaxonomySession session = new TaxonomySession(site);
TermStore termStore = session.TermStores["Managed Metadata Service"];
Group group = termStore.Groups["Test Terms"];
TermSet termSet = group.TermSets["Testing"];
try
{
Term keywordTerm;
keywordTerm = termSet.CreateTerm("apple", CultureInfo.CurrentCulture.LCID);
termStore.CommitAll();
}
catch (Exception)
{
//Term already exist in the current term set
}
}
}

This is how it looks in the metadata store after adding the term.



Feel free to give me feedback.
Thank You.

Luckshan Roy

Sharepoint create new folder in a document library and upload files using c#

Hi everyone this is a simple c# code to create a folder in sharepoint library and upload files.


using (SPSite site = new SPSite("http://cd-lroy:2222"))
{
using (SPWeb web = site.OpenWeb())
{
SPFolder myLibrary = web.Folders["SiteAssets"].SubFolders["SitePages"];
SPFolderCollection subfolders = myLibrary.SubFolders;
subfolders.Add("NewFolder");
SPFolder newFolder = subfolders["NewFolder"];
String filePath = @"C:\Users\lroy\Desktop\sharepoint-coding";

if (!System.IO.File.Exists(filePath))
throw new FileNotFoundException("File not found.", filePath);

else
{
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(filePath);
FileStream fileStream = File.OpenRead(filePath);

//Upload document
SPFile spfile = newFolder.Files.Add(fileName, fileStream, replaceExistingFiles);
newFolder.Update();
}
}
}


Added folder in the document library


Added document inside the created folder


Feel free to comment.
Cheers.

Luckshan Roy.