ssms tools pack unauthorized access exception - sql-server

Just installed tools pack for ssms 2008
http://www.ssmstoolspack.com/Download
Keep seeing this on start up, most functions appear to work fine, just really annoying, cannot figure out what it's trying to do that is so bad, I'm running this as Administrator, still doesn't fix the error...
Exception Type:System.UnauthorizedAccessException
Error Messsage:
Attempted to perform an unauthorized operation.
Extra Data:
- Method: SSMSToolsPackC10.dll.WindowColoring.InitialLoadServersToSettings
Error StackTrace:
at System.Security.AccessControl.Win32.SetSecurityInfo(ResourceType type, String name, SafeHandle handle, SecurityInfos securityInformation, SecurityIdentifier owner, SecurityIdentifier group, GenericAcl sacl, GenericAcl dacl)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, SafeHandle handle, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, AccessControlSections includeSections, Object exceptionContext)
at System.Security.AccessControl.NativeObjectSecurity.Persist(String name, AccessControlSections includeSections)
at System.Security.AccessControl.FileSystemSecurity.Persist(String fullPath)
at System.IO.File.SetAccessControl(String path, FileSecurity fileSecurity)
at System.Configuration.Internal.WriteFileContext.DuplicateTemplateAttributes(String source, String destination)
at System.Configuration.Internal.WriteFileContext.DuplicateFileAttributes(String source, String destination)
at System.Configuration.Internal.WriteFileContext.Complete(String filename, Boolean success)
at System.Configuration.Internal.InternalConfigHost.StaticWriteCompleted(String streamName, Boolean success, Object writeContext, Boolean assertPermissions)
at System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext, Boolean assertPermissions)
at System.Configuration.Internal.DelegatingConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext, Boolean assertPermissions)
at System.Configuration.ClientSettingsStore.ClientSettingsConfigurationHost.WriteCompleted(String streamName, Boolean success, Object writeContext)
at System.Configuration.UpdateConfigHost.WriteCompleted(String streamName, Boolean success, Object writeContext)
at System.Configuration.MgmtConfigurationRecord.SaveAs(String filename, ConfigurationSaveMode saveMode, Boolean forceUpdateAll)
at System.Configuration.Configuration.SaveAsImpl(String filename, ConfigurationSaveMode saveMode, Boolean forceSaveAll)
at System.Configuration.Configuration.Save()
at System.Configuration.ClientSettingsStore.WriteSettings(String sectionName, Boolean isRoaming, IDictionary newSettings)
at System.Configuration.LocalFileSettingsProvider.SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection values)
at System.Configuration.SettingsBase.SaveCore()
at System.Configuration.SettingsBase.Save()
at System.Configuration.ApplicationSettingsBase.Save()
at p.e()
--------------- Filtered Assemblies ---------------
PostSharp
Full Name: PostSharp, Version=3.1.49.9, Culture=neutral, PublicKeyToken=b13fd38b8f9c99d7
File Path: C:\Program Files (x86)\SSMS Tools Pack\SSMS Tools Pack 2008\PostSharp.dll
File Version: 3.1.49.0
SSMSToolsPack10
Full Name: SSMSToolsPack10, Version=3.2.2.0, Culture=neutral, PublicKeyToken=a49c9b5533ef3445
File Path: C:\Program Files (x86)\SSMS Tools Pack\SSMS Tools Pack 2008\SSMSToolsPack10.dll
File Version: 3.2.2.0
SSMSToolsPackB10
Full Name: SSMSToolsPackB10, Version=3.2.2.0, Culture=neutral, PublicKeyToken=a49c9b5533ef3445
File Path: C:\Program Files (x86)\SSMS Tools Pack\SSMS Tools Pack 2008\SSMSToolsPackB10.dll
File Version: 3.2.2.0
SSMSToolsPackC10
Full Name: SSMSToolsPackC10, Version=3.2.2.0, Culture=neutral, PublicKeyToken=a49c9b5533ef3445
File Path: C:\Program Files (x86)\SSMS Tools Pack\SSMS Tools Pack 2008\SSMSToolsPackC10.dll
File Version: 3.2.2.0

