Thursday, 24 December 2015

CRUD on MongoDB

1.  Connect to Mongo DB:




2. Create collection:




3. Insert Document:




4. Update Document: 




5. Delete document:




6. Retrieve from collection:




7. Drop collection:





Setting up MongoDB

Installation Procedure:


  • If your system is running on one of these Windows Server 2008 R2, Windows Vista, or windows 7 Please follow the below
  • To resolve memory mapping issues while installing MongoDB one has to install a hotfix from https://support.microsoft.com/en-gb/kb/2731284 which has a link to download hotfix sent through an email .


  • There are 3 builds of MongoDB for Windows
    • MongoDB for Windows 64 bit
    • MongoDB for Windows 32 bit
    • MongoDB for Windows 64 bit legacy
Download the latest release compatible with your system from the link: http://www.mongodb.org/downloads?_ga=1.149793334.1228321965.1432748496





  • Once the download is complete,double click on the installer package and follow the installation wizard. While installing you must specify a installation directory by choosing “Custom” option, The installation wizard will assume that you have installed at C:\mongodBy following the above procedure the following 10+ executable files will installed in the bin folder. And they are required files to MongoDB mongod.exe, mongo.exe, mongodump.exe, mongorestore.exe, mongoimport.exe, mongoexport.exe, mongostat.exe, and mongotop.exe.




  • MongoDB need a folder (data directory) to store its data. By default, it will store in “C:\data\db“, create this folder manually. MongoDB won’t create it for you. 
  • It’s recommended to add C:/MongoDB/Server/3.0/bin to Windows environment variable, so that you can access the MongoDB’s commands in command prompt easily as shown





Setting up Eclipse for MongoDB:

  • To connect to mongodb from java, we need to install mongodb java driver.
  • Get jar file of mongodb Java driver from: http://docs.mongodb.org/ecosystem/drivers/java/
  •  Let’s see with an example how to work with mongodb java.
  •  In eclipse: create dynamic web project. Right click project->configure build path->Add external Jars. Select and add mongo db java jar to build path.




  • Add jar file to class path also:  Run->Run configuration-> select your server-> class path. Add jar files.



This completes setting up mongo db. Now you can start writing code to connect to mongo db and perform operation on mongodb. 






Saturday, 12 December 2015

Inserting and retrieving values for all types of Fields in ShrePoint 2013 using JSOM

//Inserting into all types of fields

function insertItem()
{
        var context=new SP.ClientContext.get_current();
var web=context.get_web();
context.load(web);
var list=web.get_lists().getByTitle("FieldsTypeDemo1");
context.load(list);
var itemCreateInfo = new SP.ListItemCreationInformation();
    var oListItem = list.addItem(itemCreateInfo);
oListItem.set_item("SingleText",SingleText);
oListItem.set_item("MultiPlainText",MultiPlainText);
oListItem.set_item('MultiRichText',MultiRichText);
oListItem.set_item('ChoiceDropDown',ChoiceDropDown);
oListItem.set_item('ChoiceRadio',ChoiceRadio);
oListItem.set_item('ChoiceCheckBox',ChoiceCheckBox);
oListItem.set_item('Num',Num);
oListItem.set_item('Currency',Currency);
//Convert date to SharePoint Date format
if(DateOnly!="")
{
var toDate=new Date(DateOnly);
var newDateOnly=(toDate.getMonth()+1)+"/"+toDate.getDate()+"/"+toDate.getFullYear();
oListItem.set_item('DateOnly',newDateOnly);
}
//Convert date and time to SharePoint DateTime format
if(DateAndTime!="")
{

//alert(time[0]);
var toDate1=new Date(DateAndTime);
var newDateTime=(toDate1.getMonth()+1)+"/"+toDate1.getDate()+"/"+toDate1.getFullYear()+" "+hr+min;
alert(newDateTime);
oListItem.set_item('DateAndTime',newDateTime);
}
var lookUp = new SP.FieldLookupValue();
    lookUp.set_lookupId(LookUpField);
    oListItem.set_item('LookUpField',lookUp);
oListItem.set_item('Y_x002f_N',YN);
if(HyperLink!="http://")
oListItem.set_item('HyperLink',HyperLink);
if(Picture!="http://")
oListItem.set_item('Picture',Picture);

//Converting to Taxonomy Managed metadata field
if(ManagedMetadata!="")
{
var field= list.get_fields().getByInternalNameOrTitle("ManagedMetadata");
var taxField = context.castTo(field, SP.Taxonomy.TaxonomyField);
   var termValue = new SP.Taxonomy.TaxonomyFieldValue();
   var id="";
   for(var i=0;i<termsLbl.length;i++)
   {
    if(termsLbl[i]==ManagedMetadata)
    {
    id=termsId[i];
    }
   }
   termValue.set_label(ManagedMetadata);
   termValue.set_termGuid(id);
   taxField.setFieldValueByValue(oListItem, termValue);
}
    oListItem.update();
context.load(oListItem);    
    context.executeQueryAsync(success,fail);
    function success()
    {
    alert("Row Inserted Successfully");
    window.location.reload();
    }
    function fail(sender,args)
{
alert(args);
window.location.reload();
}
}




