Is there a way to make a region of code "read only" in visual studio? - 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.

Related

D / DLang : Inhibiting code generation of module-private inlined functions

I have a D module which I hope contains public and private parts. I have tried using the keywords private and static before function definitions. I have a function that I wish to make externally-callable / public and ideally I would like it to be inlined at the call-site. This function calls other module-internal functions that are intended to be private, i.e. not externally callable. Calls to these are successfully inlined within the module and a lot of the cruft is disposed of by CTFE plus known-constant propagation. However the GDC compiler also generates copies of these internal routines, even though they have been inlined where needed and they are not supposed to be externally callable. I'm compiling with -O3 -frelease. What should I be doing - should I expect this even if I use static and/or private?
I have also taken a brief look at this thread concerning GCC hoping for insight.
As I mentioned earlier, I've tried both using private and static on these internal functions, but I can't seem to suppress the code generation. I could understand this if a debugger needed to have copies of these routines to set breakpoints in. I need to stress that this could perhaps be sorted out somehow at link-time, for all I know. I haven't tried linking the program, I'm just looking at the generated code in the Matt Godbolt D Compiler Explorer using GDC. Everything can be made into templates with a zero-length list of template parameters (e.g. auto my_fn()( in arg_t x ) ), tried that, it doesn't help but does no harm.
A couple of other things to try: I could try and make a static class with private parts, as a way of implementing a package, Ada-style. (Needs to be single-instance strictly.) I've never done any C++, only massive amounts of asm and C professionally. So that would be a learning curve.
The only other thing I can think of is to use nested function definitions, Pascal/Ada-style, move the internal routines to be inside the body of their callers. But that has a whole lot of disadvantages.
Rough example
module junk;
auto my_public_fn() { return my_private_fn(); }
private
static // 'static' and/or 'private', tried both
auto my_private_fn() { xxx ; return whatever; }
I just had a short discussion with Iain about this and implementing this is not as simple as it seems.
First of all static has many meanings in D, but the C meaning of translation unit local function is not one of them ;-)
So marking these functions as private seems intuitive. After all, if you can't access a function from outside of the translation unit and you never leak an address to the function why not remove it? It could be either completely unused or inlined into all callers in this case.
Now here's the catch: We can't know for sure if a function is unused:
private void fooPrivate() {}
/*template*/ void fooPublic()()
{
fooPrivate();
}
When compiling the file GDC knows nothing about the fooPublic template (as templates can only be fully analyzed when instantiated), so fooPrivate appears to be unused. When later using fooPublic in a different file GDC will rely on fooPrivate being already emitted in the original source - after all it's not a template so it's not being emitted into the new module.
There might be workarounds but this whole problem seems nontrivial. We could also introduce a custom gcc.attribute attribute for this. It would cause the same problems with templates, but as it's a specific annotation for one usecase (unlike private) we could rely on the user to do the right thing.

Should I always use the override contextual keyword?

