Category Archives: Tips and Tricks

Reusable Content Control – Sharepoint 2013 MasterPage

SharePoint-2013
Although the Reusable Content list works well for adding content to content placeholders in a publishing page, there are times when I want to use it to store reusable content that should show up in my master page or in page layouts. For instance, I’d like the copyright message that appears in the footer to be maintained by content owners, so that each time a new year rolls by, they can update the date in the footer without needing to get a developer involved to update the master page.
This is a control I’ve developed that retrieves a particular item from the Reusable Content list by the item’s title, and displays it. It retrieves the item by a simple CAML query.
using System;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
namespace BB.SP2010.WebControls
{
public class ReusableContentControl : WebControl
{
private string reusableContentListItemTitle;
      public string ReusableContentListItemTitle
{
set { reusableContentListItemTitle = value; }
}
      protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
{
SPWeb rootWeb = SPContext.Current.Site.RootWeb;
SPList reusableContentList = rootWeb.Lists[“Reusable Content”];
         SPQuery query = new SPQuery();
query.Query = String.Format(“<Where><Eq><FieldRef Name=’Title’/><Value Type=’Text’>{0}</Value></Eq></Where>”,
reusableContentListItemTitle);
SPListItemCollection listItems = reusableContentList.GetItems(query);
if (listItems.Count > 0)
{
SPListItem listItem = listItems[0];
            Literal reusableContent = new Literal();
reusableContent.Text = listItem[“Reusable HTML”].ToString();
this.Controls.Add(reusableContent);
}
         base.RenderChildren(writer);
}
}
}
To use this control, first add a reference to the assmebly in your page, like this:
<%@ Register Tagprefix=”CustomWebControls” Namespace=”BB.SP2010.WebControls” Assembly=”BB.SP2010.WebControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=2f91cfdda5cd365b” %>
Next, add the control to your page, passing in the title of the Reusable List list item you want to render to the page:
<CustomWebControls:ReusableContentControl runat=”server” ID=”copyrightControl” ReusableContentListItemTitle=”Copyright”/>
I’m not caching the results because, if you have caching turned on on your Publishing site, the CAML query itself should be cached.
Ref : savtechsol

WebPart Zone in Page Layout not displaying – Sharepoint 2013

SharePoint-2013

It has happen to me many times, but I always forget and start worrying

Simple Solution : putting IE into Compatibility Mode 🙂

Cannot see Master Pages in SharePoint Designer 2013 In root site

SharePoint-2013

If you just want to edit the master page without fixing the missing items in the sidebar, you can navigate to _catalogs/masterpage through the “All Files” section in SharePoint Designer.

On the other hand, if you want to fix it, here’s how I managed to do it:

We were facing the same problem in one of our SharePoint 2013 installations. I searched for that and I only found answers saying that I’d need to activate the publishing feature in the site collection scope, however that was not the problem since it was already activated.

Later I found out that the “Lists and Libraries” section in the Site Objects would not show any results. The problem is that we had a list in the site that was using a list template from an old solution that was not installed anymore, causing ListData.svc — a web service used by SharePoint Designer — to crash. You can see more here: Why don’t Lists and Libraries show up in SharePoint Designer?

After I deleted that list though the SharePoint Management Shell, not only the lists started to show up in the Lists and Libraries section, as also the Master Pages and Page Layouts sections reappeared.

Ref : Sharepoint StackExchange

How to execute a stored procedure within C# program – with Parameter, using Loop

csharp

Here is a sample :

using (SqlConnection conn = new SqlConnection(ConnectionString) {
    conn.Open();

    // 1.  create a command object identifying the stored procedure
    SqlCommand cmd  = new SqlCommand("CustOrder", conn);

    // 2. set the command object so it knows to execute a stored procedure
    cmd.CommandType = CommandType.StoredProcedure;

    // 3. add parameter to command, which will be passed to the stored procedure
    cmd.Parameters.Add(new SqlParameter("@CusID", custId));

    // execute the command
    using (SqlDataReader rdr = cmd.ExecuteReader()) {
        // iterate through results, printing each to console
        while (rdr.Read())
        {
            Console.WriteLine("Product: {0,-35} Total: {1,2}",rdr["ProductName"],rdr["Total"]);
        }
    }
}

Reading from web.config’s AppSettings in a SharePoint timer job

csharpSharePoint-2013

Well, this was not as straight-forward as i first thought. Why? Because the timer job does not run in the same App Domain as the web application. They are in two separate processes : W3WP.EXE  and OWSTIMER.EXE for the Web Application worker process and the SharePoint timer respectively.

So, how do you go about it?

Well, firstly you need to add reference to your timer job as follows (unless your using VB !):

using System.Configuration;
using System.Web.Configuration;

Reading AppSettings in Timer

using (SPSite site = new SPSite(“http://SiteCollectionUrl&quot;))

        {

            Configuration config = WebConfigurationManager.OpenWebConfiguration(“/”, site.WebApplication.Name);

            returnconfig.AppSettings.Settings[“AppSettingKeyToRead”].Value;

        }

Admittedly, this solution is hard coding the Uri of the Site Collection, but this is purely for demonstration purposes.

CAML QUERY IN SHAREPOINT 2013 (Examples)

SharePoint-2013

Collaborative Application Markup Language (CAML) is an XML-based language that is used in Microsoft SharePoint Foundation to define the fields and views that are used in sites and lists.

We can use queries to get data from SharePoint lists with filtering. As a best practice, it is recommended to filter data for large lists to improve performance.

Following can be various samples when we use CAML queries.

1)   CAML query with simple filtering

SPQuery oquery = newSPQuery();

oquery.Query = “<Where><Eq><FieldRef Name=’Child_x0020_Type’ /><Value Type=’Text’>” + childType.ToString().Trim() + “</Value></Eq></Where>”;

2)      CAML query with SORTING (OrderBy)

SPQuery oquery = newSPQuery();

oquery.Query = “<Where><Eq><FieldRef Name=’Article_ID’ /><Value Type=’Text’>” + articleID.ToString().Trim() + “</Value></Eq></Where><OrderBy><FieldRef Name =\”Modified\” Ascending=\”FALSE\”/></OrderBy>”;

SPListItemCollection col = lstTestArticles.GetItems(oquery);

3)      CAML query with few conditions (AND, AND)