This error indicates you don't have write permissions on the folder:
C:\Users\YourUserName\AppData\Local\Microsoft_Corporation\DefaultDomain_Path_LongAlphaNumericSequenceHere\10.50.xxxx.x\
And it can't save the settings.
As for the other stuff, email me through the website and we can talk further.

Related

WPF to UWP Visual Studio conversion build error

im following this msdn tutorial to covert my WPF to UWP
I go this build error when trying to build the app.
Severity Code Description Project File Line Suppression State
Error MSB4018 The "GenerateResource" task failed unexpectedly.
System.InvalidOperationException: Item named 'themes/lightbrushes.baml' of
type 'System.IO.UnmanagedMemoryStream' cannot be added to the resource file
because it is not serializable.
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(ReaderInfo
reader, IResourceWriter writer)
at Microsoft.Build.Tasks.ProcessResourceFiles.WriteResources(ReaderInfo
reader, String filename)
at Microsoft.Build.Tasks.ProcessResourceFiles.ProcessFile(String inFile,
String outFileOrDir)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log,
ITaskItem[] assemblyFilesList, List`1 inputs, List`1 satelliteInputs, List`1
outputs, Boolean sourcePath, String language, String namespacename, String
resourcesNamespace, String filename, String classname, Boolean publicClass,
Boolean extractingResWFiles, String resWOutputDirectory)
at Microsoft.Build.Tasks.ProcessResourceFiles.Run(TaskLoggingHelper log,
ITaskItem[] assemblyFilesList, List`1 inputs, List`1 satelliteInputs, List`1
outputs, Boolean sourcePath, String language, String namespacename, String
resourcesNamespace, String filename, String classname, Boolean publicClass,
Boolean extractingResWFiles, String resWOutputDirectory)
at Microsoft.Build.Tasks.GenerateResource.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecution
Host.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.
<ExecuteInstantiatedTask>d__26.MoveNext() Deployment.Bridge C:\Program
Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\VisualStudio\v15.0\AppxPackage\Microsoft.AppXPackage.Targets 1251
Note that 'themes/lightbrushes.baml' is not part of the app files
Any help is greatly appreciated
I've seen a similar behavior while trying to convert satellite assemblies to PRIs.
You can try to disable this adding the next property to your jsproj file:
<AppxGeneratePrisForPortableLibrariesEnabled>false</AppxGeneratePrisForPortableLibrariesEnabled>

MsDeploy with DbDacFx provider and Database reference

