An alternative to TaskEx.FromResult on a platform where it's not available - task-parallel-library

I am converting a portable class library to use a different profile (78). Most of the changes were related to reflection API, and now I have few last lines that don't compile, all of them are using TaskEx.FromResult.
TaskEx.FromResult is handy when a method returns Task, and a value of T needs to be wrapped and returned from the method, e.g.:
public Task<int> ReturnTaskOfInt()
{
return TaskEx.FromResult(42);
}
Unfortunately TaskEx is not available for some PCL profiles. Perhaps it shouldn't be hard to write a replacement for it, and I will appreciate an advise.

Oops, it was damn easy. TaskEx.FromResult is not available, but Task.FromResult is there.

Related

How can I manually compile something inside Eclipse?

One way of doing seemed to be to use the java.lang.Compiler
I tried to use the java.lang.Compiler inside Eclipse anddid not understand the Object any parameters for the methods of that class? And putting in a class did not seem to work either.
Compiler.command(any) // what is meant by any? What are valid objects to put there?
Compiler.compileClass(clazz) // Nothing happens when I out a class in there?
Compiler.compileClasses(string) // hm?
How to can I print a hello message with a Compiler inside Eclipse...?
Reading the documentation is a very important skill you need to learn.
Whenever you come across a class or a method that you don't know the functionality of, simply look at the documentation first.
Here is the docs for java.lang.Compiler: https://docs.oracle.com/javase/7/docs/api/java/lang/Compiler.html
This is the first sentence of the document:
The Compiler class is provided to support Java-to-native-code compilers and related services. By design, the Compiler class does nothing; it serves as a placeholder for a JIT compiler implementation.
So, the answer to your question is, it does nothing. According to the documentation, it does nothing. It is used to start up the Java compiler when the JVM starts. You are not meant to use this.

Single responsibility principle - function

I'm reading some tuts about SOLID programming, and I'm trying to refactor my test project to implement some of those rules.
Often I have doubts with SingleResponsibilityPrinciple, so I hope someone could help me with that.
As I understood, SRP means that (in case of a function), function should be responsible for only one thing. And that's seems pretty easy and simple, but I do get in a trap of doing more than thing.
This is simplified example:
class TicketService {
private ticket;
getTicket() {
httpClient.get().then(function(response) {
ticket = response.ticket;
emit(ticket); <----------------------
});
}
}
The confusing part is emit(ticket). So, my function is named getTicket, that's exactly what I'm doing there (fetching it from server e.g.), but on the other hand, I need to emit that change to all other parts of my application, and let them know that ticket is changed.
I could create separate set() function, where I could do setting of private variable, and emit it there, but that seems like a same thing.
Is this wrong? Does it break the rule? How would you fix it?
You could also return the ticket from the getTicket() function, and then have a separate function called setUpdatedTicket() that takes a ticket and sets the private parameter, and at the end calls the emit function.
This can lead to unexpected behavior. If I want to re-use your class in the future and I see with auto-completion in my IDE the method getTicket() I expect to get a Ticket.
However renaming this method to mailChangedTicket, ideally you want this method to call the getTicket method (which actually returns the ticket) and this way you have re-usable code which will make more sense.
You can take SRP really far, for example your TicketService has a httpClient, but it probably doesn't matter where the ticket comes from. In order to 'fix' this, you will have to create a seperate interface and class for this.
A few advantages:
Code is becoming more re-usable
It is easier to test parts separately
I can recommend the book 'Clean Code' from Robert C. Martin which gives some good guidelines to achieve this.

How good idea is it to use code contracts in Visual Studio 2010 Professional (ie. no static checking) for class libraries?

