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

Get absolute URL to listitem’s default display form – Sharepoint2013

csharp

Problem : 

I need to have an absolute URL of a listitem’s display form – currently I do it the following way:

On http://mydomain.com/:

item.ParentList.ParentWeb.Url.TrimEnd('/') //"http://mydomain.com"
+ "/" 
+ item.ParentList.DefaultDisplayFormUrl.Trim('/')//"Lists/WorkflowTasks/DispForm.aspx"
+ "?ID=" + item.ID //"?ID=1"

This gets me the correct URL, meaning http://mydomain.com/Lists/WorkflowTasks/DispForm.aspx?ID=1.

However this fails when my site collection is on a slightly more sophisticated host url, for examplehttp://mydomain.com/sites/secondsite/ – both methods from my code return the url containing the “/sites/secondsite/ part so I end up with http://mydomain.com/sites/secondsite/sites/secondsite/Lists/etc

How do I code it in a more reliable way?

Solution :

There are a couple of methods for this available in the object model without the need to handle the slashes etc yourself, one method using MakeFullUrl:

var fullUrl = item.ParentList.ParentWeb.Site.MakeFullUrl(item.ParentList.DefaultDisplayFormUrl);

Also

+ "?ID=" + item.ID //"?ID=1"

Resolved.

Using C# to read data from a SharePoint list using the SharePoint REST API

If you’re working with a C# application that is required to read information contained in a SharePoint list located on an external SharePoint farm, the SharePoint REST API can provide just the solution that you’re looking for.  Here is some sample code that you can use for accessing the information contained in that SharePoint list:

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;

namespace Sample
{
    public class SharePointListReader
    {
        ...

        public List<SharePointListItem> GetAllSPListItems()
        {
            List<SharePointListItem> posts = new List<SharePointListItem>();
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://webapp/site/_api/web/lists/getbytitle('listName')/items?$select=id,Title");
            request.Method = "GET";
            request.Accept = "application/json;odata=verbose";
            request.ContentType = "application/json;odata=verbose";
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;
            WebResponse response = request.GetResponse();
            Data data = null;

            // Read the returned posts into an object that can be consumed by the calling application
            using (response)
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    try
                    {
                        string jSON = reader.ReadToEnd();
                        data = serializer.Deserialize(jSON);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(string.Format("An error occurred when reading the list items from SharePoint: {0}; {1}", ex.Message, ex.StackTrace));
                    }
                }
            }
            foreach (SharePointListItem post in data.d.results)
            {
                posts.Add(post);
            }
            return posts;
        }
    }

    public class Data
    {
        public Results d { get; set; }
    }

    public class Results
    {
        public SharePointListItem[] results { get; set; }
    }

    public class SharePointListItem
    {
        public string id { get; set; }
        public string Title { get; set; }
    }
}

SharePoint : can’t see app templates for Announcement & survey

SharePoint-2013

Just check if Team Collaboration Lists feature activated? you can find this under Site Settings > Site features.

This feature enables Wiki Page Library, Links, Announcements, Calendar, Discussion Board, Tasks and few other templates.

If you still have the issue then the easiest way is by directly accessing create.aspx page which you can find user _layouts/15/create.aspx.

For SharePoint 2013: http://<site URL>/_layouts/15/create.aspx

For SharePoint 2010: http://<site URL>/_layouts/create.aspx

My Weblog registry is a directory which stores settings and options for my Professional Life (mostly SharePoint)