We are using DbDacFx provider to sync our production machine.
We have ssdt database project in our solution that we deploy along with our website.
The A.sqlproj has references to master.dacpac and another database project's dacpac, say X.dacpac.
All dacpacs are in same location for deployment.
When we try to deploy the A.dacpac we get errors as below:
Info: Deploying package to database: Faulted. Error: The reference to external elements from the source named 'X.dacpac' could not be resolved, because no such source is loaded. Error: The reference to external elements from the source named 'master.dacpac' could not be resolved, because no such source is loaded. .....above errors repeated multiple times..... An error occurred when the request was processed on the remote computer. Error: Exception has been thrown by the target of an invocation. ---> System.Exception: Member 'ClassName' was not found. at System.Runtime.Serialization.SerializationInfo.GetElement(String name, Type& foundType) at System.Runtime.Serialization.SerializationInfo.GetString(String name) at System.Exception..ctor(SerializationInfo info, StreamingContext context) --- End of inner exception stack trace --- at System.RuntimeMethodHandle._SerializationInvoke(Object target, SignatureStruct& declaringTypeSig, SerializationInfo info, StreamingContext context) at System.Runtime.Serialization.ObjectManager.CompleteISerializableObject(Object obj, SerializationInfo info, StreamingContext context) at System.Runtime.Serialization.ObjectManager.FixupSpecialObject(ObjectHolder holder) at System.Runtime.Serialization.ObjectManager.DoFixups() at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage) at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, IMethodCallMessage methodCallMessage) at Microsoft.Web.Deployment.Base64EncodingHelper.DeserializeHelper(BinaryFormatter formatter, Byte[] buffer) at Microsoft.Web.Deployment.Base64EncodingHelper.Deserialize(String str, Exception& handledException) at Microsoft.Web.Deployment.SerializationHelper.Deserialize(String str) at Microsoft.Web.Deployment.SqlDacPacProvider.ProcessExeOutput() at Microsoft.Web.Deployment.SqlDacPacProvider.RunExecutableAsync(String exeName, String arguments, Int32 waitInterval, Int32 retryAttempts) at Microsoft.Web.Deployment.SqlDacPacProvider.Add(DeploymentObject source, Boolean whatIf) at Microsoft.Web.Deployment.DeploymentObject.Add(DeploymentObject source, DeploymentSyncContext syncContext) at Microsoft.Web.Deployment.DeploymentSyncContext.HandleAdd(DeploymentObject destObject, DeploymentObject sourceObject) at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildren(DeploymentObject dest, DeploymentObject source) at Microsoft.Web.Deployment.DeploymentSyncContext.SyncChildrenOrder(DeploymentObject dest, DeploymentObject source) at Microsoft.Web.Deployment.DeploymentSyncContext.ProcessSync(DeploymentObject destinationObject, DeploymentObject sourceObject) at Microsoft.Web.Deployment.DeploymentObject.SyncToInternal(DeploymentObject destObject, DeploymentSyncOptions syncOptions, PayloadTable payloadTable, ContentRootTable contentRootTable, Nullable1 syncPassId) at Microsoft.Web.Deployment.DeploymentAgent.HandleSync(DeploymentAgentAsyncData asyncData, Nullable1 passId) Error: Member 'ClassName' was not found. at System.Runtime.Serialization.SerializationInfo.GetElement(String name, Type& foundType) at System.Runtime.Serialization.SerializationInfo.GetString(String name) at System.Exception..ctor(SerializationInfo info, StreamingContext context) Error count: 1.
Need to know how we can overcome the issues.
Thanks
Yatin.
Do the referenced dacpacs exist on the machine that is running the deploy?
If they do the easiest is to copy the dacpacs into the same folder as the dacpac you are deploying as the same directory will be checked, failing that the original path that contained the original dacpac.
This is still a pain.
We plan on scripting the sqlpackage.exe file command through runCommand provider and get automation going !!
Closing the question.
Thanks

Error after upgrading from DNN 7.0 to 7.4.1 (Version Upgrade package)

