How to use WiX preprocessor pragmas? - wix

I'm currently working on a test WiX project to see what I can do with it.
Recently, I've stumbled upon the fact that I can override the ProcessPragma method in my preprocessor extension to write WiX source code at compile time. Having a preprocessor function that returns an xml string without the compiler going berserk sounds neat. So I looked into it, but the response in this wix-users thread is quite brief and doesn't explain much. Google doesn't return anything interesting beyond that. So I dug through the WiX source code to learn more.
The xml documentation for the method is as follows:
/// <summary>
/// Processes a pragma defined in the extension.
/// </summary>
/// <param name="sourceLineNumbers">The location of this pragma's PI.</param>
/// <param name="prefix">The prefix of the pragma to be processed by the extension.</param>
/// <param name="pragma">The name of the pragma.</param>
/// <param name="args">The pragma's arguments.</param>
/// <param name="writer">The xml writer.</param>
/// <returns>false if the pragma is not defined.</returns>
/// <comments>Don't return false for any condition except for unrecognized pragmas.
Throw errors that are fatal to the compile. use core.OnMessage for warnings and messages.</comments>
So as a test, I had the XmlWriter produce a dummy property and then return true.
Now, to actually call it in my WiX project. In Preprocessor.cs, I found the following:
switch (reader.NodeType)
{
case XmlNodeType.ProcessingInstruction:
switch (reader.LocalName)
{
// other cases such as define, include, foreach,
// and other preprocessor directives
case "pragma":
this.PreprocessPragma(reader.Value, writer);
break;
}
break;
Which hinted that the syntax for using a pragma would be: <?pragma prefix.name?>
But this gives me the following warning: The pragma 'prefix.name' is unknown. Please ensure you have referenced the extension that defines this pragma.
I have a feeling I'm on the right track, as it gives me a warning related to pragmas, but I honestly have no clue what I'm doing here. It seems like it's uncharted territory.
Does anyone know what I'm doing wrong, or point me in the right direction?
UPDATE
Seems like my project was the problem. I used my extension in another project and it worked like a charm.
And for anyone reading this in the future, the syntax is <?pragma prefix.name args?> where the arguments are just a string. And as a side note, you don't close the XmlWriter in your override method.

First, ensure you are passing the -ext path\to\YourPragmaExtensionAssembly.dll to candle.exe. Candle will load your extension, look for the AssemblyDefaultWixExtension attribute that points to the class that inherits from WixExtension, then ask for your PreprocessorExtension class if you override the PreprocessorExtension property.
It's a little bit of wiring up that could be simplified in future versions (like v4.0) of the WiX toolset. But there is an example in the WiX v3.x toolset at: src\ext\PreProcExampleExtension\wixext that should show the way.

Related

Add path to Current AppDomain

I have two completely different directories. Directory 1 contains my application and Directory 2 having few assemblies. During run-time when application launches, I will load the assemblies. By default, the executing Assembly's AppDomain will discover the assemblies in Directory 1 (application folder) or GAC. If the file is not there, we will get the error. But I have to extend the AppDomain's search directory to search in Directory 2 also. That is, AppDomain will search Directory1 (local bin), then GAC, then other defaults at last search in Directory 2.
I have tried :
1. By setting PrivateBinPath, but it is restricted only within ApplicationBaseDirectory.
2. By AssemblyResolve, but it is not directly referenced. The AssemblyResolve code never hits also.
Using the AssemblyResolve event is generally the correct way. If it is never hit, it is probably bound to too late. For instance, when the CLR encounters a method, it will compile it completely, resolving all its references. If such resolution fails, it will fail always. If you bind the AssemblyResolve event after any or all assemblies failed binding, the event will never hit.
To resolve this, make sure that the AssemblyResolve event is bound as early as possible. In an executable this is easy enough (first thing in the entry point of your application, or any cctor of a type you use there). In a library this can be harder, best practice approach is to use the module initializer, which is run whenever a module is loaded (most assemblies contain one module).
Since the module initializer cannot be set by C# or any other .NET language I know of, you have to resort to method weaving. I personally like Fody and as it turns out, there's a predefined Fody package called Fody Module Init for exactly this thing.
Just place, somewhere publicly in your library, the following code:
public static class ModuleInitializer
{
public static void Initialize()
{
// bind to the CurrentDomain.AssemblyResolve event
}
}
Fody also works with other languages (you don't specify which you use), but then you'll have to create the static ModuleInitializer class by hand.
Using this approach, you can be certain that the AssemblyResolve event will be called for any assembly that CLR's Fusion cannot find by itself.

Find Self-Referential Code in IntelliJ

In IntelliJ when code is not used anywhere it will be "grayed out." Is there any way to see if a set of classes aren't used anywhere?
I have this set of classes with references to each other so IntelliJ is counting this set of classes as being used. In this case I know the code is useless but it would be nice to have the ability to automatically detect this sort of thing. The logic to do this isn't amazingly difficult... Does anyone know if this is possible in IntelliJ?
This "greyed out" mark simply reflects declaration usages in other source code files or framework configuration files. Declaration usage search cannot detect orphan clusters of classes as these classes are formally referenced.
There is a technique, that may help here: define some root set of entry points (main() methods, web.xml declarations, etc) and trace all the references, effectively building a graph of used classes/methods. Once graph is completed, you can treat unvisited classes as dead code. Pretty similar to what Java garbage collector does during young gen collection. It is quite difficult and resource consuming for on-the-fly code analysis, so Intellij has it implemented as a separate inspection one can run manually.
To demonstrate it let's create a fresh project containing the following code:
public class Main {
public static void main(String[] args) {
System.out.println(new Used());
}
}
class Used {}
class ObviouslyUnused {}
class TrickyUnused1 {
TrickyUnused1() {
System.out.println(new TrickyUnused2());
}
}
class TrickyUnused2 {
TrickyUnused2() {
System.out.println(new TrickyUnused1());
}
}
In the editor we can see, that only ObvoiuslyUnused is greyed out. Let's run an "Unused declaration" inspection:
and here we go, inspections shows, that our unused self-referenced class cluster is not reachable:
You should be aware, though, that there are always means of referencing code in implicit ways: reflection, native calls, runtime code generation, SPI implementations, references from framework configuration files, etc. So no static anlisys tool can be 100% accurate when detecting dead code.

FxCop (/VS2010 Code Analysis), possible to flag method result as "callers responsibility now" for IDisposable?

If I write the following code:
public void Execute()
{
var stream = new MemoryStream();
...
}
then code analysis will flag this as:
Warning 1 CA2000 : Microsoft.Reliability : In method 'ServiceUser.Execute()', call System.IDisposable.Dispose on object 'stream' before all references to it are out of scope. C:\Dev\VS.NET\DisposeTest\DisposeTest\ServiceUser.cs 14 DisposeTest
However, if I create a factory pattern, I still might be required to dispose of the object, but now FxCop/Code Analysis doesn't complain. Rather, it complains about the factory method, not the code that calls it. (I think I had an example that did complain about the factory method, but the one I post here doesn't, so I struck that out)
Is there a way, for instance using attributes, to move the responsibility of the IDisposable object out of the factory method and onto the caller instead?
Take this code:
public class ServiceUser
{
public void Execute()
{
var stream = StreamFactory.GetStream();
Debug.WriteLine(stream.Length);
}
}
public static class StreamFactory
{
public static Stream GetStream()
{
return new MemoryStream();
}
}
In this case, there are no warnings. I'd like FxCOP/CA to still complain about my original method. It is still my responsibility to handle that object.
Is there any way I can tell FxCOP/CA about this? For instance, I recently ventured into the annotation attributes that ReSharper has provided, in order to tell its analysis engine information it would otherwise not be able to understand.
So I envision something like this:
public static class StreamFactory
{
[return: CallerResponsibility]
public static Stream GetStream()
{
return new MemoryStream();
}
}
Or is this design way off?
There is a difference between FxCop 10 (which ships with the Windows 7 and .NET 4.0 SDK) and Code Analysis 2010 (which ships with Visual Studio Premium and higher). Code Analysis 2010 has a set of additional rules, which includes a highly improved version of the IDisposable rules.
With Code Analysis 2010 under Visual Studio Premium, the Factory isn't being flagged (as the rule now sees the IDisposable variable is returned to the calling method). The Receiving method, however, isn't flagged either, due to one of the corner case exceptions to the rule. There is a list of method names that will cause the rule to trigger. If you rename your GetStream method to CreateStream, suddenly the rule will trigger:
Warning 4 CA2000 : Microsoft.Reliability : In method 'ServiceUser.Execute()',
call System.IDisposable.Dispose on object 'stream' before all references to it are out
of scope. BadProject\Class1.cs 14 BadProject
I was unable to locate the list of method pre-fixes that will work. I've tried a few and Create~, Open~ trigger the rule, many others that you might expect to work, don't, including Build~, Make~, Get~.
Additionally there is a long list of bugs surrounding this rule. The rule was altered in Visual Studio 2010 to trigger fewer false positives, but now it sometimes misses items it should have flagged (and would have flagged in the previous version). There wasn't enough time to fix the rules in the Visual Studio 2010 time frame (check the bug report comments).
With the upcoming Roslyn compilers, Code Analysis will probably see a major upgrade, until then there are only minor updates to be expected. The current build of Visual Studio Dev11 does not trigger where you want it.
So concluding, no your attribute wouldn't help much, as the rule already detects that you're passing the IDisposable as a return value. Thus Code Analysis knows it's not good to dispose it before returning. If you're using the undocumented naming rules, the rule will trigger. Maybe an attribute could extend the naming rules, but I'd rather have Microsoft would actually fix the actual rule.
I created a connect bug requesting the naming guideline to be documented in the rules documentation.
Comment from Microsoft:
Posted by Microsoft on 1/19/2012 at 10:41 AM
Hello,
Thank you for taking the time to investigate this and file the request for the documentation update. However after some discussion with our documentation team, we have decided to not document the naming convention as you requested.
As you indicated on the stackoverflow thread, there have historically been a lot of reliability issues with this rule, and keying off of the names was an internal implementation detail added to try to reduce the number of false positives. However this is not considered prescriptive guidance for how developers should name their methods, it was added after a survey of common coding practices. We believe the long-term fix is to improve the reliability of the rule, not add naming guidance to our public documentation based on internal implementation details that will continue to change as the rule is improved.
Best Regards,
Visual Studio Code Analysis Team

Can an Invariant method [ContractInvariantMethod] work inside an Interface Contract?

I'm creating an Interface Contract as described in § 2.8 Interface Contracts of Feb 4, 2011 Code Contracts User Manual (PDF). This is not a problem.
Additionally I want to mix an Object Invariant (see § 4.2 ContractInvariantMethod) into the same Interface Contract. This is a problem. I cannot find examples of Object Invariants being used on Interface Contracts.
I tried adding an Object Invariant to the Interface Contract seen in the following partial code snippet. It compiles. At runtime it doesn't raise any errors, however it doesn't appear to do anything positive (i.e. be invoked) either.
/* Note: The intention of this snippet is to cause the data implementation
* to fail if it is not initalized before its public data access methods are called.
*/
[ContractClassFor(typeof(IDataProxy))]
abstract class IDataProxyContract : IDataProxy
{
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(IsInited == true, "Instance not initialized.");
}
I can't find documentation that specifically addresses this scenario or refutes it.
At this point I'm unsure if I'm missing a step to make it work, or if Code Contract technology ignores the Object Invariant in this context altogether. I would like to make it work. Does anybody know the answer?
Apparently the answer is in the DevLabs forum answered by Manuel Fahndrich, Microsoft (MSFT):
Object invariants are not supported on interfaces at the moment. I can
see why they might be handy though.
Full context and code sample here...
They are off by default.
My guess is that the contracts are not enabled by the compiler options, so they don't get weaved into the code.
the solution is to download this package from devlabs
http://msdn.microsoft.com/en-us/devlabs/dd491992
after you install it, go to the project properties, and you'll see another tab.
then, you can enable an option: "Perform runtime contract checking: full"
Invariants provide a mechanism for constraining the internal state of an object.
They are seen as implementation details which is why they are implemented inside a private method. Interfaces obviously have no concept of state (even properties are just syntactic sugar for methods), and consequently cannot have invariants. In their most primitive use, invariants are used on fields. However, the concept of automatic properties has obviously blurred this line, leading to confusion in this case.
I agree there should be a more concise way of contracting properties, simply because your pre and post conditions are invariably going to be the same.

How to document the Main method? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Okay, so I've got a .NET console application with it's Main method, contained in a Program class. You know, the usual:
class Program
{
static void Main(string[] args)
{
// Do something spectactular
}
}
Since I've started using StyleCop and FxCop so rigorously, I've become kind of nit-picky about making sure everything is properly documented.
Then it hit me. I have absolutely no idea how to properly document Program and Program.Main.
I suppose, in the long run, that you could go with the following:
/// <summary>
/// Encapsulates the application's main entry point.
/// </summary>
class Program
{
/// <summary>
/// The application's main entry point.
/// </summary>
static void Main(string[] args)
{
// Do something spectactular
}
}
But that seems woefully inadequate (despite the fact that my Main routines always delegate to other classes to do the work).
How do you folks document these things? Is there a recommendation or standard?
In my humble opinion, it's not worth the trouble to document the main function, especially if you are just going to say "The application's main entry point." If someone doesn't know that Main is the application's main entry point, you don't want them anywhere near your code :-)
If you were to put anything there, you might document what the expected or accepted arguments are, but I think there are better places to document program options (like, a usage function that prints usage, the users manual, a readme file, or elsewhere), since that information is useful not only to developers but also to users of the software.
Documentation is there to add something that's not obvious from the code. And tools are there to help you, not to dictate you what should and should not be documented.
"The application's main entry point" does not add anything, so don't write it.
If there's anything non-obvious like parameters, document this.
Add documentation at the class level that describes what the console program actually does, so it's purpose.
In the Main method, document the required arguments etc., unless if you hand that off, 'main entry point' does suffice.
I tend to hand it off to an instance method in Program called Run(string[] args), so in that case, document the Run method with the arguments/switches options.
The body of my Main() method then simply looks like:
Program prog = new Program();
prog.Run(args);
Don't, just don't.
Just look at those 2 samples you created and compare which is more readable?
I'll bet you'll choose the one without comments.