2009年7月1日星期三

Grant full trust for multiple assemblies with one SetSecurity Proj

[Objective]
With VSTO 2005 SE, an addin that use other .NET dll(assemblies) is developed. In order to deplying the project, we use Windoes Installer follows the instructions as below
http://blogs.msdn.com/chcast/archive/2007/03/28/creating-visio-add-ins-with-vsto-2005-se.aspx

However, after setup, we must grant full trust for all asseblies(including the addin one). In order to do it automatically, we made some modification in SetSecurity project. It is described as below.

1 Add new method in [CaspolSecurityPolicyCreator.cs] to register multiple asseblies with one parent group
2 Modify [SetSecurity.cs] to use the new method
3 Set CustomActioData in Setup(Installer) project

[Solutions]
1 In [CaspolSecurityPolicyCreator.cs], Add a new method of AddMultiSecurityPolicy() as following. The code is based on AddSecurityPolicy() with some modification highlighted in red


internal static void AddMultiSecurityPolicy(
bool machinePolicyLevel,
string assemblyName,
string solutionCodeGroupName,
string solutionCodeGroupDescription,
string targetDir,
string assemblyCodeGroupName,
string assemblyCodeGroupDescription)
{
string frameworkFolder = GetFrameworkFolder();

//string solutionInstallationLocation = Path.GetDirectoryName(assemblyPath);
string solutionInstallationLocation = targetDir;

string solutionInstallationUrl = Path.Combine(solutionInstallationLocation, "*");

string policyLevel;
string parentCodeGroup;
if (machinePolicyLevel)
{
policyLevel = "-m"; // Use Machine-level policy.
parentCodeGroup = "My_Computer_Zone"; // Use My_Computer_Zone for assemblies installed on the computer.
}
else
{
policyLevel = "-u"; // Use User-level policy.
parentCodeGroup = "All_Code";
}

// Add the solution code group. Grant no permission at this level.
string arguments = policyLevel + " -q -ag " + parentCodeGroup + " -url \"" + solutionInstallationUrl + "\" Nothing -n \"" + solutionCodeGroupName + "\" -d \"" + solutionCodeGroupDescription + "\"";
try
{
RunCaspolCommand(frameworkFolder, arguments);
}
catch (Exception ex)
{
string error = String.Format("Cannot create the security code group '{0}'.", solutionCodeGroupName);
throw new Exception(error, ex);
}

// Add the assembly code group. Grant FullTrust permissions to the main assembly.

try
{
Int16 index;
string[] assemblys = assemblyName.Split(',');

string[] assemblyCGN = assemblyCodeGroupName.Split(',');
index = 0;
foreach (string assembly in assemblys)
{
string assemblyPath = Path.Combine(targetDir, assembly);

// not using the assembly strong name as the membership condition.
arguments = policyLevel + " -q -ag \"" + solutionCodeGroupName + "\" -url \"" + assemblyPath + "\" FullTrust -n \"" + assemblyCGN[index] + "\" -d \"" + assemblyCodeGroupDescription + "\"";

RunCaspolCommand(frameworkFolder, arguments);
index++;
}
}
catch (Exception ex)
{
try
{
// Clean the solutionCodeGroupName.
RemoveSecurityPolicy(machinePolicyLevel, solutionCodeGroupName);
}
catch { }

string error = String.Format("Cannot create the security code group '{0}'.", assemblyCodeGroupName);
throw new Exception(error, ex);
}
}


2 Find the codes below in [SetSecurity.cs], and make modification as in red
try

{
bool allUsers = String.Equals(allUsersString, "1");
//string assemblyPath = Path.Combine(targetDir, assemblyName);
// Note that Install method may be invoked during Repair mode and the code group
// may already exist.
// To prevent adding of another code group, remove the code group if it exists.
try
{
// The solutionCodeGroupName must be a unique name; otherwise, the method might delete wrong code group.
CaspolSecurityPolicyCreator.RemoveSecurityPolicy(allUsers, solutionCodeGroupName);
}
catch {}
/*

CaspolSecurityPolicyCreator.AddSecurityPolicy(
allUsers,
solutionCodeGroupName,
solutionCodeGroupDescription,
assemblyPath,
assemblyCodeGroupName,
assemblyCodeGroupDescription);
*/

CaspolSecurityPolicyCreator.AddMultiSecurityPolicy(
allUsers,
assemblyName,
solutionCodeGroupName,
solutionCodeGroupDescription,
targetDir,
assemblyCodeGroupName,
assemblyCodeGroupDescription);

stateSaver.Add("allUsers", allUsers);

}
catch (Exception ex)
{
throw new InstallException("Cannot set the security policy.", ex);
}

3 In Setup project, the CustomActioData in CustomAction-->Install-->Primary output of SetSecurity-->Property Window, use the following string in one line