SPQuery oquery = newSPQuery();

oquery.Query = “<Where><And><And><Eq><FieldRef Name=’Child_x0020_Type’ /><Value Type=’Text’>” + childType.ToString().Trim() + “</Value></Eq>” +

“<Eq><FieldRef Name=’Parent_x0020_Type’ /><Value Type=’Text’>” + parentType + “</Value></Eq></And>” + “<Eq><FieldRef Name=’Article_x0020_Type’ /><Value Type=’Text’>” + articleType.ToString().Trim() + “</Value></Eq>” +

“</And></Where><OrderBy><FieldRef Name =’Title’ Ascending=’TRUE’/></OrderBy>”;

4)      CAML query with DATETIME

SPQuery oquery = newSPQuery();

query.Query = “<Where><And><Geq><FieldRef Name=’Modified’ /><Value Type=’DateTime’ IncludeTimeValue=’TRUE’>” + SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtStartTime.SelectedDate) + “</Value></Geq>” +

“<Leq><FieldRef Name=’Modified’ /><Value Type=’DateTime’ IncludeTimeValue=’TRUE’>” +

SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtendTime.SelectedDate) + “</Value></Leq></And></Where>”;

5)      CAML query with USER

SPQuery oquery = newSPQuery();

query.Query = “<Where><And><And><Geq><FieldRef Name=’Modified’ /><Value Type=’DateTime’ IncludeTimeValue=’TRUE’>” + SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtStartTime.SelectedDate) + “</Value></Geq>” +

“<Leq><FieldRef Name=’Modified’ /><Value Type=’DateTime’ IncludeTimeValue=’TRUE’>” +                       SPUtility.CreateISO8601DateTimeFromSystemDateTime(dtendTime.SelectedDate) + “</Value></Leq></And><Eq><FieldRef Name=’Editor’ LookupId=’TRUE’ /><Value Type=’User’>” + myuser.ID + “</Value></Eq></And></Where>”;

6)      CAML query with Integer

SPQuery oquery = newSPQuery();

oquery.Query = “<Where><And><Eq><FieldRef Name=’Article_x0020_Type’ /><Value Type=’Text’>” + articleCategory.ToString().Trim() + “</Value></Eq>” +

“<Eq><FieldRef Name=’Status’ /><Value Type=’Integer’>” + 1 + “</Value></Eq>” +

“</And></Where>”;

SPListItemCollection oCol = TestArticle.GetItems(oquery);

7)      CAML Query to get documents

SPWeb oWeb = SPContext.Current.Web;

SPList olist = oWeb.Lists[Constants.TESTProcessRootFolderName()];

SPView oView = olist.Views[“All Documents”];

SPQuery oQuery = newSPQuery(oView);

oQuery.RowLimit = 22;

oQuery.ViewAttributes = “Scope=\”Recursive\””;

oQuery.Query = “<Where><Contains><FieldRef Name=’Title’ /><Value Type=’Text’>” + relatedID.ToString(“00″) + “-” + “</Value></Contains></Where><OrderBy><FieldRef Name =\”Modified\” Ascending=\”FALSE\”/></OrderBy>”;

SPListItemCollection collListItemsAvailable = olist.GetItems(oQuery);

return collListItemsAvailable;

How to Write an SPQuery to Sort Your List – SharePoint 2010 and 2013

SharePoint-2013

If you’re working with an SPListItemCollection, you might have the need to sort the data that stored in the collection. The best way I’ve found to do this is to build an SPQuery object and use that to actually query for the information. Using an object of this type makes it possible to send in whatever sort and/or orderby clause we’d like to use.

For example:

1
<OrderBy><FieldRef Name='EventDate' Ascending='FALSE'></FieldRef></OrderBy>

The full query would look something like this:

SPQuery oQuery = new SPQuery();
 
oQuery.Query = "<Where><Eq><FieldRef Name='AP_x0020__x002f__x0020_O'/>" +
"<Value Type='Text'>" + fruitName + "</Value></Eq></Where>" +
"<OrderBy><FieldRef Name='EventDate' Ascending='FALSE'></FieldRef></OrderBy>";

If you receive an error similar to:

One or more field types are not installed properly. Go to the list settings page to delete these fields.

Then you’ve set the FieldRef Name incorrectly. The trick to resolving this is:

  1. Navigate to your list that the column/field is contained within
  2. Click the New button as you normally would to create a new item in this list
  3. Click on View, Source from the toolbar in your browser window.
  4. Finally, do a find on the phrase fieldinternalname and locate the field you’re trying to query on
  5. Whatever value is stored in fieldinternalname is what you’ll want to use in your query

Any questions, let me know.

UPDATE: I recently discovered another trick to this. If you want to avoid having to seek out what the internal name of a particular field is, when you first name your column, do not include any spaces or special characters. Once the field (column) has been created, go back and rename the field to include the spaces or special characters as desired. SharePoint will still retain the original field name without spaces and you can use that directly in your query without issue.

Ref : SharePoint Development & Ops