Wednesday, December 2, 2015

Add Full Breadcrumbs to SharePoint Document Library

Add Full Breadcrumbs to SharePoint Document Library


Inexcusably, SharePoint has no true breadcrumb navigation. In document libraries, navigating up and down the folder hierarchy is a painful series of pageloads. Fortunately, there are options.
If you have access to the server, you can create a custom code solution in SharePoint Designer or Visual Studio and serve it up. But before devoting resources to a server configuration change and all that entails, there’s a client side option that’s much easier to implement.

As a user of document libraries with folders up to a dozen levels deep, this is much appreciated.  The best part about this solution is the simplicity, it’s pure javascript and CSS, with no dependencies like jQuery or other outside libraries.  This means it works in IE8+, and creates no additional load on the server.
On note I will make, be sure the “title” option is set for the document library web part, which is not the default in SharePoint 2013. If it is not showing, the breadcrumb will be hidden. It’s also simple enough to modify the javascript to draw the breadcrumb to another element elsewhere on the page.

/*
* Adds a breadcrumb to "Document Library" Web Parts
* Copyright 29/11/2013 - Alexis Nominé - MIT Licence
* Mdified by Oumaima Achkari - Adaptation to SharePoint 2013 - 02/12/2015
*/

_spBodyOnLoadFunctionNames.push("doBreadCrumbs");//execute after DOM loaded

function doBreadCrumbs(){

                // Get 'RootFolder' value in URL
                var rootStr = getUrlParam('RootFolder');   
                if (rootStr != '') {
                               // Get all links in WebParts titles (IE8+)
                               var webpartHeaders = document.querySelectorAll('.ms-webpart-titleText a');
                               // For each link
                               for(var i = 0; i < webpartHeaders.length; i++){
                                               var webpartHeader = webpartHeaders[i];
                                               // Get link target
                                               var link = decodeURIComponent(webpartHeader.getAttribute('href'));
                                               // If target contains 'RootFolder' value, then we have our Web Part.
                                               // Let's generate our breadcrumb
                                               var pathname = window.location.pathname;
                                               if(rootStr.indexOf(link) != -1){
                                                   var path = rootStr.replace(link, ''); // Folder path, relative to Doc Lib
                                                    var basepath = rootStr.replace(path, ''); // Doc Lib path
                                                              
                                                    var breadcrumb = '<span class="breadcrumb">';
                                                     var LibraryName = $(".ms-webpart-titleText").text();
                                                    breadcrumb += '<a href="' + location.pathname + '">'+ LibraryName  +'</a>'; // link to base page
                                                              
                                                               // Create link for each sub-folder
                                                               var folders = path.split('/');
                                                              
                                                               for(var i = 1; i < folders.length; i++){
                                                                              var currentfolder = folders[i];
                                                              
                                                                              basepath += "/" + currentfolder;
                                                                              // Replace 'RootFolder' value in URL without touching any other variables(orderby, etc.)
                                                                              var folderlink = window.location.search.replace('RootFolder=' + encodeURIComponent(rootStr), 'RootFolder=' + encodeURIComponent(basepath));
                                                                              breadcrumb += ' &gt; <a href="'+ pathname+'?RootFolder=' +encodeURIComponent(basepath)+ '">' + currentfolder  + '</a>';
                                                                              //breadcrumb += ' &gt; <a href="Formations.aspx?RootFolder=/Formations/'+encodeURIComponent(currentfolder)+ '" ">' + currentfolder  + '</a>';
                                                               }
                                                               breadcrumb += '</span>';
                                                              
                                                               // Insert breadcrumb
                                                               //webpartHeader.getElementsByClassName("span")[0].innerHTML += breadcrumb;
                                                               $(".js-webpart-titleCell").append(breadcrumb);
                                                               //document.getElementById("WebPartTitleWPQ2").innerHTML += breadcrumb;

                                               }
                               }
                }
}

/* Get param value from query string */
function getUrlParam(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));}

Wednesday, October 28, 2015

SharePoint 2013 Search REST API

SharePoint 2013 Search REST API