//retriving from all types of fields
function getAllItems()
{
        

var context=new SP.ClientContext.get_current();
var web=context.get_web();
context.load(web);
var list=web.get_lists().getByTitle("FieldsTypeDemo1");
context.load(list);
var query = new SP.CamlQuery();
    var items = list.getItems(query);
    context.load(items);
context.executeQueryAsync(success,fail);
function fail(sender,args)
{
alert("Call failed:"+args.get_message());
}
function success()
{
var item = items.getEnumerator();
while(item.moveNext())
{
var row = item.get_current();
$("#SingleTextInfo").text(row.get_item("SingleText"));
$("#MultiPlainTextInfo").text(row.get_item("MultiPlainText"));
document.getElementById("MultiRichTextInfo").innerHTML=row.get_item("MultiRichText");
$("#ChoiceDropDownInfo").text(row.get_item("ChoiceDropDown"));
$("#ChoiceRadioInfo").text(row.get_item("ChoiceRadio"));
$("#ChoiceCheckBoxInfo").text(row.get_item("ChoiceCheckBox"));
$("#NumInfo").text(row.get_item("Num"));
$("#CurrencyInfo").text(row.get_item("Currency"));
var date1=new Date(row.get_item("DateOnly"));
$("#DateOnlyInfo").text(((date1.getMonth()+1)+"/"+date1.getDate()+"/"+date1.getFullYear()));
var date2=new Date(row.get_item("DateAndTime"));
$("#DateAndTimeInfo").text(((date2.getMonth()+1)+"/"+date2.getDate()+"/"+date2.getFullYear()+" "+date2.getHours()+":"+date2.getMinutes()));
                               
                               //get Lookup value for look up field
$("#LookUpFieldInfo").text(row.get_item("LookUpField").get_lookupValue());
if(row.get_item("Y_x002f_N")==true)
$("#YNInfo").text("Yes");
else
$("#YNInfo").text("No");

                                 //get URL for HyperLink an dPicture fields
var url1=row.get_item("HyperLink").get_url();
var url2=row.get_item("Picture").get_url();
document.getElementById("HyperLinkInfo").innerHTML='<a href="'+url1+'" target="new">'+url1+'</a>';
document.getElementById("PictureInfo").innerHTML='<a href="'+url2+'" target="new">'+url2+'</a>';

//display label name
                               $("#ManagedMetadataInfo").text(row.get_item("ManagedMetadata").$0_1); 
}
}
}


Tuesday, 8 December 2015

JSOM To Create WorkFlow in Sharepoint 2013


If you want to pro-grammatically create workflow in SharePoint 2013 use following steps:

1. First create workflow in SharePoint Designer 2013.

2. Save workflow as template

This will save workflow.wsp in SiteAsstes. Download that.

3. Change the extension of workflow.wsp to .cab. This converts file to RAR file. Extract it.
4. Get the file from "Files\wfsvc\87f127f963084cdf884a683bcb76e3e0 ". content of this file is used as xaml in below code.


var ctx = SP.ClientContext.get_current();
var servicesManager = SP.WorkflowServices.WorkflowServicesManager.newObject(ctx, ctx.get_web());
var definition = SP.WorkflowServices.WorkflowDefinition.newObject(ctx, ctx.get_web());
definition.set_xaml(xaml);
definition.set_displayName("Test");
var deploymentService = servicesManager.getWorkflowDeploymentService();
deploymentService.saveDefinition(definition);
ctx.load(definition);
ctx.executeQueryAsync(function () {
deploymentService.publishDefinition(definition.get_id());
ctx.executeQueryAsync(function () {
var subscription = SP.WorkflowServices.WorkflowSubscription.newObject(ctx, ctx.get_web());
subscription.set_name("Test");
subscription.set_enabled(true);
subscription.set_definitionId(definition.get_id());
var targetListId="07E21547-3ACD-4297-909E-6660F443E892";
subscription.set_eventSourceId(targetListId);
subscription.set_eventTypes(["ItemAdded"]);
var subscriptionService = servicesManager.getWorkflowSubscriptionService();
subscriptionService.publishSubscriptionForList(subscription, targetListId);
ctx.executeQueryAsync(function () {
console.log("done");
},function (sender,arg) {
console.log(arg.get_message());
});
});
});

