I recently got excited by the idea of statically check design by contract in .net 4.0 / Visual Studio 2010.
However I was saddened to find out that it will only be available in Visual Studio Team System. http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx
Are there any alternatives which give statically checked design by contract for c#?
Will the mono project be adding this functaionality to there compiler?
He's referring to the theorem prover.
There's nothing stopping the open-source or commercial community from implementing their own. The Contracts classes are part of the BCL and trivially easy to add to, say, Mono. "We'll" need to make a theorem prover if we want to statically check things.
The prover is not part of the compiler. It basically runs as follows:
Compile a version of the binary with CONTRACTS_FULL defined. This emits all Contract attributes and calls to the Contract class static methods.
Load the assembly "for reflection only," and parse all the method's byte code. A detailed flow analysis with state information will allow certain contracts to be shown "always true." Some will be "known false at some point." Others will be "unable to statically prove the contract."
As the tool gets better, it will go from giving warnings about every contract to eventually offering similar proving results to the Microsoft version.
Edit: Man, if Reflector was open sourced it would be great for this. A first-pass implementation could certainly operate as a plugin. That way the prover logic can be designed without worrying about how the binaries are loaded. Once it proves functional (get it?), the logic could be extracted and built to operate on the syntax trees produced by another assembly loader (one that is open source). The important/novel thing here is the prover logic - the assembly loader has been done multiple times and nothing changes spectacularly for this use.
Code contracts do not require the C# compiler as they are implemented as classes in the .NET Framework 4.0. Any .NET compiler that can emit a managed assembly is usable, although C++/CLI will likely emit an incompatible assembly when mixing managed and native code.
There are additional tools executed by the IDE to rewrite the resulting IL so that the contracts appear in the correct location, and thus the Mono project authors would need to write similar tools for contracts to work on the Mono platform.
See this post for more information.
Related
I'm developing a TypeScript code generator that will use custom attributes on C# classes to generate TypeScript definitions and code files.
I'm considering two options for TypeScript code generation / source file analysis:
Reflection on compiled assemblies
Roslyn CTP
The tool would use custom attributes on properties and methods to generate a TypeScript file. Right now I'm not planning to convert the C# method body to JavaScript, but in the future this may be done. So for this reason I am seriously considering Roslyn. However to simply generate the outline of my TypeScript classes I think I could use reflection and custom attributes.
I am wondering:
a) Does Roslyn provide functionality that is impossible with Reflection? My understanding is that I cannot get method bodies with Reflection.
b) Would the Roslyn CTP license prevent my from distributing the tool under an open source license? This is not clear to me after reading the license
I just did something along these lines - works great for creating your datamodel in Typescript from your c# classes. I built it to generate a single AMD-module with an interface which mimics the basic data of your Models. Also supports Generics, and creates a class with Knockout properties, including a toJS() method and an update(data:Interface) method to update your class.
The whole thing is just a single T4 template. If anyone finds this and is interested: http://spabuilder.wordpress.com/2014/07/31/generating-typescript-from-c/
Also honors [KeyAttribute] and [Timespan] attributes for data models if you are using data annotations.
I've been messing around with generating js, and I'm finding Reflection to be a better tool for this. I'm basically pointing my generator at the bin folder of the project which the metadata comes from. There might be some difficulties with loading all the needed assemblies, and caveats with versions of assemblies in the bin folder, and versions of the same assemblies that your generator project references. But once you get over all of this, which I did with minimal difficulty, Reflection is a lot easier to use, and more reliable.
With Roslyn, you are basically just parsing c#. Roslyn does this very well, but I'm hesitant to switch to it from Reflection. With reflection, you get metadata more reliably.
Let's say you want the Prefix property of a RoutePrefixAttribute that decorates a controller class. If you're parsing c#, you may have:
[RoutePrefix("stringliteral")] or [RoutePrefix(constantString)]. So, you have to worry about whether it's a literal or a constant expression, then find out how to get the value of a constant expression, worry about all the different ways in which you can pass parameters to an atatribute (for example, will this break your code: [RoutePrefix(Prefix="literal")]...
Once you're dealing with the actual runtime objects with reflection, everything is just easier. You have a nice RoutePrefixAttribute object, and you can go routePrefix.Prefix to get, reliably, the value of the prefix.
This is just one example of how doing things with Reflection is easier. It's the difference between gathering metadata from a set of c# objects in a type-safe way, and scraping data from c# code, albeit with a really nice scraping tool.
EDIT: Since writing this answer, I've bit the bullet and switched to Roslyn. It's fairly powerful once you get the hang of it, and I did find one big advantage: you can get a reference to the workspace from a visual studio plugin, and easily do all kinds of stuff within the plugin.
Update Nov, 2018
The accepted answer is valid because it's dated in Aprl,2013
Now roslyn is distributed under Apache License Version 2.0
excerpt from the license:
Redistribution.
You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You meet the following conditions:...
Roslyn have a number of nuget packages
Doesn't the license only forbid you personally from distributing the binaries? It doesn't forbid you from adding a dependency from your NuGet package to the Rosyln CTP NuGet package. You personally cannot deliver the bits, but you can have NuGet pull in Roslyn automatically.
So just avoid checking Rosyln source or binaries into your version control.
The Roslyn website not clearly states that:
The current license is for evaluation and preview purposes only and
does not allow redistribution of the Roslyn binaries. Sharing of
sample projects built on the Roslyn APIs is permitted, but sample
users must have either the Roslyn CTP or the Roslyn NuGet package
installed in order to build and run.
I wouldn't use the current Roslyn CTP - simply because there will be new versions in 2014 and those will bring many breaking changes for sure. So you might end up with totally deprecated code.
(There recently was a blog post on this by a MS team member, but I'm afraid I currently don't have the link at hand.)
EditThere's a good chance that Roslyn then will get a license that also permits for commercial use...
Update - July 2015
Roslyn is still in CTP, but their FAQ on GitHub is much more to the point:
For sample code or learning purposes, the recommended way to redistribute the Roslyn DLLs is with the Roslyn NuGet package: [url:Microsoft.CodeAnalysis|http://www.nuget.org/packages/Microsoft.CodeAnalysis].
So it appears that you still cannot redistribute the DLLs in finished products. The project will need to be open sourced and the solution will need a reference the NuGet package.
Original Answer (November 2012)
I don't believe you can distribute under open source.
6.DISTRIBUTABLE CODE. The software contains code that you are permitted to distribute in programs you develop if you comply with the
terms below.
6.c Distribution Restrictions you may not modify or distribute the source code of any Distributable Code so that any part of it becomes
subject to an Excluded License. An Excluded License is one that
requires, as a condition of use, modification or distribution,
the code be disclosed or distributed in source code form; or item
others have the right to modify it.
At first it sounds like you could do it if you just include the Roslyn binaries, but the Distributable Code definition specifically says "The software contains code..." and I believe that is what everything after is referring to.
To your other question, Roslyn isn't fully finished and is still Beta. I don't know exactly if it is currently in a state that allows it to handle your needs. That's something you may just want to spend a couple of hours tinkering with. I wouldn't think it had more functionality than what .NET currently allows. You can see what they recently added in September here and what is currently not implemented here.
For my experience using T4 generations based on reflection, as TypeLite does, is somehow simpler but has some drawbacks, like once the project depends on the classes that have been generated, regenerating them with a breaking change (renamed a class) will lead to a non compiling project so running the template again will output a blanck file and the user will have an hard time making everything compile again.
So, having the same need, i started experimenting with Roslyn, and it seems very promising, but i have many doubts on how to use it properly...
You can take a look at what i'm doing and maybe help me here: https://github.com/TrabacchinLuigi/RoslynExporter
I've been trying to apply code protection using the SmartAssembly obfuscator to a WPF Prism application, but it the application refuses to work properly when being obfuscated.
The only option that works for it is: Prevent Microsoft IL Disassembler from opening my assembly.
The Red-Gates help describes it as: SmartAssembly can add an attribute to your assembly that prevents Microsoft's Common Intermediate Language (IL) Disassembler (ildasm.exe) from opening your assembly.
I wonder how serious is this protection, is it worth to be applied if the code isn't really obfuscated.
Or, in other words, what is it this Microsoft's Common Intermediate Language (IL) Disassembler (ildasm.exe)? Is it the main part of every known .NET reverse engineering tool or is it just one of the many such tools?
ildasm.exe is the IL disassembler that comes with the .Net Framework. It's the one tool that everyone has if they have .Net. It's not a component, so other disassemblers are not based on it or anything.
The attribute in question is the SuppressIldasmAttribute. I do not know if other disassemblers such as Reflector or ILSpy respect this attribute, but I doubt it. A cursory Google search suggests that is not the case, and that the SuppressIldasmAttribute only affects ildasm.exe itself.
As such, it doesn't really protect your assembly and isn't much use as an obfuscation tool. But if you are obfuscating anyway, I don't see any reason why you wouldn't apply this attribute, as it at least blocks the easiest (most commonly available) method of disassembly and I don't think it does any harm.
This is question is inspired by the question: In what areas does F# make "absolute no sense in using"?
In theory, it should be possible to use any .NET supported language in a single project. Since every thing should be compiled into IL code, then linked into a single assembly.
Some benefits would include the ability to use say F# for one class, where F# is more suited to implement it's function, and C# for another.
Is there some technical limitation I'm overlooking that prevents this sort of setup?
A project is restricted to a single language because, under the hood, a project is not much more than an MSBuild script which calls one of the command-line compilers to produce an assembly from the various source code files "contained" in the project folder. There is a different compiler for each language (CSC.exe is for example the one for C#), and what each project has to do to turn its "contained" source code into an assembly differs with each language.
To allow multiple languages to be compiled into a single assembly, the project would basically have to produce an assembly for each language, then IL-Merge them. This is costly, requires complex automation and project file code generation, and in most circumstances it's a pretty fringe need, so the VS team simply didn't build it in.
While projects are restricted to a single language, a solution is not... and solutions can contain multiple projects.
As others mentioned, a project is a stand-alone unit that is compiled by a single compiler.
I hear the question about including e.g. one F# type in a larger C# project quite often, so I'll add some details from the F# specific point of view. There are quite a few technical problems that would make it really difficult to mix F# and C# in one project:
C# compiler sees all classes, while F# type declarations are order-dependent. I'm not sure how would you even specify what types should the F# code see at which point.
F# compiler needs to know how declarations are used in order to infer types. Would it also get usage information from the C# compiler?
The two compilers use different representation of types. When compiling, there are no System.Type information, so how would they share the information? (Both of them would need to agree on some common interface that allows them to include language-specific information - and the information may be also incomplete).
I think this is enough to explain that doing this is not just a feature that may or may not be done depending on the schedule. It is actually an interesting research problem.
For what it's worth, it's possible to have ASP.NET projects that use C# and VB.NET (or anything else, you define the compilers in web.config), just in different files.
All code files are processed by a single compiler. That's why a project can only contain a single language.
Mixing languages may not make much sense either, since each language generates it's own IL.
This of course doesn't restrict you form having multiple projects from different langauges in the same solution, since each project is compiled independently
Consider using ILMerge if you want to maintain a single .exe or .dll built by a number of different compilers.
Technically, you can mix languages in a single project, if one (or more) of those languages are scripting languages. See How to use Microsoft.Scripting.Hosting? for more details.
I know this isn't what you were talking about, but it's a little fun fact if you weren't aware.
The project file is nothing but an elevated list of command line parameters to the relevant compiler. A file with the extension of .csproj contains the parameters for a C# compiler, .vbproj for the VB.NET compiler and so on.
You can however create two or more projects in the same solution file, one for each language and then link them together in one exe file using ILMerge.
I tried to use code protection (code is encrypted and can't be reflected) made by clisecure with postsharp but secured dlls won't compile when post sharp is used in solution. I use just PostSharp.Laos and PostSharp.Public
Have You ever tried such combination? Did you manage to make it work. If so please tell what obfuscation tool and what code weaving framework have you been using?
I have successfully used Dotfuscator and Postsharp in combination but only with the compile time IL Weaving and not yet with any runtime interception. Everything should be fairly straightforward as long as you obfuscate the binary that PostSharp post-compilation weaving outputs.
The usual obfuscation caveats apply to any of your cross cutting code (especially where you use reflection) as obfuscation changes symbol names and you will need to exclude any symbols from being renamed or pruned that will be reflected upon or that use late binding.
There are some tricks when using an obfuscator. For instance, you cannot change the name of aspect types and fields of aspect types because aspect are serialized by PostSharp and deserialized at runtime. You may want to use obfuscation exceptions for aspects.
Another issue is that you cannot rename some methods that are the target of aspects. I think this happens only with generic methods or methods of generic types.
An alternative is to use an obfuscator that does not rename the code, such as WIBU. I did not try, however.
Something I'm not to clear about, I understand there are differences between C# and VB.NET (mainly in the use of pointers) but why if both have a Common CLR, does XNA (for example) only work with C# and not VB.NET, or is it that the add ins to visual studio have been aimed at C# rather than VB.Net, and infact the language extensions work in both
Sorry if it's a obvious question, thought I'd ask
It's the tool set that defines the language support. XNA, for example, simply did all their work with C# and only shipped support for it. You could still write an app in VB.NET and manually compile it from the command line. As long as your app didn't compile down to any illegal IL (opcodes that XNA doesn't support) it will still run. The primary issue is resources - they don't have the manpower to do full development and testing of all of the languages, so they picked one.
The CLR has been ported to various platforms, not all of which are equal. The XBox 360 CLR, for instance, does not have Reflection.Emit or even all of the IL ops that the full CLR does. Hence, a different compiler may emit IL codes that are legal on the full CLR, but illegal on the Compact CLR.
The other issue is the availability of class libraries. The full BCL includes the Microsoft.VisualBasic namespace, which is automatically referenced by the VB.NET compiler. This contains VB6 compatibility functions, the My namespace features, as well as some compiler helper functions, and is commonly referred to as the VB.NET runtime.
Whenever the CLR is ported, certain assemblies are ported - and others are not. For the XBox, Microsoft.VisualBasic was not ported. This means that you cannot reference anything from that namespace. While it's fairly easy to not reference the compatibility or My namespaces, the compiler services can be inserted into the compiled IL without you explicitly calling them.
In VB.NET 8, you could pass an undocumented and unsupported -novbruntimeref switch to vbc.exe to keep it from referencing Microsoft.VisualBasic.dll. Unfortunately, this would sometimes cause odd compiler errors. In VB.NET 9, it's become documented and supported and renamed to /vbruntime.
The 3rd case is addins and Visual Studio support. This is up to the individual packages, as to whether they support templates, code gen, etc. for each language. I believe some 3rd parties have released VB.NET templates for XNA, though it's not officially supported.
Bottom line, I guess, is that it's a mix of technical concerns (CLR ports, BCL availability, compiler IL output) and support (testing, funding, and addins for other languages).
From all accounts VB.NET and C# are 99.9999 equivalent when it comes to the CLR. But there are some slight differences that may bite you. In addtion I remember reading on some microsoft blog that there are some things the CLR can do that are not (yet) programmable by either VB.NET or C# and have to be done by IL. Interesting indeed.