In this post I'll go through the details of the SharePoint 2013 Search REST API. This new REST service is the best way to go in a variety of application scenarious. SharePoint Apps built in JavaScript is one good example. External Applications to SharePoint that require search functionality; can also leverage this service as the endpoint for communication into the Search platform.

The old search.asmx SOAP web service is marked as deprecated in SP2013and the new Search RESTservice is the replacement.

Location of the Search Rest service
The Search REST service is located at the following URI: http://host/site/_api/search

The Search REST API
The Search REST service exposed by the URI specified above provides the following methods or entry points:


query
Supports HTTP Get and is used to retrieve search results.
postquery
Supports HTTP POST and is used to retrieve search results. This method can be used to overcome URI length restrictions when using the HTTP GET based method "query".
suggest
Supports HTTP GET and is used to retrieve query suggestions.

Query Parameters
The following table lists the query parameters available for the query entry point:

Name
Description
Type
Default
querytext
The text of the search query.
String - Maximum query text length allowed by the Keyword Query OM is 4096 characters.
Empty
http://host/site/_api/search/query?querytext='search is cool'
querytemplate
The query template text.
String
Empty
 
enableinterleaving
Specifies if the result sets which are generated by executing query rule actions to add result  block should be mixed with the result set for the original query.
bool
True
http://host/site/_api/search/query?querytext='terms'&enableinterleaving=false
sourceid
Specifies the unique identifier of the Result Source to use for executing the search query.
String
Empty
http://host/site/_api/search/query?querytext='term'&sourceid='8413cd39-2156-4e00-b54d-11efd9abdb89'
rankingmodelid
The GUID of the Rank Model to be used for this search query.
String
Empty
 
startrow
A zero-based index of the first search result to be returned.
Integer [ >= 0]
0
http://host/site/_api/search/query?querytext='terms'&startrow=11
rowlimit
The maximum number of search results to be returned, starting at the index specified in  startrow.
Integer [ >= 0]
10
http://host/site/_api/search/query?querytext='terms'&startrow=11&rowlimit=3
rowsperpage
The number of results to return per page.
Integer [ >= 0]
0
 
selectproperties
Specifies the list of managed properties to return for each search result item. For a managed property to be returned; the Retrievable flag must be set to "true" in the Search Schema.
String
Empty
http://host/site/_api/search/query?querytext='terms'&selectproperties='Path,Url,Title,Author'
culture
Specifies the identifier of the language culture of the search query. If present, the value must be a valid LCID of a culture name. A list of LCIDs is available here.
Integer
-1
http://host/site/_api/search/query?querytext='terms'&culture=1044
refiners
Specifies a list of refiners to return as a comma-separated list of strings.
String
Empty
http://host/site/_api/search/query?querytext='terms'&refiners='companies,contentclass,ContentType,FileExtension,FileType'
refinementfilters
The list of refinement tokens for drilldown into search results. Refinement tokens are returned as part of the RefinementResults table for the search query.
String
Empty
http://host/site/_api/search/query?querytext='sharepoint'&refiners='filetype'&refinementfilters='filetype:equals("pptx")'
hiddenconstraints
Specifies additional query terms that will be appended to the query.
String
Empty
http://host/site/_api/search/query?querytext='terms'&hiddenconstraints='powerpoint'
sortlist
Specifies the list of properties to sort the search results by.
String
Empty
http://host/site/_api/search/query?querytext='terms'&sortlist='rank:ascending'
enablestemming
Specifies whether stemming is enabled for the query.
bool
True
http://host/site/_api/search/query?querytext='terms'&enablestemming=false
trimduplicates
Specifies whether duplicate items should be removed from search results. This property can also
 be used to collapse hits in the result set.
bool
True
http://host/site/_api/search/query?querytext='terms'&trimduplicates=false
trimduplicatesincludeid
Specifies the value associated with a collapse group, typically used when a user clicks the duplicates link of an item with duplicates.
long
0L
http://host/site/_api/search/query?querytext='terms'&trimduplicates=true&trimduplicatesincludeid=47
timeout
Specifies the amount of time, in milliseconds, before the query request times out.
Integer
30000
http://host/site/_api/search/query?querytext='terms'&timeout=50000
enablenicknames
Specifies whether the exact terms in the search query are used to find matches, or if nicknames
 are used as well.
