Update for MyMasters Solution -16th Nov 2011

Hi Everyone recently i uploaded a new version (1.1) of MyMasters solution.

the solution now covering fallowing questions’ answers :

* How to deploy a custom wellcome page to Personal Site ?
* How to add custom webparts to a page ?
* How to use XsltListViewWebPart and add a document library as a webpart ?

You can download new version from CodePlex site of MyMasters solution:
http://mymasters.codeplex.com/

Please visit related post about MyMasters:
http://blog.bugrapostaci.com/2011/10/24/attach-custom-master-page-to-personal-site-with-featurestabling-for-sharepoint-2010/

Here is a code sample for above questions :
as you guess CreateWellcomePage function has been calling in Feature Reciever class of MyMasters Feature.

  1. private void CreateWellcomePage(SPFeatureReceiverProperties properties)
  2.         {
  3.             SPSite site = (SPSite)properties.Feature.Parent;
  4.             SPWeb web = site.OpenWeb();
  5.             PublishingSite pSite = new PublishingSite(site); //Get Publishing Site Object
  6.             SPContentType ctype = pSite.ContentTypes[“Welcome Page”]; //Get builtin “Wellcome Page” content type
  7.             PageLayoutCollection pageLayouts = pSite.GetPageLayouts(ctype, true); //Get builtin pagelayouts for this content type
  8.             PageLayout pageLayout = pageLayouts[0]; //Select first one which is BlankWebPartPage pagelayout
  9.             PublishingWeb pWeb = PublishingWeb.GetPublishingWeb(web); //Get Publishing Web.
  10.             PublishingPageCollection pPages = pWeb.GetPublishingPages(); // Get Page Collection
  11.             //TempFile for changing default page
  12.             string tempFileName = “TempFileForChangeWellcomePage.aspx”;
  13.             PublishingPage tempPage = null;
  14.             try
  15.             {
  16.                 //Get if there is an existing wellcome.aspx
  17.                 PublishingPage pPageExist = pPages[pWeb.Url + “/Pages/Wellcome.aspx”];
  18.                 if (pPageExist != null)
  19.                 {
  20.                     //Check wellcome.aspx is default page
  21.                     if (pWeb.DefaultPage.UniqueId == pPageExist.ListItem.File.UniqueId)
  22.                     {
  23.                         //if it is a default page we have to create a template page because the default page is not deleted.
  24.                         //Create a temporary page
  25.                         tempPage = pPages.Add(tempFileName, pageLayout);
  26.                         tempPage.ListItem.File.CheckIn(“Chk”);
  27.                         tempPage.ListItem.File.Publish(“Pub”);
  28.                         //Set this temporary file as default page so we can able to delete existing wellcome.aspx
  29.                         pWeb.DefaultPage = tempPage.ListItem.File;
  30.                         pWeb.Update();
  31.                     }
  32.                     //Delete Existing Wellcome.aspx
  33.                     if (pPageExist.ListItem.File.CheckedOutByUser != null)
  34.                     {
  35.                         pPageExist.ListItem.File.UndoCheckOut();
  36.                     }
  37.                     pPageExist.CheckOut();
  38.                     pPageExist.ListItem.Delete();
  39.                     pWeb.Update();
  40.                 }
  41.             }
  42.             catch(Exception ex)
  43.             {
  44.             }
  45.             //Create a new Wellcome.aspx file
  46.             PublishingPage pPage = pPages.Add(“Wellcome.aspx”, pageLayout);
  47.             SPListItem newpage = pPage.ListItem;
  48.             newpage[“Title”] = “Wellcome to my personal site”;
  49.             //Add need webparts to page.
  50.             using (SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(pPage.Url, PersonalizationScope.Shared))
  51.             {
  52.                 //Get WebPart Catalog
  53.                 SPList webPartCatalog = web.GetCatalog(SPListTemplateType.WebPartCatalog);
  54.                 foreach (SPListItem item in webPartCatalog.Items)
  55.                 {
  56.                     if (item.DisplayName == “LatestBlogPostsPublic”)
  57.                     {
  58.                         string fileName = string.Format(“{0}/{1}”, item.Web.Url, item.File.Url);
  59.                         XmlTextReader reader = new XmlTextReader(new StringReader(item.Web.GetFileAsString(fileName)));
  60.                         string error;
  61.                         System.Web.UI.WebControls.WebParts.WebPart wx = wpMgr.ImportWebPart(reader, out error);
  62.                         wpMgr.AddWebPart(wx, “Header”, Convert.ToInt32(0));
  63.                     }
  64.                 }
  65.                 //Add existing Document Library views
  66.                 SPList SharedDocumentsList = web.Lists[“Shared Documents”];
  67.                 SPView SharedDocumentsListView = SharedDocumentsList.Views[0];
  68.                 SPList PersonalDocumentsList = web.Lists[“Personal Documents”];
  69.                 SPView PersonalDocumentsListView = PersonalDocumentsList.Views[0];
  70.                 XsltListViewWebPart wp = new XsltListViewWebPart();
  71.                 wp.ListId = SharedDocumentsList.ID;
  72.                 wp.Title = “Shared Documents”;
  73.                 wp.ChromeType = PartChromeType.TitleOnly;
  74.                 wp.ViewGuid = SharedDocumentsListView.ID.ToString();
  75.                 wp.XmlDefinition = SharedDocumentsListView.GetViewXml();
  76.                 wpMgr.AddWebPart(wp, “Header”, Convert.ToInt32(1));
  77.                 XsltListViewWebPart wp2 = new XsltListViewWebPart();
  78.                 wp2.ListId = PersonalDocumentsList.ID;
  79.                 wp2.Title = “Personal Documents”;
  80.                 wp2.ChromeType = PartChromeType.TitleOnly;
  81.                 wp2.ViewGuid = PersonalDocumentsListView.ID.ToString();
  82.                 wp2.XmlDefinition = PersonalDocumentsListView.GetViewXml();
  83.                 wpMgr.AddWebPart(wp2, “Header”, Convert.ToInt32(2));
  84.             }
  85.             newpage.File.CheckIn(“Administravily Check in”);
  86.             newpage.File.Publish(“Administravily Published”);
  87.             //set wellcome.aspx as default page.
  88.             pWeb.DefaultPage = newpage.File;
  89.             pWeb.Update();
  90.             //delete if tempfile is exists.
  91.             if (tempPage != null)
  92.             {
  93.                 tempPage.ListItem.Delete();
  94.             }
  95.             pWeb.Update();
  96.         }