After completing an upgrade to DNN 7.4 I get the error outlined below. Everything went smoothly and there were no errors in the install log. This happens on any page, and there are no new dependencies on Visual Studio I presume...
2015-06-12 17:43:49,567 [scrumorg-stage][Thread:5][ERROR] DotNetNuke.Common.Internal.EventHandlersContainer`1[[DotNetNuke.Services.FileSystem.IFileEventHandlers, DotNetNuke, Version=7.4.1.280, Culture=neutral, PublicKeyToken=null]] - The type initializer for 'DotNetNuke.ExtensionPoints.ExtensionPointManager' threw an exception.
System.TypeInitializationException: The type initializer for 'DotNetNuke.ExtensionPoints.ExtensionPointManager' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.ModuleHandle.ResolveTypeHandle(Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Int32 attributeCtorToken, Boolean mustBeInheritable)
at System.Reflection.CustomAttribute.IsDefined(RuntimeType type, RuntimeType caType, Boolean inherit)
at System.ComponentModel.Composition.AttributedModel.AttributedPartCreationInfo.IsPartDiscoverable()
at System.ComponentModel.Composition.AttributedModel.AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(Type type, ICompositionElement origin)
at System.ComponentModel.Composition.Hosting.TypeCatalog.get_PartsInternal()
at System.ComponentModel.Composition.Hosting.TypeCatalog.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at DotNetNuke.ExtensionPoints.SafeDirectoryCatalog..ctor(String directory)
at DotNetNuke.ExtensionPoints.ExtensionPointManager.InitializeMefCompositionContainer()
at DotNetNuke.ExtensionPoints.ExtensionPointManager..cctor()
--- End of inner exception stack trace ---
at DotNetNuke.ExtensionPoints.ExtensionPointManager.ComposeParts(Object[] attributeParts)
at DotNetNuke.Common.Internal.EventHandlersContainer`1..ctor()
Any ideas what I'm missing or what might be happening?
So this issue ended up being a custom DLL found in the BIN folder of the DNN website that Ryan was upgrading.
My non-scientific approach to resolving this was to:
Remove DLLS in bulk in the BIN folder (keep a copy of the DLLs as you aren't sure which one is the problem, put them back after testing)
Load the site (using admin/site settings page)
See if page still errored, if so, repeat steps 1 and 2
Ends up the DLL that was causing the problem was I believe a webservice/api URL for testing. Removing that corrected the issue on the 7.3.4 instance of DNN that they were using.

SQL Server 2012 installation error: Landing Page

After uninstalling SQL Server 2012 and 2008, then reinstalling, I get this error:
Unhandled exception has occurred in your application...
An error occurred creating the configuration section handler for userSettings/Microsoft.SqlServer.Configuration.LandingPage.Properties.Settings:
See the end of this message for details on invoking just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handler for userSettings/Microsoft.SqlServer.Configuration.LandingPage.Properties.Settings: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified. (C:\Users\hy\AppData\Local\Microsoft_Corporation\LandingPage.exe_StrongName_ryspccglaxmt4nhllj5z3thycltsvyyx\10.0.0.0\user.config line 5) ---> System.IO.FileNotFoundException: Could not load file or assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' or one of its dependencies. The system cannot find the file specified.
File name: 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
at System.Configuration.TypeUtil.GetTypeWithReflectionPermission(IInternalConfigHost host, String typeString, Boolean throwOnError)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.Init(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.InitWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord)
at System.Configuration.RuntimeConfigurationRecord.CreateSectionFactory(FactoryRecord factoryRecord)
at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
--- End of inner exception stack trace ---
at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.ClientSettingsStore.ReadSettings(String sectionName, Boolean isUserScoped)
at System.Configuration.LocalFileSettingsProvider.GetPropertyValues(SettingsContext context, SettingsPropertyCollection properties)
at System.Configuration.SettingsBase.GetPropertiesFromProvider(SettingsProvider provider)
at System.Configuration.SettingsBase.GetPropertyValueByName(String propertyName)
at System.Configuration.SettingsBase.get_Item(String propertyName)
at System.Configuration.ApplicationSettingsBase.GetPropertyValue(String propertyName)
at System.Configuration.ApplicationSettingsBase.get_Item(String propertyName)
at Microsoft.SqlServer.Configuration.LandingPage.LandingPageForm.OnLoad(EventArgs e)
at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
at System.Windows.Forms.Control.CreateControl()
at System.Windows.Forms.Control.WmShowWindow(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Delete the
C:\Users\hy\AppData\Local\Microsoft_Corporation\LandingPage.exe_StrongName_ryspccglaxmt4nhllj5z3thycltsvyyx\
directory, and try again.
I believe the uninstall sometimes does not clean up the files completely.
Search in this folder:
C:\Users\user_name\AppData\Local\Microsoft_Corporation
There you will find files or folders like
LandingPage.exe,
or
LandingPage.
Delete all these folders.
Works for Windows 10.
You should be able to find it if you search for %localappdata%\Microsoft_Corporation%
Rename the user.config file located at
C:\Users[USER_NAME]\AppData\Local\Microsoft_Corporation\LandingPage.exe_StrongName_ryspccglaxmt4nhllj5z3thycltsvyyx\10.0.0.0
to
USER.CONFIG.BAK
Delete this Folder C:\Users\yourName\AppData\Local\Microsoft_Corporation\LandingPage.exe_StrongName_ryspccglaxmt4nhllj5z3thycltsvyyx\
Run the command: rd /s /q %localappdata%\Microsoft_Corporation1as

Code Access Security in Reporting Services 2008

I have a Delivery Extension running inside Reporting Service 2008.
It has been running fine for a long time. But now I want to make an insert into a database from within the extension.
First error I got, was this:
Exception: System.Security.SecurityException Exception Message: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. Stacktrace: at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
at System.Security.PermissionSet.Demand()
at System.Data.Common.DbConnectionOptions.DemandPermission()
at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
at System.Data.SqlClient.SqlConnection.Open()
Then I added this, before my code that opens the connection and does the insert:
SqlClientPermission sqlPermission = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted);
sqlPermission.Assert();
Then the error message changed to this:
Exception: System.Security.SecurityException Exception Message: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed. Stacktrace: at System.Security.CodeAccessSecurityEngine.CheckNReturnSO(PermissionToken permToken, CodeAccessPermission demand, StackCrawlMark& stackMark, Int32 unrestrictedOverride, Int32 create)
at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Assert()
Then I added the following line:
SecurityPermission permission = new SecurityPermission(PermissionState.Unrestricted);
permission.Assert();
And now the error I get is this:
Exception: System.Security.SecurityException Exception Message: Stack walk modifier must be reverted before another modification of the same type can be performed. Stacktrace: at System.Security.CodeAccessSecurityEngine.Assert(CodeAccessPermission cap, StackCrawlMark& stackMark)
at System.Security.CodeAccessPermission.Assert()
My code that contains the actual SqlConnection specific code is in an assembly referenced from the Delivery Extension. The Permission specific code was inside that assembly, but I tried moving it into the Delivery Extension assembly - but wothout any luck.
user407428 is correct, trying to enable two different modifiers is what is causing your problem. The best principle is to allow the permission for the part of the code that requires it, and then to disable the permission afterwords. So that when you need the next permission you can modify those rights again.
SqlClientPermission sqlClientPermission = new SqlClientPermission(PermissionState.Unrestricted);
sqlClientPermission.Assert();
//<your code that requires SqlClientPermission here>
CodeAccessPermission.RevertAccess();
SecurityPermission securityPermission = new SecurityPermission(PermissionState.Unrestricted);
securityPermission.Assert();
Some more things to take into account is that it is mostly not required to keep an object to the stack-walk, so the assert can be simplified to a single line, ei.
System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
If you modified the stack-walk in a encapsulating method, the inner stack would probably not be able to modify the modifiers again. Ex.
public void UseSecurityPermission()
{
CodeAccessPermission.RevertAssert();
new System.Security.Permissions.SecurityPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
<Some code that requires the SecurityPermission>
}
static void Main(string[] args)
{
new System.Security.Permissions.FileIOPermission(System.Security.Permissions.PermissionState.Unrestricted).Assert();
//< Some code that requires IOPermission>
UseSecurityPermission();
}
Even though UseSecurityPermission() reverts the stack-walk permission, it would not work, because the compiler can't get the security descriptor in the context.
Some further reading:
Programming with Stack-Walk Modifiers
At the point you are trying to modify the access permissions you may already have inherited it from higher level, or maybe you have done it somewhere before the point you are.
For example we have code like this:
SqlClientPermission sqlClientPermission = new SqlClientPermission(PermissionState.Unrestricted);
sqlClientPermission.Assert();
SecurityPermission securityPermission = new SecurityPermission(PermissionState.Unrestricted);
securityPermission.Assert();
We will have the exception like yours.

Resources