Thursday, March 2, 2017

SharePoint 2010 - Analytics Report: Search Failure Reports

Hi Friends,

In SharePoint 2010, many times we have business requirements where we need to generate custom search reports related to "Failed Queries" and "No result queries". We also had one similar requirement for one of our client so thought to share the running code with you guys to ease the work.

public void GenerateReport()
        {
            DataTable table = null;
            DataRow dr = null;
            try
            {
                if (!string.IsNullOrEmpty(reportRequest.SrchFailureRptStDt) &&
                    !string.IsNullOrEmpty(reportRequest.SrchFailureRptEdDt))
                {
                    // Get Datatable Definition
                    table = GetTable();

                    #region Fetch data from SharePoint and populate Datatable
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite site = new SPSite(this.currSiteColl.Url))
                        {
                            AggregationContext aggregationContext = AggregationContext.GetContext(site.WebApplication);
                            if (aggregationContext != null)
                            {
                                List<ViewParameterValue> viewParamsList = new List<ViewParameterValue>();
                                DataPacket dataPacket = null;
                                bool isException = false;

                                try
                                {
                                    viewParamsList.Add(new ViewParameterValue("StartDateId", Common.DateTimeToDateId(Convert.ToDateTime(this.reportRequest.SrchFailureRptStDt).ToUniversalTime())));
                                    viewParamsList.Add(new ViewParameterValue("EndDateId", Common.DateTimeToDateId(Convert.ToDateTime(this.reportRequest.SrchFailureRptEdDt).ToUniversalTime())));
                                    viewParamsList.Add(new ViewParameterValue("AggregationId", aggregationContext.AggregationId));
                                    viewParamsList.Add(new ViewParameterValue("IncludeSubSites", true));

                                    dataPacket = FrontEndDataRetriever.QueryData(aggregationContext, null, "fn_WA_GetTopFailedSearchQueries", viewParamsList, null, null, 1, 25000, false);

                                }
                                catch (Exception ex)
                                {
                                 
                                }

                             
                                if (dataPacket.DataTable != null && dataPacket.DataTable.Rows.Count > 0)
                                {                                  

                                    foreach (DataRow objDataRow in dataPacket.DataTable.Rows)
                                    {
                                     

                                     

                                            table.Rows.Add(dr);
                                            table.AcceptChanges();

                                         
                                        }
                                        #endregion
                                    }
                                }
                                else
                                {
                                    Logger.WriteLog(Logger.Category.Information, "ProcessMTIReports - " + Constants.SRCH_FAIL_REP_NAME, "Start Processing the report for data: Blank");
                                    dr = table.NewRow();
                                    dr["Term"] = "No search results returned.";
                                    //dr["No. of Queries"] = 0;
                                    //dr["% Abandoned"] = 0;
                                    table.Rows.Add(dr);
                                    table.AcceptChanges();
                                }
                            }
                        }
                    });
                    #endregion

                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private static DataTable GetTable()
        {
            DataTable table = new DataTable();
            table.Columns.Add("Term", typeof(string));
            table.Columns.Add("No. of Queries", typeof(int));
            table.Columns.Add("% Abandoned", typeof(int));
            return table;
        }

Thanks

Saturday, January 3, 2015

Create a Managed Metadata Service TermSet in a Term Group using CSOM in SharePoint 2013

Steps:
1. Make sure Managed metadata service is running in CA.
2. Create a Visual studio Console Application and run as Admin.
 
3. Add below references:
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using System.Collections.ObjectModel;
 
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Taxonomy;
using System.Collections.ObjectModel;
 
namespace MMSApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            ClientContext clientContext = new ClientContext("Site collection url");
 
            TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
 
            TermStore termStore = taxonomySession.TermStores.GetByName("Term Store Name");
 
            Guid guid = new Guid("6h4f3b5c-224f-5faa-de7a-57735d3eb7d5");
            TermGroup termGroup = termStore.GetGroup(guid);
 
            string termSetName="Put New Term Set Name";
 
            Guid newTermSetGuid=Guid.NewGuid();
 
            int lcid=1033;
 
            TermSet termSetColl = termGroup.CreateTermSet(termSetName, newTermSetGuid, lcid);           
 
            clientContext.ExecuteQuery();
        }
    }
}
 
