Wednesday, December 30, 2015

SharePoint Programs

To fetch the User name in Console application is as follows

using Microsoft.SharePoint;

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

            SPSite rootSite = new SPSite("http://SureshNVSP:2222/");
            SPWeb rootWeb=  rootSite.RootWeb;
            SPUserCollection  userList =  rootWeb.AllUsers;
            foreach (SPUser objUser in userList)
            {
                Console.WriteLine(objUser.Name);
            }
            Console.Read();
        }
    }
}
********************************************************************

Q) Write a Query SharePoint List by using LINQ


// Get DataContext from page context
DataContext data = new DataContext(SPContext.GetContext(this.Context).Web.Url);

// Get the SharePoint list
EntityList Customers = data.GetList("Customers");

// Query for customers from India
var indiaCustomers = from customer in Customers
where customer.City == "India"
select customer;

foreach (var indiaCust in indiaCustomers)
{
Console.Writeline("id = {0}, City = {1}", indiaCust.CustomerId, londonCust.City);
}
******************************************************************** 
Q) Write a program to Get All Alerts in the Site Collection 
public void GetAlerts(Button btn)
    {
        SPSite rootSite = SPContext.Current.Site;
        SPWeb rootWeb = rootSite.OpenWeb();

        //Using RunWithElevatedPrivileges

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            // Get references to the site collection and site for the current context.
            // The using statement makes sures these references are disposed properly.

            SPList alertList = rootWeb.Lists[LIBName.Trim()];
            DeleteAllExistingItems(alertList, btn); // Delete existing items

            using (SPSite siteCollection = new SPSite(rootSite.ID))
            {
                foreach (SPWeb curretWeb in siteCollection.AllWebs) 
                       //Get alerts for each web
                {
                    using (SPWeb web = siteCollection.OpenWeb(curretWeb.ID))
                    {
                        web.AllowUnsafeUpdates = true;

                        try
                        {
                            SPAlertCollection allAlerts = web.Alerts;

                            foreach (SPAlert AlertItem in allAlerts)
                            {
                                AddAlertToTable(alertList, AlertItem);
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Delete failed: " + ex.Message);
                            throw;
                        }

                        web.AllowUnsafeUpdates = false;
                    }
                }
            }

        });
    } 
 ******************************************************************** 
Q) Programmatically Upload Documents in a Document Library 
     public void DocumnetsUpload(SPWeb site)
    {
        if (FileUploadControl.HasFile)
        {
            SPFolder folder = site.GetFolder("Document_Library_Name");

            SPFileCollection files = folder.Files;

            //path of the file to upload
            Stream fStream = FileUpload1.PostedFile.InputStream; 

            byte[] contents = new byte[fStream.Length];

            fstream.position = 0;

            fStream.Read(contents, 0, (int)fStream.Length);

            fStream.Close();

            string Filename = FileUpload1.FileName;

            string URL = SPContext.Current.Site.Url + "/Document_Library_Name/" + Filename;

            SPFile currentFile = files.Add(URL, contents);
        }
    }

 ********************************************************************  
Q) Write a program to Delete all Items in a list 
Note: Deleting all items in list will send all the items to recycle bin. To avoid fill-up recycle bin, we can just turn the recycle bin off while deleting the items.

public void DeleteAllItems(SPList CurrentList)
    {
        bool IsRecycleBinEnabled = SPContext.Current.Web.Site.WebApplication.RecycleBinEnabled;

        if (IsRecycleBinEnabled)
        {
            //set the use off the recyclebin to false SPContext.Current.Web.site.Webapplication.RecycleBinEnabled = fasle;
        }

        StringBuilder sbDelete = new StringBuilder();

        sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?<Batch>");

        foreach (SPListItem item in CurrentList.Items)
        {
            sbDelete.Append("<Method>");

            sbDelete.Append("<SetList Scope=\"Request\"" + CurrentList.ID + "</SetList>");

            sbDelete.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");

            sbDelete.Append("<SetVar Name=\"Cmd\"<Delete</SetVar>");

            sbDelete.Append("</Method>");
        }

        sbDelete.Append("</Batch>");
        try
        {
            SPContext.Current.Site.RootWeb.ProcessBatchData(sbDelete.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine("Delete failed: " + ex.Message);
            throw;
        }
        if (!IsRecycleBinEnabled)
        {
            //set the use off the recyclebin to false 
           //SPContext.Current.Web.site.Webapplication.RecycleBinEnabled = true;
        } 
 ********************************************************************   
  Q)  SharePoint  search using FullTextSqlQuery 
//Here SharedServices2 refers to the Shared Service Provider servicing the site in Question 
    ServerContext context = ServerContext.GetContext("SharedServices2"); 
    FullTextSqlQuery qrySearch = new FullTextSqlQuery(context); 
//Specifies the results set containing the main search results from 
//the content index matching the search query. 
    qrySearch.ResultTypes = ResultType.RelevantResults; 
//Sremming : expansion of searches to include plural forms and 
//other word variations :-)
    qrySearch.EnableStemming = true; 
    qrySearch.TrimDuplicates = false; 
    qrySearch.QueryText = "SELECT URL, Title, Size, Write, HitHighlightedSummary FROM SCOPE() where \"scope\"='NTFS Archive' And FREETEXT(*,'" + TextBox1.Text.Trim() + 
"')"; 
    ResultTableCollection results = qrySearch.Execute(); 
    ResultTable resultTable = results[ResultType.RelevantResults]; 
// Data Table to Store Search Results 
    DataTable dtResults = new DataTable(); 
    dtResults.Load(resultTable, LoadOption.OverwriteChanges);

No comments:

Post a Comment