bool
False
http://host/site/_api/search/query?querytext='terms'&enablenicknames=true
enablephonetic
Specifies whether the phonetic forms of the query terms are used to find matches.
bool
False
http://host/site/_api/search/query?querytext='terms'&enablephonetic=true
enablefql
Specifies whether the query string is according to the FAST Query Language (FQL) syntax.
Bool
False
http://host/site/_api/search/query?querytext='terms'&enablefql=true
hithighlightedproperties
Specifies the list of properties to include in the HitHighlightedProperties for each result item.
String
Empty
http://host/site/_api/search/query?querytext='terms'&hithighlightedproperties='Title,Author'
bypassresulttypes
Specifies if the search result item type should be returned for the query results.
bool
False
 
processbestbets
Specifies if the search promoted results should be returned, if available, as a result set.
bool
True
 
clienttype
Name of a client which issued query.
String
Empty
 
personalizationdata
Gets or sets the unique identifier (GUID) for the current user who submitted the search query.
String
Empty
 
resultsurl
Specifies the URL for the page where the search results are going to be displayed.
String
Empty
 
querytag
Any custom tags to be used to identify the query. Multiple tags are separated by semicolons.
String
Empty
 
enablequeryrules
Specifies if Query Rules are turned on for this query.
bool
True
http://host/site/_api/search/query?querytext='terms'&enablequeryrules=false
enablesorting
Indicates whether results should be sorted.
bool
True
http://host/site/_api/search/query?querytext='terms'&enablesorting=false


Suggest Parameters
The following table lists the query parameters available from the suggest entry point:
  
Name
Description
Type
Default
querytext
The text of the search query.
String
Empty
http://host/site/_api/search/suggest?querytext='nad'
inumberofquerysuggestions
The number of query suggestions to retrieve.
Integer [ > 0]
5
http://host/site/_api/search/suggest?querytext='nad'&inumberofquerysuggestions=6
inumberofresultsuggestions
The number of personal results to retrieve.
Integer [ > 0]
5
http://host/site/_api/search/suggest?querytext='nad'&inumberofresultsuggestions=6
fprequerysuggestions
Specifies whether to retrieve pre-query suggestions or post-query suggestions.
bool
False
http://host/site/_api/search/suggest?querytext='nad'&fprequerysuggestions=true
fhithighlighting
Specifies whether the query suggestions should be highlighted. If "true", the terms
 in the returned query suggestions that match terms in the specified query are  surrounded with <B> and </B> HTML tags.
bool
True
http://host/site/_api/search/suggest?querytext='nad'&fhithighlighting=true
fcapitalizefirstletters
Specifies whether to capitalize first letters in each term in query suggestions.
bool
False
http://host/site/_api/search/suggest?querytext='nad'&fcapitalizefirstletters=true
showpeoplenamesuggestions
Specifies if people names should be included in query suggestions.
bool
False
http://host/site/_api/search/suggest?querytext='nad'&showpeoplenamesuggestions=true
culture
Specifies the identifier of the language culture of the search query. If present, the value must be a valid LCID of a culture name. A nice list of LCIDs is available here.
Integer
-1
http://host/site/_api/search/suggest?querytext='nad'&culture=1044


 References:

Tuesday, October 27, 2015

Captcha Control - Create your own Captcha to use it in your SharePoint Visual WebPart.

Captcha Control - Create your own Captcha to use it in your SharePoint Visual WebPart.

Create your own Captcha to use it in your SharePoint Visual WebPart.

I create a Captcha string using some random numbers and texts. Then I create aBitmapImage from the Captcha string to show it into my WebPart. I use ViewState topreserve Captcha string value after the user clicks the Submit button.

Add the below Panel control to the VisulaWebPart.ascx

<asp:Panel id="Captcha" CSSClass="MyCaptcha" Visible="False"  runat="server">
  <asp:Label ID="LblCaptcha" runat="server" CssClass="LabelQT" Text="Please confirm you are human by typing the text you see in the image."></asp:Label>
  <img runat="server" id="imgCtrl" />
  <asp:ImageButton ID="RefreshCaptcha" runat="server" CssClass="BtnRefresh"ImageUrl="../_layouts/15/images/Refresh.png" OnClick="RefreshCaptcha_Click" Width="39px" />
   <asp:TextBox ID="TBoxChapctha" CSSClass="TxtBoxChapctha" Text="" runat="server"AutoPostBack="False"></asp:TextBox>
