Monday, 14 November 2011
Web Part Page Maintenance – Get rid of that broken web part (SharePoint: Tricks for web part customization)
Trick 1: Deleting a bad web part
If you have just added a web part to a page and you get the dreaded error page as a result, add ?Contents=1 to the page’s URL.
http://……./default.aspx?Contents=1
You can now delete the offending web part.
Trick 2: Getting to web parts when there is no “Edit Page” in Site Actions
Add &ToolPaneView=2 to then end of the URL. This example will let you see the web parts on a list’s NewForm page.
http://……./NewForm.aspx?……..&ToolPaneView=2
Wednesday, 21 September 2011
Create a new term in Existing Group and Term Set Under Managed Metadata Service Application with PowerShell
Use this script if you want to create a new term in the SharePoint 2010 Managed Metadata Service with PowerShell:
#Connect to Central Admin
$taxonomySite = get-SPSite http://centraladminsite:port
#Connect to Term Store in the Managed Metadata Service Application
$taxonomySession = Get-SPTaxonomySession -site $taxonomySite
$termStore = $taxonomySession.TermStores["Managed Metadata Service"]
write-host "Connection made with term store -"$termStore.Name
#Connect to the Group and Term Set
$termStoreGroup = $termStore.Groups["Group Name"]
$termSet = $termStoreGroup.TermSets["Term Set Name"]
#Create term, term description, and a synonym
$term = $termSet.CreateTerm("Test Term", 1033)
$term.SetDescription("This is a test", 1033)
$term.CreateLabel("This is a test synonym", 1033, $false)
#Update the Term Store
$termStore.CommitAll()
Thursday, 8 September 2011
Yield keyword in C Sharp
public static IEnumerable<int> GetIntCollectionFromString(string SomeString)
{
string[] val = SomeString.Split(' ');
int intVal;
foreach (string token in val)
{
if (int.TryParse(token, out intVal))
{
yield return intVal;
}
else
{
yield break;
}
}
}
Here since we are using the yield keyword the function will return the collection of intVal instead of the value of intVal. The statement will only return when the iteration of the loop is complete.
There are some limitation with the yield keywords.
Unsafe blocks are not allowed
Parameters to the method, operator, or accessor cannot be ref or out.
Wednesday, 7 September 2011
How To Create an ASP.NET HTTP Handler by Using Visual C# .NET
Open Microsoft Visual Studio .NET. In Visual C# .NET, create a new Class Library project named MyHandler.
Set a reference to the System.Web.dll assembly.
Add the following directive to the class:
using System.Web;
Rename the class SyncHandler.cs, and then change the class definition to reflect this.
Implement the IHttpHandler interface. Your class definition should appear as follows:
public class SyncHandler : IHttpHandler
Implement the IsReusable property and the ProcessRequest method of the IHttpHandler interface. Because this is a synchronous handler, return False for the IsReusable property so that the handler is not pooled.
public bool IsReusable
{
get {return false;}
}
public void ProcessRequest(HttpContext context)
{
context.Response.Write("Hello from custom handler.");
}
Compile the project.
Deploy the Handler
Create a new directory named Handler under the C:\Inetpub\Wwwroot directory.
Create a subdirectory named Bin in the newly created Handler directory. The resultant path is C:\Inetpub\Wwwroot\Handler\Bin.
Copy MyHandler.dll from your project's Bin\Debug directory to the C:\Inetpub\Wwwroot\Handler\Bin directory.
Follow these steps to mark the new Handler directory as a Web application:
Open Internet Services Manager.
Right-click the Handler directory, and then click Properties.
On the Directory tab, click Create.
Follow these steps to create an application mapping for the handler. For this handler, create a mapping to the Aspnet_isapi.dll file for the *.sync extension. Whenever a .sync file is requested, the request is routed to ASP.NET, and ASP.NET executes the code in the handler.
Right-click on the Handler Web application, and then click Properties.
On the Directory tab, click Configuration.
Click Add to add a new mapping.
In the Executable text box, type the following path: Microsoft Windows 2000:
C:\WINNT\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll
Microsoft Windows XP:
C:\WINDOWS\Microsoft.NET\Framework\<version#>\Aspnet_isapi.dll
In the Extension text box, type .sync.
Make sure that the Check that file exists check box is cleared, and then click OK to close the Add/Edit Application Extension Mapping dialog box.
Click OK to close the Application Configuration and the Handler Properties dialog boxes.
Close Internet Services Manager.
Configure the System
In the C:\Inetpub\Wwwroot\Handler directory, create a new file named Web.config.
Add the following code to Web.config:
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.sync" type="MyHandler.SyncHandler, MyHandler" />
</httpHandlers>
</system.web>
</configuration>
In the verb="*" attribute, we instruct the handler to process a request that uses any verb (for example, POST, HEAD, GET, and so on). If you want this handler to process only the POST request, change this to verb="POST".
In the path="*.sync" attribute, we instruct the handler to process any incoming requests for files with the .sync extension.
In the type="MyHandler.SyncHandler, MyHandler" attribute, we instruct the handler that processes the request to implement in the MyHandler.SyncHandler namespace, and this class resides in the MyHandler assembly.
Test the Module
To test a handler, a page does not need to exist in the file system. For example, request the Default.sync file in the Handler Web application (http://
Hello from custom handler.
Monday, 5 September 2011
Organizing Data in Lists
Lists and Their Elements
Metadata is a semantically enhanced description of the data to express the meaning of data. For example, adding additional information (such as author, date, and keywords) to a document stored in a document library enhances the ability of a search engine to find it and order the results. SharePoint’s list model is amazingly flexible. Moreover, it empowers ordinary users to create and manage their own data store—normally a function “for experts only.” After years of computer technology advancement, the administration of a data model is no longer rocket science. However, this does not mean that you—as a developer—cannot programmatically interact with the data model. The whole power of the list model and its associated parts is available through the object model. Whatever the end user may do (and most of what they can’t do) through the UI, you can accomplish with the object model.
Early on in your contact with SharePoint lists, you should have encountered the term content type. Though they are ignored by many, they are, as a matter of fact, a core concept.
CONTENT TYPE DEFINITION
A content type is a reusable collection of settings you want to apply to a certain category of content. Content types enable you to manage the metadata and behaviors of a document or item type in a centralized, reusable way.
Creating a List Programmatically
You can easily create a new list using the Add method of the SPListCollection type. The code shown next demonstrates this in a console application.
using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = null;
string listName = "Books";
// Check whether the list already exists
try
{
list = web.Lists[listName];
}
catch (ArgumentException)
{
}
if (list == null)
{
Guid listId = web.Lists.Add(listName, "All our books",
SPListTemplateType.GenericList);
list = web.Lists[listId];
list.OnQuickLaunch = true;
list.Update();
}
Console.WriteLine("Created list {0} with id {1}", list.Title, list.ID);
}
}
This code runs in a console application and creates a new generic (custom) list without any additional columns. Before creating a new list, you should check whether it already exists. You can either loop through all lists or try to access the new list and catch the exception thrown if it doesn’t yet exist. An alternative approach is to use a LINQ query:
bool exists = (from l in web.Lists.OfType
where l.Title.Equals(listName)
select l).Count() > 0;
The list itself is not queryable and must be copied into a List
Adding Fields to the List
Once the list exists, you can add fields. Fields represent the columns. Internally, a field is a type derived from SPField. SharePoint includes a number of predefined fields for specific types. The following example demonstrates adding several fields for scalar types:
list.Fields.Add("ISBN", SPFieldType.Text, true);
list.Fields.Add("LeadAuthor", SPFieldType.Text, true);
list.Fields.Add("Price", SPFieldType.Currency, false);
list.Update();
The SPFieldType enumeration contains all possible types. You can also define custom types and extend the list of field types. A field type is not only a scalar or complex value; it can also have a relationship to a custom field editor.
Changing Field Properties
Certain properties are not available through the UI. Even SharePoint Designer, with its advanced capabilities, eventually reaches its limits. The example in the next Listing shows how to enable an invisible field to appear in the dialogs again and remove the read-only flag.
using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
SPList questions = web.Lists["Questions"];
SPField field = questions.Fields["Voters"];
field.Hidden = false;
field.ReadOnlyField = false;
field.Update();
}
}
The change affects only the SPField object—not the list. The code snippet assumes you have a Questions list with a Voters field that is hidden and read-only. The changes are assigned to the underlying content type if the column is defined there. There is no need to change the particular content type directly.
Adding Items to the List
Adding items is as straightforward as adding fields. However, the procedure is not yet type-safe because the column’s ID must be provided as a string or Guid. The field name you need to use here is the internal Name, not the DisplayName.
Using a string that clearly describes the field is recommended:
SPListItem item = list.Items.Add();
item["Title"] = "ASP.NET Extensibility";
item["ISBN"] = "978-1-4305-1983-5";
item["LeadAuthor"] = "Joerg Krause";
item["Price"] = 59.99;
item.Update();
An ArgumentException is thrown if a field name does not exist. Alternatively, you can use the field’s zero-based index or its Guid to identify the field. This is recommended if the index or Guid is returned from any previous operation, to avoid errors due to mistyping.
Working with Attachments
Each item in a SharePoint list has an associated SPAttachmentCollection array. The collection contains strings, which may seem odd, as you would expect SPFile objects instead. What you see is a direct representation of the underlying storage model. Attachments are part of the containing web. This means that all lists share all their attachments in one library. The names collection must be combined with the web’s URL to give the complete address to the file in the repository.
Fortunately, the SPAttachmentCollection has several useful direct methods, such as Add, Delete, and Recycle.
SPList list = web.Lists["MyList"];
foreach (string fileName in item.Attachments)
{
SPFile file = item.ParentList.ParentWeb.GetFile(
item.Attachments.UrlPrefix + fileName);
// Work with SPFile
}
Another usage scenario could look like this:
using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["WordDocuments"];
SPListItem item = list.Items[id];
if (item.Attachments.Count > 0)
{
SPFile attachment = item.ParentList.ParentWeb.GetFile(
item.Attachments.UrlPrefix + item.Attachments[0]);
Stream content = attachment.OpenBinaryStream();
using (Package p = Package.Open(content))
{
// handle as a package (just a suggestion)
}
}
}
}
This code assumes that you have a list, called WordDocuments. The current item is selected by using the variable id. The code checks whether one or more attachments are present, and if so, it reads the first attachment (index zero). The attachment is loaded into an SPFile object and read as a binary stream. We suggest you use the Package class to access files in the package format (such as XPS, DOCX, XSLX, and so forth). The Package class is defined in the namespace System.IO.Packaging—the containing assembly is WindowsBase.dll.
Item- and List-Level Event Receivers
Synchronous vs. Asynchronous Events
SharePoint is rich with the events it exposes. We can categorize SharePoint events in two ways: by the “level” that fires the event (site, list, item) and by the type of the event (synchronous or asynchronous).
WHAT SYNCHRONOUS/ASYNCHRONOUS MEANS FOR EVENTS?
Synchronous events happen “before” the actual event. You have the HttpContext; you can display an error message in the browser, and if needed, you can cancel the event before it occurs.
Asynchronous events happen “after” the actual event. There is no HttpContext; you cannot directly show an error message, and you cannot cancel the event. On the other hand, you can handle what happens after the event is fired, including manipulating the object.
As examples of synchronous and asynchronous events, consider item-level events such as ItemAdding and ItemAdded. With ItemAdding, you can inspect the item, and, if necessary, cancel the addition and display an error message in the SharePoint page to the user. Inside the ItemAdded event, however, you know that the item is already in the SharePoint list, but you can start some post-add actions concerning that item.
Synchronous events are also called “before” events. They appear before the internal operation occurs. The event handler is also blocking the current flow. For this reason, we recommend you avoid time-consuming operations here.
Event Description
ItemAdding Occurs when a new item is added to its containing object
ItemAttachmentAdding Occurs when a user adds an attachment to an item
ItemAttachmentDeleting Occurs when a user removes an attachment from an item
ItemCheckingIn Occurs as a file is being checked in
ItemCheckingOut Occurs before an item is checked out
ItemDeleting Occurs before an existing item is completely deleted
ItemFileMoving Occurs when a file is being moved
ItemUncheckedOut Occurs before an item is being unchecked out
ItemUpdating Occurs when an existing item is changed, for example, when the user changes data in one or more fields
Asynchronous events are classified as “after” events. They are called asynchronously. Lengthy operations do not block the current thread. Because the internal operation is completed, you can safely manipulate the freshly added or changed data.
Event Description
ItemAdded Occurs after a new item has been added to its containing object
ItemAttachmentAdded Occurs after a user adds an attachment to an item
ItemAttachmentDeleted Occurs after a user removes an attachment from an item
ItemCheckedIn Occurs after an item is checked in
ItemCheckedOut Occurs after an item is checked out
ItemDeleted Occurs after an existing item is completely deleted
ItemFileMoved Occurs after a file is moved
ItemUncheckingOut Occurs after an item is unchecked out
ItemFileConverted Occurs after a file has been converted
ItemUpdated Occurs after an existing item is changed, for example, when the user changes data in one or more fields
List Events
List events (see below) occur for list operations that affect the whole list, such as schema changes. As for the list item events, you can choose synchronous and asynchronous events. The implementation uses the SPListEventReceiver base class—you simply override the appropriate methods.
Synchronous List-Level Events are shown next:
Event Description
FieldAdding Occurs when a field link is being added to a content type
FieldDeleting Occurs when a field is being removed from the list
FieldUpdating Occurs when a field link is being updated
Asynchronous List-Level Events are similar:
Event Description
FieldAdded Occurs after a field link is added
FieldDeleted Occurs after a field has been removed from the list
FieldUpdated Occurs after a field link has been updated
Developing and Deploying an Event Receiver
This section contains a step-by-step guide to developing event receivers and attaching them to the appropriate objects. In this example, we will create a simple receiver, which will handle two asynchronous events (ItemAdded and ItemUpdated) in all Document and Picture libraries at a SharePoint web site, and deploy it as a feature at the site level. The templates Visual Studio 2010 provides for this adds the required configuration files. The template comes with a wizard that asks for the particular event you want to create. Therefore, there is just one template for all possible events.
The wizard asks for the SharePoint site and whether the solution is a sandboxed or farm solution. Next you can select the type of event (List, List Item, and so on) and what specific event handler the wizard should create.
The wizard creates the package (solution), the feature that activates and deactivates the event handlers, and the event handler definition. An event handler definition consists of an Element.xml file that defines events, where they attach and the entry point of the assembly that contains the code:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Receivers ListTemplateId="104">
<Receiver>
<Name>EventReceiver1ItemAdded</Name>
<Type>ItemAdded</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>ItemEventReceiverProject.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
<Receiver>
<Name>EventReceiver1ItemUpdated</Name>
<Type>ItemUpdated</Type>
<Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
<Class>ItemEventReceiverProject.EventReceiver1.EventReceiver1</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
</Receivers>
</Elements>
The Event Handler Code
The code snippet created by the wizard (see Listing 4-14) attaches the two events to their event handlers. This is shown “as is.” No changes were made to fix namespaces or anything else.
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace Apress.SP2010.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
}
/// <summary>
/// An item is being updated.
/// </summary>
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
}
}
}
The receiver class must inherit from SPItemEventReceiver. To attach other events, you can override the corresponding methods in this class and extend the Elements.xml to connect the handler with the event source.
Document Libraries
Reading a File from the Shared Documents Library
Each site contains a library called Shared Documents. Code shown next explains how to retrieve a file as an SPFile object.
using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
if (web.GetFolder("Shared Documents").Exists)
{
SPFolder folder = web.GetFolder("Shared Documents");
SPFile file = folder.Files["WordTemplate.docx"];
}
}
}
Adding a Folder to a Library
If you work with folders, your users might not be satisfied with the UI support. For greater capability, you can create a function that adds folders programmatically.
using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
SPList lib = web.Lists["Shared Documents"];
SPFolder parent = lib.RootFolder;
SPFolder child = parent.SubFolders.Add("SubFolderName");
parent.Update();
}
}
This code adds a SubFolderName folder to the library’s root.
Saving Data to Libraries
To upload a file to a library, you use a similar approach (see Listing 4-21). The file must be available as a Stream or a byte array.
using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
spweb.AllowUnsafeUpdates = true;
SPFolder folder = web.Folders[site.URL + "/Shared Documents/"];
byte[] content = null;
using (FileStream filestream = new FileStream(@"C:\Sample.docx",
System.IO.FileMode.Open))
{
content = new byte[(int) filestream.Length];
filestream.Read(content, 0, (int) filestream.Length);
filestream.Close();
}
SPFile file = folder.Files.Add("Sample.docx", content, true);
// do something usefil with file
}
}
You can add the file to a specific folder:
SPFile file = folder.SubFolders["SubFolder"].Files.Add("Sample.docx",
content,
true);
The content variable is the same as shown previously.
Document Sets
Document sets have several advantages:
Each set has its own version history. It’s not necessary to track changes at the document level.
You can assign access rights on a per-set level.
You can assign and start workflows related to a set.
Users can download the whole document set as a ZIP file.
The home page related to a document set is a wiki page that can be edited easily.
Documents that are part of a document set can share their metadata.
Before you can access and use document sets programmatically, some preparatory steps are required. The document sets feature is available at the site collection level. To activate it, open the site settings and click “Site collection features.” On the next page, click the Activate button near the Document Sets feature entry.
A document set can now be created by adding a new content type, which inherits from the built-in content type Document Set.
Query Data Using CAML
Modify parameters to transport complex data
Define the body of SOAP messages to transport data using web services
Configure SharePoint for usage or deployment
Add specific behavior to features
SharePoint utilizes many XML files to define behavior and content. Most of these files use CAML as the dialect to express SharePoint-specific settings. In this section, we examine more closely the usage of CAML to query the data store. CAML is defined in several schemas. When you first attempt to understand CAML, it looks like an amalgam of many different dialects. However, it’s simply a collection of schemas that make CAML powerful enough for both data schema definition and data retrieval.
Using CAML to Retrieve Data
The Query schema is well documented, and numerous examples are available. However, the first time you try it, you’ll discover it’s not self-explanatory. All queries must be executed against a list. You need a reference to either an SPList or SPView object, which accepts a CAML query and can run it. The following examples demonstrate the bare bones of the technique.
The basic way to query data from SharePoint lists is to use queries constructed with CAML. The next code snippet shows a simple CAML query to fetch all items from a SharePoint list called Books whose Publisher is Apress .
public IEnumerable<SPListItem> GetBooksFromAPress()
{
SPList list = SPContext.Current.Web.Lists["Books"];
SPQuery query = new SPQuery();
query.Query = @"<Where>
<Eq>
<FieldRef Name='Publisher' />
<Value Type='Text'>Apress</Value>
</Eq>
</Where>";
IEnumerable<SPListItem> books = list.GetItems(query).OfType<SPListItem>();
return books;
}
In this example, the list is obtained from the current SPWeb instance. A new SPQuery object is instantiated to contain the query. The query is written as an XML string fragment.
With CAML, you can easily build your own custom queries, including conditions (Where) and logical operators (AND, OR) in XML format. Internally, SharePoint translates the CAML query into a SQL query to retrieve the data from the SharePoint content database.
How to Create a CAML Query
You can use LINQ to XML and the XElement type to create a query:
SPQuery queryl = new SPQuery();
queryl.Query = new XElement("Where",
new XElement("Eq",
new XElement("FieldRef", new XAttribute("Name", "Company")),
new XElement("Value", new XAttribute("Type", "Text")))) .ToString();
While this approach takes care of closing tags correctly and will always create valid XML, it does not seem easier. The CAML keywords are strings, and hence they can suffer from typing errors. You might consider using constants to predefine such keywords:
const string WHERE = "Where";
const string EQ = "Eq";
const string FIELDREF = "FieldRef";
const string VALUE = "Value";
const string NAME = "Name";
const string TYPE = "Type";
SPQuery queryc = new SPQuery();
queryc.Query = new XElement(WHERE,
new XElement(EQ,
new XElement(FIELDREF, new XAttribute(NAME, "Company")),
new XElement(VALUE, new XAttribute(TYPE, "Text"))))
.ToString();
That’s indeed safe and compact, but it’s still a manually built query. To overcome the manual construction of CAML queries, there are some useful implementations of CAML query builders that support creating a CAML query in a safe manner. To demonstrate this, check out an example using CAML.NET from John Holliday, which is a free project hosted on CodePlex (www.codeplex.com/camldotnet). Here is how to use it:
public IEnumerable<SPListItem> GetBooksFromAPress2()
{
SPList list = SPContext.Current.Web.Lists["Books"];
SPQuery query = new SPQuery();
query.Query = CAML.Where(
CAML.Eq(
CAML.FieldRef("Publisher"),
CAML.Value("APress")
)
);
IEnumerable<SPListItem> books = list.GetItems(query).OfType<SPListItem>();
return books;
}
If you need to use many manually constructed CAML queries, we strongly recommend using a CAML query builder such as CAML.NET. This is the least error-prone and most efficient method.
Joins and Projections
NOTE
Though this may look like a replacement for lookups, it does not eliminate the need for them. A join uses a field reference previously defined by a lookup. Thus, you have to create a lookup field first.
Regular lookups can be multilookups—meaning that you can form a many-to-many relationship. Using joins, this is not possible; you must use a single-value lookup.
Joins and projections have a direct representation in views and queries. This includes the corresponding properties—Joins and ProjectedField—of the SPQuery and SPView objects. While both objects use CAML, the XML snippets do not become part of a regular query, and they are not child elements of the
Joins
From SQL you may know that there are different kinds of joins. In CAML you can define two kinds of joins, INNER and LEFT, using the Type attribute:
<Joins>
<Join Type="INNER" ListAlias="Authors">
<Eq>
<FieldRef Name="FullName" RefType="Id" />
<FieldRef List="Authors" RefType="Id" />
</Eq>
</Join>
</Joins>
An inner join links two lists using an existing lookup. The result is a combination of both result sets. A left join (known in SQL as a LEFT OUTER JOIN) will return the same combination but includes the result of the parent list even if the related list does not have a matching entry. The common right join available in SQL is not supported by CAML.
Projected Fields in Views
The ProjectedFields element enables fields from the foreign lists to be viewed in the list view. The fields must also be identified in the ViewFields child element of the View element. The foreign lists are identified by their aliases, as defined in the Joins element. Again, if there is only one join, then there is no alias that is different from the list’s internal name. In this case, the reference in ViewFields uses the actual list name.
The ShowField attribute identifies which field from the foreign list is used in the view. This must be the internal name. The Type attribute always has the value Lookup—it does not indicate the data type of the field. The source type of a projected field is limited to a number of simple types, such as Counter, Currency, Integer, and Text.
Using Joins and Projected Fields
The following example shows how to use joins and projections. It is a console application that uses two lists: Books and Authors. The Books list relates to Authors through a field called LeadAuthor. The Authors list derives from Contacts and has an additional field called FullName.
The application (Listing 4-31) retrieves data from these two lists.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Xml;
namespace Apress.SP2010.CAMLJoins
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("http://sharepointserve"))
{
using (SPWeb web = site.OpenWeb())
{
SPList bookList = web.Lists["Books"];
SPList authList = web.Lists["Authors"];
SPField la = bookList.Fields["LeadAuthor"];
SPField fa = authList.Fields["Full Name"];
string join = @"<join Type='LEFT' ListAlias='Authors'>
<eq>
<fieldref Name='" + la.InternalName
+ @"' RefType='ID' />
<fieldref List='Authors' Name='ID' />
</Eq>
</Join>";
string projField = @"<field Name='Fullname' Type='Lookup'
List='Authors'
ShowField='" + fa.InternalName
+ "' />";
SPQuery query = new SPQuery();
query.Query = "";
query.Joins = join;
query.ProjectedFields = projField;
query.ViewFields = @"<fieldref Name='Fullname' />
<fieldref Name='Title' />";
SPListItemCollection items = bookList.GetItems(query);
foreach (SPListItem item in items)
{
Console.WriteLine("{0} has these lead authors: ",
item.Title);
if (item["Fullname"] == null)
{
Console.WriteLine(" no authors assigned");
continue;
}
SPFieldLookupValue sc =
new SPFieldLookupValue(item["Fullname"].ToString());
Console.WriteLine(" -{0}", sc.LookupValue);
}
}
}
Console.ReadLine();
}
}
}
The join is from the parent list Books to the child list Authors. This is defined by List='Authors' in the join’s second FieldRef element. The ListAlias attribute must echo this, as it is the only join. The first FieldRef refers to the parent list’s lookup field, using the internal name. It’s read from the SPField object that has a property InternalName.
The variable pfld stores the projected fields. The declaration contains one field, FullName, from the Authors list. ShowField is also defined using the internal name. The name defined in the Name attribute is used in the ViewField definition. The Title field is also added to the result set. The XML snippets are assigned to the appropriate properties of SPQuery.
The GetItems method executes the query. Because item["Fullname"] returns a lookup, the value it returns is in the form of “#1;Joerg Krause.” To process it, we create an SPFieldLookupValue object, passing the data as a string into the constructor to re-create the lookup value. From this object the LookupValue returns the full name.
Friday, 2 September 2011
Prevent duplicate item in a SharePoint List
ItemAdding Event Handler
public override void ItemAdding(SPItemEventProperties properties) { base.ItemAdding(properties); if (properties.ListTitle.Equals("My List")) { try { using(SPSite thisSite = new SPSite(properties.WebUrl)) { SPWeb thisWeb = thisSite.OpenWeb(); SPList list = thisWeb.Lists[properties.ListId]; SPQuery query = new SPQuery(); query.Query = @""; SPListItemCollection listItem = list.GetItems(query); if (listItem.Count > 0) { properties.Cancel = true; properties.ErrorMessage = "Item with this Name already exists. Please create a unique Name."; } } } catch (Exception ex) { PortalLog.LogString("Error occured in event ItemAdding(SPItemEventProperties properties)() @ AAA.BBB.PreventDuplicateItem class. Exception Message:" + ex.Message.ToString()); throw new SPException("An error occured while processing the My List Feature. Please contact your Portal Administrator"); } } } Feature.xml <?xml version="1.0" encoding="utf-8"?> <Feature Id="1c2100ca-bad5-41f5-9707-7bf4edc08383" Title="Prevents Duplicate Item" Description="Prevents duplicate Name in the "My List" List" Version="12.0.0.0" Hidden="FALSE" Scope="Web" DefaultResourceFile="core" xmlns="http://schemas.microsoft.com/sharepoint/"> <ElementManifests> <ElementManifest Location="elements.xml"/> </ElementManifests> </Feature> <font color="red">Element.xml</font> <?xml version="1.0" encoding="utf-8" ?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/"> <Receivers ListTemplateId="100"> <Receiver> <Name>AddingEventHandler</Name> <Type>ItemAdding</Type> <SequenceNumber>10000</SequenceNumber> <Assembly>AAA.BBB, Version=1.0.0.0, Culture=neutral, PublicKeyToken=8003cf0cbff32406</Assembly> <Class>AAA.BBB.PreventDuplicateItem</Class> <Data></Data> <Filter></Filter> </Receiver> </Receivers> </Elements> " + properties.AfterProperties["Title"] + "
Error: The search request was unable to connect to the Search Service
Error message: "The search request was unable to connect to the Search Service"
Resolution:
1. Go to Central Admin > Operations > Services on Server > Office SharePoint Server Search Service
Make sure the "Use this server for serving search queries" is checked.
2. Also verify that the search account is configured in both search services
Go to Central Admin > Operations > Services on Server > Office SharePoint Server Search service
Go to Central Admin > Operations > Services on Server > Windows SharePoint Services Search
3. Make sure the search account specified in "Default content access account" is used on above settings.
SharePoint Useful CodePlex Tools for SharePoint
To manage where the column are displayed (e.g.: new or edit mode). To Hide columns from newform.aspx, editform.aspx and dispform.aspx etc
http://wsslistconfigurator.codeplex.com/
To add 'Only their own' permission for the document library.
http://moresharepoint.codeplex.com/
Ad Rotator WebPart
http://spadrotator.codeplex.com/
Caml Query Builder
http://spadrotator.codeplex.com/
JQuery SPServices
http://spservices.codeplex.com
Hit Counter WebPart
http://hitcounter.codeplex.com/
Cascading drop downs
http://customfieldcontrols.codeplex.com/
To manage alerts on list or item for SharePoint groups.
http://advancedalert.codeplex.com
Useful Sharepoint Designer Custom Workflow Activities
http://spdactivities.codeplex.com/wikipage?title=Copy%20List%20Item%20Extended%20Activity&ProjectName=spdactivities
SharePoint User Change Password
http://userchangepassword.codeplex.com/>
List of users and their access
http://accesschecker.codeplex.com/
SharePoint Navigation Menu
http://spnavigationmenu.codeplex.com/>
Thursday, 1 September 2011
SharePoint 2010 Color Calendar 2 steps (Nested if else Conditions 19 nested if conditions)
Add the calculated column "colorCalendar" in sharePoint calendar list, and paste the following in the formula field :
="<div style='width:100%;background-color:"&IF(Category="meeting","#4FDB51",IF(Category="work hours","#F08616",IF(Category="holiday","#F55875",IF(Category="gifts","#F558D5",IF(Category="A","#9932CC",IF(Category="B","#FFD700",IF(Category="C","#00FF00",IF(Category="D","#FAF0E6",IF(Category="E","#FF00FF",IF(Category="F","#CD853F",IF(Category="G","#BC8F8F",IF(Category="H","#008080",IF(Category="I","#FFFF00",IF(Category="J","#9ACD32",IF(Category="K","#F5F5F5",IF(Category="L","#A52A2A",IF(Category="anniversary","#DC143C",IF(Category="get-together","#E0F558",IF(Category="birthday","#6E80FA","#FF4040")))))))))))))))))))&";'> "&Title&"</div>"
The possible nested if else conditions in SharePoint 2010 is 19, all those profiles which says it is less than this are wrong. This calculated field working great at my end
Go to Calendar View and set "colorCalendar" for the month view title, week view title and day view title.
Now add a content editor web part in the calendar page and paste the following script to change color background color of calendar events :
<style> .ms-acal-time { DISPLAY: none } .ms-acal-selected { PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; BACKGROUND: 0% 50%; PADDING-TOP: 0px } .ms-acal-item { PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; BACKGROUND: 0% 50%; PADDING-TOP: 0px } .ms-acal-sdiv SPAN { MARGIN-LEFT: 0px } .ms-acal-sdiv DIV.ms-acal-title SPAN { MARGIN-LEFT: 0px } .ms-acal-rootdiv DIV { PADDING-BOTTOM: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; HEIGHT: 100%; PADDING-TOP: 0px }</style> <script> // Color coded calendars for SharePoint 2010 // load our function to the delayed load list _spBodyOnLoadFunctionNames.push('colorCalendarEventLinkIntercept'); // hook into the existing SharePoint calendar load function function colorCalendarEventLinkIntercept() { var OldCalendarNotify4a = SP.UI.ApplicationPages.CalendarNotify.$4a; SP.UI.ApplicationPages.CalendarNotify.$4a = function () { OldCalendarNotify4a(); colorCalendarEventLinks(); } } // hide the hyperlinks function colorCalendarEventLinks() { // find all DIVs var divs = document.getElementsByTagName("DIV"); for (var i=0;i'); divs[i].title = divs[i].title.substring(0, divs[i].title.indexOf('<')) + divs[i].title.substring(divs[i].title.indexOf('>')+1, divs[i].title.lastIndexOf('<')); } // find "x more items" links and re-remove links on Expand/Contract if (divs[i].className.toLowerCase()=="ms-acal-ctrlitem") { var links = divs[i].getElementsByTagName("A"); if (links.length==1) { links[0].href="javascript:colorCalendarEventLinks();void(0);" } } } }</script>
Wednesday, 31 August 2011
SharePoint: Hiding the Search Box
To hide the search control on just one page:
Add a Content Editor Web Part (CEWP)
Edit the web part and click the Source Editor button
Paste the following:
<style> #SRSB {display:none} </style>
To hide the search control on all pages:
Use SharePoint Designer to edit your master page and put the above style tag just after the SharePoint style controls
<SharePoint:CssLink runat="server"/>To let the site owners hide or show by using a feature:
<SharePoint:Theme runat="server"/>
<style> #SRSB {display:none} </style>
The search box is actually an ASP.Net Web User Control (.ASCX) that can be replaced by using a SharePoint “feature”. If you want nothing displayed you can just create a one line .Net Web User Control (using Notepad if you like):
<%@ Control Language="VB" ClassName="yourclassname" %>
Here's an article with enough info to get you started on building the feature (just leave out the Google stuff):
http://techtrainingnotes.blogspot.com/2009/07/sharepoint-custom-search-boxes-google.html
Upgrading an Existing Master Page to the SharePoint Foundation Master Page
There have been significant changes to the user interface (UI) for Microsoft SharePoint Foundation 2010, including the addition of the Server ribbon. By default, the v4.master page includes the Server ribbon. Many of the commands previously found in menus and toolbars now exist inside of the Server ribbon. As a result, if your existing master page does not contain the Server ribbon, many commands will be unavailable. This topic shows you how to add the Server ribbon along with any new controls or content placeholders that are required for an existing master page to render correctly in SharePoint Foundation 2010.
There are some controls that were previously included with the default master page that have been moved into the new Server ribbon UI. Because these controls now exist inside the Server ribbon, if you plan to update an existing master page with Server ribbon functionality, you need to remove the following controls from your existing master page. These controls will be added when your incorporate the Server ribbon into your master page.
-
Publishing Console - <PublishingConsole:Console>
Site Actions Menu - <PublishingSiteAction:SiteActionMenu>
Sign-in and Log-in Control
Important |
---|
If you are using a custom sign-in control, you can move the control inside or outside of the Server ribbon, based on your layout. |
You must ensure that the new ContentPlaceHolder controls exist in order to update your master page to be compatible with SharePoint Foundation 2010. The following table lists all of the placeholders required for update your master page to be compatible with SharePoint Foundation 2010.
Important |
---|
The PlaceHolderTitleAreaClass placeholder is now in the head tag. Any customizations that add a WebPartZone in a content tag to this placeholder will cause an error on the page. |
Placeholder Control | Description | New |
---|---|---|
<asp:ContentPlaceHolder id="PlaceHolderQuickLaunchTop" runat="server"> | The top of the Quick Launch menu. | Yes |
<asp:ContentPlaceHolder id="PlaceHolderQuickLaunchBottom" runat="server"> | The bottom of the Quick Launch menu. | Yes |
<asp:ContentPlaceHolder id="PlaceHolderPageTitle" runat="server"/> | The title of the site. | No |
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/> | A placeholder in the head section of the page used to add extra components such as ECMAScript (JavaScript, JScript) and Cascading Style Sheets (CSS) to the page. | No |
<asp:ContentPlaceHolder id="PlaceHolderBodyAreaClass" runat="server"/> | The class of the body area. | No |
<asp:ContentPlaceHolder ID="SPNavigation" runat="server"> | A control used for additional page editing controls. | No |
<asp:ContentPlaceHolder id="PlaceHolderSiteName" runat="server"> | The name of the site where the current page resides. | No |
<asp:ContentPlaceHolder id="PlaceHolderPageTitleInTitleArea" runat="server" /> | The title of the page, which appears in the title area on the page. | No |
<asp:ContentPlaceHolder id="PlaceHolderPageDescription" runat="server"/> | The description of the current page. | No |
<asp:ContentPlaceHolder id="PlaceHolderSearchArea" runat="server"> | The section of the page for the search controls. | No |
<asp:ContentPlaceHolder id="PlaceHolderGlobalNavigation" runat="server"> | The breadcrumb control on the page. | No |
<asp:ContentPlaceHolder id="PlaceHolderTitleBreadcrumb" runat="server"> | The breadcrumb text for the breadcrumb control. | No |
<asp:ContentPlaceHolder id="PlaceHolderGlobalNavigationSiteMap" runat="server"> | The list of subsites and sibling sites in the global navigation on the page. | No |
<asp:ContentPlaceHolder id="PlaceHolderTopNavBar" runat="server"> | The container used to hold the top navigation bar. | No |
<asp:ContentPlaceHolder id="PlaceHolderHorizontalNav" runat="server"> | The navigation menu that is inside the top navigation bar. | No |
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBarDataSource" runat="server" /> | The placement of the data source used to populate the left navigation bar. | No |
<asp:ContentPlaceHolder id="PlaceHolderCalendarNavigator" runat="server" /> | The date picker used when a calendar is visible on the page. | No |
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBarTop" runat="server"/> | The top section of the left navigation bar. | No |
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBar" runat="server"> | The Quick Launch bar. | No |
<asp:ContentPlaceHolder id="PlaceHolderLeftActions" runat="server"> | The additional objects above the Quick Launch bar. | No |
<asp:ContentPlaceHolder id="PlaceHolderMain" runat="server"> | The main content of the page. | No |
<asp:ContentPlaceHolder id="PlaceHolderFormDigest" runat="server"> | The container where the page form digest control is stored. | No |
<asp:ContentPlaceHolder id="PlaceHolderUtilityContent" runat="server"/> | The additional content at the bottom of the page. This is outside of the form tag. | No |
<asp:ContentPlaceHolder id="PlaceHolderTitleAreaClass" runat="server"/> | The class for the title area. This is now in the head tag. Any customizations that add a WebPartZone in a content tag to this placeholder will cause an error on the page. | No |
<asp:ContentPlaceHolder id="PlaceHolderPageImage" runat="server"/> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderTitleLeftBorder" runat="server"> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderMiniConsole" runat="server"/> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderTitleRightMargin" runat="server"/> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderTitleAreaSeparator" runat="server"/> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderNavSpacer" runat="server"> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderLeftNavBarBorder" runat="server"> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderBodyLeftBorder" runat="server"> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
<asp:ContentPlaceHolder id="PlaceHolderBodyRightMargin" runat="server"> | This placeholder does not appear as part of the UI and must be present for backward compatibility. | No |
The Server ribbon is a new addition to the UI for SharePoint Foundation. The SPRibbonPeripheralContent controls in the v4.master page contain content that renders inside the Server ribbon area. This content can be moved outside of the Server ribbon if desired. The following procedure shows the code for adding the Server ribbon to the page.
To add the Server Ribbon
Open your master page file (.master).
Copy and paste the following code inside the form tag to add the Server ribbon to the page.
Important The following code sample contains commented sections where you copy and paste controls from your custom master page or from the v4.master page. Any ContentPlaceholder controls inside the Global Navigation section need to be added to the page elsewhere if you do not add them within the Server ribbon.
<div id="s4-ribbonrow" class="s4-pr s4-ribbonrowhidetitle"> <div id="s4-ribboncont"> <SharePoint:SPRibbon runat="server" PlaceholderElementId="RibbonContainer" CssFile=""> <SharePoint:SPRibbonPeripheralContent runat="server" Location="TabRowLeft" CssClass="ms-siteactionscontainer s4-notdlg"> <%-- Insert the Site Actions Menu Here --%> </SharePoint:SPRibbonPeripheralContent> <%-- Insert the Global Navigation Here --%> <SharePoint:SPRibbonPeripheralContent runat="server" Location="TabRowRight" ID="RibbonTabRowRight" CssClass="s4-trc-container s4-notdlg"> <%-- Insert the Top-Right Corner Controls Here --%> </SharePoint:SPRibbonPeripheralContent> </SharePoint:SPRibbon> </div> <div id="notificationArea" class="s4-noti"> <%-- Notifications will appear in this div element. --%> </div> <asp:ContentPlaceHolder ID="SPNavigation" runat="server"> <SharePoint:DelegateControl runat="server" ControlId="PublishingConsole"> </SharePoint:DelegateControl> </asp:ContentPlaceHolder> <div id="WebPartAdderUpdatePanelContainer"> <asp:UpdatePanel ID="WebPartAdderUpdatePanel" UpdateMode="Conditional" ChildrenAsTriggers="false" runat="server"> <ContentTemplate> <WebPartPages:WebPartAdder ID="WebPartAdder" runat="server" /> </ContentTemplate> <Triggers> <asp:PostBackTrigger ControlID="WebPartAdder" /> </Triggers> </asp:UpdatePanel> </div> </div>
Save your master page file.
Major functional areas of a SharePoint interface
Figure Label |
Functional Area |
Description of Functionality |
---|---|---|
A |
Server ribbon |
The entire top portion of the UI is part of the ribbon. What is displayed depends on the user's current context. |
B |
Site Actions |
The main menu for interacting with SharePoint, used primarily by content authors and administrators. |
C |
Global breadcrumbs control |
A new implementation of the global breadcrumbs control that was first introduced in Microsoft Office SharePoint Server 2007. When clicked, the icon displays a dynamic HTML that shows a hierarchical view of the site. Use it to navigate up levels of the hierarchy from the current location in the hierarchy. |
D |
Page State Action button |
The button used to control the page state, and that typically displays a shortcut to edit or save the current page. |
E |
Ribbon contextual tabs |
Tabs present menus that are specific to the functions of the SharePoint site. What is displayed changes based on what the user is interacting with on the page. Some of the items will not be used on every site. |
F |
Welcome menu |
This menu shows the welcome message and enables the user to view their profile, to sign out, and to sign in as a different user. If other language packs are installed, the functionality to change the user's language is also available here. When the user is not logged on, the Welcome menu also shows the Sign In link. |
G |
Developer Dashboard button |
The button that opens the Developer Dashboard that typically appears at the bottom of the screen. The Developer Dashboard contains statistics about the page rendering and queries. This icon is shown when the Developer Dashboard's display level is set to OnDemand (other options include On and Off). Administrators can set the Developer Dashboard display level by using Windows PowerShell or by using the SharePoint API. |
H |
Title logo |
Sometimes referred to as site icon. It typically shows the SharePoint site icon, but can display a user-defined logo instead. |
I |
Breadcrumb |
This is a breadcrumb-like control that is specific to the v4.master master page. It includes the Site Title and the placeholder for Title in Title Area, which typically contains the Page Title. The Site Title is linked to the top level of the site. |
J |
Social buttons |
Used for marking items as liked and for adding tags and notes to content. |
K |
Global navigation |
Sometimes referred to as the Top Link Bar or Top Navigation Bar, it is the primary horizontal navigation mechanism for the site. |
L |
Search area |
The search box is used to enter terms for performing searches on the site. |
M |
Help button |
The help button links to the SharePoint 2010 help documents. |
N |
Quick Launch |
Provides current navigation. Sometimes referred to as the Left Navigation. It is the secondary or vertical navigation mechanism of the pages related to the current location. |
O |
Tree View |
Provides a Windows Explorer–style representation of the site. Because of its appearance, the tree view is often better suited for intranet sites. |
P |
Recycle Bin |
Provides a link to the Recycle Bin for the site, which is the area where items are stored when deleted. Typically, this is better suited for intranet sites. |
Q |
All Site Content |
A link to the All Site Content page. This was the View All Site Content link in Office SharePoint Server 2007. Typically, this is better suited for intranet sites. |
R |
Body area |
Represents the main content placeholder that includes all of the content that is specific to the page. Required for rendering the content of the page. |
REFERENCE
SharePoint 2010 Base CSS Classes
This will be the first of many SharePoint 2010 posts. I will be focusing on a few of the main CSS classes used for SharePoint 2010 Public Beta. As the product becomes more final there might be some changes to the class names but I will be sure to create a new post if that happens. This will be quite a lengthy but it should be helpful. The default CSS given below are just highlights of the full CSS attributes for that class.
I will be using a basic team site as my base for the screenshots.
Here is a basic structure of the main areas that I will cover.
- Ribbon Row
- Table Row Left
- Site Actions
- Navigate Up
- Edit
- Tab List
- Browse
- Page
- Table Row Right
- Give Feedback
- Welcome Menu
- Table Row Left
- Workspace
- Body Container
- Title Row
- Title
- Title Logo
- Title Text / Breadcrumb
- Page Description
- Social Data
- Separator
- I like It
- Tags/Notes
- Top Header 2/Top Links
- li Static-Selected
- li Static
- Search
- Help
- Title
- Status Bar Container
- Main Area
- Left Panel
- Navigation Manager
- li Static (Header)
- ul li Static (Link)
- Special Navigation Links List
- Recycle Bin
- View All Site Content
- Navigation Manager
- Content Table / Body Area
- Web Part Cell
- Web Part Header
- WP Title
- WP Header TD
- WP Header Menu
- WP Header Selection
- Web Part Content
- Web Part Header
- Web Part Cell
- Left Panel
- Title Row
- Body Container
Ribbon Row:
Class/ID = “body #s4-ribbonrow”
Default CSS:
min-height:43px;
background-color:#21374c;
Comments: This is the container for all of the items in the top ribbon
Table Row Left:
Class/ID = “ms-cui-TabRowLeft”
Default CSS:
float:left;
margin-top:20px;
Comments: This is the container Site Actions, Navigate Up and Edit
Site Actions:
Class/ID = “ms-siteactionsmenuinner”
Default CSS:
border-color:#21374C;
border-top-color:#394f63;
background:url("/_layouts/images/bgximg.png") repeat-x -0px -467px;
background-color:#21374c;
Comments: Main Style for Site Actions menu
Navigate Up:
Class/ID = “.s4-breadcrumb-anchor,.ms-qatbutton”
Default CSS:
margin:0px 3px 0px 0px;
padding:2px 5px 0px;
Comments: There is an image “fgimg.png” that sits within an “A” hyperlink Tag. This image is large and has many icons in it. It uses inline absolute positioning to show the correct Icon.
”position: absolute; top: -112px !important;”
Here is what the “fgimg.png” image looks like:
Edit:
Class/ID = “.s4-breadcrumb-anchor,.ms-qatbutton” (Same as Above)
Default CSS:
Same As Above
Comments: Same as above except that the background image position is different. “position: absolute; top: -235px;”
Browse:
Class/ID = “.ms-cui-tt-s > .ms-cui-tt-a”
Default CSS:
border-color:#b6babf;
background-color:#fff;
color:#23272c !important;
Comments: This is the selected state of the browse button. Note the “s” at the end of the class.
Page:
Class/ID = “.ms-cui-tt-span”
Default CSS:
padding:4px 10px 4px;
border-top:1px solid transparent;
text-align:center;
Comments: This is the non-selected state of the page button.
Give Feedback:
Class/ID = “No Class Or ID Specified, See below”
Default CSS:
Inline CSS and Image
Comments: If you would like to remove this icon via CSS, use the following:
.ms-cui-TabRowRight a img{
display: none;
}
Welcome Menu:
Class/ID = “.ms-welcomeMenu”
Default CSS:
padding:2px 5px 3px;
margin:0px 3px;
font-size:1em;
font-family:Verdana,sans-serif;
border:1px solid transparent;
Comments: The class for the arrow is “.ms-viewselector-arrow”
Workspace:
Class/ID = “body #s4-workspace”
Default CSS:
overflow:visible !important;
overflow-y:scroll;
overflow-x:auto;
position:relative;
left:0px;
Comments: This is the container and scroll area for the site.
Body Container:
Class/ID = “body #s4-bodyContainer”
Default CSS:
min-width:760px;
Comments: This class controls the minimum width.
Title Row:
Class/ID = “body #s4-titlerow”
Default CSS:
display:block !important;
Comments: This is the container for the Title, Tags, Ribbon, Main navigation, Search and Help.
Title Row:
Class/ID = “.s4-title”
Default CSS:
padding:0px 0px 0px 10px;
margin:0px;
min-height:64px;
background:url("/_layouts/images/bgximg.png") repeat-x -0px -1013px;
background-color:#f9f9f9;
word-wrap:break-word;
-ms-word-wrap:break-word;
overflow-x:hidden;
Comments: Notice that there is a min height of 64px and a background image is applied by default.
Title Logo:
Class/ID = “.s4-titlelogo”
Default CSS:
padding:12px 10px 12px 0px;
text-align:center;
vertical-align:middle;
Comments: The logo can be changed via the Admin UI. Default Image size is 35x35px
Title Text:
Class/ID = “.s4-titletext”
Default CSS:
width:100%;
Comments: The title text is also the bread crumb.
Page Description:
Class/ID = “.s4-title .s4-pagedescription,.s4-title .s4uniqpermdescription”
Default CSS:
margin-top:6px;
font-size:1em;
color:#5d6878;
font-weight:normal;
Comments: This only shows up if you have specified a description of the site.
Social Data:
Class/ID = “ms-socialNotif-Container”
Default CSS:
width:120px;
overflow-x:auto;
overflow-y:hidden;
padding:0px 3px;
Comments: This is the container that holds both I Like It and Notes.
Social Separator:
Class/ID = “.ms-socialNotif-groupSeparator”
Default CSS:
height:60px;
position:relative;
top:4px;
margin:0px 3px;
border-right:1px solid;
border-right-color:#e7e7e8;
Comments: This is the slight line on the left of the social tags.
I Like It:
Class/ID = “.ms-socialNotif”
Default CSS:
width:48px;
height:60px;
overflow:hidden;
margin:0px 1px;
padding:0px 2px;
border:1px solid transparent;
Comments: This class is shared with the tags and notes. The text uses the class “.ms-socialNotif-text” and the image “mossfgimg.png” with inline style of
position: absolute; top: -132px !important;
Here is what the “mossfgimg.png” image looks like:
Tags & Notes:
Class/ID = “.ms-socialNotif”
Default CSS:
Same As “I Like It” above
Comments: This class is shared with the I like It Feature. The image “mossfgimg.png” with inline style of
position: absolute; top: -300px !important;
Class/ID = “body #s4-topheader2”
Default CSS:
background:url("/_layouts/images/selbg.png") repeat-x left top;
background-color:#f6f6f6;
vertical-align:middle;
min-height:25px;
border-top:1px solid #e0e0e0;
border-bottom:1px solid #b8babd;
Comments: This class makes up the majority of the navigation row style.
Top Links:
Class/ID = “.s4-toplinks”
Default CSS:
padding:0px;
Comments: This is the container for the main navigation, search and help.
Top Link Selected:
Class/ID = “.s4-toplinks .s4-tn a.selected”
Default CSS:
border-color:#91cdf2;
border-bottom-color:#addbf7;
border-top-color:#c6e5f8;
background:url("/_layouts/images/selbg.png") repeat-x left top;
background-color:#ccebff;
color:#003759;
padding:4px 5px;
margin:0px 5px;
Comments: The hover class is “.s4-toplinks .s4-tn a.selected:hover”
Top Link Static:
Class/ID = “.s4-tn li.static > .menu-item”
Default CSS:
color:#3b4f65;
white-space:nowrap;
border:1px solid transparent;
padding:4px 10px;
height:15px;
Comments: The hover class is “.s4-tn li.static > a:hover”
Search:
Class/ID = “.s4-search table”
Default CSS:
width: 212px;
margin-right: 17px;
Comments: This is the container for the search box. The class resides in the Search.css file.
Search Input:
Class/ID = “.s4-search input”
Default CSS:
width: 212px;
margin-right: 17px;
Comments: Note that this class does not change width, border color or height. You could use this to change the background color.
Search Image:
Class/ID = “.s4-search .ms-searchimage”
Default CSS:
background-color:#fff;
border:1px solid #e3e3e3 !important;
height:16px;
padding:2px 3px 1px;
border-left:none !important;
margin-top:3px;
Comments: This class controls the border around the go image.
Help:
Class/ID = “.s4-help”
Default CSS:
margin:4px;
Comments: This uses the “fgimg.png” with inline style of:
position: absolute; top: -293px !important;
Status Bar Container:
Class/ID = “.s4-statusbarcontainer”
Default CSS:
None
Comments: I am not 100% sure where or how this is used. I can only imagine that this is a publishing class.
Main Area:
Class/ID = “body #s4-mainarea”
Default CSS:
float:left;
clear:both;
Comments: This includes both left navigation and content
Left Panel:
Class/ID = “body #s4-leftpanel”
Default CSS:
width:155px;
float:left;
Comments: This is the left navigation
Left Panel Headers:
Class/ID = “.s4-ql ul.root > li > .menu-item,.s4-qlheader,.s4-qlheader:visited”
Default CSS:
font-size:1.2em;
color:#0072bc;
margin:0px;
padding:3px 4px 3px 10px;
word-wrap:break-word;
overflow-x:hidden;
Comments: This class controls the look of the header text
Left Panel Links:
Class/ID = “.s4-ql ul.root ul > li > a”
Default CSS:
padding:3px 4px 4px 10px;
color:#3b4f65;
word-wrap:break-word;
overflow-x:hidden;
zoom:1;
Comments: This class controls the look of the link text
Special Navigation Links List:
Class/ID = “.s4-specialNavLinkList”
Default CSS:
margin:0px;
border-top:1px solid #dbddde;
padding-top:5px;
Comments: This class makes the line above the recycle bin
Recycle Bin:
Class/ID = “.s4-specialNavLinkList a”
Default CSS:
padding:3px 4px 3px 10px;
color:#3b4f65;
Comments: This is a shared class with view all site content
View All Site Content:
Class/ID = “.s4-specialNavLinkList a”
Default CSS:
Same As Above
Comments: This is a shared class with Recycle Bin
Content Table Body Area:
Class/ID = “.s4-ca”
Default CSS:
margin-left:155px;
margin-right:0px;
min-height:324px;
Comments: This is main class for the body content. Notice the 155px margin to the left. This basically moves the content over so that it does not overlap the left navigation.
Web Part Cell:
Class/ID = “.s4-wpcell”
Default CSS:
border:1px solid transparent;
Comments: This would be a good class to define a pixel line around web parts.
Web Part Header:
Class/ID = “.ms-WPHeader”
Default CSS:
background-color:#FFFFFF;
Comments: This controls the background color of the wp header.
Web Part Header TD:
Class/ID = “.ms-WPHeader td”
Default CSS:
border-bottom:1px solid #EBEBEB;
Comments: This controls the border color of the wp header.
Web Part Header Menu:
Class/ID = “.ms-WPHeaderTdMenu”
Default CSS:
width:21px;
border:1px solid transparent;
Comments: This class is for the web part menu spacing.
Web Part Header Selection:
Class/ID = “.ms-WPHeaderTdSelection”
Default CSS:
width:21px;
Comments: This class is for the web part selector spacing.
Web Part Content:
Class/ID = “.ms-wpContentDivSpace”
Default CSS:
margin-left:5px;
margin-right:5px;
Comments: This class adds marginal space left and right for the web part content.
There are many many many more classes that I could cover but these are some of the main ones to get you going. I will cover more in future posts.
Please leave a comment!
Popular Posts
-
To see a site collection's hidden user information list append /_catalogs/users/simple.aspx onto the end of the site collection url. ...
-
Please Check the below complete code to bind SharePoint list items to a DataTable/ Gridview. In this post, we are using the list named ...
-
To bind the drop down list data with a field from the SharePoint list you can use the below code methods:- Method 1 if (!Page.IsP...
-
By Default SharePoint shows 3 events for any date in the calendar view, if we want to show all the events then we have to use any of the fol...
-
This Javascript function checks if the parameter supplied exists in the query string. If the parameter supplied is found in the query strin...
-
You can use CAML to do the following: Modify parameters to transport complex data Define the body of SOAP messages to transport data usin...
-
You can use below powershell command to change sharepoint user display name. Set-SPuser -identity "User name" -DisplayName ...
-
SharePoint solutions are either deployed globally or targeted to a particular web application. The decision of which is made automatically...
-
The sharepoint site is very slow when we access it first time. After that the response time is good. The reason is compilation and cachin...
-
The following Event Handler code will prevent users from creating duplicate value in "Title" field. ItemAdding Event Handler ...