Suppose you are creating a page using Features, now you want that page to be hidden from the navigation when you create it. How will you go about it---
Create a Feature Receiver for that page and enter the below code at Feature activated event.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
PublishingWeb publishingWeb = null;
var objWeb = properties.Feature.Parent as SPWeb;
try
{
if (PublishingWeb.IsPublishingWeb(objWeb))
{
publishingWeb = PublishingWeb.GetPublishingWeb(objWeb);
// get the pages collection
PublishingPageCollection pages = publishingWeb.GetPublishingPages();
if (pages[publishingWeb.Url + "/Pages/chat.aspx"] != null)
{
//page exists hide it
PublishingPage page = pages[publishingWeb.Url + "/Pages/chat.aspx"];
page.IncludeInCurrentNavigation = false;
page.IncludeInGlobalNavigation = false;
}
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
Wednesday, January 19, 2011
Wednesday, January 12, 2011
How to add a page in pages directory of Sharepoint site
Suppose you want to add a new page in the pages library of your sharepoint site programatically, how will you go about it.
Create the structure in your project -
12 - template - features - NewPageFeature -
In that create an aspx page, a feature.xml file and an elements.xml file
You will also need a cs file outside of the 12 folder, and will provide the path to the same in your aspx file.
Feature.xml ---------------------------------------------------------
Feature Id="94D273A9-B9AE-46f0-A56A-03289ACC87FF"
Title="IMCHATPAGE"
Description="Activate Chat Page"
Scope="Web"
Hidden="True"
xmlns="http://schemas.microsoft.com/sharepoint/"
ElementManifests
ElementManifest Location="Elements.xml"/
ElementManifests
/Feature
Element.xml -----------------------------------------------------------
?xml version="1.0" encoding="utf-8"? Module Name="Pages" Url="$Resources:cmscore,List_Pages_UrlName;" Path="" RootWebOnly="False"
File Name="Chat.aspx" Url="Chat.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="False" /
/Module
/Elements
.aspx file ---------------------------------------------------------
In your aspx file, include the path of you cs file like below -
Inherits="Eversheds.InstantMessaging.Chat, Eversheds.InstantMessaging,Version=1.0.0.0,Culture=neutral, PublicKeyToken=b0c7276684f0a390"
Run wsp builder and your page will be created in the pages directory of your site
Create the structure in your project -
12 - template - features - NewPageFeature -
In that create an aspx page, a feature.xml file and an elements.xml file
You will also need a cs file outside of the 12 folder, and will provide the path to the same in your aspx file.
Feature.xml ---------------------------------------------------------
Feature Id="94D273A9-B9AE-46f0-A56A-03289ACC87FF"
Title="IMCHATPAGE"
Description="Activate Chat Page"
Scope="Web"
Hidden="True"
xmlns="http://schemas.microsoft.com/sharepoint/"
ElementManifests
ElementManifest Location="Elements.xml"/
ElementManifests
/Feature
Element.xml -----------------------------------------------------------
?xml version="1.0" encoding="utf-8"?
File Name="Chat.aspx" Url="Chat.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="False" /
/Module
/Elements
.aspx file ---------------------------------------------------------
In your aspx file, include the path of you cs file like below -
Inherits="Eversheds.InstantMessaging.Chat, Eversheds.InstantMessaging,Version=1.0.0.0,Culture=neutral, PublicKeyToken=b0c7276684f0a390"
Run wsp builder and your page will be created in the pages directory of your site
Tuesday, December 28, 2010
Delete web part from the web part gallery
In case you want to delete the web part as soon as a feature is deactivated, you can write a feature receiver for the same.
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
//Remove the web part from web part gallery
SPSite site = null;
StringBuilder sb = new StringBuilder();
try
{
using (SPWeb web = properties.Feature.Parent as SPWeb)
{
SPList list = web.Lists["Web Part Gallery"];//site.GetCatalog(SPListTemplateType.WebPartCatalog);
for (int i = list.ItemCount - 1; i >= 0; i--)
{
// format name to look like a feature name
string webpartName = list.Items[i].Name;
webpartName = webpartName.Substring(0, webpartName.IndexOf("."));
// delete web parts that have been added
if ((webpartName == "WPChat") || (list.Items[i].DisplayName.Equals("WPChat")))
{
list.Items[i].Delete();
break;
}
}
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
finally
{
if (site != null)
site.Dispose();
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
//Remove the web part from web part gallery
SPSite site = null;
StringBuilder sb = new StringBuilder();
try
{
using (SPWeb web = properties.Feature.Parent as SPWeb)
{
SPList list = web.Lists["Web Part Gallery"];//site.GetCatalog(SPListTemplateType.WebPartCatalog);
for (int i = list.ItemCount - 1; i >= 0; i--)
{
// format name to look like a feature name
string webpartName = list.Items[i].Name;
webpartName = webpartName.Substring(0, webpartName.IndexOf("."));
// delete web parts that have been added
if ((webpartName == "WPChat") || (list.Items[i].DisplayName.Equals("WPChat")))
{
list.Items[i].Delete();
break;
}
}
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
finally
{
if (site != null)
site.Dispose();
}
}
Add entries to web.config using wsp
In order to use your solution to add web.config entries follow the below approach-
Step 1: Create feature folder
Step 2: Create Feature.xml file -
Feature Id="113AEEBD-97B0-411a-B118-F6FE6D232C5E"
Title="IMWEBCONFIG"
Description="This feature modifies the Web Application web.config"
Scope="WebApplication"
ReceiverAssembly="Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverWebConfig"
xmlns="http://schemas.microsoft.com/sharepoint/"
/Feature
Step 3: Create feature receiver class
SPWebConfigModification webConfigModifications;
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var oWebApp = properties.Feature.Parent as Microsoft.SharePoint.Administration.SPWebApplication;
try
{
if (!oWebApp.IsAdministrationWebApplication)
{
ModifyWebConfigEntries(oWebApp);
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
public void ModifyWebConfigEntries(SPWebApplication oWebApp)
{
#region Http Module Section
webConfigModifications = new SPWebConfigModification();
webConfigModifications.Path = "configuration/system.web/httpModules";
webConfigModifications.Name = "add[@name='CustomHttpModule']";
webConfigModifications.Sequence = 0;
webConfigModifications.Owner = "addCustomModule";
webConfigModifications.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
webConfigModifications.Value = @" ";
oWebApp.WebConfigModifications.Add(webConfigModifications);
#endregion
SPWebService.ContentService.WebApplications[oWebApp.Id].Update();
//Applies the web config settings in all the web application in the farm
SPWebService.ContentService.WebApplications[oWebApp.Id].WebService.ApplyWebConfigModifications();
}
Step 1: Create feature folder
Step 2: Create Feature.xml file -
Feature Id="113AEEBD-97B0-411a-B118-F6FE6D232C5E"
Title="IMWEBCONFIG"
Description="This feature modifies the Web Application web.config"
Scope="WebApplication"
ReceiverAssembly="Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverWebConfig"
xmlns="http://schemas.microsoft.com/sharepoint/"
/Feature
Step 3: Create feature receiver class
SPWebConfigModification webConfigModifications;
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
var oWebApp = properties.Feature.Parent as Microsoft.SharePoint.Administration.SPWebApplication;
try
{
if (!oWebApp.IsAdministrationWebApplication)
{
ModifyWebConfigEntries(oWebApp);
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
public void ModifyWebConfigEntries(SPWebApplication oWebApp)
{
#region Http Module Section
webConfigModifications = new SPWebConfigModification();
webConfigModifications.Path = "configuration/system.web/httpModules";
webConfigModifications.Name = "add[@name='CustomHttpModule']";
webConfigModifications.Sequence = 0;
webConfigModifications.Owner = "addCustomModule";
webConfigModifications.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
webConfigModifications.Value = @"
oWebApp.WebConfigModifications.Add(webConfigModifications);
#endregion
SPWebService.ContentService.WebApplications[oWebApp.Id].Update();
//Applies the web config settings in all the web application in the farm
SPWebService.ContentService.WebApplications[oWebApp.Id].WebService.ApplyWebConfigModifications();
}
Monday, December 27, 2010
Create list in Feature using list templates
Suppose you have your list templates ready with you. Now you want to deploy the same using a solution. How will you do that using a Feature.
Step 1: Create a Feature folder in your solution
Step 2: Create a folder for your templates say 'ListTemplates' and place all your stp files there.
Step 3: Create a Feature.xml file -
Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="93E56B63-EA76-43b7-9068-162DCFA1FAE4"
Title="IMEVUSERLIST"
Description="Deploy user list for Instant Messaging"
Scope="Web"
Hidden="false"
Version="1.0.0.0"
ReceiverAssembly="Eversheds.InstantMessaging,Version=1.0.0.0,Culture=neutral, PublicKeyToken=b0c7276684f0a390"
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverEVUserList"
ElementManifests
ElementManifest Location="Elements.xml"/
/ElementManifests
Properties xmlns="http://schemas.microsoft.com/sharepoint/"
!-- Instant Messaging Lists --
Property Key="InstantMessagingLists" Value="EVChatImage,EVConfigInfo,EVUserList"/
/Properties
/Feature
Step 3: Create Elements file
?xml version="1.0" encoding="utf-8" ?
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
/Elements
Step 4: Create feature receiver
namespace Eversheds.InstantMessaging.FeatureReceiver
{
public class ReceiverEVUserList : SPFeatureReceiver
{}
}
Override all events. Below is the code for FeatureActivated
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb parentWeb;
SPSite siteCollection;
if (properties.Feature.Parent is SPWeb)
{
parentWeb = (SPWeb)properties.Feature.Parent;
siteCollection = parentWeb.Site;
}
else if (properties.Feature.Parent is SPSite)
{
parentWeb = ((SPSite)properties.Feature.Parent).RootWeb;
siteCollection = (SPSite)properties.Feature.Parent;
}
else
{
throw new Exception("Unable to retrieve SPWeb - this feature is not Site or Web-scoped.");
}
string directory = properties.Definition.RootDirectory;
try
{
if (!directory.EndsWith("\\"))
directory += "\\";
directory += "ListTemplates";
if (System.IO.Directory.Exists(directory))
{
string[] templates = System.IO.Directory.GetFiles(directory, "*.stp", System.IO.SearchOption.TopDirectoryOnly);
SPDocumentLibrary listTemplates = siteCollection.GetCatalog(SPListTemplateType.ListTemplateCatalog) as SPDocumentLibrary;
UploadTemplates(listTemplates, templates);
// Add lists from the List Template Gallery
parentWeb.AllowUnsafeUpdates = true; //get the list of list templates from the web
SPListTemplateCollection customListTemplates = siteCollection.GetCustomListTemplates(parentWeb); //create the connection library using the uploaded list template
//Get list collection
SPListCollection listCollection = parentWeb.Lists;
//Create List EVConfigInfo------------------------
if (ListExists(listCollection, "EVConfigInfo"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVConfigInfo"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpConfigInfo = customListTemplates["EVConfigInfo"];
parentWeb.Lists.Add("EVConfigInfo", "List for Config Info", stpConfigInfo);
//Create List EVUserList------------------------
if (ListExists(listCollection, "EVUserList"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVUserList"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpUserList = customListTemplates["EVUserList"];
parentWeb.Lists.Add("EVUserList", "List for User Info", stpUserList);
//Create List EVChatImage------------------------
if (ListExists(listCollection, "EVChatImage"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVChatImage"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpChatImage = customListTemplates["EVChatImage"];
parentWeb.Lists.Add("EVChatImage", "List for Chat image", stpChatImage);
parentWeb.Update();
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
#region UploadTemplates
///
/// Method to create Sharepoint Lists from template files
///
///
///
private void UploadTemplates(SPDocumentLibrary templateGallery, string[] templateFiles)
{
if (templateGallery != null)
{
foreach (string template in templateFiles)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(template);
SPQuery query = new SPQuery();
query.Query = string.Format(" " + "{0} ", fileInfo.Name);
SPListItemCollection existingTemplates = templateGallery.GetItems(query);
int[] Ids = new int[existingTemplates.Count];
for (int i = 0; i < existingTemplates.Count; i++)
{
Ids[i] = existingTemplates[i].ID;
}
for (int j = 0; j < Ids.Length; j++)
{
templateGallery.Items.DeleteItemById(Ids[j]);
} byte[] stp = System.IO.File.ReadAllBytes(template);
templateGallery.RootFolder.Files.Add(fileInfo.Name, stp);
}
}
}
#endregion
private static bool ListExists(SPListCollection collection, string title)
{
bool flag = false;
foreach (SPList list in collection)
{
if (list.Title == title)
flag = true;
}
return flag;
}
Step 5: Deploy using wsp builder. The lists will be created
Step 1: Create a Feature folder in your solution
Step 2: Create a folder for your templates say 'ListTemplates' and place all your stp files there.
Step 3: Create a Feature.xml file -
Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="93E56B63-EA76-43b7-9068-162DCFA1FAE4"
Title="IMEVUSERLIST"
Description="Deploy user list for Instant Messaging"
Scope="Web"
Hidden="false"
Version="1.0.0.0"
ReceiverAssembly="Eversheds.InstantMessaging,Version=1.0.0.0,Culture=neutral, PublicKeyToken=b0c7276684f0a390"
ReceiverClass="Eversheds.InstantMessaging.FeatureReceiver.ReceiverEVUserList"
ElementManifests
ElementManifest Location="Elements.xml"/
/ElementManifests
Properties xmlns="http://schemas.microsoft.com/sharepoint/"
!-- Instant Messaging Lists --
Property Key="InstantMessagingLists" Value="EVChatImage,EVConfigInfo,EVUserList"/
/Properties
/Feature
Step 3: Create Elements file
?xml version="1.0" encoding="utf-8" ?
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
/Elements
Step 4: Create feature receiver
namespace Eversheds.InstantMessaging.FeatureReceiver
{
public class ReceiverEVUserList : SPFeatureReceiver
{}
}
Override all events. Below is the code for FeatureActivated
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPWeb parentWeb;
SPSite siteCollection;
if (properties.Feature.Parent is SPWeb)
{
parentWeb = (SPWeb)properties.Feature.Parent;
siteCollection = parentWeb.Site;
}
else if (properties.Feature.Parent is SPSite)
{
parentWeb = ((SPSite)properties.Feature.Parent).RootWeb;
siteCollection = (SPSite)properties.Feature.Parent;
}
else
{
throw new Exception("Unable to retrieve SPWeb - this feature is not Site or Web-scoped.");
}
string directory = properties.Definition.RootDirectory;
try
{
if (!directory.EndsWith("\\"))
directory += "\\";
directory += "ListTemplates";
if (System.IO.Directory.Exists(directory))
{
string[] templates = System.IO.Directory.GetFiles(directory, "*.stp", System.IO.SearchOption.TopDirectoryOnly);
SPDocumentLibrary listTemplates = siteCollection.GetCatalog(SPListTemplateType.ListTemplateCatalog) as SPDocumentLibrary;
UploadTemplates(listTemplates, templates);
// Add lists from the List Template Gallery
parentWeb.AllowUnsafeUpdates = true; //get the list of list templates from the web
SPListTemplateCollection customListTemplates = siteCollection.GetCustomListTemplates(parentWeb); //create the connection library using the uploaded list template
//Get list collection
SPListCollection listCollection = parentWeb.Lists;
//Create List EVConfigInfo------------------------
if (ListExists(listCollection, "EVConfigInfo"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVConfigInfo"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpConfigInfo = customListTemplates["EVConfigInfo"];
parentWeb.Lists.Add("EVConfigInfo", "List for Config Info", stpConfigInfo);
//Create List EVUserList------------------------
if (ListExists(listCollection, "EVUserList"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVUserList"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpUserList = customListTemplates["EVUserList"];
parentWeb.Lists.Add("EVUserList", "List for User Info", stpUserList);
//Create List EVChatImage------------------------
if (ListExists(listCollection, "EVChatImage"))
{
//get Guid for list
SPList l = parentWeb.Lists["EVChatImage"];
Guid listId = l.ID;
//delete list
parentWeb.Lists.Delete(listId);
}
SPListTemplate stpChatImage = customListTemplates["EVChatImage"];
parentWeb.Lists.Add("EVChatImage", "List for Chat image", stpChatImage);
parentWeb.Update();
}
}
catch (Exception ex)
{
using (StreamWriter w = new StreamWriter("C:\\log.txt"))
{
w.WriteLine(ex.ToString());
}
}
}
#region UploadTemplates
///
/// Method to create Sharepoint Lists from template files
///
///
///
private void UploadTemplates(SPDocumentLibrary templateGallery, string[] templateFiles)
{
if (templateGallery != null)
{
foreach (string template in templateFiles)
{
System.IO.FileInfo fileInfo = new System.IO.FileInfo(template);
SPQuery query = new SPQuery();
query.Query = string.Format("
SPListItemCollection existingTemplates = templateGallery.GetItems(query);
int[] Ids = new int[existingTemplates.Count];
for (int i = 0; i < existingTemplates.Count; i++)
{
Ids[i] = existingTemplates[i].ID;
}
for (int j = 0; j < Ids.Length; j++)
{
templateGallery.Items.DeleteItemById(Ids[j]);
} byte[] stp = System.IO.File.ReadAllBytes(template);
templateGallery.RootFolder.Files.Add(fileInfo.Name, stp);
}
}
}
#endregion
private static bool ListExists(SPListCollection collection, string title)
{
bool flag = false;
foreach (SPList list in collection)
{
if (list.Title == title)
flag = true;
}
return flag;
}
Step 5: Deploy using wsp builder. The lists will be created
Populate the web part gallery programatically
Suppose you are deploying everything using solutions. You have lots of webparts. How will you populate the web part gallery using your solution. This will allow the user to just add the web part to the page immediately after deploying wsp.
Step1 - Create a Feature.xml file
Feature Id="D34D00B1-EC5C-4da8-8C50-009CB4B8BB42"
Title="IMCHATFEATURE"
Description="This is the chat Webpart"
Version="12.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/"
ElementManifests
ElementManifest Location="elements.xml"/
ElementFile Location="WPChat.webpart" /
/ElementManifests
/Feature
Step 2: Create an Element File
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
Module Name="WebPartPopulation" Url="_catalogs/wp" RootWebOnly="TRUE" List="113"
File Url="WPChat.webpart" Type="GhostableInLibrary"
/File
/Module
/Elements
Step 3: Create a .webpart file for your webpart
webParts
webPart xmlns="http://schemas.microsoft.com/WebPart/v3"
metaData
type name="Eversheds.InstantMessaging.WebParts.WPChat, Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "/type
importErrorMessage>Can not import WPChat/importErrorMessage
/metaData
data
properties
property name="Title" type="string"WPChat/property
property name="Description" type="string"A web part which allows the user to chat/property
/properties
/data
/webPart
/webParts
Step 4: Lastly create the .cs file for your web part
namespace Eversheds.InstantMessaging.WebParts
{
public class WPChat : System.Web.UI.WebControls.WebParts.WebPart
{}
}
Place all files in step1,2 and 3 in your feature folder. Deploy using wsp builder. The cs file should be outside the 12 hive folder.
Your web part will be available for the user in the gallery.
Step1 - Create a Feature.xml file
Feature Id="D34D00B1-EC5C-4da8-8C50-009CB4B8BB42"
Title="IMCHATFEATURE"
Description="This is the chat Webpart"
Version="12.0.0.0"
Hidden="FALSE"
Scope="Web"
DefaultResourceFile="core"
xmlns="http://schemas.microsoft.com/sharepoint/"
ElementManifests
ElementManifest Location="elements.xml"/
ElementFile Location="WPChat.webpart" /
/ElementManifests
/Feature
Step 2: Create an Element File
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
Module Name="WebPartPopulation" Url="_catalogs/wp" RootWebOnly="TRUE" List="113"
File Url="WPChat.webpart" Type="GhostableInLibrary"
/File
/Module
/Elements
Step 3: Create a .webpart file for your webpart
webParts
webPart xmlns="http://schemas.microsoft.com/WebPart/v3"
metaData
type name="Eversheds.InstantMessaging.WebParts.WPChat, Eversheds.InstantMessaging, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=b0c7276684f0a390 "/type
importErrorMessage>Can not import WPChat/importErrorMessage
/metaData
data
properties
property name="Title" type="string"WPChat/property
property name="Description" type="string"A web part which allows the user to chat/property
/properties
/data
/webPart
/webParts
Step 4: Lastly create the .cs file for your web part
namespace Eversheds.InstantMessaging.WebParts
{
public class WPChat : System.Web.UI.WebControls.WebParts.WebPart
{}
}
Place all files in step1,2 and 3 in your feature folder. Deploy using wsp builder. The cs file should be outside the 12 hive folder.
Your web part will be available for the user in the gallery.
Subscribe to:
Posts (Atom)