Saturday, June 8, 2013

Creating a custom Page Layout in SharePoint 2010

Creating a custom Page Layout in SharePoint 2010 is not too different than creating a custom Page Layout in SharePoint 2007. However, the process of creating a SharePoint Solution Package has changed in Visual Studio 2010. This article will walk you through the steps.

 First, open Visual Studio and create a new C# project, using the "Empty SharePoint Project" template, listed under the SharePoint 2010 project templates. For this example, we'll name our project "MyCustomPageLayout".


 For this example, we'll be deploying our solution as a "Farm solution".

 Click "Finish" to wire up your solution to your particular SharePoint site.

 Content Type:

 First thing to do is to define a content type.
I will call my Content Type: PicturePageContentType To do this: -

 - Go to: Site Settings –> Site content types
 - Next, click Create

 In the following screen you insert information about the content type.
An import thing to do is let it inherit from the right parent content type.
This needs to be from the group: Publishing Content Types and the parent needs to be Page.

 So far nothing special, next I added some non existing columns.
On the following page click Add from new site column.



 Define in the screen the follows up the columns that you would like to add to the your content type (Page Layout in the end).



 After you added all the columns you needed you can overview it when you’re looking at you content type. You’ll see that I added Page Content, this was one from the already existing site columns.

<Field ID="{7169882F-9B0C-4EA8-A096-9822C720D3BB}" Name="PageContent" DisplayName="PageContent" Type="HTML" RichText="TRUE" RichTextMode="FullHtml" />  <Field ID="{ECD16AAB-CEA3-4D0A-9F48-16F59B29C73A}" Name="PageImage" DisplayName="PageImage" Type="Image" RichText="true" />

  Note: If you added a from column to your page you cannot delete it:) If you want to get rid of it you need to delete the whole content type. 

Create the Page Layout 

As with SharePoint 2007, we'll need to provision our Page Layouts to our SharePoint Site Collection Master Page Gallery by using a "Module" element. To do this, right click on the Project and say you want to add a new item. Select "Module" from the list of SharePoint 2010 items.

We'll name the Module "masterpage". When you create the new module, you'll see something like this:


 By default, the module contains a sample text file you, so you can see how the Module deploys a file to SharePoint. However, we don't need it, so we'll delete Sample.txt. Next, we need to wire up our module to point to the URL of the Master Page Gallery, so we'll add a "Url" attribute to the Module node. Our Elements.xml file should now contain this XML:

<?xml version="1.0" encoding="utf-8"?> <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Module Name="masterpage" Url="_catalogs/masterpage">
  </Module>
</Elements>
  <Module Name="masterpage" Url="_catalogs/masterpage">   </Module> </Elements>

Next, we're going to dop our new Page Layout file into the Module. To do thhis, we'll right-click on the "masterpage" module in the Visual Studio explorer and select "Add new item". We're once again presented with the "Add New Item" dialog. If we were to select "Application Page" from the SharePoint 2010 menu, we'd get a code-behind page in addition to our ASPX page, which we don't want. Since all we want to provision is markup (and not code), we're going to use a shortcut. Select the "General" node and select "Text File" from the list of items. However, name the file "MyCustomPageLayout.aspx". Add your Page Layout markup into your MyCustomPageLayout.aspx page.



You can do it how I do it, which is to create a new Page Layout in SharePoint designer,

 Now, we need to add the code for PageLayout1.aspx. It's easier to design for the page first in SharePoint designer and then cop the code over.
So let's open SharePoint designer to the site you are developing on. Select "Page Layouts" under Site Objects.


 In the ribbon click "New Page Layout". In the dialog box select Custom Content Types and ContentType1. Enter a URL Name and Title



 In the Toolbox, under SharePointControls, Server Controls, Content Fields you should see PageContent and PageImage. Drag these two fields onto the page in the "PlaceHolderMain" content area so it looks like this Once again,



 the FieldName values most likely won't match yours since that's a guid generated by the system. We will make two changes before we copy the code over to our project. Instead of leaving the guid for the field names we will change the FieldName to the actual names of the fields -- PageContent and PageImage so the code will be

<PublishingWebControls:RichImageField FieldName="PageImage" runat="server"></PublishingWebControls:RichImageField><PublishingWebControls:RichHtmlField FieldName="PageContent" runat="server"></PublishingWebControls:RichHtmlField>


This makes it easier when deploying the solution to dev, staging, and production since the FieldName guids rarely match when moving to a different SharePoint 2010 environment.

Also, in the Page directive at the top of the page get rid of the following text: meta:webpartpageexpansion="full" meta:progid="SharePoint.WebPartPage.Document"

Take the code from the DesignPageLayout and copy it over to the PageLayout1.aspx page in your project.

