Sunday, April 24, 2011
Deleting layout from layout gallery
This we can also do through code as below-
private static void DeleteLayoutFromGallery(SPWeb web, string layoutName)
{
SPFile layout = web.GetFile(web.Site.Url.ToString() + "/_catalogs/masterpage/" + layoutName);
SPFolder layoutFolder = layout.ParentFolder;
SPFolder tempFolder = layoutFolder.SubFolders.Add("tempFolder");
layout.MoveTo(tempFolder.Url + "/" + layout.Name);
tempFolder.Delete();
}
The important point to note is- All the pages refering the deleted layout will not get the layout reference and hence will get corrupted. Even if we re-add those layouts through feature, broken references will still be broken and pages will remain be corrupted. If we will try to open those pages, It will display error message reading- "Resource can not be found."
Show only required layouts in available layout gallery - PublishingWeb.SetAvailablePageLayouts method
using(SPSite site=new SPSite(url))
{
PublishingSite pubSite=new PublishingSite(site);
PublishingWeb pubWeb = PublishingWeb.GetPublishingWeb(site.OpenWeb());
SPContentType associatedCType = pubSite.ContentTypes["My ContentType"];
if (associatedCType != null)
{
PageLayoutCollection allLayouts = pubSite.GetPageLayouts(associatedCType, true);
pubWeb.SetAvailablePageLayouts(allLayouts.ToArray(), true);
}
pubWeb.Update();
}
Thats it. The above piece of code will add all the layouts inheriting from content type associatedCType and remove all other layouts from the available layout gallery. Only added layouts will be available for creating pages
Friday, December 10, 2010
Creating webpart instance from assembly name and adding it into a webpart zone- SharePoint
We used Assembly class to create an instance of the webpart.
Here is the code-
using System.Reflection;
private static void GetWebsRecursively(SPWeb web, string pageName, string RemovedWebPartDll, string RemovedWebParttitle, string newWebPart, string IsPageOrLayout,string newWebPartTitle)
{
//pageName= name of the page/layout from where webpar has to be replaced
//RemoveWebPartDll= name of the DLL which has to be removed
//RemovedWebParttitle= title of the webpart to be removed
//newWebPart= DLL name of the webpart to be added
//IsPagOrLayout= value to indicate whether the page is publishing page
// or a layout. value would either be page or layout.
SPFile objFile = null;
string strCheckInMsg = "";
try
{
AppDomain domain = AppDomain.CurrentDomain;
AppDomain newDomain = AppDomain.CreateDomain("wpDomain");
DirectoryInfo dirInfo = new DirectoryInfo(@"C:\WINNT\assembly\gac_msil\" + newWebPart.Substring(0, newWebPart.LastIndexOf('.')));
DirectoryInfo[] dir = dirInfo.GetDirectories();
FileInfo[] file = dir[0].GetFiles();
string filePath = file[0].FullName;
Assembly asm = newDomain.Load(File.ReadAllBytes(filePath));
System.Web.UI.WebControls.WebParts.WebPart newWP = null;
newWP = (System.Web.UI.WebControls.WebParts.WebPart)asm.CreateInstance(newWebPart);
strCheckInMsg = "Modified by webpart delete console app";
if (PublishingWeb.IsPublishingWeb(web))
{
PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web);
if (IsPageOrLayout.ToUpper() == "PAGE")
{
string path = web.Url.ToString() + "/Pages/" + pageName;
objFile = web.GetFile(path);
}
else
{
string path = web.Url.ToString() + "/_catalogs/masterpage/" + pageName;
objFile = web.GetFile(path);
}
}
// If file is already in checked out state then first checkin that and approve
if (objFile.CheckOutStatus != SPFile.SPCheckOutStatus.None)
{
objFile.CheckIn(strCheckInMsg);
objFile.Publish(strCheckInMsg);
objFile.Approve(strCheckInMsg);
}
if (objFile.CheckOutStatus == SPFile.SPCheckOutStatus.None)
{
objFile.CheckOut();
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
}
SPLimitedWebPartManager wpMgr = SPContext.Current.Web.GetLimitedWebPartManager(objFile.Url, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
for (int i = 0; i < wpMgr.WebParts.Count; i++)
{
if (wpMgr.WebParts[i].GetType().FullName.ToUpper() == RemovedWebPartDll.ToUpper() && wpMgr.WebParts[i].Title.ToUpper() == RemovedWebParttitle.ToUpper())
{
string s = wpMgr.GetZoneID(wpMgr.WebParts[i]);
wpMgr.DeleteWebPart(wpMgr.WebParts[i] as System.Web.UI.WebControls.WebParts.WebPart);
newWP.Title = newWebPartTitle;
wpMgr.AddWebPart(newWP, s, 1);
web.Update();
}
}
objFile.CheckIn(strCheckInMsg);
objFile.Publish(strCheckInMsg);
objFile.Approve(strCheckInMsg);
}
}
catch (Exception ex)
{
Console.WriteLine("Error Occoured Message : " + ex.InnerException);
}
}
This code will replace the existing webpart from new webpart provided the new webpart is present in the GAC.
sounds very good :)
Tuesday, November 17, 2009
Caching with SPList-Sharepoint
To implement caching we can use PortalSiteMapProvider class. The GetCachedListItemsByQuery() method of PortalSiteMapProvider Class to get the cached data.Below is the code snippet-
string strVal;
SPWeb web=SPControl.GetContextWeb(context);
SPQuery query = new SPQuery();
query.Query = "CAML Query";
PortalSiteMapProvider provider = PortalSiteMapProvider.CurrentNavSiteMapProviderNoEncodePortalWebSiteMapNode node = provider.FindSiteMapNode(web.ServerRelativeUrl.ToString()) as PortalWebSiteMapNode;
SiteMapNodeCollection items = provider.GetCachedListItemsByQuery(node, "List Name", query, web);
if (items != null)
{
foreach (PortalListItemSiteMapNode item in items) {
strVal = item["column name"].ToString();
}
}
Now strVal will get the cached data.
Alternatevely we can use HttpRunTime.cache, provided by ASP.Net, to implement caching in following way-
SPList lstStore;
SPListItemCollection items;
if (HttpRuntime.Cache["configstorelist"] == null)
{
lstStore = web.GetList(strlistPath);
HttpRuntime.Cache.Add("configstorelist", lstStore, null, DateTime.MaxValue, TimeSpan.FromMinutes(10),System.Web.Caching.CacheItemPriority.Default, null);
}
else
{
lstStore = (SPList)HttpRuntime.Cache["configstorelist"];
}
Here we will check if the Cache object is null or not. if it is null, it will call getList() method, else it will take the data from Cache object.One more point is to use GetList() method instead of SPList.Lists["name"] as SPList.Lists iterate through all the list so it may reduce the performance in large projects. So it is advisable to use GetList().
Monday, November 16, 2009
Accessing SPList-cross web application, sitecollection and site
private string GetListvalue()
{
string strVal=string.Empty;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
Uri uri = new Uri(SPContext.Current.Web.Url.ToString());
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://" + uri.Host));
if (webApp != null && webApp.Sites != null && webApp.Sites.Count > 0)
{
using (SPWeb web = SPContext.Current.Site.RootWeb)
{
foreach (SPSite site in webApp.Sites)
{
foreach (SPWeb web in site.AllWebs)
{
if (IfListExists(web, "List Name"))
{
SPList lstStore;
SPListItemCollection items;
lstStore = web.GetList(list path);
SPQuery query = new SPQuery();
query.Query = "CAML query";
items = lstStore.GetItems(query);
strVal = items[0]["Column name"].ToString();
}
}
}
}
}
}
});
return strVal;
}
Here I am accessing a sigle column from the first row that will be returned by the query.
The IfListExists() method will use Linq to check whether the list exists or not. Sharepoint don't have any method or properties to check the existance of the list. Another alternative is to use the Extension Methods. Below is the definition of the IfListExists() method-
private static bool IfListExists(SPWeb web, string listName)
{
return web.Lists.Cast
}
Thats it.
Hopes it will help. :)
Wednesday, July 29, 2009
Accessing multiple lists across multiple sites - SPSiteDataQuery
1. joined subview using sharepoint designer ( click here to see)
2. Using SPSiteDataQuery class
SPSiteDataQuery class can be used to run CAML query across multiple lists in multiple websites within a site collection. It can be defined as-
SPSiteDataQuery query = new SPSiteDataQuery();
SPSiteDataQuery class returns a DataTable Class which can be used to access the data.
SPSiteDataQuery class has few properties which need to be set in order to use it. These properties are-
a. Lists- Can be used to specify list type, lists which has to be used in query through ListID, Maximum number of lists can be used in query etc. List Type is specified by BaseType attribute. The value of BaseType attribute will be
0 for a generic list
1 for a document library
3 for a discussion forum
4 for a survey
5 for a issues list.
The Lists property can be set as
query.Lists="<Lists BaseType="'0'/">";
If we want to query some specific lists only then we must specify their list ID as below-
<List ID=\"E8A71D9E-DDB6-4A2A-985C-976FCFBBDD23\"/>
to get the list ID go to list setting page take the value of 'List' querystring from page URL. It will be like-
%7BE8A71D9E%2DDDB6%2D4A2A%2D985C%2D976FCFBBDD23%7D
replace %7B with '{', %7D with '}' and %2D with a '-' and we will have the list ID as
{E8A71D9E-DDB6-4A2A-985C-976FCFBBDD23}.
The maximum number of lists that the query can use will be specified by MaxListsLimit attribute as below-
<Lists BaseType='0' MaxListsLimit='10'>
b. Webs Property- This will specify the scope of the query. It may have any of the three values-
1. SiteCollection- query will run through the whole site collection.
query.Webs = "<Webs Scope="'SiteCollection'/">";
2. Recursive- query will run within website and its child site.
query.Webs = "<Webs Scope="Recursive">";
3. Blank- query will run through current web only.
query.Webs = "<Webs Scope="'">";
c. ViewFields property- It can be used to specify the column we are going to display. It can be used a follow-
query.ViewFields = "<FieldRef Name='Department' Nullable='TRUE' /><FieldRef Name='desc' Nullable='TRUE' />"
If we set the value Nullable='TRUE' then the query will fetch the data even if the column has null value in the corresponding row.
d. Query property- It is used to specify the CAML query as below-
query.Query="<Where><Eq><FieldRef Name="'ID'"><Value Type=" 'Counter'"> 1</Value></Eq></Where>";
e. RowLimit- This property will limit the number of rows which has to be fetched.
It can be used as-
query.RowLimit=5; ( To limit the number of rows to 5)
Below is the sample code to use SPSiteDataQuery-
SPWeb web = SPControl.GetContextWeb(Context);
SPSiteDataQuery q = new SPSiteDataQuery();
query.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>1</Value></Eq></Where>";
query.ViewFields = "<FieldRef Name='Department' Nullable='TRUE' /><FieldRef Name='desc' Nullable='TRUE' /><FieldRef Name='DepartmentLink' Nullable='TRUE' />";
query.Lists = "<Lists BaseType='0'><List ID=\"E8A71D9E-DDB6-4A2A-985C-976FCFBBDD23\"/><List ID=\"B59FC80A-B586-4F31-A376-2FE20896641D\"/><List ID=\"3482EBF1-A2A7-4420%2DA920-09EA2635C557\"/></Lists>";
query.Webs = "<Webs Scope='SiteCollection'/>";
query.RowLimit = 10;
DataTable t = web.GetSiteData(query);
The DataTable will be populated by the data fetched from the list. It can be used to display the contents on the web page.
Wednesday, July 22, 2009
Displaying data from more than one list- Joined subview in SharePoint designer
1. open the site from sharepoint designer.
2. Select data source library from right task pane and and then click on 'create a new linked source'. Below is the screen shot-
3. In data source properties dialogue box, click on configure linked source.
4. A new box will appear as below. Select the lists/library that you want to link and then click on next.
5. In the linked data source wizard, there will be two options- merging and joining. Now select the second option i.e. join the contents and then click finish and then Ok. Below is the screen shot-
Now our data source has been created.
6. Now open the page where you want to display the data. Add a dataview control from dataview menu to the content region.
7. Now click on newly created data source and then select show data as below-
8. After clicking on show data, it will display all the columns in the data source. select the columns from first list which you want to display on dataview. Drag and drop the selected column to the dataview control-
9. The selected column will be inserted in dataview inside TD tag. Now suppose you wants to display data from second list on the right. Then right Click on TD in designer and then select insert cell to the right as below-
10. Now Select the desired columns from second list and then select "insert as joined subview" from top as below-
11. A join subview dialog box will be open. Here we will columns from the two list which have matching data as here I used ID column-
After selecting the column click on Ok. Now the selected column will be inserted in the newly created TD tag.
Its done now. It will display data from the two list based on the value of matching column. The look and feel of the subview might not be perfect but it can be updated by doing a little modification in HTML which is generated for the joined subview and by applying custom CSS classes.
Tuesday, July 7, 2009
MySIte Customization
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\GLOBAL\ application directory with name default.master.
we can open it in Sharepoint designer and customize it to give look and feel. But this is not a recommended approach. If we will modify the default.master, then we will not be able to use default view of mysite anymore as we are customizing the master page from site definition.
An alternate and recommended way to do it is feature stapling. In feature stapling, we can create a custom master page and replace that with default.master at run time using the feature.
The site templates for MySite are-
SPSPERS (private view)- SPSMSITEHOST (public view)
The master page for these two templates need to be replaced with our custom master page. I found a great blog by sridhar to achieve the feature stapling-
http://blogs.msdn.com/sridhara/archive/2007/05/19/customizing-mysite-in-moss-2007.aspx
Using this blog I was able to customize the look and feel of master page.
Now my next task was to add a content editor webpart in default.aspx. The solution for this is a bit tricky. I had to play with ONET.XML to add the webparts.
Here is the steps I followed
1. Open the ONET.XML file from the location - C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\SiteTemplates\SPSPERS\XML\ using some editor.( dont forget to take a backup of the same.)
2. Find the Modules tag and then
3. Remove all the lines inside
http://schemas.microsoft.com/WebPart/v2< /a>">
]]>
If you dont want to see the other webpart, you can comment or remove them.
4. save and close the ONET.XML
5. Do an IIS reset.
Thats it. Now the default.aspx will display content editor webpart.
Adding custom links
To add custom left links and remove the links coming on the left, do the following-
Open ONET.XML and find 'navbar'
So when we add our custom link, we will have to add them in resource file also.
For this, the entry in the resource file would be-
Name -- category_MySiteHome
value-- Home
Its fine. Now comment the existing
'Home' will be the text appeared on the link.
Adding built-in page for custom links
Now we have created custom link. we would like to have a custom page which will be linked to the custom link we have created.
Create an ASP.Net Application. Add a page home.aspx into the application. In the aspx file, put proper HTML and webpart zone as you want to be on the page. If you are adding a zone then add 'webpartpages:webpartzone' tag instead of 'asp:webpartzone' tag. you may add the additional functionality and events on code behind file. give a strong name to the project and build it.
Now we need a feature which will be used to deploy this page into mysite.
First create feature.xml file. open it in a editor and add the following-
< ?xml version="1.0" encoding="utf-8" ?>
< id="A28CE77C-7E79-49e1-867E-AF4280466BA7" title="custom pages for mysite" description="" xmlns="http://schemas.microsoft.com/sharepoint/" scope="Web" hidden="false" version="1.0.0.0">
<>
< location="element.xml">
< location="home.aspx">
< /elementmanifests>
< /feature>
Now Create element.xml file. Open it in an editor and add the following-
< ?xml version="1.0" encoding="utf-8" ?>
< xmlns="http://schemas.microsoft.com/sharepoint/">
< url="">
< url="home.aspx" name="home.aspx" type="Ghostable">
< /File>
< /Module>
< /Elements>
Now create a folder say- MySitePages. Put feature.xml,element.xml and home.aspx file into it. put this folder in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\ directory. Take the DLL of your ASP.Net application and put it into GAC.
Now we may use stsadm -o installfeature and stsadm -o activatefeature utility to deploy and activate the feature. we can activate the feature at site level after creating mysite.
After activating the page will be attached to the mySite.
Its done now. :)
Wednesday, June 24, 2009
The two ways of developing custom webparts using .Net
There are two ways to create custom webpart-
1. using User control
2. using class library project
One may ask that which method is better. As far as I am concern, when you need a complex UI in your webpart then use user control otherwise you may use class library project.
Creating webpart using User control
We need to follow few steps-
1. Create an ASP.Net web application and add an user control into it. Give some interesting name to it.
2. create your UI and write your code and build your application.
You can deploy it in two way-
a. Using smartpart- a third party tool to add user control to your sharepoint site
b. by deploying the DLL into GAC and putting your ASCX file into
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES directory.
Smartpart can be downloaded from here
Deployment using smartpart
- Take the DLL and put it in the bin folder of your web application. i.e. inside C:\Inetpub\wwwroot\wss\VirtualDirectories\port number\BIN\ directory.
- Create a folder named 'UserControls' inside the web application ( inside the C:\Inetpub\wwwroot\wss\VirtualDirectories\port number\ directory) and put the ascx file in that folder.
- Open the web.config. Increase the trust level to Full. we dont need safecontrol entry for user control as it will be there for smartpart.
- Do an IIS reset. your user control is ready to use.
- To use it, Open the page where you want to add webpart, in edit mode. Click on 'add a webpart' in webpart zone. select smartpart from webpart zone. open the tool pane and select the user control. click on Ok. Its done now.
Deployment without Smartpart
- Sign your web Application with strong name and build it again.
- take your DLL and put it in GAC.
- Take the ASCX file and put it on C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\CONTROLTEMPLATES directory.
- Add a SafeControls entry into web.config.
- Do an IIS reset.
- Go to webpart gallery on your site and click on New tab.
- Select your webpart and populate the gallery with it. Now the webpart will be in webpart gallery for use.
Creating webpart using class library project
Follow the below steps-
- Open visual studio and create class library project.
- write your custom code for webparts and rendering controls using CreatChildControls() and Render() methods.
- Sign your project with strong name.
- Build the project.
- Put the DLL into the GAC.
- Add the SafeControl entry into the web.config file specifying the namespace and assembly.
- Do an IIS reset.
- Go to webpart gallery on your site and click on New tab.
- Select your webpart and populate the gallery with it. Now the webpart will be in webpart gallery for use.
Thats It.
Hopes it would be helpful for everyone.
Regards
Deewaker
Monday, June 1, 2009
OWA-Sharepoint Integration- A tricky solution
http://blogs.msdn.com/tconte/archive/2007/01/17/owa-web-part-with-single-sign-on.aspx
I used Single-sign-on solution from this blog. In this an HTML file has been used which is using an IFRAME control for OWA login form and submitting the credential automatically to the OWA login form. To enable SSO, I used below blog.
http://www.thorprojects.com/blog/archive/2008/08/02/moss-single-sign-on-setup-step-by-step.aspx
With the help of network administrator I was able to enable the SSO on sharepoint server.As we are authenticating the user from AD, we need to put all the user credentials into SSO database once. later when u will update the credential from AD, it will automatically be updated in SSO database. The problem with this solution is-the credentials will be passed as clear text in querystring. to resolve this I wrote some custom encryption method. As here the encryption will me server side and the decryption will be on client side so I did not tried to use built-in encryption provided in .Net. Instead I followed custom encryption as below-
public string EncryptCredentials(string Cred)
{
try
{
string EncryptedCred = string.Empty;
string[] arr = new string[10];
for (int i = 0; i < Cred.Length; i++)
{
arr[i] = Cred.Substring(i, 1);
}
for (int i = 0; i < Cred.Length; i++)
{
switch (arr[i])
{
case "A":
{
arr[i] = "!@#$%";
break;
}
......... and so on.
}
}
}
}
Now we need to decrypt the credentials on client side to pass it on OWA login form. I wrote some javascript decryption code to decrypt the credentials as below-
function getPassword(pwd)
{
var len=pwd.toString().length;
var arr=new Array();
var i;
var ClearPwd="";
for(i=0;i < len;i+=5)
{
arr[i]=pwd.toString().substring(i,i+5);
}
for(i=0;i < len;i+=5)
{
switch (arr[i])
{
case "!@#$%":
{
arr[i] = "A";
break;
} .......
n so on
}
ClearPwd+=arr[i];
}
}
Here the encrypted credential has been taken into array of string each having length five. This will again decrypt the credentials and that will be passed to OWA login form. Now the credential is being decrypted and can be passed to login form of OWA. Also, it will not be visible to anyone as a clear text. Its done Now. you may use the webpart now. hopes it will help. :)
Regards
Deewaker