I know that the override contextual keyword was introduced to write safer code (by checking for a virtual function with the same signature) but I don't feel good about it, because it seems to be redundant for me to write override every time I want to override a virtual function.
Is it a bad practice to not use override contextual keyword for 99% of cases? Why/when should I have to use it (a compiler warning is not enough when we are hiding a virtual function mistakenly)?
EDIT: In other words; what is the advantage of using the override contextual keyword in C++11 while we always had a compiler warning if we were hiding a virtual function mistakenly in C++03 (without using override contextual keyword)?
The override keyword is totally useful and I would recommend using it all the time.
If you misspell your virtual function it will compile fine but at runtime the program will call the wrong function. It will call the base class function rather than your override.
It can be a really difficult bug to find:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
virtual int func()
{
// do stuff for bases
return 3;
}
};
class Derived
: public Base
{
public:
virtual int finc() // WHOOPS MISSPELLED, override would prevent this
{
// do stuff for deriveds
return 8;
}
};
int main()
{
Base* base = new Derived;
std::cout << base->func() << std::endl;
delete base;
}
Annotations are what you call contextual keywords, they serve as clarification, to make sure anyone who reads the code realizes it is a function that overrides a function in a superclass or a interface.
The compiler can also give a warning if the originally overridden feature was removed, in which case you might want to think about removing your function as well.
As far as I know, nothing bad happens if you ommit anotations. It's neither right nor wrong. Like you stated correctly already: annotations are introduced to write safer code.
However: They won't change your code in any functional way.
If you work as a single programmer on your own project it might not matter wheter you use them or not. It is however good practice to stick to one style (i.e. either you use it, or you don't use it. Anything inbetween like sometimes using it and sometimes not only causes confusion)
If you work in a Team you should discuss the topic with your teammates and decide wheter you all use it or not.
What is the advantage of using override contextual keyword in C++11 while we always had a compiler warning if we were hiding a virtual function mistakenly
Nearly none!?
But:
It depends on how much warnings will be accepted by your build rules. If you say, every warning MUST be fixed, you will get the same result UNTIL you are using a compiler which give you the warning.
We have decided to always use override and remove virtual on overriding methods. So the "overhead" is zero and the code is portable in the meaning of "give an error" on misuse.
I personally like this new feature, because it makes the language clearer. If you say this is an override, it will be checked! And if we want to add a new method with different signature, we will NOT get a false positive warning, which is important in your scenario!

An alternative to TaskEx.FromResult on a platform where it's not available

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.

What determines the order of compliation or execution of source file in Delphi Prism?

Having written my Delphi Prism program enough to compile and run on Window and Linux (mono) without compilation errors, I am finding out that my constructors and load events are firing at different order than I expected. I thought, files get executed in the order that they are listed in the project file like in Delphi .dpr file. Speaking of .dpr file, is there a similar file for Delphi Prism that I am not looking into. I looked into program.pas file and properties. I didn't see anything there to give me a hint or clue.
How do you make sure that the project files get executed in right order in Delphi Prism?
Delphi Prism compiles in the order the files are defined in the project. However, there should not be anything that depends on the order of the files as there are no initialization sections.
As for your other question. Program.pas by default contains the entry point, it's a method called "Main", you could see this as the main begin/end.
.NET does not know about the order your classes are listed in your program file. It just sees classes.
Under normal circumstances you could think of this rule:
Static (class) constructors are executed immediately before the instance .ctor or another static (class) method is called on this class for the first time
While this is not true every time (they could be called earlier, but not later), this is a good approximation which works out most of the time.
So to ensure a certain order for static class initialization, I rely on the following:
I have one static class that has an Initialize() method. This method is the first thing I call in the Main() method of my program. In this method I call Initialize-Methods on other classes in the required order. This makes sure, that the initialization code is executed.

VS.Net Unit Testing -- possible to have project-scoped test setup?

Within a test file (MyTest.cs) it is possible to do setup and teardown at the class and the individual test level. Do similar hooks exist for the entire project? Entire solution?
No I don't believe that they do.
Typically when people ask this question it's because they have tests whoch are depending on something heavy, like a DB setup which needs to be reset for each test pass. Usually the right thing to do here is to mock/stub/fake the dependency out and remove the part that's causing the issue. Of course your reasons for this may be completely different.
Updated: So thinking about this some more I think you could do something with attributes and static types. You could add an assembly level attribute to each test assembly and pass it a static type.
[OnLoadAttribute(typeof(ProjectInitializer))]
When the assembly loads the type will get resolved and it's static constructor will be executed the first time it's resolved (when the assembly is loaded).
Doing something at a solution level is much harder because it depends how your unit test runner deals with tests and how it loads tests into AppDomains, per test, per test class or per test project. I suspect most runners create a new AppDomain per project.
I'm not exactly recommending this as I haven't tried it and there may be some repercussions. It's an idea you might want to try. Another option would be do derive all your tests from a common base class which has a constructor which resolves a singleton that in turn does your setup. This is less hacky but means having a common base class. You could also use an aspect oriented approach I suspect.
Hope this helps. These are just thoughts as to how you could do this.
Ade
We use the [AssemblyInitialize] / [AssemblyCleanup] attributes for project level test setup and cleanup code. We do this for two things:
creating a test database
creating configuration files in a temp directory
It works fine for us, although we have to be careful that each test leaves the database how it found it. Looks a little like this (simplified):
[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
{
ConnectionString = DatabaseHelper.CreateDatabaseFornitTests();
}
[AssemblyCleanup]
public static void AssemblyCleanup()
{
DatabaseHelper.DeleteDatabase(ConnectionString);
}
I do not know of a way to do this 'solution' wide (I guess this really means for the test run - across potentially multiple projects)

Resources