Thanks, Prabhat

Friday, December 26, 2014

SharePoint 2013 App Deployment PowerShell

In SharePoint 2013 App Development and Deployment we come across situations to automate the Upload and Install of SharePoint 2013 App to Corporate Catalog. Please find below the PowerShell to automate that process.

#-----Function to Load SharePoint PowerShell Environment----#
function LoadSharePointPowerShellEnvironment
{
    write-host "Setting up PowerShell environment for SharePoint..." -foregroundcolor Yellow
    Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
    write-host "SharePoint PowerShell Snapin loaded." -foregroundcolor Green
}
#-----Function to create output log file--#
function CreateLogFile {
param($logFileName)
 New-Item $logFileName -type File
 Set-Content $logFileName "Starting App Upload and Deployment......"
}
function Main($inputAppCatalogSiteCollectionUrl, $inputFolderLocation, $inputSiteCollectionUrl)
{
    try
    {
        $logFileName = [System.String]::Format("{0}{1}_{2}_{3}{4}", $inputFolderLocation + "\","Output_", $dateSuffix, $timeSuffix,".csv")
       
        $sourceApp = ([microsoft.sharepoint.administration.spappsource]::CorporateCatalog)
       
        $inputAPPName = "Test.app"       
        $inputAPPPath = [System.String]::Format("{0}{1}", $inputFolderLocation + "\", $inputAPPName)
        CreateLogFile $logFileName
       
        #Uploading app in app Catalog       
        UploadFile $inputAppCatalogSiteCollectionUrl "Apps for SharePoint" $inputAPPPath          
            
        Write-Host "APP added in App Catalog -" $inputSiteCollectionUrl;
        Write-Host "Import to Destination Site started"  $inputSiteCollectionUrl;
       
        #Importing app
        $spapp =Import-SPAppPackage -Path  $inputAPPPath -Site $inputSiteCollectionUrl -Source $sourceApp    
        Write-Host "Import to Destination Site Completed"  $inputSiteCollectionUrl;            
        Write-Host "Installation to Destination Site Started"  $inputSiteCollectionUrl;
        #Installing app
        $instance = Install-SPApp -Web $inputSiteCollectionUrl -Identity $spapp
        Write-Host "Installation to Destination Site Completed"  $inputSiteCollectionUrl;
}
catch
{
    Write-Host "Error Occured: $_.Exception.Message"
    Add-Content $logFileName "Error in Method Main."
    Add-Content $logFileName "Error Details: $_.Exception.Message"
}
}

function UploadFile($WebURL, $DocLibName, $FilePath)
{
    try
    {
        $Web = Get-SPWeb $WebURL
        if($Web -ne $null)
        {               
            $List = $Web.GetFolder($DocLibName)
           
            $Files = $List.Files
           
            $FileName = $FilePath.Substring($FilePath.LastIndexOf("\")+1)
           
            $folder = $List.RootFolder
            $SPFilePath = ($folder.URL + "/" + $FileName)
           
            $spFile = $web.GetFile($SPFilePath)
           
            if ($spFile -ne $null)
            {
                Write-Host "Already Exist in App Catalog-" $inputSiteCollectionUrl;
                Write-Host "OverWriting Existing file in App Catalog-" $inputSiteCollectionUrl;
            }
           
            $File= Get-ChildItem $FilePath
            $Files.Add("AppCatalog/" + $FileName, $File.OpenRead(), $true)
        }
        else
        {
            Write-Host "Web not found for URL : -" $inputSiteCollectionUrl;
            write-host "Method: Main, SPWeb Object is null." -foregroundcolor "Yellow"
            Add-Content $logFileName "Method: Main, SPWeb Object is null."
        }
    }
    catch
    {
        Write-Host "Error Occured: $_.Exception.Message"
        Add-Content $logFileName "Error in Method Main."
        Add-Content $logFileName "Error Details: $_.Exception.Message"
    }
    finally
    {
        if($spWeb -ne $null)
        {
            $spWeb.Dispose()
        }
    }
}
# Calling LoadSharePointPowerShellEnvironment Method
LoadSharePointPowerShellEnvironment
Main "http://AppCatalog.qa" "C:\Solutions" "http://abc-pc1873-1/sites/abc/"

Thanks, Prabhat

Security in SharePoint Apps

Tuesday, April 15, 2014

Download a WSP Solution From SharePoint

I had a requirement where I need to download the deployed WSP from central admin,but CA doesn't provide link to download that. After investigating I found a solution using PowerShell. So sharing that may be you can benefit of that.

$farm = Get-SPFarm
$file = $farm.Solutions.Item("corporate.build.wsp").SolutionFile
$file.SaveAs("d:\corporate.build.wsp")

Thanks

Sunday, October 21, 2012

SharePoint 2010: Attach Disposition Workflow To Content Type using PowerShell

Hi Friends,

Many times we are needed to attach a "Disposition Workflow" with a Content Type in SharePoint 2010. This is pretty easy to accoplish. Please find the PowerShell to do this.

# Method Calling
AddWorkflowToContentType $site $ContentTypeName "Disposition Approval" "WFA" $TaskListName

#Method Definition
function AddWorkflowToContentType($site, $ctName, $WfName, $WfAssociationName, $TaxTaskList)
   {
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint')
    [void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Office.Policy')
  
    [Guid]$wfTemplateId = New-Object Guid
    $web = $site.RootWeb
       $ct = $web.ContentTypes[$ctName]
       $culture = New-Object System.Globalization.CultureInfo("en-US")
       $template = $site.RootWeb.WorkflowTemplates.GetTemplateByName($WfName, $culture)
   
       if($template -ne $null)
       {                       
      $tasklist = $TaxTaskList
                     $historylist = "Workflow History"
                    
                        # Checking For WorkFlow History List; If not exists then create it
                        if(!$web.Lists[$historylist])
                        {
                            $web.Lists.Add($historylist, "A system library used to store workflow history information that is created in this site.  It is created by the Publishing feature.",
                            "WorkflowHistory", "00BFEA71-4EA5-48D4-A4AD-305CF7030140", 140, "100")
                           
       if (!$web.Features["00BFEA71-4EA5-48D4-A4AD-305CF7030140"]) {
                                Enable-SPFeature -Identity WorkflowHistoryList -Url $web.Url
                            }
      
                            $wfHistory = $web.Lists[$historylist]
                            $wfHistory.Hidden = $true
                            $wfHistory.Update()
                        }

                        # Checking For WorkFlow Task List; If not exists then create it
                        if(!$web.Lists[$tasklist])
                        {
                            $web.Lists.Add($tasklist, "This system library was created by the Publishing feature to store workflow tasks that are created in this site.", "WorkflowTasks", "00BFEA71-A83E-497E-9BA0-7A5C597D0107", 107, "100")
                        }
     
                        # Creating Workflow Association with Content Type
                        $association = [Microsoft.SharePoint.Workflow.SPWorkflowAssociation]::CreateSiteContentTypeAssociation($template, $WfAssociationName, $web.Lists[$tasklist], $web.Lists[$historylist])
                       
      $association.AllowManual = $false
                        #$association.AutoStartCreate = $true
                        $ct.AddWorkflowAssociation($association)
                        $ct.UpdateWorkflowAssociationsOnChildren($true, $true, $true, $false)
                        $association.Enabled=$true
                        $ct.Update()
                        $web.Update()
                        #$ct.WorkflowAssociations[0]           
       }
       else
       {
        Write-Error "Workflow Template not found"
                    Add-Content $logFileName "Workflow Template not found."
       }
   }

Happy Coding!!!

Prabhat

Monday, October 1, 2012

Mobile Entree For SharePoint 2010

Hi Friends,

This week I was involved in one POC on Mobile Development of SharePoint 2010. There I came around Mobile Entree Server(ME). Please check ME details:

Mobile Entree is a SharePoint solution for developing mobile solutions within SharePoint features and allow access to SharePoint APIs. Just install ME(Mobile Entree) on a SharePoint Farm and start using its power to create Mobile Apps instantly. Its allows number of great features to work with.

Refer below links:

1. http://blogs.msdn.com/b/seanpirtle/archive/2010/03/04/mobile-entree-s-mobile-sharepoint-solution.aspx
2. http://www.h3s-inc.com/services/Pages/Mobile-Entree-Development.aspx

Thanks
Prabhat