Snippets and info

A collection of useful bits of code, advice and informative advice

Sunday, July 25, 2004

Visual Studio / C# Express Tweaks Part 2: Project Assembly Settings

Following on from earlier where I talked about using FXCop with Visual C# Express (or indeed any other version of Visual Studio), I'm now going to quickly run through the top issues that FXCop will report with newly made assemblies (and indeed most mature assemblies). Specifically I'm talking about these:

  • CriticalError : Assemblies should have the CLSCompliantAttribute.
  • CriticalError : Assemblies should be marked with the ComVisible attribute.
  • CriticalError : Assemblies should have Permission Requests.

Where the rain gets in

So what are these issues and why do you get them free with your new projects? Well tackling them in order "CLSCompliant" does what it says on the tin - it enforces the Common Language Specification rules that allow an assembly to produce valid Common Language Runtime code (or IL - Intermediate Language). You might now be thinking: "Isn't C# built on top of the CLR , why does it need to say it's compliant?", well the answer is that C# isn't hundred percent compliant and in fact allows you to do some CLR no-nos. By specifying CLS Compliance Visual Studio (or at least your Compiler) will enforce the slightly stricter rules of the CLS.

Next up; ComVisible, basically this deals with Net objects in the Win32 world and to be honest if you don't know anything about this you should simply declare the attribute as false, as is indeed the Microsoft recommendation (it recommends marking the Assembly invisible and individual 'known good' Methods Visible).

Lastly Permission Requests; this is the implementation of an underused feature of the .Net Framework; the ability to declare the permissions that a program requires in order to run properly. Let me explain; in normal execution a .Net program will be constantly monitored by the framework, if your program attempts to execute a command it does not have sufficient rights for (due to where the program was run from or the user's security settings etc...) the framework will step in a stop execution. So do Permission Requests get you round this? No, but they allow you to declare up front what you want to be able to do and give the user an opportunity to trust your application and grant those rights (which is infinitely better than your program failing mid process). Now this is a very simple way of looking at security and the subject deserves a proper understanding (which I'm not going to do here), especially when you get to the cases of denying rights to third party code and of course "Click Once" (the .Net internet deployment platform).

So why aren't these preset for your new application? Short answer because the alternative is for Microsoft to second guess what you want from your program (think- "It looks like you're writing a letter?"), long answer - well that's what the MSDN is for.

Fixing a Hole.

So how do I sort these issues out? Well firstly ensure that they are issues. Occasionally you may wish to produce non CLS compliant code etc... Assuming this is not the case we can easily knock these off of FXCop's list.