/assemblyName="AAA.dll,BBB.dll,CCC.dll" /targetDir="[TARGETDIR]\" /solutionCodeGroupName="HITACHI.kyaddin" /solutionCodeGroupDescription="Code group for kyaddin" /assemblyCodeGroupName="AAA,BBB,CCC" /assemblyCodeGroupDescription="Code group for kyaddin" /allUsers=[ALLUSERS]

Build and run the setup.exe

With the above modification, we enhanced the SetSecurity to support granting full trust for multiple assemblies

Limitation: All assemblies must be located in same folder.

Comment: With similar modifications the followings can be done to improve SetSecurity
1 to support different targetdir
Attention: For those assemblies without strong name, they must be located under the application folder.
2 Now we can support to grant full trust to assemblies that all with strong name or none. In order to grant assemblies with strong name or without strong name identically, we can consider the followings.
Adding new membership like /StrongName = "1, 0, 1".
In AddMultiSecurityPolicy(), add the process to check StrongName and make different arguments.

2009年6月25日星期四

Walkthrough: Calling Code in an Application-Level Add-in from VBA(MSDN document)

http://msdn.microsoft.com/en-us/library/bb608614.aspx

1 Define a class that you can expose to other Office solutions
Add the following statements to the top of the file.

Imports System.Data
Imports System.Runtime.InteropServices
Imports Excel = Microsoft.Office.Interop.Excel

Replace the empty AddInUtilities class declaration with the following code.

Public Interface IAddInUtilities
Sub ImportData()
End Interface



Public Class AddInUtilities
Implements IAddInUtilities

' This method tries to write a string to cell A1 in the active worksheet.
Public Sub ImportData() Implements IAddInUtilities.ImportData

Dim activeWorksheet As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet

If activeWorksheet IsNot Nothing Then
Dim range1 As Excel.Range = activeWorksheet.Range("A1")
range1.Value2 = "This is my data"
End If
End Sub
End Class

2 Exposing the method for external use
Add the following code to ThisAddin class

Private utilities As AddInUtilities

Protected Overrides Function RequestComAddInAutomationService() As Object
If utilities Is Nothing Then
utilities = New AddInUtilities()
End If
Return utilities
End Function


3 Code to call VSTO Method
Add the following VBA code to the code file. This code first gets a COMAddIn object that represents the ExcelImportData add-in. Then, the code uses the Object property of the COMAddIn object to call the ImportData method.

Sub CallVSTOMethod()
Dim addIn As COMAddIn
Dim automationObject As Object
Set addIn = Application.COMAddIns("ExcelImportData")
Set automationObject = addIn.Object
automationObject.ImportData
End Sub

Delpoying Visio 2007 Addin with VSTO 2005 SE

Delpoying Visio 2007 Addin with VSTO 2005 SE
http://blogs.msdn.com/chcast/archive/2007/03/28/creating-visio-add-ins-with-vsto-2005-se.aspx

0 Creating a VSTO add-in for Visio

1 Deployment
Steps
1. Install .NET 2.0 Framework
2(*) Install VSTO SE Runtime
3(*) Install Visio 2007 Primary Interop Assembly
4. Add required add-in registry settings
5. Copy add-in assembly.
6. Copy any Visio templates and stencils
7(*). Grant full trust to add-in

1.1 install OfficeVSTO2005SEWindowsInstaller.msi.
http://go.microsoft.com/fwlink/?linkid=83721

1.2 Adding the Visual Studio Tools for Office Packages to the Bootstrapper

1.2.1 Preparing the Runtime
The default location of the {SamplesDir} token below is “C:\Program Files\Microsoft Visual Studio 2005 Tools for Office SE Resources\VSTO2005SE Windows Installer Sample” or something like that

Microsoft Visual Studio 2005 Tools for Office Second Edition runtime
http://go.microsoft.com/fwlink/?linkid=49612
Copy vstor.exe into the {SamplesDir}\packages\VSTOSERuntime directory.

Microsoft Visual Studio 2005 Tools for the Microsoft Office System (VSTO2005) Language Package
http://go.microsoft.com/fwlink/?linkid=56602
Copy the file vstolp20.exe into the directory {SamplesDir}\packages\VSTOLP.

1.2.2 Preparing the Office Component Check
In Visual Studio 2005 Command Prompt, change the directory to {SamplesDir}\projects\Checks
cl.exe /Oxs /MT /GS ComponentCheck.cpp advapi32.lib
copy the executable file ComponentCheck.exe into {SamplesDir}\packages\Office2003PIA and {SamplesDir}\packages\Office2007PIA

1.2.3 Preparing for the Release of Office2007 Microsoft Office System Update: Redistributable Primary Interop Assemblies
http://www.microsoft.com/downloads/details.aspx?familyid=59daebaa-bed4-4282-a28c-b864d8bfa513
Copy O2007PIA.msi into the directory {SamplesDir}\packages\Office2007PIA

