Thursday, 5 September 2013

Search Query APIs in SharePoint 2013

To develop the custom solution types for the search results, SharePoint 2013 Provides several query APIs for search and giving us lots of ways to access the search results.

SharePoint 2013 provides the following in addition to Server Object Model which was available in previous versions.

Clicent Object Model(CSOM)
JavaScript Object Model (JSOM)
Representational State Transfer (REST) Service.

API Name
Class library or schema and path
.NET CSOM
Microsoft.SharePoint.Client.Search.dll
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\ISAPI
Silverlight CSOM
Microsoft.SharePoint.Client.Search.Silverlight.dll
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS\ClientBin
JavaScript CSOM
SP.search.js
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\TEMPLATE\LAYOUTS
REST service endpoints
http://server/_api/search/query
http://server/_api/search/suggest
Server object model
Microsoft.Office.Server.Search.dll
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\15\ISAPI

Using Client APIs is one of the best practices in SharePoint 2013 when you can. Client APIs include the .NET, Silverlight, Phone, and JavaScript client object models, and the REST service. 


1) Query using the .NET Client Object Model

This enable to access search results for online, on – premises and development. The search in SharePoint 2013 CSOM is built on the SharePoint 2013 CSOM.

For the .NET managed CSOM, get a ClientContext instance (located in the Microsoft.SharePoint.Client namespace in the Microsoft.SharePoint.Client.dll). Then use the object model in theMicrosoft.SharePoint.Search.Client.Query namespace in the Microsoft.SharePoint.Search.Client.dll.

Follow below example.

using (ClientContext _clientContext = new ClientContext("http://<<serverName>>/sites/<<siteCollectionPath>>"))
{
    KeywordQuery _keywordQuery = new KeywordQuery(_clientContext);
    _keywordQuery.QueryText = "SharePoint 2013";
    SearchExecutor _searchExecutor = new SearchExecutor(_clientContext);
    ClientResult<ResultTableCollection> _results = _searchExecutor.ExecuteQuery(_keywordQuery);
    _clientContext.ExecuteQuery();
}


2) Query using the JavaScript client object model

First we need to get a ClientContext instance, and then use the object model in the SP.Search.js file.

Here's a basic example.
var _clientContext = new SP.ClientContext("<<serverRelativeUrl>>");
var _contextSite = _clientContext.get_site();
var _keywordQuery = new Microsoft.SharePoint.Client.Search.Query.KeywordQuery(_clientContext); 
_keywordQuery.set_queryText("SharePoint2013"); 
var _searchExecutor = new Microsoft.SharePoint.Client.Search.Query.SearchExecutor(_clientContext);  
var _results = _searchExecutor.executeQuery(_keywordQuery); 
context.executeQueryAsync(onQuerySuccess, onQueryError);
 
3) Query using the REST service

SharePoint 2013 includes a REST service that enables you to remotely execute queries against the SharePoint 2013 Search service from client applications by using any technology that supports REST web requests. The Search REST service exposes two endpoints, query and suggest, and will support both GET and POST operations. Results are returned in either XML or JavaScript Object Notation (JSON) format.
The following is the access point for the service: http://<<server>>/_api/search/. You can also specify the site in the URL, as follows: http://<<server>>/site/_api/search/. The search service returns results from the entire site collection, so the same results are returned for both ways to access the service.


4) Query using the .NET server object model

Applications that use the server object model must run directly on a server that is running SharePoint 2013. The search Query server object model resides in the Microsoft.Office.Server.Search.Querynamespace, which is located in Microsoft.Office.Server.Search.dll.
As in SharePoint Server 2010, you use the KeywordQuery class to define the query, and then called the Execute() method to submit the query. In SharePoint 2013, the Execute method is obsolete, and while it will still work, you should use the SearchExecutor class instead. To submit the query, call the ExecuteQuery() method, passing the instance of the KeywordQuery class in the call.

Follow below example.

using (SPSite _siteCollection = new SPSite("<serverRelativeUrl>")) 
{
    KeywordQuery _keywordQuery = new KeywordQuery(_siteCollection);
    _keywordQuery.QueryText = "SharePoint2013";
    SearchExecutor _searchExecutor = new SearchExecutor(); 
    ResultTableCollection _resultTableCollection = _searchExecutor.ExecuteQuery(_keywordQuery); 
    _resultTableCollection = _resultTableCollection.Filter("TableType", KnownTableTypes.RelevantResults); 
    ResultTable _resultTable = _resultTableCollection.FirstOrDefault(); 
    DataTable dataTable = _resultTable.Table; 
}

