Saturday, June 8, 2013

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                    }

Friday, March 8, 2013

Error occurred in deployment step 'Recycle IIS Application Pool'


 Problem: in a project using SharePoint 2010 and Visual Studio 2010 during a deployment procedure we required to retract some packages before deploy a new version, during this process visual studio suddenly show us the next error:



'Recycle IIS Application Pool': The open operation did not complete within the allotted timeout of 00:01:00. The time allotted to this operation may have been a portion of a longer timeout.

Solution: some times the best solution is find the most easy way, so after trying to restart IIS and try the process again unsuccessfully, the solution is close visual studio, then open the solution and try retract the package one more time .. yeap, believe me it works!! :D

SetMasterAndWelcomePageOn feature activates Programatically


[Code]

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {            try            {               SPSecurity.RunWithElevatedPrivileges(delegate                {                    using (var web = properties.Feature.Parent as SPWeb)                    {                        if (web == null) return;
                        web.ValidateFormDigest();                        SetMasterPage(web);                        SetDefaultHomePage(web);                      }                });            }            catch (Exception ex)            {            }            finally            {            }        }
        private static void SetDefaultHomePage(SPWeb varoWeb)        {            try            {                    varoWeb.AllowUnsafeUpdates = true;                    SPFolder folder = varoWeb.RootFolder;                    folder.WelcomePage = "Pages/home.aspx";                    folder.Update();                    varoWeb.AllowUnsafeUpdates = false;            }            catch (Exception e)            {    throw new SPException("Error when trying to Set DefaultPage. Error: " + e.Message);            }        }  
        private void SetMasterPage(SPWeb varWeb)        {            try            {                var strMasterUrl = "/_catalogs/masterpage/myMasterPage.master";
                varWeb.AllowUnsafeUpdates = true;                varWeb.MasterUrl = strMasterUrl;                varWeb.CustomMasterUrl = strMasterUrl;                varWeb.Update();                varWeb.AllowUnsafeUpdates = false;            }            catch (Exception e)            {                throw new SPException("Error when trying to Set MasterPage. Error: " + e.Message);            }        }

Set draft security visibility to document library


To set security that only approver and administrator see pending files
     Set DraftVerrsionVisibility=”2” in Schema.xml

To learn more about DraftVersionvisibility please read this DraftVisibility Types


1-      Using xml
<List xmlns:ows="Microsoft SharePoint" EnableContentTypes="TRUE" Title="Articles" Direction="$Resources:Direction;" Url="Lists/Articles" BaseType="1" xmlns="http://schemas.microsoft.com/sharepoint/" ModeratedList="TRUE" DraftVersionVisibility="2">


2-      Programmatically
   private void applyApproverDraftVisibilityToAllLists(SPWeb oWeb)
        {            oWeb.AllowUnsafeUpdates = true;            SPListCollectionAdapter listAdapter = new SPListCollectionAdapter(oWeb.Lists);            var result = from list in listAdapter                         select list;            foreach (SPList list in result)            {                list.DraftVersionVisibility = DraftVisibilityType.Approver;            }            oWeb.AllowUnsafeUpdates = false;        }public class SPListCollectionAdapter : List<SPList>
    {        private readonly SPListCollection _listCol;        public SPListCollectionAdapter(SPListCollection listCol)        {            _listCol = listCol;            Refresh();        }        private void Refresh()        {            Clear();            foreach (SPList item in _listCol)            {                Add(item);            }        }    }