Showing posts with label console app. Show all posts
Showing posts with label console app. Show all posts

Monday, 13 August 2012

Impersonating a SharePoint search

Here is code which will run a SharePoint search and return the results in a StreamWriter object, which can be outputted to a file. Hook it up to a console app and off you go!
Note 
-  you must specify a row limit or it will only return the first 50 results
-  user under which it runs will need to have read access to the content database containing the Central Administration Shared Services. This is usually called SharedServices1_DB or some such variant. Error logs will indicate very clearly if that error occurs so make sure to have good error handling
- Microsoft.Office.Server.Search.Query is another one of those annoying DLLs that is impossible to find. It's not one of the SharePoint dlls - you might find it in the ISAPI folder or otherwise in the list of other .NET dlls.

using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.Office.Server;
using Microsoft.Office.Server.Search;
public class SearchResults
    {
        public string errorArgs;
        public SearchResults()
        {
            //constructor don't do nuthin'
            errorArgs = string.Empty;
        }
        protected DataTable ReturnSearchResults(string searchCriterion, string siteUrl)
        {
            DataTable dt = new DataTable();
           
            try
            {
               //Available fields: Title,FileExtension,ContentType,Created,LastModifiedTime,IsDocument,owsStartDate,Path
                
                searchCriterion = searchCriterion.Replace(" ", "+");
                string fullTextSQL = "SELECT Title, FileExtension, ContentClass, ContentType, Created, URL FROM SCOPE() ";
                fullTextSQL = fullTextSQL + "WHERE CONTAINS ('" + searchCriterion + "') ";
                //do whole site for the moment
                using (SPSite site = new SPSite(siteUrl))
                {
                    errorArgs = "accessing office search component";
                    Microsoft.Office.Server.Search.Query.FullTextSqlQuery search = newMicrosoft.Office.Server.Search.Query.FullTextSqlQuery(site);
                    Microsoft.Office.Server.Search.Query.ResultTableCollection results;
                    //configure the query - limit it to 50 for the moment
                    errorArgs = "preparing search";
                    search.QueryText = fullTextSQL;
                    search.ResultTypes = Microsoft.Office.Server.Search.Query.ResultType.RelevantResults;
                    search.RowLimit = 1000;
                    search.TrimDuplicates = true;
                    results = search.Execute();
                    errorArgs = "search successful";
                    if (results.Count > 0)
                    {
                        using (Microsoft.Office.Server.Search.Query.ResultTable relevantResults = results[Microsoft.Office.Server.Search.Query.ResultType.RelevantResults])
                        { dt.Load(relevantResults, LoadOption.OverwriteChanges); }
                    }
                    return dt;
                }
            }
            catch (Exception ex)
            {
               //handle error here
                return null;
            }
            finally
            {
            }
        }
        public StreamWriter ReturnResultsInStream(string searchCriterion, string siteUrl,FileStream fs)
        {
            try
            {
                StreamWriter stream = new StreamWriter(fs);
                DataTable results = this.ReturnSearchResults(searchCriterion, siteUrl);
                foreach (DataRow dr in results.Rows)
                {
                    foreach (object field in dr.ItemArray)
                    {
                        if (field is string)
                        {
                            stream.Write(field.ToString());
                            stream.Write(";");
                        }
                    }
                    stream.WriteLine();
                }
                return stream;
            }
            catch(Exception ex)
            {
                //HANDLE YOUR ERROR HERE
                return null;
            }
        }
    }

Thursday, 26 April 2012

Argh! I Locked Myself Out!

But I didn't get back in by being given a key - more like kicking the door down, but anyway...

A few days ago I was testing something on the dev machine and removed a few user groups from the site permissions list on a site collection. They were still associated with the site, just had no site permissions. I was logged in as site admin. Went to do something on one of those sites and what do you know, I can't get in! Checked the site collection admin, where I was queen of everything and all looked well. Checked Central Admin and the Sharepoint:80 web application, found my errant site collection, and yes I was site admin. Still couldn't get in.

Here is how I got back in. I do not recommend using this as a method to get in. It is a horrible hack and will consign me to SharePoint Hell. I only did it because it was a dev machine and the outcome was not important. However - it is an example of how to dynamically add an existing SharePoint user group onto a Site Permissions list if it isn't on it already:


using (SPSite site = new SPSite("http://notmyemployerssitecoll/sc/sample/"))
{
     using (SPWeb web = site.OpenWeb())
     {
         foreach (SPGroup group in web.AssociatedGroups)
         {
             if (group.Name.Contains("My Little Lost Group"))
             {
                 //assign it permissions to control everything
                 //obviously when we do this for real, we want it to grab the
                 //existing role assignment
                 SPRoleAssignment roleAssignment = newSPRoleAssignment(web.SiteGroups[group.Name]);
                 SPRoleDefinitionBindingCollection roleDefinition = roleAssignment.RoleDefinitionBindings;
                 roleDefinition.Add(web.RoleDefinitions["Full Control"]);
                 web.RoleAssignments.Add(roleAssignment);
                 web.Properties[group.Name] = "Full Control";
                 web.Properties.Update();
             }
         }
     }
}

Thursday, 27 October 2011

The All-Singing, All-Dancing Site Collection Recursion Code!

Need to update some setting in every site in your site collection? Hunting around the internet googling "Recursion", "Site Collection" and "SharePoint"? Here I am to your rescue. Create a console application, add in a ref to Sharepoint and replace the one line in Main() with your site collection. Stick your own code into the bit where it says "Put your code here", run, and Bob's your uncle, auntie and whatever sort of relative you're having yourself. Can be adapted for web part too if you want. The streamwriter dumps a load of updates into your chosen folder.

Why, you're welcome :)

//Code by Susan Lanigan, 25/10/2011

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using System.IO;



namespace RecursiveConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {

            //call once and let recursion take care of the rest
          //start from a site collection top level URL
            //NOTE - if you want to break completely on an error
            //stick a try-catch block up here and get the sub to throw;
            DoTheWork("http://myServer/mySiteColl", string.Empty);


        }

        static void DoTheWork(string siteUrl, string parentWebName, string eMail)
        {
            string errorArgs = string.Empty;

            try
            {

                using (SPSite site = new SPSite(siteUrl))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        // another try-catch for the filestreamer
                        //write console output to file
                        FileStream fs = new FileStream("c:\\Susan\\LogForSite_" + parentWebName + "_" + web.Name + ".txt", FileMode.Create);
                        StreamWriter sw = new StreamWriter(fs);
                        TextWriter tmp = Console.Out;

                        try
                        {

                            Console.SetOut(sw);
                            Console.WriteLine("Writing update for site: " + web.Url);
                            //DO YOUR WORK HERE AND WRITE TO STREAMWRITER ETC.

                            //...


                        }
                        catch (Exception fileEx)
                        {
                            Console.WriteLine(fileEx.Message);
                            return;
                        }
                        finally
                        {
                            sw.Close();
                            fs.Close();
                        }

                        //reset console output
                        Console.SetOut(tmp);

                        //now for the subsites
                        SPWebCollection subSites = web.Webs;

                        foreach (SPWeb subSite in subSites)
                        {
                            //RECURSION HERE
                            DoTheWork(subSite.Url, web.Name, eMail);
                            subSite.Close();
                        }

                    }



                }

            }



            catch (Exception ex)
            {
                //custom error handling stuff
                Console.WriteLine(ex.Message);
                Console.ReadLine();
               
                return;
            }

        }
        }

}