Friday, 7 September 2012

Exporting Site Permissions Programmatically (C#.NET) - MOSS 2007

While working on permission i got  a requirement to export site permissions an write to a text file separated by pipe line..

Please find the codes below


  private void ExportPermissions()
    {
        StringBuilder strBuilderLogger_public = new StringBuilder();
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite mySite = new SPSite("SITE URL"))
            {
                using (SPWeb myWeb = mySite.OpenWeb("WEB NAME"))
                {

                    if (myWeb != null)
                    {
                        //Logging
                        strBuilderLogger_public.AppendLine("Site Name|List Name|List Item Name|Current Permissons|Parent Permissions|Has Unique Permissions");

                        string strSiteCurrentRoleDefinitions_public = GetRoleAssignmentsByObject(myWeb, null, null).ToString();
                        //Roles Logging
                        strBuilderLogger_public.AppendLine(myWeb.Title + "|||" + strSiteCurrentRoleDefinitions_public + "|" + "|TRUE");

                        foreach (SPList myList in myWeb.Lists)
                        {
                            if (!myList.Hidden)
                            {

                                string strListCurrentRoleDefinitions_public = GetRoleAssignmentsByObject(null, myList, null).ToString();
                                if (!myList.HasUniqueRoleAssignments)
                                {

                                    strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "||" + strListCurrentRoleDefinitions_public + "|" + strSiteCurrentRoleDefinitions_public + "|TRUE");

                                }
                                else
                                {

                                    strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "||" + strListCurrentRoleDefinitions_public + "|" + strSiteCurrentRoleDefinitions_public + "|FALSE");
                                }


                                SPQuery mySpQuery = new SPQuery();
                                mySpQuery.ViewAttributes = "Scope=\"RecursiveAll\"";
                                SPListItemCollection mySPListItemCollection = myList.GetItems(mySpQuery);

                                strBuilderLogger_public.AppendLine("Site Name|List Name|List Item Name|Current Permissons|Parent Permissions|Has Unique Permissions");
                                string strMyFileName = string.Empty;

                                foreach (SPListItem mySPListItem in mySPListItemCollection)
                                {
                                    string strListItemName_public = string.Empty;
                                    if (mySPListItem["Name"].ToString().ToUpper() != mySPListItem.DisplayName.ToUpper())
                                    {
                                        strListItemName_public = mySPListItem["Name"].ToString() + "_" + mySPListItem.DisplayName;
                                    }
                                    else
                                    {
                                        strListItemName_public = mySPListItem["Name"].ToString();
                                    }

                                    string strItemCurrentRoleDefinitions_public = string.Empty;
                                    strItemCurrentRoleDefinitions_public = GetRoleAssignmentsByObject(null, null, mySPListItem).ToString();

                                    //Checking Item Unique Permission
                                    if (!mySPListItem.HasUniqueRoleAssignments)
                                    {

                                        strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "|" + strListItemName_public + "|" + strItemCurrentRoleDefinitions_public + "|" + strListCurrentRoleDefinitions_public + "|TRUE");
                                    }
                                    else
                                    {

                                        strBuilderLogger_public.AppendLine(myWeb.Title + "|" + myList.ToString() + "|" + strListItemName_public + "|" + strItemCurrentRoleDefinitions_public + "|" + strListCurrentRoleDefinitions_public + "|FALSE");
                                    }
                                }
                            }
                        }
                        //Logging
                        WriteLogEntry(strLoggerFileName_public, "Site Level Broken Permission Exported List", strBuilderLogger_public.ToString());
                    }
                }
            }


        });
    }

    public void WriteLogEntry(string loggerFileName, string strTitle, string strMessage)
    {
        try
        {

            //Create Logger Folder if not exists
            if (!System.IO.Directory.Exists(@"C:\logs\"))
            {
                System.IO.Directory.CreateDirectory(@"C:\logs\");
            }

            string strFileLoc = loggerFileName;
            StreamWriter writer = new StreamWriter(strFileLoc, true);
            writer.WriteLine(DateTime.Now.ToString() + " :- " + strTitle + System.Environment.NewLine + strMessage + System.Environment.NewLine + "");
            writer.Close();
        }
        catch { }
    }

    private StringBuilder GetRoleAssignmentsByObject(SPWeb myWeb, SPList myList, SPListItem myListItem)
    {
        StringBuilder strBuilderLogger = new StringBuilder();
        SPRoleAssignmentCollection myRoleAssignmentCollection;
        if (myWeb != null)
        {
            myRoleAssignmentCollection = myWeb.RoleAssignments;
        }
        else if (myList != null)
        {
            myRoleAssignmentCollection = myList.RoleAssignments;
        }
        else
        {
            myRoleAssignmentCollection = myListItem.RoleAssignments;
        }

        foreach (SPRoleAssignment myRoleAssignment in myRoleAssignmentCollection)
        {
            SPPrincipal myPrincipal = myRoleAssignment.Member;
            string strPrincipalNameAndRoleDefinition = myPrincipal.Name;
            SPRoleDefinitionBindingCollection myRoleDefinitionBindingCollection = myRoleAssignment.RoleDefinitionBindings;
            bool flag = false;
            foreach (SPRoleDefinition myRoleDefinition in myRoleDefinitionBindingCollection)
            {
                if (myRoleDefinition.Name.ToUpper() != "Limited Access".ToUpper())
                {
                    strPrincipalNameAndRoleDefinition += "-" + myRoleDefinition.Name;
                    flag = true;
                }

            }
            //Logging
            if (flag)
            {
                strBuilderLogger.Append(strPrincipalNameAndRoleDefinition + ",");
            }

        }

        if (!string.IsNullOrEmpty(strBuilderLogger.ToString()))
        {

            string strBeforeFormat = string.Empty;
            strBeforeFormat = strBuilderLogger.ToString();
            strBeforeFormat = strBeforeFormat.Substring(0, strBeforeFormat.Length - 1);
            strBuilderLogger = new StringBuilder();
            strBuilderLogger.Append(strBeforeFormat);
        }

        return strBuilderLogger;
    }


Tuesday, 10 July 2012

WCF TraceListener


WCF exception messages are very generic and tough to decode.

WCF default TraceListener Objects for core WCF Objects. I have mentioned below details description for some important objects.

Assembly Name
Description
System.ServiceModel
Logs the following
Message Process
Reading of Configuaration information
Transport-level action
Security request.
System.Runtime.Serialization
Emits the information when objects are serialized or deserialized. WCF always serializes and de- serializes information during the request so it is good event to see the content of the request.
System.ServiceModel.IdentityModel
Generates trace data for authentication and authorization.


The tracing information of these objects help you to find out any exception details easily.

You can enable tracing by adding below code in web.config file.

<system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true">
        <listeners>
          <add name="wcfTraceListener" type="System.Diagnostics.XmlWriterTraceListener" initializeData="D:\logs\WcfTrace.svclog" />
        </listeners>
      </source>
    </sources>
  </system.diagnostics>

After adding the above code in web.config file, WCF trace file will be created in the given location when you run WCFservice.

To view the file you need SvcTraceViewer.exe, which will be present in “C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin folder.” Or else you can referrer to the below link to get tool.


Monday, 2 April 2012

How to get detailed error description in SharePoint


By default SharePoint will display basic message to users this is useless when we are doing any trouble shooting to display complete error description and stack trace of the error you need to modify the web.config for the WebApplication.

We can achieve this by following below steps.

1)     Disable Custom Errors: Set the customErrors mode to "Off"

Find:

<system.web>
<customErrors mode="On" />

Change To:

<system.web>
<customErrors mode="Off" />


2)    Enable the Call Stack Trace: Set the CallStack value of the SafeMode element to "true"

Find:

<SharePoint>

<SafeMode ... CallStack="false" ... >

</SharePoint>


Change To:

<SharePoint>

<SafeMode ... CallStack="true" ... >

</SharePoint>


3)    Enable Debugging Mode: Set batch and debug to "true"