I create class libraries, some which are used by others around the world, and now that I'm starting to use Visual Studio 2010 I'm wondering how good idea it is for me to switch to using code contracts, instead of regular old-style if-statements.
ie. instead of this:
if (fileName == null)
throw new ArgumentNullException("fileName");
use this:
Contract.Requires(fileName != null);
The reason I'm asking is that I know that the static checker is not available to me, so I'm a bit nervous about some assumptions that I make, that the compiler cannot verify. This might lead to the class library not compiling for someone that downloads it, when they have the static checker. This, coupled with the fact that I cannot even reproduce the problem, would make it tiresome to fix, and I would gather that it doesn't speak volumes to the quality of my class library if it seemingly doesn't even compile out of the box.
So I have a few questions:
Is the static checker on by default if you have access to it? Or is there a setting I need to switch on in the class library (and since I don't have the static checker, I won't)
Are my fears unwarranted? Is the above scenario a real problem?
Any advice would be welcome.
Edit: Let me clarify what I mean.
Let's say I have the following method in a class:
public void LogToFile(string fileName, string message)
{
Contracts.Requires(fileName != null);
// log to the file here
}
and then I have this code:
public void Log(string message)
{
var targetProvider = IoC.Resolve<IFileLogTargetProvider>();
var fileName = targetProvider.GetTargetFileName();
LogToFile(fileName, message);
}
Now, here, IoC kicks in, resolves some "random" class, that provides me with a filename. Let's say that for this library, there is no possible way that I can get back a class that won't give me a non-null filename, however, due to the nature of the IoC call, the static analysis is unable to verify this, and thus might assume that a possible value could be null.
Hence, the static analysis might conclude that there is a risk of the LogToFile method being called with a null argument, and thus fail to build.
I understand that I can add assumptions to the code, saying that the compiler should take it as given that the fileName I get back from that method will never be null, but if I don't have the static analyzer (VS2010 Professional), the above code would compile for me, and thus I might leave this as a sleeping bug for someone with Ultimate to find. In other words, there would be no compile-time warning that there might be a problem here, so I might release the library as-is.
So is this a real scenario and problem?
When both your LogToFile and Log methods are part of your library, it is possible that your Log method will not compile, once you turn on the static checker. This of course will also happen when you supply code to others that compile your code using the static checker. However, as far as I know, your client's static checker will not validate the internals of the assembly you ship. It will statically check their own code against the public API of your assembly. So as long as you just ship the DLL, you'd be okay.
Of course there is a change of shipping a library that has a very annoying API for users that actually have the static checker enabled, so I think it is advisable to only ship your library with the contract definitions, if you tested the usability of the API both with and without the static checker.
Please be warned about changing the existing if (cond) throw ex calls to Contracts.Requires(cond) calls for public API calls that you have already shipped in a previous release. Note that the Requires method throws a different exception (a RequiresViolationException if I recall correctly) than what you'd normally throw (a ArgumentException). In that situation, use the Contract.Requires overload. This way your API interface stays unchanged.
First, the static checker is really (as I understand it) only available in the ultimate/academic editions - so unless everyone in your organization uses it they may not be warned if they are potentially violating an invariant.
Second, while the static analysis is impressive it cannot always find all paths that may lead to violation of the invariant. However, the good news here is that the Requires contract is retained at runtime - it is processed in an IL-transformation step - so the check exists at both compile time and runtime. In this way it is equivalent (but superior) to a regular if() check.
You can read more about the runtime rewriting that code contract compilation performs here, you can also read the detailed manual here.
EDIT: Based on what I can glean from the manual, I suspect the situation you describe is indeed possible. However, I thought that these would be warninings rather than compilation errors - and you can suppress them using System.Diagnostics.CodeAnalysis.SuppressMessage(). Consumers of your code who have the static verifier can also mark specific cases to be ignored - but that could certainly be inconvenient if there are a lot of them. I will try to find some time later today to put together a definitive test of your scenario (I don't have access to the static verifier at the moment).
There's an excellent blog here that is almost exclusively dedicated to code contracts which (if you haven't yet seen) may have some content that interests you.
No; the static analyzer will never prevent compilation from succeeding (unless it crashes!).
The static analyzer will warn you about unproven pre-/post-conditions, but doesn't stop compilation.

Is there a way to make a region of code "read only" in visual studio?

