Thursday, 26 September 2013

SharePoint Programming CAML

Q)Query a List by using CAML in SharePoint ?

Microsoft.SharePoint.SPQuery object has Query property that accepts a CAML fragment, which defines the query to be performed. A ViewFields property defines the fields to return.

Code Sample:

SPQuery query = new SPQuery;
query.Viewfields = @"<fieldref name="Title"><fieldref name="Expires">";
query.Query =
@"<where>
<lt>
<fieldref name="Expires">
<value type="DateTime"><today></today></value>
</fieldref></lt>
</where>";
SPList list = SPContext.Current.Web.Lists.TryGetList("Announcements");
SPListItemCollections items = list.GetItems(query);
</fieldref></fieldref>

Each FieldRef element has a Name attribute that specifies the name of the list field to return from the query.
The CAML fragment may contain Where, OrderBy, and GroupBy elements.

<where>
</where>
<orderby>
<fieldref>
</fieldref></orderby>
<groupby>
<fieldref>
<groupby>
</groupby></fieldref></groupby>

Where condition may contain:

And,BeginsWith,Contains,Eq,FieldRef,Geq,GroupBy,Gt,IsNotNull,IsNull,Join, Leq,Lt,Neq, Now,Or etc
SPQuery object can be used to query across two lists that are joined by a Lookup field.

Showing you a sample from Inside book:

SPWeb site = SPContext.Current.Web;
SPList listInstructors = site.Lists["Instructors"];
SPList listModules = site.Lists["Modules"];
SPQuery query = new SPQuery;
query.Query = "<where><eq><fieldref name="\"Audience\"/">" +
"<value type="\"Text\"">Developer</value></fieldref></eq></where>";
query.Joins = "<join type="\"Inner\"" listalias="\"classInstructors\"">" +
"<eq><fieldref name="\"Instructor\"" reftype="\"Id\"">" +
"<fieldref list="\"classInstructors\"" name="\"Id\""></fieldref></fieldref></eq></join>";
query.ProjectedFields =
"<field name="Email" type="Lookup" list="classInstructors" showfield="Email">";
query.ViewFields = "<fieldref name="\"Title\""><fieldref name="\"Instructor\"">" +
"<fieldref name="\"Email\"">";
SPListItemCollection items = listModules.GetItems(query);
</fieldref></fieldref></fieldref></field>
Q)How to get user profiles details programmatically in sharepoint 2010
The below 2 function will show how to get user profile and how to access the profile properties.

private UserProfile GetUserInfo(string AccountName)
{
UserProfile profile = null;
SPServiceContext serviceContext = SPServiceContext.Current;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
if (AccountName != string.Empty)
{
profile = profileManager.GetUserProfile(AccountName);
}
else
{
profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
}
return profile;
}

void GetCurrentUserDetails()
{
UserProfile userProfile = GetUserInfo("");
lblUserName.Text = GetUserName(userProfile);
if (userProfile[PropertyConstants.FirstName].Value != null)
{
lblUserName.Text += " (" + userProfile[PropertyConstants.FirstName].Value.ToString() + ")";
}
try
{
imgBtnUserImage.ImageUrl = userProfile[PropertyConstants.PictureUrl].Value.ToString();
}
catch (Exception ex)
{
imgBtnUserImage.ImageUrl = "/_layouts/ExpressionsWP/0.jpg";
}
if (userProfile[PropertyConstants.Department].Value != null)
{
ltrAddress.Text = userProfile[PropertyConstants.Department].Value.ToString();
}
if (ltrAddress.Text != string.Empty)
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += "," + userProfile[PropertyConstants.Location].Value.ToString();
}
}
else
{
if (userProfile[PropertyConstants.Location].Value != null)
{
ltrAddress.Text += userProfile[PropertyConstants.Location].Value.ToString();
}
}
}


Q) How to use CAML Query with SPQuery Object?

SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
@"
//Write a query(using CAML)

";
SPList list = site.Lists["Litware News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {
Console.WriteLine(expiredItem["Title"]);
}

Q)How to use SPSiteDataQuery ?

SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";
string queryText =
@"

//Write a query(using CAML)

";
query.Query = queryText;
DataTable table = site.GetSiteData(query);
foreach (DataRow row in table.Rows) {
Console.WriteLine(row["Title"].ToString());
}

Q)Difference between SPquery and SPSiteDataQuery?

SPQuery object return an SPListItemCollection. SPSiteDataQuery object are different, because they return an ADO.NET DataTable object.

Q)Visit through document library in SharePoint Site.?

SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;
// Add document library to DropDownList control
lstTargetLibrary.Items.Add(
new ListItem(docLib.Title, docLib.ID.ToString()));
}
}

Q. How would you retrieve large number of Items form the list ?
 Ans. To retrieve large number of items with a better performance we can either use SPQuery or PortalSiteMapProvider Class. Read More with Examples..
           
Retrieving large number of Items from sharepoint list If you have to reterive a large number of Items and also need a better performance then you should use one of the methods below :
            1. Using SPQuery
            2. Using PortalSiteMapProvider Class

           Lets see the examples for both the methods : Our Query - Query to get all the Items in a list where Category is "Sp2007"
        SPQuery -
        // Get SiteColl
        SPSite curSite = new SPSite("http://myPortal");
        //Get Web Application
        SPWeb curWeb = curSite.OpenWeb();
        // Create a SPQuery
        Object SPQuery curQry = new SPQuery();
        // Write the query
        curQry.Query = " SP2007 ";
        // Set the Row Limit
        curQry.RowLimit = 100;
        //Get the List
        SPList curList = curWeb.Lists(new Guid("myListGUID"));
        //Get the Items using Query
        SPListItemCollection curItems = curList.GetItems(curQry);
        // Enumerate the resulting items
        foreach (SPListItem curItem in curItems)
    { string ResultItemTitle = curItem["Title"].ToString();
    }
   
    PortalSiteMapProvider class -

    The class includes a method called GetCachedListItemsByQuery that retrieves data from a list based on an SPQuery object that is provided as a parameter to the method call.
        The method then looks in its cache to see if the items already exist. If they do, the method returns the cached results, and if not, it queries the list, stores the results in cache and returns them from the method call.
 
     // Get Current Web
        SPWeb curWeb = SPControl.GetContextWeb(HttpContext.Current);
        //Create the Query
        SPQuery curQry = new SPQuery();
        curQry.Query = "SP2007";
        // Get Portal Map Provider
        PortalSiteMapProvider ps = PortalSiteMapProvider.WebSiteMapProvider;
        PortalWebSiteMapNode pNode = TryCast (ps.FindSiteMapNode (curWeb.ServerRelativeUrl), PortalWebSiteMapNode);
        // Get the items
        pItems = ps.GetCachedListItemsByQuery(pNode, "myListName_NotID", curQry, curWeb);
        // Enumerate all resulting Items
        foreach (PortalListItemSiteMapNode curItem in pItems)
    {
        string ResultItemTitle = curItem["Title"].ToString();
    } 

No comments:

Post a Comment