Setup IIS App Pool and deploy codes by PowerShell


$iisSiteLocation = "D:\InetPub\wwwroot\iis\VirtualDirectories\" + $iisFolder"
$iisSite = "IIS:\Sites\My_Apps_Site (443)"

$NewAppPoolName = "My_Apps_Site_Service_AppPool"
CreateApplicationPool($NewAppPoolName)

CopyFilesWithWebConfigToIISLocation $sourceLocation $iisSiteLocation $appFolderName

function CreateApplicationPool([string] $AppPoolName){

$NewPool = Get-Item IIS:\AppPools\"$AppPoolName" -ErrorAction SilentlyContinue

Write-Host $AppPoolName

if($NewPool -eq $null) {
Write-Host "Creating Application Pool..."
New-WebAppPool -Name $AppPoolName
$NewPool = Get-Item IIS:\AppPools\"$AppPoolName"
$cred = Get-Credential
$NewPool.ProcessModel.Username = $cred.GetNetworkCredential().Domain +"\"+ $cred.GetNetworkCredential().UserName
$NewPool.ProcessModel.Password = $cred.GetNetworkCredential().Password
$NewPool.ProcessModel.IdentityType = 3
$NewPool.ManagedRuntimeVersion = "v4.0"
$NewPool | Set-Item
}
Else {
Write-Host "Application Pool already exists."
}
}

 

function CopyFilesWithWebConfigToIISLocation ([string] $sourceDir, [string] $destDir, [string] $appFolderName) {
$sourceFileLocation = $sourceDir + "\" + $appFolderName
$destFileLocation = $destDir + "\" + $appFolderName

write-host "Copy files from " $sourceFileLocation " to " $destFileLocation
Copy-Item $sourceFileLocation $destDir -recurse -force
Copy-Item "$sourceFileLocation\WebConfig\PROD\web.config" $destFileLocation -force}
}

SharePoint 创建一个新的Feature

为了部署方便,在project中应建立和wss路径相似的目录结构。建立目录结构TEMPLATE\FEATURES\工程名,这个目录下建立feature.xml和element.xml

<Feature Id=”” Title=”Hello World Feature” Description=”This is my very first custom feature” Scope=”Web” Hidden=”FALSE” ImageUrl=”menuprofile.gif”

ReceiverAssembly=”HelloWorld, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=b59ad8f489c4a334″
ReceiverClass=”HelloWorld.FeatureReciever”

xmlns=”http://schemas.microsoft.com/sharepoint/“>

<ElementManifests>
<ElementManifest Location=”elements.xml” />
</ElementManifests>

</Feature>

Title:active feature时的名字,Description:active feature时的描述,

Scope:feature部署的level,WEB代表部署到每个site,

hidden:若为TRUE,则该feature不能从UI上激活,即不暴漏给用户,只能用命令行或者在其他feature激活时通过代码激活,FALSE即可以让用户来操作。

ReceiverAssembly,ReceiverClass:如果在active feature或deactive feature时添加event,可以使用该属性引用定义该event的类。

程序运行时会在GAC和该网站站点下_app_bin这两个地方查找该程序集。

<ElementManifests>
<ElementManifest Location=”elements.xml” />
</ElementManifests>

这个节点指该feature中真正的内容

What is Assembly

程序集(Assembly)的概念:

首先:程序集是一个或多个托管模块,以及一些资源文件的逻辑组合。因为它是一个逻辑上的组合,所以程序集的逻辑表示和物理表示可以相互分离。如何将代码和资源划分到不同的文件中完全取决于我们。例如,我们可以将一些很少使用的类型或资源放在一个单独的Assembly Module中,然后根据需要(比如第一次用到的时候),从web上下载它们。如果没有用到,它们将不会被下载。这样既节省磁盘空间,也减少了安装时间。程序集允许我们将文件的部署分解开来,同时又将所有的文件看作一个单独的集合。

其次:因为CLR是直接和程序集打交道的,所以程序集也是组件复用,以及实施安全策略和版本策略的最小单元(安全策略,版本信息等都只能是加在程序集上)。

注意:程序集是一个逻辑组合,它可以包含很多个文件。大多数程序集(比如使用Visual Studio.NET创建的那些)一般都是单文件程序集,也就是只有一个.exe或者.dll文件(目前.NET的程序集只有这两种格式)。在这种情况下,程序集清单(manifest)直接嵌入到单文件程序集中。但是,你也可以用“程序集生成工具”(Al.exe)来创建多文件程序集。也可以只创建一个只包含清单的程序集。