Every so often, I'm done modifying a piece of code and I would like to "lock" or make a region of code "read only". That way, the only way I can modify the code is if I unlock it first. Is there any way to do this?
The easiest way which would work in many cases is to make it a partial type - i.e. a single class whose source code is spread across multiple files. You could then make one file read-only and the other writable.
To declare a partial type, you just use the partial contextual keyword in the declaration:
// MyClass.First.cs:
public partial class MyClass
{
void Foo()
{
Bar();
}
void Baz()
{
}
}
// MyClass.Second.cs:
public partial class MyClass
{
void Bar()
{
Baz();
}
}
As you can see, it ends up as if the source was all in the same file - you can call methods declared in one file from the other with no problems.
Compile it into into a library dll and make it available for reference in other projects.
Split up the code into separate files and then check into a source control system?
Given your rebuttal to partial classes... there is no way that I know of in a single file, short of documentation. Other options?
inheritance; but the protected code in the base-class (in an assembly you control); inheritors can only call the public/protected members
postsharp - stick the protected logic in attributes declared externally
However, both of these still require multiple files (and probably multiple assemblies).
I thought about this, but I would prefer to keep the class in one file. – danmine
Sorry, mac. A bit of voodoo as a SVN pre-commit might catch it but otherwise no solution other than // if you change this code you are fired
This is totally unnecessary if you're using a version control system. Because once you've checked it in, it doesn't matter what part of the code you edit, you can always diff or roll back. Heck, you could accidentally wipe out all the source code and still get it back.
I'm getting a really bad "code smell" from the fact that you want to lock certain parts of the code. I'm guessing that maybe you're doing too much in one class, in which case, refactor it to a proper set of classes. The fact that, after the 10+ years visual studio has existed, this feature isn't available, should suggest that perhaps your desire to do this is a result of poor design.

C# 3.0 Autoproperties - whats the difference?

0 What's the difference between the following?
public class MyClass
{
public bool MyProperty;
}
public class MyClass
{
public bool MyProperty { get; set; }
}
Is it just semantics?
Fields and properties have many differences other than semantic.
Properties can be overridden to provide different implementations in descendants.
Properties can help alleviate versioning problems. I.e. Changing a field to a property in a library requires a recompile of anything depending on that library.
Properties can have different accessibility for the getter and setter.
"Just semantics" always seems like a contradiction in terms to me. Yes, it changes the meaning of the code. No, that's not something I'd use the word "just" about.
The first class has a public field. The second class has a public property, backed by a private field. They're not the same thing:
If you later change the implementation of the property, you maintain binary compatibility. If you change the field to a property, you lose both binary and source compatibility.
Fields aren't seen by data-binding; properties are
Field access can't be breakpointed in managed code (AFAIK)
Exposing a field exposes the implementation of your type - exposing a property just talks about the contract of your type.
See my article about the goodness of properties for slightly more detail on this.
In that case, yes it is mostly semantics. It makes a difference for reflection and so forth.
However, if you want to make a change so that when MyProperty is set you fire an event for example you can easily modify the latter to do that. The former you can't. You can also specify the latter in an interface.
As there is so little difference but several potential advantages to going down the property route, I figure that you should always go down the property route.
The first one is just a public field, the second one is a so-called automatic property. Automatic properties are changed to regular properties with a backing field by the C# compiler.
Public fields and properties are equal in C# syntax, but they are different in IL (read this on a German forum recently, can't give you the source, sorry).
Matthias
The biggest difference is that you can add access modifiers to properties, for example like this
public class MyClass
{
public bool MyProperty { get; protected set; }
}
For access to the CLR fields and properties are different too. So if you have a field and you want to change it to a property later (for example when you want to add code to the setter) the interface will change, you will need to recompile all code accessing that field. With an Autoproperty you don't have this problem.
I am assuming you are not writing code that will be called by 3rd party developers that can’t recompile their code when you change your code. (E.g. that you don’t work for Microsoft writing the .Net framework it’s self, or DevExpress writing a control toolkip). Remember that Microsoft’s .NET framework coding standard is for the people writing the framework and tries to avoid a lot of problems that are not even issues if you are not writing a framework for use of 3rd party developers.
The 2nd case the defined a propriety, the only true advantage of doing is that that data binding does not work with fields. There is however a big political advantage in using proprieties, you get a lot less invalid complaints from other developers that look at your code.
All the other advantages for proprieties (that are well explained in the other answers to your questions) are not of interest to you at present, as any programmer using your code can change the field to a propriety later if need be and just recompile your solution.
However you are not likely to get stacked for using proprieties, so you make as well always use public proprieties rather the fields.

Resources