A Practical Guide to SharePoint 2013

A Practical Guide to SharePoint 2013
A Practical Guide to SharePoint 2013 - Book by Saifullah Shafiq

Thursday, September 6, 2007

Using caspol.exe to add assemblies to full trust assembly list

Code Access Security Policy Tool (Caspol.exe) can be used to modify security policy for different policy levels. You can use it to add an assembly to the full trust assembly list for a specific policy level. Security exception is common when you try to run your application from a network share. See following article for more details:
You also get stuck sometimes when you try to deploy your application to a local folder. See following article for details:
In this tip, I will show you how you can use caspol.exe to add your assembly to a full trust assembly list.
caspol.exe is located in the following directory:
Use the following command to put an assembly to the trust: 
caspol.exe -u -addgroup All_Code -url "*"  FullTrust -name "Your Assembly Name"
Assembly name will be like "YourCompany.ApplicationName" (without extension)
Suppose, you are deploying your application on a remote machine using a script. How will you run the caspol.exe tool on the remote machine? One way is to create a batch file and run it programmatically on the remote machine after copying the assembly to that machine. Create a batch file and copy the following in the file:
caspol.exe -polchgprompt off -u -addgroup All_Code -url "*"  FullTrust -name "MyAssembly"
caspol.exe -polchgprompt on
polchgprompt option enables or disables the prompt that is displayed whenever Caspol.exe is run using an option that would cause policy changes. addgroup adds a new code group to the code group hierarchy. For more details, see following article:
Now, call this batch file programmatically from your deployment application.
string tempFolder = Environment.GetEnvironmentVariable("Temp");
FileStream fyle = new FileStream(tempFolder + "file://errlog.txt",FileMode.Create,FileAccess.Write/);
StreamWriter sw = new StreamWriter(fyle);
sw.Write("Ready to run the batch file!");
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = Environment.CurrentDirectory + "\security.bat";
sw.Write("security.bat ran successfully!");
Remember, this can be a unattended installation, so you  may want to log errors. You can log errors to the Windows log file. You can also create your own text file for logging errors, as shown in the code above. The code creates "errlog.txt" file in the Windows' Temp directory and then executes the batch file. This code does not show how to trap and log errors, you can simply use try ... catch blocks to write the errors in the text file.
Using this technique you can put assemblies to a list of full trust assemblies.