强命名程序集(Strong Name Assembly)的概念

因为不同的公司可能会开发出有相同名字的程序集来,如果这些程序集都被复制到同一个相同的目录下,最后一个安装的程序集将会代替前面的程序集。这就是著名的Windows “DLL Hell”出现的原因。

很明显,简单的用文件名来区分程序集是不够的,CLR需要支持某种机制来唯一的标识一个程序集。这就是所谓的强命名程序集。

一个强命名程序集包含四个唯一标志程序集的特性:文件名(没有扩展名),版本号,语言文化信息(如果有的话),公有秘钥。

这些信息存储在程序集的清单(manifest)中。清单包含了程序集的元数据,并嵌入在程序集的某个文件中。

下面的字符串标识了四个不同的程序集文件:

“MyType, Version=1.0.1.0, Culture=neutral, PublicKeyToken=bf5779af662fc055”

“MyType, Version=1.0.1.0, Culture=en-us, PublicKeyToken=bf5779af662fc055”

“MyType, Version=1.0.2.0, Culture=neturl, PublicKeyToken=bf5779af662fc055”

“MyType, Version=1.0.2.0, Culture=neutral, PublicKeyToken=dbe4120289f9fd8a”

如果一个公司想唯一的标识它的程序集,那么它必须首先获取一个公钥/私钥对,然后将共有秘钥和程序集相关联。不存在两个两个公司有同样的公钥/私钥对的情况,正是这种区分使得我们可以创建有着相同名称,版本和语言文化信息的程序集而不引起任何冲突

与强命名程序集对应的就是所谓的弱命名程序集。(其实就是普通的没有被强命名的程序集)。两种程序集在结构上是相同的。都使用相同的PE文件格式,PE表头,CLR表头,元数据,以及清单(manifest)。二者之间真正的区别在于:强命名程序集有一个发布者的公钥/私钥(PublickKeyToken)对签名,其中的公钥/私钥对唯一的标识了程序集的发布者。利用公钥/私钥对,我们可以对程序集进行唯一性识别、实施安全策略和版本控制策略,这种唯一标识程序集的能力使得应用程序在试图绑定一个强命名程序集时,CLR能够实施某些“已确知安全”的策略(比如只信任某个公司的程序集)。

创建好了公钥/私钥对,创建强命名程序集就很容易了。只需要把System.Reflection.AssemblyKeyFileAttribute特性加入到源代码中就可以了: [assembly:AssemblyKeyFile(“MyCompany.keys”)]

程序集的部署方式
一个程序集有两种部署方式:
a)私有方式 和应用程序部署在同一目录下的程序集称作私有部署程序集。弱命名程序集只能进行私有部署。

b)全局方式
全局部署方式将程序集部署在一些CLR已确知的地方,当CLR搜索程序集时,它会知道到这些地方去找。强命名程序集既可以进行私有部署,也可以进行全局部署。

如何部署强命名程序集(Strong Name Assembly)和GAC
a)GAC的概念
如果一个Assembly要被多个应用程序访问,那么他就必须放在一个CLR已确知的目录下,并且CLR在探测到有对该Assembly的引用时,它必须 能自动到该目录下寻找这个程序集。这个已确知的目录称作GAC(Global Assembly Cache),就是全局程序集缓存。它一般位于下面的目录下:<System Drive>:\Windows\Assembly\GAC。
GAC的作用就是提供给CLR一个已知的确定的目录去寻找引用的 程序集。

把程序集安装到GAC有几个好处。首先,GAC使得很多程序可以共享程序集,这从整体上减少了使用的物理内存;其次,我们很容易将一个新版的程序集部署到 GAC中,并通过一种发布者策略(差不多就是一种重定向方法,比如将原来引用版本为1.0.0.0程序集的程序,通过更改它的配置文件,转而让程序去引用 版本为2.0.0.0的程序集)来使用新版本;最后,GAC还提供了对不同版本程序集的并存(side-by-side)管理方式。

初探SharePoint部署 – WSS Solution Package

Feature.xml (Defines the feature and specifies the location of assemblies, files, dependencies, or properties that support the Feature.)

Feature.xml是很常见的配置文件,用来指定所安装的Feature中要包含的DLL,以及其详细配置文件Elements.xml的路径。Feature.xml我们可以认为是单个Feature的入口点,大多数时间之需要指明Elements.xml的路径,而无需将具体操作置入Feature.xml。这样做是为了让我们的配置文件更结构化,功能化。

