Pages

Thursday, February 13, 2014

Retrieve Author of SPListItem as SPUser in SharePoint; programmatically (C#)

Introduction
Updated on 15th July 2014

I was assigned in a project where I had to retrieve the author of the SPListItem as SPUser programmatically.

Solutions

In these solutions I’m returning the login name. But you can get the SPUser.

Solution 01

  1. public string GetListItemAuthorNameSPBuiltInFieldId(SPListItem spListItem)
  2.       {
  3.           string loginName = string.Empty;
  4.           SPWeb spWeb = SPContext.Current.Web;
  5.  
  6.           var fullUserName = spListItem[SPBuiltInFieldId.Author] as string;
  7.           var userName = fullUserName.Split('#')[1];//This is only to get the user name. My fullUserName was 1;#Setup Admin.
  8.           SPUser spUser = spWeb.EnsureUser(userName);//You can get SPUser from here
  9.           loginName = spUser.LoginName;
  10.           return loginName;
  11.  
  12.       }
It is recommended to SPBuiltInFieldId in order to retrieve build in fields.

Solution 02

  1. public string GetListItemAuthorName(SPListItem spListItem)
  2.   {
  3.       string loginName = string.Empty;
  4.       var spFieldUser = spListItem.Fields.GetFieldByInternalName("Author") as SPFieldUser;
  5.  
  6.       if (spFieldUser != null && spListItem["Author"] != null)
  7.       {
  8.           var fieldValue = spFieldUser.GetFieldValue(spListItem["Author"].ToString()) as SPFieldUserValue;
  9.           if (fieldValue != null)
  10.           {
  11.               var spUser = fieldValue.User;//Get the SPUser
  12.               loginName = spUser.LoginName;//Get the login name from SPUser
  13.           }
  14.       }
  15.       return loginName;
  16.   }


Conclusion

I will update how to retrieve values from SPField in future days.

Friday, February 7, 2014

Query all the documents by its file type from a Site and its all sub sites using SPSiteDataQuery

Introduction

I had to develop a web part where I had to query and display all the document items which the file extensions are “docx” under a particular site collection including its sub sites. I used SPSiteDataQuery class in order to achieve.

Solution

 
using (SPSite spSite = new SPSite(SPContext.Current.Web.Url))
            {
                using (SPWeb spWeb = spSite.OpenWeb())
                {
                    SPSiteDataQuery spSiteDataQuery = new SPSiteDataQuery();

                    spSiteDataQuery.Query =
                    @"<Where>
      <Eq>
         <FieldRef Name='DocIcon' />
         <Value Type='Computed'>docx</Value>
      </Eq>
   </Where>";
                    spSiteDataQuery.ViewFields = "<FieldRef Name='FileLeafRef' /><FieldRef Name='Editor' /><FieldRef Name='ContentType' />";
                    spSiteDataQuery.Lists = "<Lists ServerTemplate='101'/>"; //Set the list template by providing its template type id

                    spSiteDataQuery.Webs = "<Webs Scope='Recursive'/>";//Recursive: Current site and any subsite
                    //Scope='SiteCollection': all webs in the current site collection

                    //Get the results into a datatable
                    DataTable resultsTable = spWeb.GetSiteData(spSiteDataQuery);

                    
                    //Bind the results in to a asp grid view
                    GridView spGridView = new GridView();
                    spGridView.AutoGenerateColumns = true;
                    spGridView.DataSource = resultsTable;
                    spGridView.DataBind();

                    Controls.Add(spGridView);
                }
            }

 
Conclusion 
The results will look something as below. 



I have posted the my sln file here. Please download in case if you need
https://drive.google.com/file/d/0ByEnOE8DAdvhSTlnMDBuWDRuWTA/edit?usp=sharing

Reference: http://msdn.microsoft.com/en-us/library/ms409088.aspx

Thursday, January 23, 2014

Enable auditing for a specific content type through "Content Type Policy Templates" in SharePoint Online | SharePoint 2013

Introduction

Recently our client project had a requirement where a document type (or a content type) should be audited for its events such as editing items and checking in and checking out items, and also the policy should be reusable for other content type when we need. When I consult my architect he in instruct me how to do it. So I thought to share how I did this.

Solution
  • First of all you have to create a policy. 
    • To create Go to Site Setting -> Select Content Type Policy Templates (under Site Collection Administration category).
    • There select Create. The Url will end with “_layouts/15/policyconfig.aspx”.
    • Create a policy as you need. As per to my requirement I need an auditing policy. I created a policy enabling Auditing by selecting Enable Auditing option – Please refer the screenshot given below.

  • Then Select the content type which you should enable auditing. You can select the content type by going to Site Setting -> Click Site content types (under Web Designer Galleries) -> Select the content type you wish to add the policy.
    • In case you don’t have a content type; to create go to Site Setting -> Click Site content types (under Web Designer Galleries )
    • Select Create option on the top and create a content type as you need.
  • Select the “Information management policy settings” under setting.
  • You will see something like this.
  • There select “Use a site collection policy:” (the 3rd option) and select your policy name and click OK.
  • Now you have associated the auditing policy with the content type. 
  • Your logs reports can be seen under Go to Site settings -> Site Collection Administration -> Audit log reports.

Conclusion

You can also create a new policy at the Content Type -> Information management policy settings. But this will applicable only for the specific content type and you cannot be reusable for other content types; simply its a content type policy and not a site collection policy.



Friday, January 3, 2014

Show SharePoint Search Results in SPGrid View - programmatically

Introduction

As I said in my earlier post I was working and trying some stuff related to SharePoint 2013 search server. Today I was trying to query and display search results in SPGrid view. I have uploaded my solution package in my drive; Please download and look for the code if you need. (Download)
I used certain blog posts as references.


Solution

Create a web part (I have created visual web part). On the .ascx page initiate a SPGridView. (For that you can use the below code)
On the ascx.cs page do the blow
On page load



   

        protected void Page_Load(object sender, EventArgs e)
        {

           string query = string.Format("Project*"); //You can give what ever query you need
           ExecuteFederatedQuery(query);
        }

 


And also you need below both methods. So please paste them also on the ascx.cs page


   

        void ExecuteFederatedQuery(string queryText)
        {
            long lastupdate;
            bool crawl;

            //Create Search service proxy
            SearchServiceApplicationProxy proxy = (SearchServiceApplicationProxy)SearchServiceApplicationProxy.GetProxy
       (SPServiceContext.GetContext(SPContext.Current.Site));

            
            LocationConfiguration locationConfig = null;
        
            LocationConfiguration[] locationConfigurations = proxy.GetLocationConfigurations(out lastupdate, out crawl);//Get all federated search locations. 
            Location location;
            LocationList locationList = new LocationList();
            QueryManager queryManager = new QueryManager();
            foreach (LocationConfiguration locationConfiguration in locationConfigurations)
            {
                //Specify any federated search location. Here default search location will be captured.  
                if (locationConfiguration.InternalName.Equals("LocalSearchIndex"))
                {
                    locationConfig = locationConfiguration;
                    break;
                }
            }
            location = new Location(locationConfig.InternalName, proxy);
            //Set the userQuery
            location.UserQuery = queryText;
            locationList.Add(location);
            queryManager.Add(locationList);
            queryManager.IsTriggered(locationList);
            XmlDocument xDoc = queryManager.GetResults(locationList);//Return the query
            if (xDoc != null)
            {
                DataSet resultSet = new DataSet();
                resultSet.ReadXml(new XmlNodeReader(xDoc));

                SortData(resultSet.Tables[1]);

            }


        }

        private void SortData(DataTable resultTable)
        {

            //Sort the results by Title name
            DataView dataView = resultTable.DefaultView;
            dataView.Sort = "Title ASC";
            DataTable resuDataTable = dataView.ToTable();


            var fileTable = new DataTable();

            DataRow fileRow;
            fileTable.Columns.Add("Title");
            fileTable.Columns.Add("Modified_Date");
            fileTable.Columns.Add("Authors");
            fileTable.Columns.Add("DocURL");

            foreach (DataRow resultRow in resuDataTable.Rows)
            {

                fileRow = fileTable.NewRow();
                fileRow["Title"] = resultRow["title"];
                fileRow["DocURL"] = resultRow["url"];
                fileRow["Modified_Date"] = resultRow["lastmodifiedtime"];
                fileRow["Authors"] = resultRow["author"];

                fileTable.Rows.Add(fileRow);
            }

            //Assign the datasource
            spGridView.DataSource = fileTable;
            spGridView.DataBind();

            
        }

 

Conclusion

The results will look something like this.


Wednesday, January 1, 2014

SharePoint 2013 Search is not working - "Search has encountered a problem that prevents results from being returned"

Introduction

Happy New Year! I was working on SharePoint search where our client had a requirement on retrieving data through SharePoint search. Hopefully my upcoming posts will be related to SharePoint Search Server.

Problem Background

Suddenly my Search Service stopped working and it didn’t return results. My “Search Results” Web part show the error with the message “Search has encountered a problem that prevents results from being returned. If the issue persists, please contact your administrator.” See the screenshot below. Please note that I couldn’t capture the screenshots from my server and the screenshots are taken from the net.

Then when I try to open Search Service Application there also, I was able to see some error message.

Under “System Status (Name of Search application service => search administration => System Status)”; “Searchable items” showed “All Errors”.

And also Search Application Topology showed a error message as 
“Search Issue Unable to load the topology from the Search Administration component”. Ideally this should show something like this (See the below Screenshot).


When I try to see ULS log; I got the below error log

Content Plugin can not be initialized - list of CSS addresses is not set.


Solution Background

The issue is that SharePoint Search is unable to load the topology from the Search Administration component.

Solution 01

Recreate the Search Service Application using the Central Administration

Solution 02

The first Option didn't work for me. So I created the Search Service Application through the PowerShell which worked fine. Please go to the below Url and you can find the script to create service application from the scratch. http://melcher.it/2012/07/sharepoint-2013-create-a-search-service-application-and-topology-with-powershell/

Conclusion

There are plenty of suggestions on msdn. Please check for this solution as well. If this works say thanks to Maximilian Melcher (http://melcher.it/about-me/)

Monday, December 23, 2013

Migrate SharePoint 2010 code (custom solutions) to SharePoint 2013

Introduction

Recently I was assigned to Migrate code which used to develop SharePoint 2010 web parts to SharePoint 2013 web parts. Here I will illustrate how I did it.

Solution

Step 01: Open the Visual Studio 2010 (SharePoint 2010) solution in Visual Studio 2012. 




Step 02: Change the Target framework to .Net Framework 4.5

Step 03: Remove all the SharePoint 2010 assemblies and add SharePoint 2013 assemblies. This is because SharePoint 2010 assemblies are located in 14 hive and in SharePoint 2013 the assemblies are located on 15 hive. The SharePoint dlls can be


  • Microsoft.Office.Server.dll
  • Microsoft.SharePoint.dll 
  • Microsoft.SharePoint.Security.dll 

There are others as well. Please refer MSDN for other common used SharePoint assemblies.

Step 04: Change Control templates/ web part location as below.

From
~/_CONTROLTEMPLATES/{Folder Name}
To
~/_CONTROLTEMPLATES/15/{Folder Name}

Step 05: Change the _layouts location files to /_layouts/15/ location. Usually images, CSS and JavaScript files are added to _layouts folder.

Images
From
/_layouts/images/
To
/_layouts/15/images/

CSS
From
/_layouts/{Folder Name}/css
To
/_layouts/15/{Folder Name}/css

JavaScript
From
/_layouts/{Folder Name}/scripts
To
/_layouts/15/{Folder Name}/scripts

Step 06: In all aspx pages you have to change the reference from SharePoint 2010 asssembly to SharePoint 2013 assemblies. To do this change the assembly version from Version=14.0.0.0 to Version=15.0.0.0

Example.

           


<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>



To

           

<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>


Conclusion
Hope this will work for you and please note that sometimes you will need to change the deployment path according to SharePoint 2013. As the above add 15 hive after the mapped folder. If you have set the master page as v4.master you should change to seattle.master

Sunday, December 1, 2013

Adding Left Navigation for SharePoint Publishing site programmatically

Problem Background

I was working on creating a webtemplate based in SharePoint 2013 based on publishing site. There I had an requirement to create Left Navigation programmatic.

Solution Background

Here I have used "Structural Navigation" as the navigation type.

Solution

Below is the method to achieve it.

           
using (SPSite spSite = new SPSite("http://cd-sjamaldeen:23855/sites/002/"))
{
    using (SPWeb spWeb = spSite.OpenWeb())
    {

        //to remove pages from quick launch navigation
        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(spWeb);
        // Current navigation 
        publishingWeb.Navigation.CurrentIncludePages = false;
        publishingWeb.Navigation.CurrentIncludeSubSites = false;
        publishingWeb.Navigation.GlobalIncludePages = false;
        publishingWeb.Navigation.GlobalIncludeSubSites = false;


        var webNavSettings = new WebNavigationSettings(spWeb);

        // Set the current navigation to Structural Navigation type
        webNavSettings.CurrentNavigation.Source = StandardNavigationSource.PortalProvider;

        // Set the global navigation to Structural Navigation type
        webNavSettings.GlobalNavigation.Source = StandardNavigationSource.PortalProvider;

        webNavSettings.Update();
      

        //add the settings page to the quick launch
        SPNavigationNodeCollection nodeColl = spWeb.Navigation.QuickLaunch;

        //Delete all the navigation nodes from QuickLaunch 
        for (int i = spWeb.Navigation.QuickLaunch.Count - 1; i > -1; i--)
        {
                        
            spWeb.Navigation.QuickLaunch[i].Delete();
        }


        publishingWeb.Update();

        SPNavigationNode googleNode = new SPNavigationNode("Google", "http://google.com");
        nodeColl.AddAsFirst(googleNode);


        SPNavigationNode yahooNode = new SPNavigationNode("Yahoo", "http://yahoo.com");
        nodeColl.AddAsLast(yahooNode);

        spSite.AllowUnsafeUpdates = true;
        spWeb.AllowUnsafeUpdates = true;
        spWeb.Update();
        spWeb.AllowUnsafeUpdates = false;
        spSite.AllowUnsafeUpdates = false;

    }
}
 
 

Conclusion

Hope your publishing site now will have the Navigation.
If you face any problems go to site setting ->  Navigation (Under Look and Feel section) see weather all your navigation setting exists.