then copying the code to Visual Studio. However, DO NOT FORGET to remove the attributes in the Page Directive at the top of the page that SharePoint Designer adds, that look like this:

 meta:webpartpageexpansion="full" meta:progid="SharePoint.WebPartPage.Document"

If you don't forget to remove those items from the Page directive, SharePoint will think your pages have been customized, even though they were deployed via a Feature.

 Next, we'll need to update the Module's Elements.xml file to tell SharePoint what to do with the new Page Layout.

 The first thing we'll need to do is to update the "Url" property of the File element, by removing the "masterpage/" prefix fromt the Url. (Since we already specified in the Module element that we're deploying the Page Layout to the "masterpages" library, if we left the "masterpages/" part of the Url on the file, SharePoint would try to provision our Page Layout into a library called "masterpages" inside the existing "masterpages" library! We don't want that!) Your new File element should look like this:

<File Path="masterpage\MyCustomPageLayout.aspx" Url="MyCustomPageLayout.aspx" />

  Now we need to specify some properties for the Page Layout. These properties are identical to the kind of properties you would specify for a Page Layout in SharePoint 2007: 

• The Title of the file in SharePoint In our case, the file itself has a URL of MyCustomPageLayout.aspx, but we can also give the page a Title that will show up when the Page Layout is being selected by the content author, such as "My Custom Page Layout". 
• The Content Type All Page Layouts must inherit from the "Page Layout" content type (which we add using a Resource file value.)
• A Publishing Preview Image The Publishing Preview Image is the image that shows up when a user picks that Page Layout from the Page Layout picker while they're creating a new page. In this example, we'll just point to the Article Page's preview image. 
• The Publishing Associated Content Type This is the Content Type that the Page Layout is representing, such as an "Article Page", "Welcome Page", etc. The value is a string representing a Lookup value that's a combination of the name of the Content Type and its unique identifier. 

Our new File node will look like this: 


<File Path="masterpage\MyCustomPageLayout.aspx" Url="MyCustomPageLayout.aspx" Type="GhostableInLibrary">       <Property Name="Title" Value="My Custom Page Layout" />       <Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;" />       <Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/CustomPageLayout.png" />       <Property Name="PublishingAssociatedContentType" Value=";#ContentTypeName;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900242457EFB8B24247815D688C526CD44D;#" /> </File>

Please note, there's no line break inside the PublishingAssociatedContentType value string; I needed to add a line break so you could see the whole value here. 

That's it! We've built our Module. 

Now, we're going to add a module for the Page Layout preview image. Right click on the project and add an additional Module element. Delete the "Sample.txt" file from it, and add your new preview image. (In our case, we'll call it CustomPageLayout.png".) Modify your module file so it looks like this:


<Module Name="Previews Images" Url="_catalogs/masterpage/$Resources:core,Culture;/Preview Images">
  <File Path="Preview Images\CustomPageLayout.png" Url="CustomPageLayout.png" Type="GhostableInLibrary">       <Property Name="Title" Value="Custom Page Layout Preview Image" />   </File> </Module>

You might have noticed that a new Feature got created for you when you created a new Module. Let's rename the Feature itself MyCustomPageLayout in the project tree, like this: 




 We'll open up our MyCustomPageLayout feature, and give it a helpful name and description. Notice that you can graphically see that your Module is a part of this Feature, and you can even see which Module files will be provisioned when the Feature is activated. 




 The last thing we need to do is to make sure our Solution Package is getting configured correctly, to include our new Feature. 
 By default, the "Empty SharePoint Project" will create a DLL for you. If we just went ahead and deployed our Solution Package with the settings as-is, we would be deploying a DLL to the GAC. However, since our solution doesn't have any code in it, it would be a blank DLL. That's a bit messy, so let's avoid that. Click on the Project in your Solution Explorer, and look in the Properties Window. Change the "Include Assembly in Package" property to "False". 



 Important note: This value is in the Properties Window. I was originally looking for it in the Properties page of the Project (say that three times fast), and I couldn't find it there.

 To deploy our new Solution Package to our Sandboxed Site, we'll go to the "Build" menu in Visual Studio, and select "Deploy MyCustomPageLayout".



 This will assemble the Solution Package, deploy the Solution Package to the Sandbox, then activate the Sandboxed feature. If we browse to our Master Page Library, we'll now see our new Page Layout. Note that, unlike SharePoint 2007, our Page Layout will appear checked out by default, if we haven't modified any of the approval or check-out settings of the out of the Master Page Gallery. We'll need to check it in and approve it for it to be available to us.


 Refrences: Links :