Advertisements

Sharepoint Deploying resource files to app_globalresources folder using Timer Job.

Hi Everyone ,
in this article i want to explain how to copy your resource files to web application’s app_globalresources folder using by a timer job.

As you know there is four place that the resource files has to be.

\14\Resources\
\14\Template\Features\<Feature Name>\Resources\
\14\Config\Resources\
[Virtual Directory] \App_GlobalResources\

I could not tell about which folder for what,  this is out of concept.But i will explain that

the files which in  \14\Config\Resources can copied to [Virtual Directory] \App_GlobalResources\ folder when a new web.application created. But what about the existing ones.
Friendly stsadm command give us some help.
STSADM -o CopyAppBinContent
But still you can run this command all your sharepoint servers.And this is not an aswer for if you aim to deploy some specific web applications.
You can use
SPWebApplication.ApplyApplicationContentToLocalServer()  fuction for do it with programmatically by creating and using a feature reciever class.

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
            if (webApp != null)
            {
                 ...Somecodes.
                 webApp.Farm.Services.GetValue().ApplyApplicationContentToLocalServer();
            }
        }

I could say that cause a latency when you click to activate button for this feature.and stsadm -o copyappbincontent and ApplyApplicationContentToLocalServer() only copy the resource files on the local server.So
we have  options with Visual Studio 2010 and Sharepoint 2010

First  i will start with the easy way if you are using Sharepoint 2010 and Visual Studio 2010 .
1) Create an Empty Element from vs ide and rename it OurResources.
2) Add a resource file to this element named TestResource.resx
3) Select TestResource.resx and Change property value of  “Build Action”  key to “Resource” from Visual Studio IDE Properties window
4) Change property value of Deployment Type key to “AppGlobalResource”
5) Expand the “Deployment Location” and set the Path is empty .for doing that we can able to copy our resource file root folder of App_GlobalResources.