Monday, 7 December 2015

Code Snippet:Auto Complte text box for SharePoint users



function getSiteUsers()
{
var call=jQuery.ajax({
        url: _spPageContextInfo.webAbsoluteUrl+"/_api/web/siteusers",
        type:"GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"
        }
    });
   
    call.done(function(data,textStatus,jqXHR){
        var users=data.d.results;
        var usrs=[];
        for(var i=0;i<users.length;i++)
        {
            if(users[i].UserId!=null&&users[i].LoginName.indexOf("onmicrosoft.com")!=-1)
            {
                    usrs.push(users[i].Title);
                   
            }
        }
        $( "#email" ).autocomplete
        ({
              /*Source refers to the list of fruits that are available in the auto complete list. */
              source:usrs,
              /* auto focus true means, the first item in the auto complete list is selected by default. therefore when the user hits enter,
              it will be loaded in the textbox */
              autoFocus: true ,
       
        });
       
    });
   
    call.fail(function(jqXHR,textStatus,errorThrown){
        var response=JSON.parse(jqXHR.responseText);
        var msg=response ? response.error.message.value : "Error";
        alert("Call Failed:"+msg);
    });
}



<input type="text" id="email" name="email"/>




  • _spPageContextInfo.webAbsoluteUrl+"/_api/web/siteusers" url gives you all site users along. Say for example My sharepoint site has only one user i.e "Madhumati Hosamani" along with this users there are some existing site users will be returned.
    • [15:02:20.490] Everyone
      [15:02:20.490] Everyone except external users
      [15:02:20.490] madhumati hosamani
      [15:02:20.490] NT AUTHORITY\authenticated users
      [15:02:20.490] _SPOCacheFull
      [15:02:20.490] _SPOCacheRead
      [15:02:20.490] System Account
      [15:02:20.490] YLO001\_spocrwl_337_16600

  • To filter and get only site use, I have used following logic 
 users[i].UserId!=null&&users[i].LoginName.indexOf("onmicrosoft.com")!=-1
 
This checks that UserID should not be null which is null in case of ['Everyone', 'Everyone except external users' and 'NT AUTHORITY\authenticated users'] and site user login name ends with onmicrosoft.com. 

  •  To set it to autocomplete of text box use following snippet: 
    • $( "#email" ).autocomplete
         ({
                        /*Source refers to the list of fruits that are available in the auto complete list. */
                        source:usrs,
                        /* auto focus true means, the first item in the auto complete list is selected by default. therefore when the user hits enter,
                        it will be loaded in the textbox */
                        autoFocus: true ,
                 
        });







Friday, 13 November 2015

SharePoint 2013 Mark-ups in HTML snippet


HTML snippet contains 4 basic elements:
1.       Header: with starting <div> and <!—CS> tags
2.       SP mark up: where snippets are enclosed in <!—MS> start and <!—ME> end tags
3.       HTML preview: enclosed in <!—PS> and <!—PE> tags
4.       Footer: with <!—CE> and </div> tags
All the above elements except HTML preview are enclosed in HTML comments to avoid interaction with DOM. A snippet starts with the name of a component, and then includes its actual ASP.NET mark-up, an HTML preview for design-time rendering, and then ending tags. The ASP.NET mark-up is commented out, but SharePoint strips out the comment tags and uses this mark-up when the HTML file is synced to the .master or .aspx file. If you know ASP.NET, you can customize this mark-up in the snippet.

ü SPM:
SharePoint namespace registration SPM ("SharePoint markup") will be used for registering the SharePoint Namespaces and declaring SharePoint controls.
Example:


ü CS and CE:
The tag CS is for Comment Start and CE is for Comment End. These tags will be ignored from SharePoint Conversion engine and help you parse the lines of markup
Example:
<!--CS: Start Page Field: Title Snippet-->

                <!--CE: End Page Field: Title Snippet-->