http://rburgundy.wordpress.com/2010/05/21/sharepoint-2010-create-page-layout-based-on-a-custom-content-type-in-visual-studio-2010/ http://www.rkinteractive.com/blogs/SoftwareDevelopment/post/2012/01/06/Creating-Custom-Content-Types-and-Page-Layouts-in-Visual-Studio-2010.aspx http://www.c-sharpcorner.com/Forums/Thread/182458/how-to-create-page-layout-in-sharepoint-2010-using-visual-st.aspx

Error occurred in deployment step 'Retract Solution': Cannot start service SPUserCodeV4 on computer

When i got this error i searched in net and found a solution to enable Microsoft Sharepoint foundation User Code Service in services section of Central Administration. Unfortunately i couldnt find a service with that name. While searching in services.msc i found that SharePoint 2010 User Code Host was not started. Once the Service was started the issue got resolved. Fix for 'Load control template... TaxonomyPicker.ascx" http://gallery.technet.microsoft.com/office/32d06697-ab7f-447e-9d0e-b6d93bee3fda Error on start & end tag Page Directive Close & open File

Wednesday, June 5, 2013

export one library in multiple site

  • I will show how to create a custom web part that represents a list or library’s view and use this web part in other sites (at least in the same site collection) without copying documents between sites. 
  • This custom web part supports a tool bar so files can be uploaded and maintained in a single library, but viewed and maintained from any site in the site collection that has this web part. 
  • Tools needed:
    • SharePoint Designer (to make one quick change, export the web part, and then optionally roll back the change)
    • Some way to find the site’s GUID (see link to a tool below)
  • First some observations:
    • While editing a web part page, click a web part’s menu and you will usually see an Export option, except for list and library web parts.
    • List and library view pages are web part pages (they have “Edit Page” in the Site Actions menu") and the displayed list is a web part.
  • So how can you export a list web part?
    Turns out to be pretty easy. Edit the page in SharePoint Designer and change one word.
    1. Open the site in SharePoint Designer and double click on a page with the web part (default.aspx, Shared Documents/Forms/Allitems.aspx, etc)
    2. In the code view find the web part and find 
      <ExportControlledProperties>false</ExportControlledProperties> 
      and change from “false” to “true”
    3. Save the page (this will “unghost” the page, but you can undo the changes after the export is complete – right-click the file in the Folder List and select Reset to Site Definition)
    4. Go to a browser and visit this page. Go to Site Actions, Edit Page.
    5. Click Edit in web part you just modified and click Export.
    6. Give the file a name and save it somewhere where you can find it in the next step.
    To import the exported settings as a new web part:
    1. Visit your top level site in the site collection and go to Site Actions, Site Settings, and in the Galleries column click Web Parts
    To add the web part.
    1. Nothing special here. Add this web part just like any other web part.

    Some differences…
    Oddly, the displayed columns are different. The AllItems view displayed Type, Name, Modified and Modified By. The new web part displays Type, Name and Modified By. This is easy to fix. Edit the web part and change the Selected View property to All Documents then you will get the same list of columns in both displays.
    The new web part does not display a toolbar by default, but this can be enabled from the web part’s properties panel. If the toolbar is enabled you will see all of the buttons found in the AllItems page, New, Upload, Actions and Settings (depending on the current user’s security rights).

    Now test the web part in a sub site….
    Error!
        Unable to add selected web part(s).
        List does not exist.
        The page you selected contains a list that does not exist.
    On the first attempt it appears that the new exported web part will not work on another site. Time for more research…

    Find the missing GUID
    Open the .DWP (.WEBPART in 2010) file created by the Export. Find these two lines:
    SP 2007
      
    <ListName …..>{ list_guid_here } </ListName>
       <WebId ….> all_zeros_guid_here </WebId>
    SP 2010
       <property name="ListName" type="string">{ list_guid_here } </property>
       …
       <property name="WebId" …>all_zeros_guid_here </property>

    SharePoint uses Globally Unique IDs (GUIDS) to identify just about everything stored in the databases. Notice that the ListName has a GUID, but the WebId is all zeros. Replace the zeros with the GUID for the site that owns the list and all will then work.

    How to find a GUID
    I can’t find any place in the the pages exposed in SharePoint Designer where the web site’s GUID is used, although the list’s GUID can be found in some of the URLs (for example after clicking Settings, List or Library Settings). I wrote two little utilities to display a site’s GUIDs, one a Windows application and the other a page you can deploy to the LAYOUTS folder on the server.
    Quick note: Internally a site is call a “web” and a site collection is called a “site”. (go figure…) The utilities above use the web and site names.

    Update the web part file
    Edit the WebId element and replace the all zeros GUID with the site’s GUID:
      SP 2007”   <WebId ….> all_zeros_guid_here </WebId>
      SP 2010    <property name="WebId" …>all_zeros_guid_here </property>
    After updating the DWP file with the site’s (web’s) GUID, re-upload it to the web part gallery and go and test the web part in a sub site.

    And for the “Strange Things” list… the GUID for the web site does not include brackets ( { } ) and is in lower case. The GUID for the list must have brackets and MUST be in UPPER CASE or it will not work.


    Reference:http://techtrainingnotes.blogspot.com/2009/03/sharepoint-one-library-multiple-sites.html 

check if current web is root web or sub web in XSL

[Code]

<xsl:if test="string-length($WebUrl) = 3">          <a href="Forms/AllNews.aspx?RootFolder=/Pages/News">          <xsl:text disable-output-escaping="yes"> </xsl:text></a>          </xsl:if>

All webpart appear as ErrorWebParts when using SPLimitedWebPartManager


Hi! recently I was given a task to update properties of multiple webparts(custom developed webparts created by extending existing SharePoint OTB webparts).
Now the trick was to fetch those webparts across pages multiple pages and update their properties and UI formatting instructions based on a configuration file which is provided at run time on feature activation.

Seems a simple enough task, where one needs to retreive page-url, fetch SPLimitedWebPart manager based on page-url.
Use SPLimitedWebPart Manager to iterate through collection of webparts which exist of specified page URL and update properties based on configuration input.

Like any other developer, I started of write code to implement this.
Half-way down the line when I began to query webparts collection using SPLimitedWebPart Manger,
I see all webparts returned are of type "ErrorWebParts".

Why? Because of the following code is called by the specific properties of the ContentByQueryWebpart

The webpart will always call the SPContext, there is no web-context. Therefore when initiating the
ContentByQueryWebpart

A workaround for this would be to provide it with a context. all what i do adding if condition before query on
webparts if HttpContetxt is null i'll add it.

[Code]

if (HttpContext.Current == null)                    {                        HttpRequest request = new HttpRequest("", web.Url, "");                        HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));                        HttpContext.Current.Items["HttpHandlerSPWeb"] = web;                    }
                   SPFile filePath = webToUpgrade.GetFile("[ path of your page ]");
                    SPLimitedWebPartManager webpartManager =                        filePath.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    SPLimitedWebPartCollection webPartColl = webpartManager.WebParts;
                    foreach (var webpart in webPartColl)                    { // write your code                    }

check current culture language in publishing page

check current language is Arabic language in publishing page

[Code]

<% if (System.Threading.Thread.CurrentThread.CurrentUICulture.LCID==1025){ %><%}else{%><%}%>

check Publishing page status

if you want to check current status in publishing page is Display mode :
[Code]

<%if (Microsoft.SharePoint.SPContext.Current.FormContext.FormMode == SPControlMode.Display)  {  %>    <asp:HyperLink runat="server" Text="<%$ Resources: SECITN.ListdefinitionStrings, backToNewsBtn %>" NavigateUrl="javascript:void(0);" OnClick="if($('.breadcrumbNode').length == 1){ $(this).attr('href','../forms/allnews.aspx?RootFolder=/' +$('.breadcrumbNode').attr('href').split('/')[1]+ '/Pages/News')}else{$(this).attr('href','../forms/allnews.aspx?RootFolder=/Pages/News')}"/>  <%}%>

All webpart appear as ErrorWebParts when using SPLimitedWebPartManager


Hi! recently I was given a task to update properties of multiple webparts(custom developed webparts created by extending existing SharePoint OTB webparts).
Now the trick was to fetch those webparts across pages multiple pages and update their properties and UI formatting instructions based on a configuration file which is provided at run time on feature activation.

Seems a simple enough task, where one needs to retreive page-url, fetch SPLimitedWebPart manager based on page-url.
Use SPLimitedWebPart Manager to iterate through collection of webparts which exist of specified page URL and update properties based on configuration input.

Like any other developer, I started of write code to implement this.
Half-way down the line when I began to query webparts collection using SPLimitedWebPart Manger,
I see all webparts returned are of type "ErrorWebParts".

Why? Because of the following code is called by the specific properties of the ContentByQueryWebpart

The webpart will always call the SPContext, there is no web-context. Therefore when initiating the
ContentByQueryWebpart

A workaround for this would be to provide it with a context. all what i do adding if condition before query on
webparts if HttpContetxt is null i'll add it.

[Code]

if (HttpContext.Current == null)                    {                        HttpRequest request = new HttpRequest("", web.Url, "");                        HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));                        HttpContext.Current.Items["HttpHandlerSPWeb"] = web;                    }
                   SPFile filePath = webToUpgrade.GetFile("[ path of your page ]");
                    SPLimitedWebPartManager webpartManager =                        filePath.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    SPLimitedWebPartCollection webPartColl = webpartManager.WebParts;
                    foreach (var webpart in webPartColl)                    { // write your code                    }