Elements.xml (Element manifest file containing definitions to the feature’s elements.)

Elements.xml文件是最终这个Feature所要做的动作的具体描述。在这里可以应用诸如CustomAction, Module, ModuleGroup, Assemblies, ActivationDependencies, Recievers等扩展标记来告诉Package在部署时要做的动作。

Package.ddf(Package.ddf is a MakeCab diamond directive file used to define the structure and contents of the solution package.)

.ddf文件指定了将来生成的.CAB文件或.WSP文件包含的内容。这里定义了所有需要部署的文件结构信息。需要注意的是,目录结构的变化需要用.SET DESTINATIONDIR=’’ 来显式指定。

Package.Target(Custom the MSBuild project used to create the WSS Solution Package for deployment of the feature. Basically, it changes the defaultTargets to the custom target which calls MakeCab.exe to produce the expected .wsp file.)

因为我们需要创建一个MSBuild项目,但最终生成.WSP文件或者.CAB文件的任务是由MAKECAB.EXE完成的。我们需要给MsBuild项目创建一个任务单,来告诉它去执行MAKECAB并根据设定来创建.WSP文件。因为MSBuild项目的默认构建动作是Build,我们需要变更项目的默认构建动作为指定的DDF,并通过更改Import Project将其要完成的任务交给MsBuild项目去做–这些任务是在Package.Target中完成的。

Elements.xml 解析:

创建Elements.xml来定义Feature的操作。

在Elements.xml中,Module是个经常被用到标记。MSDN给出的解释是(具体的解释参考MSDN)Specifies files with which to provision SharePoint Web sites within an element manifest. 它和File标记联合使用,其实它本质上是按照Module和File指定的路径将文件拷贝到服务器,而这里你还可以通过Properties比较来对这些文件添加一些属性。

<?xml version=”1.0″ encoding=”utf-8″?>

<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”&gt;

<Module Name=”MasterPages”

Url=”_catalogs/masterpage”

Path=”MasterPages”

RootWebOnly=”TRUE”>

<File Url=”CustomPageLayouts.master”

Type=”GhostableInLibrary”>

 

<Property Name=”ContentType”

Value=”$Resources:cmscore,contenttype_masterpage_name;” />

<Property Name=”PublishingPreviewImage”

Value=”~SiteCollection/_catalogs/masterpage/Preview Images/CustomPageLayouts.jpeg, ~SiteCollection/_catalogs/masterpagePreview Images/CustomPageLayouts.jpeg” />

<Property Name=”Title”

Value=”Allan’s custom master page.” />

 

</File>

</Module>

 

<Module Name=”PreviewImages”

Url=”_catalogs/masterpage/Preview Images”

Path=”MasterPages”

RootWebOnly=”TRUE”>

<File Url=”CustomPageLayouts.jpeg”

Name=”CustomPageLayouts.jpeg”

Type=”GhostableInLibrary”/>

</Module>

 

</Elements>

http://msdn.microsoft.com/en-us/library/ms414322

 

 

 

Using Features and Solutions to Deploy your SharePoint Customizations

citied: http://www.simple-talk.com/dotnet/.net-tools/using-features-and-solutions-to-deploy-your-sharepoint-customizations/

What are Features?

So what are these features I’ve mentioned?

Well, features are packages of functionality that you can activate or deactivate in a SharePoint farm. They have four possible scopes:

  • Farm
  • Web application
  • Site
  • Web

A farm level feature, as the name suggests, is something that affects the whole farm, for example provisioning a custom timer job or deploying a Business Connectivity Services model.

A web application feature can be activated so that it only affects a single web application, and a typical example is a feature that modifies the web.config file.

A site scoped feature can be activated so that it only affects a site collection, an example being the deployment of a master page to the master pages catalogue.

Finally, a web scoped feature can be activated for a single site, for instance setting the default master page for that site.

What are Solutions?

They are the files you use to deploy your changes to SharePoint. They have the WSP file extension, and are often referred to as just WSP files. In reality, they are cabinet files that contain your customizations, plus a manifest XML file that tells SharePoint how to deploy your changes.

In SharePoint 2010 there are two types of solutions: farm solutions and sandboxed solutions.

Farm solutions are the same as the solutions we had in SharePoint 2007 and are deployed to the farm. In layman’s terms, your application or update is deployed as is; files on the file system are deployed exactly as that, files on the file system.

