Tag Archives: Tips

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 🙂

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"]);
        }
    }
}

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.

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

Error occurred in deployment step ‘Install app for SharePoint’: The provided App differs from another App with the same version and product ID

SharePoint-2013

Problem:
Cannot deploy a solution and getting the error: Error occurred in deployment step ‘Install app for SharePoint’: The provided App differs from another App with the same version and product ID.

Solution:
Open the AppManifest.xml in code view and generate a new guid for the app -> Change value of ProductID.

This task requires the application to have elevated permissions.

I start my Visual Studio 2010, create new SharePoint project and after giving project name and clicking OK I get this error:

ElevatedPrivVS2010

This task requires the application to have elevated permissions.

I already started VS2010 as administrator, but that’s not the solution yet.

I log to the server via Remote Desktop with my domain account. To be able to connect VS to SharePoint, my account needs to be added to local administrators group (get your admin/domain admin to do that).
Afterwards, I need to log out from Windows (thus ending my session) and log in again. Now, when I run Visual Studio as administrator, I can create new SharePoint project.

Regular Expressions Example (c#) – CSharp

csharp

The following example shows the use of Regular Expresssions in C#.This program has basic validation scripts for validation easily useable in all programs.

/*
<HowToCompile>
csc /r:System.Text.RegularExpressions.dll,System.dll Validation.cs
</HowToComplie>
*/
using System.Text.RegularExpressions;
using System;
class Validation
{
public static void Main()
{
String strToTest;
Validation objValidate=
new Validation();
Console.Write(“Enter a String to Test for Alphabets:”);
strToTest=Console.ReadLine();
if(objValidate.IsAlpha(strToTest))
{
Console.WriteLine(“{0} is Valid Alpha String”,strToTest);
}
else
{
Console.WriteLine(“{0} is not a Valid Alpha String”,strToTest);
}
}
// Function to test for Positive Integers.
public bool IsNaturalNumber(String strNumber)
{
Regex objNotNaturalPattern=
new Regex(“[^0-9]”);
Regex objNaturalPattern=
new Regex(“0*[1-9][0-9]*”);
return !objNotNaturalPattern.IsMatch(strNumber) &&objNaturalPattern.IsMatch strNumber);
}
// Function to test for Positive Integers with zero inclusive
public bool IsWholeNumber(String strNumber)
{
Regex objNotWholePattern=
new Regex(“[^0-9]”);
return !objNotWholePattern.IsMatch(strNumber);
}
// Function to Test for Integers both Positive & Negative
public bool IsInteger(String strNumber)
{
Regex objNotIntPattern=
new Regex(“[^0-9-]”);
Regex objIntPattern=
new Regex(“^-[0-9]+$|^[0-9]+$”);
return !objNotIntPattern.IsMatch(strNumber) &&
objIntPattern.IsMatch(strNumber);
}
// Function to Test for Positive Number both Integer & Real
public bool IsPositiveNumber(String strNumber)
{
Regex objNotPositivePattern=
new Regex(“[^0-9.]”);
Regex objPositivePattern=
new Regex(“^[.][0-9]+$|[0-9]*[.]*[0-9]+$”);
Regex objTwoDotPattern=
new Regex(“[0-9]*[.][0-9]*[.][0-9]*”);
return !objNotPositivePattern.IsMatch(strNumber) &&
objPositivePattern.IsMatch(strNumber) &&!objTwoDotPattern.IsMatch(strNumber);
}
// Function to test whether the string is valid number or not
public bool IsNumber(String strNumber)
{
Regex objNotNumberPattern=
new Regex(“[^0-9.-]”);
Regex objTwoDotPattern=
new Regex(“[0-9]*[.][0-9]*[.][0-9]*”);
Regex objTwoMinusPattern=
new Regex(“[0-9]*[-][0-9]*[-][0-9]*”);
String strValidRealPattern=”^([-]|[.]|[-.]|[0-9])[0-9]*[.]*[0-9]+$”;
String strValidIntegerPattern=”^([-]|[0-9])[0-9]*$”;
Regex objNumberPattern =
new Regex(“(” + strValidRealPattern +”)|(” +
trValidIntegerPattern + “)”);
return !objNotNumberPattern.IsMatch(strNumber) &&!objTwoDotPattern.IsMatch
strNumber) && !objTwoMinusPattern.IsMatch(strNumber) && objNumberPattern.IsMatch(strNumber);
}
// Function To test for Alphabets.
public bool IsAlpha(String strToCheck)
{
Regex objAlphaPattern=
new Regex(“[^a-zA-Z]”);
return !objAlphaPattern.IsMatch(strToCheck);
}
// Function to Check for AlphaNumeric.
public bool IsAlphaNumeric(String strToCheck)
{
Regex objAlphaNumericPattern=
new Regex(“[^a-zA-Z0-9]”);
return !objAlphaNumericPattern.IsMatch(strToCheck);
}
}

There is another simple way to perform these validation think of it while the next article comes.