Second you can use ApplicationResourceFiles element on your Solution xml
<ApplicationResourceFiles> 
    <ApplicationResourceFile Location=”blog.resx”/> 
    <ApplicationResourceFile Location=”blog.en-US.resx”/> 
  </ApplicationResourceFiles>

But what if you are developing a farm scope feature or webapplication scope features that should add extra resource file to selected web applications or you have multiple server farm and you want to deploy resource files accross the farm .This time you may need a TimerJob for deploying your resource files.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IO;

namespace ResourceDeployment
{

    public class DeployResourcesJob : SPJobDefinition {
        public readonly static string DefinitionName = "job-deploy-resources";

        #region Constructors
        public DeployResourcesJob() : base() { }
        public DeployResourcesJob(SPWebApplication webApp) : base(DeployResourcesJob.JobDefinitionName, webApp, null, SPJobLockType.None) {
            this.Title = "Deploy Resource Files";
        }
        #endregion

        public static void ActivateJob(SPWebApplication webApp) {
            // Delete if any existing jobs
            DeployResourcesJob.Delete(webApp.JobDefinitions, JobDefinitionName);

            DeployResourcesJob job = new DeployResourcesJob(webApp);
            job.Schedule = new SPOneTimeSchedule(DateTime.Now.AddHours(-2));
            job.Update();
        }

       public static void RemoveJob(SPJobDefinitionCollection jobDefinitions, string name) {
           DeployResourcesJob existingJob = jobDefinitions.GetValue(DeployResourcesJob.JobDefinitionName);
            while (existingJob != null)
            {
                existingJob.Delete();
                existingJob.Unprovision();
                existingJob = jobDefinitions.GetValue(DeployResourcesJob.JobDefinitionName);
            }
        }

       public override void Execute(Guid targetInstanceId) {

             string source = SPUtility.GetGenericSetupPath("Resources");
            // Copy or remove the resource file for all zones
            if (Directory.Exists(source)) {
                foreach (SPUrlZone zone in this.WebApplication.IisSettings.Keys) {

                    // Get the location of the App_GlobalResources folder under the target Web Application
                    string destination = this.WebApplication.GetIisSettingsWithFallback(zone).Path + "\\App_GlobalResources";

                    if (Directory.Exists(destination)) {
                        string[] resourceFiles = Directory.GetFiles(source, "MyResource*.resx");
                        foreach (string filename in resourceFiles)
                        {
                            string destinationFilename = destination + "\\" + Path.GetFileName(filename);
                            File.Copy(filename, destinationFilename, true);

                        }
                    }

                }
            }
        }

}
}

Here Some Resources:
http://blogs.msdn.com/b/johnwpowell/archive/2009/11/29/sharepoint-2010-localization-with-visual-studio-2010.aspx
http://blogs.msdn.com/b/maximeb/archive/2008/04/26/deploying-resource-files-across-a-farm.aspx
http://cicoria.com/cs1/blogs/cedarlogic/archive/2010/01/31/deployment-of-resource-files-resx-to-app-globalresources-under-sharepoint.aspx

End of Article 🙂

Sharepoint solution deployment with Stsadm

Tips & Tricks :
Here is the command list of stsadm that deploy a wsp file to your sharpoint site.
.
//First we retract if exist solution
stsadm -o retractsolution -name myproject.wsp -immediate
.
// Forcing sharepoint to run timer jobs.
stsadm -o execadmsvcjobs
.
//and delete solution after retract
stsadm -o deletesolution -name myproject.wsp
.
//add solution
stsadm -o addsolution -filename c:\solutions\Hello.wsp
.
//deploy it
stsadm -o deploysolution -name Hello.wsp -immediate -allowGacDeployment
.
//Execute timer jobs
stsadm -o execadmsvcjobs
.
//Recycle Application Pool.
%windir%\system32\inetsrv\appcmd recycle AppPool “Application Pool Name”
.
Thats all .