Sandboxed solutions are new to SharePoint 2010 and deploy your files to the SharePoint Content Database.

If your solution contains either a farm or a web application scoped feature, it can only be deployed as a farm solution.

Solutions that only contain site and web scoped features can usually be deployed using either a sandbox or farm solution. However, be aware that unless you take care, you could successfully deploy code using a sandboxed solution that is not permitted to run. The Community SharePoint Kit for Developers contains a great tool which limits Intellisense Visual Studio 2010 to show only supported methods and properties when building for sandbox solutions.

Sandboxed or Farm Solutions?

As I previously mentioned, whether you design for sandboxed or farm solutions is often driven by project requirements. Let’s say I want to deploy a new master page for a site; this is perfectly achievable through a sandboxed solution. But then let’s also say I need to deploy a new custom control that I’ve included in the master page, and that control needs to be deployed to the %SharePoint Root%\Template\CONTROLTEMPLATES folder as an ASCX file and its associated DLL needs to be placed into the GAC; now the story is different and I have to deploy using a farm solution.

As a guideline, the accepted best practice is to aim for a sandboxed solution initially, but move to a farm solution if your project functionality dictates this. However, it is important to remember that hosted SharePoint environments will often only permit sandboxed solutions, so in this case the platform is a major influencer in your decision.

Creating the feature

Open up Visual Studio 2010 and select File -> New -> Project. In the Add New Project dialog box (shown in Figure 2), under Installed Templates, select SharePoint -> 2010, highlight Empty SharePoint Project, and then name your project accordingly.

Figure 2: Add New Project dialog box

Next, on the SharePoint Customization Wizard dialog box, we want to select Deploy as a sandbox solution. Add in the URL to your site collection, which should be different from the one you edited your master page in, and click Finish. This will create a project called SimpleTalk.

Now select the SimpleTalk project node in the Solution Explorer, right-click and select Add -> New Item, then select Start Master Page (CKSDev), give it a name of simpletalk and click Add.

At this point we have all the files we need to deploy our master page and we just need to do a little cut-and-paste. But let’s examine in a little more detail what we actually have in the solution, which should now look as in Figure 3.

Figure 3: SimpleTalk Solution Explorer

The feature folder contains two files used by Visual Studio 2010 (VS2010) for constructing the final feature that SharePoint will need in order to deploy your master page. These files are:

  • The feature control file with the extension .feature; this is used by VS2010 only and is never deployed.
  • The feature template XML file. This contains the outline XML that VS2010 will use to construct the final feature.xml file, which must be present in a SharePoint feature. This too is used only by VS2010 and is never itself deployed. 

It is the feature.xml file which actually gets deployed and which tells SharePoint 2010 what is in the feature, and thereby what SharePoint needs to do with the files associated with the feature. The feature.xml file will only be created when you instruct VS2010 to package your solution.

Next, we see the package control file and the package template. This works in a similar manner to the feature. Neither of these two files ever gets deployed, but they are used by VS2010 to construct a file called manifest.xml, which exists in the WSP solution file.

Finally, the folder simpletalk has been added with two files: Elements.xml and simpletalk.master. The second is plainly an ASP.NET Master Page; the former is another SharePoint specific file, and whilst it does not strictly need to be called Elements.xml, by convention it nearly always is. The Elements.xml file in this case looks as shown in Figure 4:

Figure 4: Elements.xml file

All this mark-up has been added by the CKS Item and will tell SharePoint that a file called simpletalk.master should be made available at a relative URL _catalogs/masterpage. Most of the other properties are metadata and should be replaced with meaningful data, and one I will mention specifically is Type=’GhostableInLibrary’, for two reasons:

  • Reason one is that this is the attribute that tells SharePoint that this document should be made available and versioned through a document library, which means that any change to the document through SPD2010 will result in the file being uploaded into the SharePoint content database and thereafter that is where the source code for the file will be held.
  • Reason two is that without this attribute, you will not see the document in the library listing and for some inexplicable reason it is omitted from the standard SharePoint Module Template in VS2010, which is why I used the CKS Template.

I want the feature to be scoped at the SiteCollection level, which means that it is available to all sites within the SiteCollection. I can do this quite easily in the Feature Designer shown in Figure 5. So, double-click on the Feature1 folder and in the Scope drop-down list change the scope to Site. We can see the simpletalk item is included in the feature as it is shown on the right-hand side of the designer.

Figure 5: Feature Designer