ü MS and ME:
The tag MS is for Markup Start and ME is for Markup End. If you want to add a snippet to the page then you should use these tags, and you can use these tags for adding SharePoint controls as well. You can get these snippets from Snippet Gallery. These are used to identify lines of .NET markup.

<!--MS:<PageFieldTextField:TextField FieldName="fa564e0f-0c70-4ab9-b863-0177e6ddd247" runat="server">-->

<!--ME:</PageFieldTextField:TextField>-->



ü  PS and PE:
Preview blocks PS and PE ("Preview start" and "preview end") surround a section of HTML code that you should not edit. These preview sections are a snapshot of the SharePoint control that snippet is inserting. A preview makes it possible for you to work more meaningfully on the HTML file in a client-side HTML editor. But, changing the content or styling within that preview has no lasting effect on the .master file, which is what SharePoint is ultimately using. To style a snippet, you have to identify and override the SharePoint styles with your own custom CSS. However, do not edit the preview code in the HTML file. It has no effect on the real page, and only serves to mislead people about what the control looks like.

<!--PS: Start of READ-ONLY PREVIEW (do not modify)-->

<!--PE: End of READ-ONLY PREVIEW-->






So to add a custom control to your HTML master page, just wrap your Register tag in an <!–SPM comment, and pair it with the custom control wrapped in <!–MS and <!– ME comments:

Applying custom stylesheet to Page-Layout in SharePoint 2013



When working with SharePoint, there may always be an occasion where you want to apply some specific styles to appear only when a page uses a specific Page Layout. For example, your Master Page may contain a Left Navigation that is needed throughout the site, but you may want to hide it just on your Landing Page Layout.
There are basically 3 ways in which this can be achieved:
1.       Custom Style sheet:
In your custom Page Layout, search for id=”PlaceHolderAdditionalPageHead“. You’ll find it in an opening tag that looks like this:
<!–MS:<asp:ContentPlaceHolder id=”PlaceHolderAdditionalPageHead” runat=”server”>–>

Underneath this tag, you may insert the usual reference to your custom style sheet using the <link> tag, with the addition of the attribute ms-design-css-conversion=”no”.
Example:
<!--MS:<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">-->
<link href="indigo_layout.css" rel="stylesheet" type="text/css" ms-design-css-conversion="no" />


Important: Remember to place the link reference right underneath the start of PlaceHolderAdditionalPageHead, as to add the attribute ms-design-css-conversion=”no”. Without them, this will not work.

2.       Using <style> tags
Alternatively you may want to enclose your custom styles within <style></style> tags and place them inside the Page Layout itself. In order to make this work, you’ll have to enclose the <style> tags within <!–MS:–>  <!–ME:–>  tags, and once again you have to place these styles underneath PlaceHolderAdditionalPageHead
Example:
<!--MS:<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server">-->
  <!--MS:<style type="text/css">-->
          #wr_leftNav { display: none !important; }
 <!--ME: </style>-->


Important: Remember to include the <!–MS–>  <!–ME:–> tags, and place the style block underneath the start of PlaceHolderAdditionalPageHead.



3.       Inline Styles
If you have some custom html markup in your page layout that you want to style, you can simply target the markup tags with inline styles.
Example:

<div id="contentBox" style="width: 400px; background: red;">




Friday, 6 November 2015

Connected web parts in Microsoft SharePoint 2013


We can filter items of one web part based on the items of other web part.
For example consider List with name “Projects” and library with “ProjectDocument”.
     
 

Note: connection is possible if there is link between these 2 lists. As you can see we have used Project as look up field in Project Document library.

Suppose if we want to filter project documents based on project selected in Project list, we make use of connections. To do this create web part with these list and library.

  •    Go-to web part menu of Project documents->connections->Get Filter value from->  Project(List name added as web-part).



 Once you select Project web part, you will get pop up.

  
  • In the pop up window:

            Provider Field Name: 
                   Select unique and required value of “Project” list. In our example it is Title of Project.
            Consumer Field name: 
                   Select field name of “Project Document” library which is linked with Project List.




Once you are done, Click finish.
This establishes connections between “Project” list and “Project Document” library.

  •  Now you can see that we have selected “MS Sharepoint” in Project list and only the related document is shown in Project Document library.








Search in SharePoint 2013



