Skip to main content

Sharepoint Programming interview Questions with Answers Part 2

Q) Write a program to fetch the Username
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://pravahaminfo-pc:1534/");
            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);
  ********************************************************************  LECT 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];
//

Comments

  1. Hi,

    You have a very nice blog on SharePoint.
    Can you also suggest some good book to learn programming in SharePoint.

    Please reply me on arunmanglick@gmail.com

    Regards,
    Arun Manglick
    http://arun-architect.blogspot.com/
    http://arun-ts.blogspot.com/

    ReplyDelete

Post a Comment

Popular posts from this blog

Social tagging overview in Sharepoint 2010

A tag is a word or phrase that identifies an individual piece of information according to a set of attributes or criteria. Tags make it easy to find and share information about a specific subject or task. Social tagging helps users categorize information in ways that are meaningful to them. Social tagging can improve the quality of search results by filtering against specific tags, and it can also connect individuals who want to share information with other users who have like interests. This article describes the social tagging features in Microsoft SharePoint Server 2010. This article does not describe how to configure social tagging features. It also does not discuss how to implement social tagging features as part of an overall social media strategy for an enterprise. About using social tagging features Social tagging features help users to share information and to retrieve relevant, high-quality content more efficiently. Such sharing encourages collaboration and b...

How to Create Secure Store Service for BCS in Sharepoint 2010

How to use Secure Store Service for SharePoint 2010.BCS Access Account representive of the Credential Owner [Impersonated User], and how to wire it up in SharePoint Designer 2010. Prep Work a)Active Directory Users in Play       1.The Service Account I am selecting as the Impersonated User (Credential Owner)       2.The Security Group where all the people that will consume BCS Data will reside b)SQL Server Security      1.Who has Access to What Setup a)Creating & Configuring the Secure Store Object b)Creating & Configuring the External Content Type in SharePoint Designer 2010 1.Creating External Connection with Secure Store 2.Creating the External Content Type c)Reviewing the External Content Type (ECT) d)Reviewing the Security on the ECT Test & Validation a)Creating an External List derived from the ECT b)Logging on as a User from the Security Group AND Secured in the permission set...

AI and Microsoft: Revolutionizing Efficiency in Nonprofit Organizations

  How AI and Microsoft Enhance Efficiency in Nonprofit Organizations In today’s fast-paced world, nonprofit organizations face unique challenges—limited resources, increasing demands, and the constant need to do more with less. But what if technology could be the game-changer they need? In my latest research paper,  "How AI and Microsoft Enhance Efficiency in Nonprofit Organizations" , I explore how cutting-edge technologies like Artificial Intelligence (AI) and Microsoft’s innovative tools are revolutionizing the way nonprofits operate. From streamlining administrative tasks to enhancing donor engagement and optimizing resource allocation, AI and Microsoft’s solutions are empowering nonprofits to focus on what truly matters—their mission. This paper dives deep into real-world examples, practical applications, and the transformative potential of these technologies. Whether you’re a nonprofit professional, a tech enthusiast, or simply curious about the intersection of technolo...