All we need to do now is copy the mark-up from our master page in SPD2010 and paste it into the simpletalk.master file in our VS2010 project, then save the master page. Once that is done we’re good to go.

Deploying our feature

To deploy our feature, we need to do the following:

  1. Add it to a solution.
  2. Upload it to the Site Collection Solution Store.
  3. Activate the solution.
  4. Activate the feature.

Sounds a lot of work to you? It does to me too. And in Microsoft Office SharePoint Server (MOSS) 2007 it was, but now with VS2010, it’s a breeze. Just right-click the SimpleTalk project and click Deploy. Wait a few seconds, and then open your SharePoint site and select Site Actions -> Site Settings -> Galleries ->Solutions, and you will see your solution appearing in the solutions gallery as in Figure 6. Note that the status is Activated, so the relevant features have all been deployed.

Figure 6: Solution Gallery

Select Site Actions -> Site Settings ->Site Collection Administration -> Site Collection Features, scroll down, and you should see the feature has been activated as shown in Figure 7:

Figure 7: Site Collection Feature

Finally, select Site Actions -> Site Settings -> Galleries -> Master Pages and page layouts. You will then see your deployed master page in the master page gallery.

Figure 8: Master page gallery

Where is our brown bar? We haven’t set it as the default, so the master page is still the original v4.master. Let’s enhance our feature so that it sets our new master page as the default master page.

Enhancing the feature with code

In our Visual Studio project, select the Feature1 folder, then right-click and select Add Event Receiver, which will create a class called Feature1.EventReceiver.cs.

We will add code to two protected overridden methods. Insert the following code into the FeatureActivated and FeatureDeactivating methods:

    public class Feature1EventReceiver : SPFeatureReceiver
    {
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{
SPWeb web = site.RootWeb;
web.AddProperty(“OldMasterUrl”, web.MasterUrl);
web.MasterUrl = String.Format(“{0}/{1}”
                  , (new Uri(web.Url)).AbsolutePath
, properties.Feature.Properties[“MasterUrl”].Value);
web.Update();
}
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
if (site != null)
{
SPWeb web = site.RootWeb;
web.MasterUrl = web.AllProperties[“OldMasterUrl”].ToString();
web.DeleteProperty(“OldMasterUrl”);
web.Update();
}
}
}

Code sample 2: Feature code

In a production environment you will need code that is a bit more defensive than this, but it will suffice for our example. So what does this code do?

SPSite site = properties.Feature.Parent as SPSite;

This line retrieves a reference to the site collection in which we are deploying the master page.

SPWeb web = site.RootWeb;

This creates a reference to the root web site of the site collection.

web.AddProperty(‘OldMasterUrl’,web.masterUrl);

This stores the existing master page URL into the ‘bucket’ collection for the root web site.

The next line is the line that actually sets the new master page.

    web.MasterUrl = String.Format(“{0}/{1}”
,(new Uri(web.Url)).AbsolutePath
, properties.Feature.Properties[“MasterUrl”].Value);

Code sample 2: Feature code

In a production environment you will need code that is a bit more defensive than this, but it will suffice for our example. So what does this code do?

SPSite site = properties.Feature.Parent as SPSite;

This line retrieves a reference to the site collection in which we are deploying the master page.

SPWeb web = site.RootWeb;

This creates a reference to the root web site of the site collection.

web.AddProperty(‘OldMasterUrl’,web.masterUrl);

This stores the existing master page URL into the ‘bucket’ collection for the root web site.

The next line is the line that actually sets the new master page.

    web.MasterUrl = String.Format(“{0}/{1}”
,(new Uri(web.Url)).AbsolutePath
, properties.Feature.Properties[“MasterUrl”].Value);

The Uri object AbsolutePath property is used to ensure the correct path to the master page is used. The URL relative to the SiteCollection is read from the Feature Properties, a collection of user properties that you can add into the Feature.Template.xml shown in Figure 9:

Figure 9: Feature Properties

This configuration property is then available at runtime and makes your code more generic.  To ensure your changes are saved we must include the following line:

web.update();

In the FeatureDeactivating code, we simply restore the original master page. The ability to rollback is one of the key benefits of using features and solutions, and I recommend that you always properly test rollback code in the FeatureDeactivating method.

With this code in place, just hit Deploy again. This will build and package your solution, deactivate the existing feature, retract the existing solution, deploy your revised solution, activate the solution, and activate your feature. So wait a few seconds and you will see your site with the SimpleTalk brown band across the page beneath the top navigation menu, as shown in Figure 1 above.