Find: <compilation batch="false" debug="false">
Change To: <compilation batch="true" debug="true">


Enable the ASP.NET tracing feature:
Include the following line in the <system.web> element of the web.config file.


<system.web> ...


<trace enabled="true" pageOutput="true"/>


Saturday, 4 February 2012

Applying Conditional Formatting to a Data View

You can use conditional formatting to easily create a Data View that applies specific styles to data values when the data meets the criteria that you specify. You can also set conditions that change the visibility of a data value, so you can show or hide data.

To apply conditional formatting to a Data View
  • Right-click the Data View, and then click Conditional formatting.The Conditional Formatting task pane opens.
  • In the Data View list, click the items in the fields that contain the data you want to format.
  • Click Create, and then click Apply Formatting. The Condition Criteria dialog box opens to enable you to create a condition.
  • In the Condition Criteria dialog box, place your mouse pointer anywhere in the first row, and click.
  • Under Field name, click the arrow, and then click the field that you want to use in the condition.
  • Under Comparison, click the arrow, and then click the operator that you want to use in the condition.
  • Under Value, click the arrow, and then click More Fields.
  • In the More Fields dialog box, click the field that you want to use to complete the condition 
  • Click OK 
  • In the Condition Criteria dialog box, click OK.
  • In the Modify Style dialog box, select the options required to create the style for your conditional formatting.
  • Click OK.