The first thing to realise is that all of these settings are contained within your AssemblyInfo file that will be either in your project root or within the project Properties subfolder depending on your version (C# Express 2005 uses the Properties subfolder). AssemblyInfo contains metadata about the DLL or EXE that will be produced by your code you will see that it is prefilled with values regarding version numbering and such like. Now to the 'fixes':

Marking an Assembly as CLSCompliant:
[assembly: System.CLSCompliant(true)]

Marking an Assembly invisible to Com services:
[assembly:System.Runtime.InteropServices.ComVisible(false)]

Finally Assembly Permissions; to properly set security permissions you must work out every time you use a framework feature that relies upon a such a permission. So how do you work that out? Well fortunately Microsoft supply a tool called PermCalc with studio (there is an application called PermView for earlier versions), that will do the hard work for you. Less good is the fact it is a command line tool, but if you've read my previous article you'll know the goodness that is the External Tools section of the Visual Studio/C# Express Tool's menu:

Fire up Tools>ExternalTools... and fill in the following:

Title
Get Debug Permissions

Command*:
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PermCalc.exe

Argument**:
$(TargetDir)$(TargetName)$(TargetExt) -nologo -library

Check the "Use Output Window" option

*Change paths to reflect your own folder structure this is the default location
**If you're are setting permissions for a library rather than an exe add -Library to the command (you may want two commands, one for each mode)

Also note you'll need to do an initial 'build' for this to work (so that the assemblies are compilied).

Security permissions are complicated by the nature of what they do however once we know what permissions are needed they are easy enough to apply. Here are some examples of permissions set in the assemblyInfo.cs:

First add this using directive (with the others at the top of the file)
using System.Security.Permissions

Now we can add some permissions, lets use File IO permissions as an example.

Add request to access C:\
[assembly:FileIOPermissionAttribute(SecurityAction.RequestMinimum, Read="c:\\")]

Some quick notes: RequestMinimum states that for this program to run we need this permission (i.e. we can't run without it), other settings are RequestOptional (which states we can optionally run without the permission - note if you allow code that relies on this permission to be run when the request was denied a SecurityException will be thrown) also there is the RequestRefuse which will stop a assembly from having a permission even if it would normally be granted.

Also note the: Read="c:\\" section this is called a flag. Flags are present on many security permissions and allow for fine grain control of permissions (IOPermissions also feature the Write flag but visit the msdn for details on other flags). If you're wondering why the value is "c:\\" not "c:\" its because '\' is an escape character and thus needs itself to be escaped (confusing eh? again MSDN is your friend).

Now in addition to specific security permissions there are also PermissionSets which allow you to specify permissions on a large scale basis. Three main categories are available; Nothing, Execution, FullTrust. I'm not going to go into these in detail but here is how to request that you application is fully trusted at runtime.

A request for full permissions
[assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name="FullTrust")]

Due to the user's security settings this code may or may not run; typically code marked "FullTrust" will run from local machines, but not from Intranets and never from the Internet (unless that user is a very trusting individual).

Remember these settings are on a assembly by assembly basis i.e. for each project in your solution (if you made an empty project and thus don't have a AssemblyInfo.cs simply copy another one to the project, edit the appropriate settings and include it in the project).

In closing, this advice is equally valid for those using VB.net just remember to alter the syntax to reflect language differences. I hope this helps those with difficulties or those who are just curious about the inner workings of .Net assemblies.

8 Comments:

At 13 October 2005 23:39, Blogger Weedy said...

I found a lot of useful info about Msdn on your blog - thank you. I also have a new Msdn Tips blog - please click over and have a look

 
At 16 January 2007 09:48, Anonymous Anonymous said...

car insurance for mexico
instant car insurance quote
car insurance for mexico
car insurance cost
best car insurance quote
car insurance dallas
budget car insurance
best car insurance
progressive car insurance quote
california car insurance
cheap car insurance quote uk
compare car insurance rate
aa car insurance
car insurance cost
new york car insurance
car insurance canada
free car insurance quote
car insurance houston
direct line car insurance
discount car insurance
state farm car insurance
compare car insurance
diamond car insurance
car insurance rats
new york car insurance
aarp car insurance
car insurance chicago
buy car insurance online
car insurance chicago
general car insurance

http://cheap-car-insurance.quickfreehost.com

Random Keyword: :)
free car insurance quote

 
At 06 February 2007 04:22, Anonymous Anonymous said...

Thanks for your wonderful blog. I've learned alot about life insurance policy
here. I've got a little site which contains info about life insurance policy , as well
as a few other things. Please stop by
Thanks

 
At 13 February 2007 15:01, Anonymous Anonymous said...

Great blog very informative re home insurance quote uk. In a simliar vain to home insurance quote uk would definitely recommend http://www.bargainplace.co.uk for **cheap car insurance** or **cheap home insurance**, even **cheap pet insurance**

 
At 02 April 2007 16:08, Anonymous Anonymous said...

integro insurance brokers
oldsmobile cars for sale
insurance business card
car travel
real estate tennessee
warranty bill of sale
insurance terms defined
homes for sale san diego
protective life insurance company

 
At 03 August 2007 00:02, Anonymous Anonymous said...

In debt? consumer credit site offers help for bill consolidation loan and other consumer debt.

 
At 20 December 2007 15:14, Anonymous new house tx said...

companies marketing mineral makeups and also get the best bargains in mineral makeup you can imagine,
find aout how to consolidate your students loans or just how to lower your actual rates.,
looking for breast enlargements? in Rochester,
homeopathy for eczema learn about it.,
Allergies, information about lipitor,
save big with great bargains in mineral makeup,

change edition interviewing motivational people preparing second
,

interviewing motivational people preparing second time
,

interviewing people motivational preparing for a second time
,

black mold exposure
,

black mold exposure symptoms
,

black mold symptoms of exposure
,

free job interview questions
,

free job interview answers
,

interview answers to get a job
,

lookfor hair styles for fine thin hair
,

search hair styles for fine thin hair
,

hair styles for fine thin hair
,

beach resort in the philippines
,

great beach resort in the philippines
,

luxury beach resort in the philippines
,
iron garden gates, here,
iron garden gates,
wrought iron garden gates
, here
,
wrought iron garden gates
,
You: The Owner's Manual: An Insider's Guide to the Body That Will Make You Healthier and Younger
,
answer from more much,
eat eating mindless more than think we we why
,
la times classified,
new york times classified


texturizer,
texturizers here,
black hair texturizer,
find aout how care curly hair,
find about how to care curly hair,
care curly hair,
lipitor rash,
lipitor reactions,
new house ventura california,
the house new houston tx,
new house washington dc,
new house washington dc,
new house ventura california,
the house new houston tx,
the house new houston tx, that you ar looking for,
new house ventura california, you need to buy,
new house washington dc,

hair surgery transplant
,

air filter allergy
,

refurbished dell laptop computers
,

hair surgery transplant
,

air filter allergy
,

refurbished dell laptop computers
,

hair surgery transplant
,

air filter allergy
,

refurbished dell laptop computers
,

chocolate esophagus heartburn study
,

chocolate esophagus heartburn study
be informed,

digestion healing healthy heartburn natural preventing way
,

digestion healing healthy heartburn natural preventing way
,


Allergies, lipitor rash,
alcohol rash,
lipitor and alcohol,
lipitor alcohol,

natural remedies to aid healing of esophagus
,

chicory heartburn
,

effectiveness of zocor vs. lipitor
,

chocolate esophagus
,
southwestern wrought iron yard gate,
exterior iron gates,
oriental wrought iron gates,
powder coated iron garden fencing,

 
At 12 April 2008 12:21, Anonymous thin hair said...

black mold exposure,black mold symptoms of exposure,wrought iron garden gates,your next iron garden gates, here,hair styles for fine thin hair,search hair styles for fine thin hair,night vision binoculars,buy, night vision binoculars,lipitor reactions,lipitor reactions,luxury beach resort in the philippines,beach resort in the philippines,homeopathy for baby eczema.,homeopathy for baby eczema.,save big with great mineral makeup bargains,companies marketing mineral makeups,prodam iphone praha,Apple prodam iphone praha,iphone clone cect manual,manual for iphone clone cect,fero 52 binoculars night vision,fero 52 night vision,best night vision binoculars,buy, best night vision binoculars,computer programs to make photo albums,computer programs, make photo albums,free printable tax forms,printable tax forms, free here,craftmatic adjustable air bedcraftmatic adjustable air bed, info hereboyd night air bedboyd night air bed, low priceair bed in wisconsinbest air beds in wisconsincloud air inflatable bedbest cloud air inflatable bedsportable sealy air bedportables, sealy air bedsaluminum rv luggage racksaluminum made, rv luggage racksair bed form raisedbest air beds form raisedsupport equipments aircraftbest support equipments for aircraftsinformercials bed airbest, informercials bed airmattress sized air bedsbest mattress sized air bedantique doorknob identificationantique doorknob, identification tipstroubleshooting dvd playertroubleshooting with the dvd playerflat panel television lcd versus plasmaflat panel television, lcd versus plasma pic the bestcauses of economic recessionwhat are the causes of economic recessionbed air foam adjustablebed air adjustable foam hoof prints antique and unusual equestrian printshoof prints, antique equestrian printsbuy adjustable air bedbuy the best adjustable air bedsair bedscanadian storesair beds, cheap canadian stores

 

Post a Comment

<< Home