</asp:Panel>

Then in VisulaWebPart.ascx.cs add the below refrences

using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Resources;


Then add 2 global stringsas below

string Chaptcha1, CaptchaT;

And add the below public procedure:
public void DrowChaptcha2()
        {

            Random rnd = new Random();
            int a = rnd.Next(1, 9);
            int b = rnd.Next(1, 9);
            int d = rnd.Next(0, 25);
            char letter = (char)('a' + d);
            int c = rnd.Next(1, 9);

            Chaptcha1 = "  " + a + " " + b + "  " + letter + "  " + c + " ";
            CaptchaT = Chaptcha1.Replace(" "String.Empty);
            ViewState["CaptchaTVS"] = CaptchaT;

            Bitmap BitmapCaptcha = CreateBitmapImage(Chaptcha1);
            MemoryStream ms = new MemoryStream();
            BitmapCaptcha.Save(ms, ImageFormat.Gif);
            var base64Data = Convert.ToBase64String(ms.ToArray());
            imgCtrl.Src = "data:image/gif;base64," + base64Data;

        }
_____________________________________________________________________________________________
In the Page_Load(object sender, EventArgs e) , check the ViewState as below:
protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack)
            {
                if (ViewState["CaptchaTVS"] != null)
                {
                    CaptchaT = (string)ViewState["CaptchaTVS"];                
                }
                else
                {
                    CaptchaT = "Not Set";
                }
            }

            if (!Page.IsPostBack)
            {
                DrowChaptcha2();             
               
            }
}
_____________________________________________________________________________________________
In the Submit Click add the below code:

protected void Submit_Click(object sender, EventArgs e)
        {
            string CaptchaB;
            bool CaptchaOK = false;
            CaptchaB = TBoxChapctha.Text;
            CaptchaB = CaptchaB.Replace(" "String.Empty);
           
          
            if (CaptchaT == CaptchaB)
            {              
                CaptchaOK = true;               
            }
            else
            {
                CaptchaOK = false;

            }
       
           if (!CaptchaOK)
            {
                ValidationLbl.Text = ValidationCaptchaTxt;
                ValidationLbl.Visible = true;
            } else
            {
                 Do Something ...       
            }
        }
_____________________________________________________________________________________________

Here is the code to refresh Captcha:

protected void RefreshCaptcha_Click(object sender, ImageClickEventArgs e)
        {           
            DrowChaptcha2();
        }


And here is the code to create a BitmapImage from the Captcha string and show it into our Visual WebPart.

 private Bitmap CreateBitmapImage(string sImageText)
        {
            Bitmap objBmpImage = new Bitmap(1, 1);

            int intWidth = 0;
            int intHeight = 0;

            // Create the Font object for the image text drawing.
            Font objFont = new Font("Arial", 20, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Pixel);

            // Create a graphics object to measure the text's width and height.
            Graphics objGraphics = Graphics.FromImage(objBmpImage);

            // This is where the bitmap size is determined.
            intWidth = (int)objGraphics.MeasureString(sImageText, objFont).Width;
            intHeight = (int)objGraphics.MeasureString(sImageText, objFont).Height;

            // Create the bmpImage again with the correct size for the text and font.
            objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));

            // Add the colors to the new bitmap.
            objGraphics = Graphics.FromImage(objBmpImage);

            // Set Background color
            objGraphics.Clear(Color.White);
            objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
            objGraphics.DrawString(sImageText, objFont, newSolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);
            objGraphics.Flush();

            return (objBmpImage);
        }


You can Change the above code to make your Captcha look different. Here is how my Captcha looks like. 

 

Sharepoint Designer 2013, XSLT List View Options ribbon option is not showing

Sharepoint Designer 2013, XSLT List View Options ribbon option is not showing I have an ordinary Wiki Page, also tried making an Article...