Thursday, 5 January 2012

Creating Search Scope in SharePoint 2007


1)     Goto Site Settings >>  Site Collection Administration >> Search Scope


2)     System will redirect to below “View Scopes” page and click on “New Scope”




3)     System takes you to below page, insert all required details Title etc. Click on Ok button, new scope will be created







4)     Adding rules to the scope.




5)     Give “Scope Rule Type” and “Behavior” and click on “Ok”.


6)     System redirect to the below page. And we have completed new scope with rules, this


Friday, 30 December 2011

Branding SharePoint 2007


1.     Challenges of Branding SharePoint
•         Consistency
•         Audience expectations
•         Audience needs
•         Internal buy-off of SharePoint
•         Security; anonymous access vs. forms authorization
•         Content Editing experience

2.     Simple and Advanced options
•      Simple OOB  customization
•      Update Logo
•      Apply a Theme
•      Adding web parts
•      Choose a different OOB Master Page

•      More advanced customization
•      Master Pages
•      Layout pages
•      Creating custom themes
•      CSS

•      Simple OOB customization demonstration

•      Update site with logo
•      Change site theme
•      Choose different Master Page Template
•      Other master page templates are available for download
•      Views in libraries
•      Content editor web part (inline styling)

3.     Page Rendering

4.     Tools
•      IE Developer Toolbar (free, from Microsoft)  
•      FireFox Firebug (free)
•      InstantSource
•      SharePoint Designer

5.     Advance Customization: Master Pages
•      What is a Master page?
•      Navigation
•      Logos
•      Search box
•      Login control
•      Editing controls
•      CSS References
•      Content Regions

6.     Advanced Customization: Working with CSS
•      There are 26 style sheets used in SharePoint
•      Majority located on server:
•      Server Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\STYLES
•      Some located in Style Library (accessible via SPD)
•      Editing core.css is NOT recommended
•      Core.css will load last, unless you specify your custom css in Site Settings, or override the css in the master page


7.     Advance Customization: Custom Theme
•      Does NOT require SharePoint Designer
•      Themes can be found on the server in:
•      Server Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\THEMES\[Theme Name]
•      Copy folder, rename
•      Rename .INF file, change theme names in .INF file
•      Modify theme.css with design changes
•      Store preview of theme in TEMPLATE\IMAGES
•      Modify TEMPLATE\Layouts\1033\spthemes.xml

8.     Advance Customization: Layout Pages
•      What is a Layout Page?
•      Template for content
•      Based on a content type

•      Holds:
•      Field controls
•      Web Parts
•      Web Part Zones
•      Custom CSS, in-line styles
•      Careful when editing; don’t rely on “Reset to Site Definition”; make a backup first
•      Override content placeholders
•      Add web part zones
•      Configure web part zones
•      Add web parts
•      Either in or out of web part zones
•      Insert content fields
•      Configure content fields
•      If need more content fields, will need to create a new content type
•      Pages based upon a page layout will be able to switch to another page layout that uses the same content type as the original page layout

9.     Advance Customization: Content Editor WP Styles
•      If NOT using theme: edit HTML Editor CSS
•      Make a copy from the server, save in Style Library
•      Add styles (prefix with “.ms-rteCustom-”; e.g., .ms-rteCustom-FabrikamTitle)
•      Register css in master page
•      New styles will appear in  Content Editor Style dropdown
•      If you are using a theme, you can add the styles you like into your theme’s css file.

10. Advance Customization: Search Results
•      Create new page
•      Use Search Results Page Layout (this page layout can be customized if the layout needs to be changed)
•      Or create your own custom search results page
•      Customize new page
•      Search control
•      Search results xslt
•      Go to Site Settings, Search Settings and point to this new page

11. Advance Customization: Search Control
•      Modify CSS
•      Import customized search control from search results page
•      On search results page, customize the search control, then export the web part
•      Import web part into master page
•      More difficult to customize from the master page since it is a web part
•      Modify search results control properties
•      Copy search control from blueband.master
•      Register control
•      Modify tag properties of control

12. Customized vs. Uncustomized
•      “Ghosted” and “Unghosted pages”
•      Performance impact of ~10%