1.       Introduction
Search is an important out of box feature of SharePoint. In SharePoint whenever you search something, SharePoint looks into ResultSource. ResultSource is a location to get search results from, and to specify a protocol for getting those results. As a SharePoint Online administrator, you can specify how search should behave for a site collection or a site. The shared Search Box at the top of most pages will use these search settings. Any settings you specify on site collection level will apply to all sites within that site collection, unless you specify other settings for the site.

2.       SharePoint 2013 Search Settings at Site level

If we specify search behaviour at site level, it will be applicable only to that site. If you want to apply it to all sites of site collection, we need to configure at site collection level and to apply to all site collections configure at admin level. Here we will see how to configure search at site level and how to set it in drop down of search box.

We configure following settings to configure search
·         Result source
·         Result type
·         Query result
To configure at site level, you will find above option under search in site settings (Figure 1)

[Figure 1]

Now let’s see how to configure each of the above options.



3.       Result Source:
When we search in SharePoint, search system associate query with result source to provide result. Followings are the ResultSource used as drop down to search in SharePoint 2013.


Search types
Result Source
Description
Everything
Local SharePoint Results
All items from the local SharePoint search index except People items
People
Local People Results
People items from the profile database of the User Profile service application
Conversations
Conversations
Discussions in microblogs, newsfeed posts, and community sites

  


[Figure 2]


Ø Configure Result Source:
ü  Go to Site settings
ü  On the Site Settings page, in the Search section, click Result Sources [refer Figure 1].
ü  On the Manage Result Sources page, click New Result Source.
ü  On the Add Result Source page, in the General Information section, do the following:
§  In the Name box, type a name for the result source.
§  In the Description box, type a description of the result source.
ü  In the Protocol section, select one of the following protocols for retrieving search results:
§  Local SharePoint, the default protocol, provides results from the search index for this Search service application.
§  Remote SharePoint provides results from the index of a search service in another farm.
§  OpenSearch provides results from a search engine that uses the OpenSearch 1.0/1.1 protocol.
§  Exchange provides results from Exchange Server 2013 through a SharePoint 2013 eDiscovery Center.
ü  In the Type section select one of the following:
§  In the previous step, if you selected either Local SharePoint or Remote SharePoint for the protocol, then in the Type section, select SharePoint Search Results to search the whole index, or select People Search Results to enable query processing that is specific to people search.
§  If you selected Remote SharePoint for the protocol, then in the Remote Service URL section, type the address of the root site collection of the remote SharePoint farm.
§  If you selected OpenSearch 1.0/1.1 for the protocol, then in the Source URL section, type the URL of the OpenSearch source.
§  If you selected Exchange for the protocol, then in the Exchange Source URL section, type the URL of the Exchange web service.


[Figure 3]

ü  In the Query Transform section, do one of the following:
§  Leave the default query transform (searchTerms) as is. In this case, the query will be unchanged since the previous transform.
§  Use the Query Builder to configure a query transform by doing the following:
§  Click Launch Query Builder.
§  In the Build Your Query dialog box, optionally build the query by specifying filters, sorting, and testing on the tabs as shown in the following tables.




Basic Tab:

Property filter
You can use property filters to query the content of managed properties that are set to queryable in the search schema.
You can select managed properties from the Property filter drop-down list. Click Add property filter to add the filter to the query.
Keyword filter
You can use keyword filters to add pre-defined query variables to the query transform. You can select pre-defined query variables from the drop-down list, and then add them to the query by clicking Add keyword filter.













Sorting Tab:

Sort results
In the Sort by menu, you can select a managed property from the list of managed properties that are set as sortable in the search schema, and then select Descending or Ascending. To sort by relevance, that is, to use a ranking model, select Rank. You can click Add sort levelto specify a property for a secondary level of sorting for search results.
Ranking Model
If you selected Rank from the Sort by list, you can select the ranking model to use for sorting.
Dynamic ordering
You can click Add dynamic ordering rule to specify additional ranking by adding rules that change the order of results within the result block when certain conditions are satisfied.











TEST tab

Query text
You can view the final query text, which is based on the original query template, the applicable query rules, and the variable values.
Query template
You can view the query as it is defined in the BASICS tab or in the text box in the Query transform section on the Add Result Source page.
Query template variables
You can test the query template by specifying values for the query variables.










For example refer below figure: Here we have filtered result by pdf file type.

[Figure 4]

ü  On the Add Result Source page, in the Credentials Information section, select the authentication type that you want for users to connect to the result source.