1.2.4 Copying the Packages into the Bootstrapper Directory
default Bootstrapper directory: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\BootStrapper\Packages
Copy the contents of the directory {SamplesDir}\packages into the bootstrapper directory.

1.3 Enhancing the Visio Add-in Setup Project

1.3.1 Signing the Assembly

1.3.2 Adding the Prerequisites to the Setup Project

1.3.3 Adding a Custom Action to Grant Trust to the Assembly

1.3.3.1 add the supplied SetSecurity project
copy the SetSecurity project from the {SamplesDir}\projects directory to the directory that contains your Addin solution.

1.3.3.2 add the primary output of the custom action project to the Setup project
Right click on Setup project --> View -->Custom Actions
In the Custom Actions editor, right-click Custom Actions --> Add Custom ActionIn the Look
In list, click Application Folder --> Add Output
The Add Project Output Group dialog box opens.
In the Project list, click SetSecurity.
Select Primary output from the list of output types --> OK.
Verify that Primary output from SetSecurity (Active) is added

1.3.3.3 add the custom action data for the Install method
In the Custom Actions editor, expand Install.Right-click Primary output from SetSecurity (Active) --> Properties Window.
In the Properties window, set the CustomActionData property to the following string. Enter this as one long string, and change MyCompanyName to your company name.
/assemblyName="MyVisioVSTOAddin.dll" /targetDir="[TARGETDIR]\" /solutionCodeGroupName="MyCompanyName.MyVisioVSTOAddin" /solutionCodeGroupDescription="Code group for MyVisioVSTOAddin" /assemblyCodeGroupName="MyVisioVSTOAddin" /assemblyCodeGroupDescription="Code group for MyVisioVSTOAddin" /allUsers=[ALLUSERS]

1.3.3.4 add the custom action data for the Rollback method
In the Custom Actions editor, expand Rollback.
Right-click Primary output from SetSecurity (Active) --> Properties Window.
In the Properties window, set the CustomActionData property to the following string:
/solutionCodeGroupName="MyCompanyName.MyVisioVSTOAddin"

1.3.3.5 add the custom action data for the Uninstall method
In the Custom Actions editor, expand Uninstall.Right-click Primary output from SetSecurity (Active) --> Properties Window.
In the Properties window, set the CustomActionData property to the following string:
/solutionCodeGroupName="MyCompanyName.MyVisioVSTOAddin"

1.3.4 Adding Launch Conditions to the Windows Installer File

1.3.4.1 add a launch condition for the VSTO 2005 SE runtimeIn the Launch Conditions editor, right-click Requirements on Target Machine --> Add Registry Launch Condition.
Select the newly added search condition, Search for RegistryEntry1.
Rename the search condition to Search for VSTO 2005 SE Runtime.
In the Properties window, change the value of Property to VSTORTVERSION.
Also in the Properties window, set the value of RegKey to the following string.
Software\Microsoft\vsto runtime Setup\v2.0.50727
Leave the Root property set to vsdrrHKLM and change the Value property to Update.
Select the newly added launch condition, Condition1.
Rename it to Display message if the Visual Studio 2005 Tools for Office SE Runtime is not installed.
In the Properties window, change the value of the Condition property to the following string.
VSTORTVERSION >= "#2"
Leave the InstallURL property blank.
Change the value of the Message property to The Visual Studio 2005 Tools for Office SE Runtime is not installed. Please run Setup.exe.

1.3.4.2 add a launch condition for the Visual Studio 2005 Tools for Office Language Pack
In the Launch Conditions editor, right-click Requirements on Target Machine --> Add Windows Installer Launch Condition.
Select the newly added search condition, Search for Component1.
Rename the search condition to Search for VSTO Language Pack.
In the Properties window, in the ComponentId property, type the following GUID:
{2E3A394E-C9BD-40C3-9990-BA7AF7C8B4AF}
Change the value of Property to COMPONENTEXISTS_VSTOLP.
Select the newly added launch condition, (Condition1).
Rename it to Display message if the Visual Studio 2005 Tools for Office Language Pack is not installed.
In the Properties window, change the value of the Condition property to COMPONENTEXISTS_VSTOLP.
Leave the InstallURL property blank.
Change the value of the Message property to The Visual Studio 2005 Tools for Office Language Pack is not installed. Please run Setup.exe.

1.4 Testing

References
1. Deploying Visual Studio 2005 Tools for Office Second Edition Solutions Using Windows Installer (Part 1 of 2)http://msdn2.microsoft.com/en-us/library/bb332051.aspx
2. Deploying Visual Studio 2005 Tools for Office Second Edition Solutions Using Windows Installer: Walkthroughs (Part 2 of 2)http://msdn2.microsoft.com/en-us/library/bb332052.aspx

关注者

软件开发技术相关