Ø Specify a result source to use for query:
A query is initially associated with a result source according to the search experience in which the user performs the query. For example, if a user clicks People below a search box (see the screen shot earlier in this article) to specify the People search experience, the query uses the "Local People Results" result source.
A Search Box is always associated with a particular Search Results. When a user types a query in a search box, the Search Box sends the query to the associated Search Results. That Search Results specifies the result source for the query; by default, this result source is "Local SharePoint Results". You can set a different result source as the default.  To do this On the Manage Result Sources page, point to the result source that you want to set as default, click the arrow that appears, and then click “Set as Default”.



4.       Result Types:
When you search for something on a SharePoint site, very often many search results are returned. By default, the search results are displayed differently so that you can easily differentiate between the different types of search results. For example, just by glancing, you can see that the search results are PowerPoint presentations, Word document, and so on.
To display search results differently like this, search results are sorted into result types. A result type is a classification of a search result. For example, if a search result is found in a Microsoft PowerPoint presentation, the search result belongs to the Microsoft PowerPoint result type. If a search result is found in a PDF file, the search result belongs to the PDF result type.

Create and configure a custom search result type
1.        Go to the Manage Result Types page by doing one of the following:
o    If you want to create a result type for a site collection:
a.        Ensure that you are an administrator for the site collection.
b.       In the site collection, go to Settings > Site settings, and then in the Site Collection Administration section, click Search Result Types.
o    If you want to create a result type for a site:
a.        Ensure that you are a site owner for the site.
b.       On the site, go to Settings > Site settings, and then in the Search section, click Result Types.
2.        To create a result type, Click New Result Type.
  1. On the Add Result Type page, in the General Information section, in the Give it a name text box, type a name for the new result type.
  2. On the Add Result Type page, in the Conditions section, do the following:
    • In the “Which source should results match?” drop-down list, select a result source such as All Sources or Documents. For any given search result, this condition will be met if the search result is from the result source that you selected from this drop-down list or you can select result source to which you want to apply this result type.
    • (Optional) In the “What types of content should match?” drop-down list, do the following:
      1. Select a type of content, such as Microsoft Word.
      2. As many times as appropriate, click Add Value and select another type of content.
  3. (Optional) On the Add Result Type page, expand the Show more conditions section, and then do the following:
    • In the “Which custom properties should match?” section, the items in the “Select a property” drop-down list are retrievable managed properties. Select a property that you want the search system to perform a match on, such as Author.
    • In the second drop-down list, specify the operator, such as “Equals any of”.
    • In the text box, specify the value against which the search system should search for a match.
Separate multiple values with semicolons. Alternatively, as many times as appropriate, click Add Value and type another value in the new text box that appears.
For example, if you select the Author property and you select the operator Equals any of, then if you specify multiple values such as Kara and Silas, the condition will be “author equals Kara or Silas”.
    • To add another property to match, click Add Property.
  1. On the Add Result Type page, in the Actions section, do the following:
    • In the “What should these results look like?” drop-down list, click a display template such as Office Document Item or PDF Item. Display templates for search results are in the Search folder in the master page gallery for the site collection. The Display template URL box automatically displays the URL of the display template that corresponds to the display template that you selected.
    • Select the Optimize for frequent use check box if you expect this result type to appear frequently in search results.





5.        Query Rule:
In a query rule, you specify conditions and correlated actions. When a query meets the conditions, the search system performs the actions to improve the relevance of the search results.
For example, you might specify a condition that checks whether the query matches a term in a SharePoint term set, or another condition that checks whether the query is frequently performed on a particular search vertical in your search system, such as Videos.
A query rule can specify the following three types of actions:
ü  Add Promoted Results that appear above ranked results
ü  Add one or more groups of results, called result blocks. A result block contains a small subset of results that are related to a query in a particular way. Like individual results, you can promote a result block or rank it with other search results.
ü  Change the ranking of results. For example, for a query that contains “download toolbox”, a query rule could recognize the word “download” as an action term and boost search results that point to a particular download site on your intranet.






               





               
Before Search Customization:


After Search customization:







Adding your Custom result source to search box:


     









         
  • Insert web part: Search->search Result






3.              Edit web part:






  •  Change query: Add created result source









After you done check it in and publish the draft


  • Add page to search setting: Go to Site settings->Search setting under search.




  • In Configure Search Navigation click on “Add Link” (If Everything, Video, People and Conversation is not already present add them too) add URL of the page you created.




                Click OK.      


                Now you can see in the below figure that result source you created is added to search box