Most questions of this type are seeking to alter the program behavior (things that could be decided at run time) or want to deal directly with debug printing. This is a bit different.
I have code that depends on a peripheral (like a card reader). Sometimes I don't use it, which means the library isn't present. (And I'm being nice, because "library" turns out to mean installing a 2GB software suite). When I remove the library, I can't open the device. If I can't open the device, I can't create the class member that uses it. With the class inoperative, I can't call its methods from within the code. Therefore, I can't just choose not to execute it; I need it to go away since it will not compile without the library.
Preprocessor directives like #if and all that are ok, maybe; but these things appear in more than one file, which means independently maintaining a #define at the top of each. I come from a simpler place (meaning, C) where one header file can be used to control this. I note that C# is rather hostile about #define (either the label exists, or not; no constants or calculations allowed), and that makes me think there's another way.
How do you handle this?
---Follow-up(s)---
I did read the "duplicate" Q/A's, and have a fairly good picture of what I'm dealing with. I didn't find those questions in my original search, but sometimes that's just how it is.
#Amy suggests that #define at the top is "not how it's done" but rather "put it on the command line". So, (if I realize we are sticking with this mechanism) the discussion might go to examining ways to have that happen . One does not simply drop to a terminal and do that. It happens as "IDE features" or "IDE hacks".
#Alexei Levenkov asks what I really want. I really want to (a) not get compile errors, and (b) do it by selectively leaving out the code. And, find the C# equivalent to the way I proposed.
Some more constraints are addressed by the fact that I haven't been using VS or C# for all that long. So I know a lot less than you all do. Considering I got the code from the last person and have to deal with what I see, I don't want to set up the person after me to have to figure out what "interesting" thing I might have done to make it work. Thus, things like hand-editing a project file may work but will also cause consternation down the line.
# Eric Lippert suggests "hostile" is really "sensible". I may have had my tongue too far into my cheek on that one. VS seems to be telling me I'm doing it wrong, so I sensed there's a "right way" I simply don't know about. As for the 2GB supporting application, I will go to various computers and pull down the repository and try out something, and so this "overhead" wants to propagate with it. It's worse if I'm linked through my phone to do the download. And if I build the application with everything included, the end user is then required to install that software suite before the program will run. In theory, they could be required to buy the software. If I sent you a tic-tac-toe game, and told you it wouldn't run until you installed Oracle, you'd probably pass on the whole thing.
I considered the "stub out the interface" idea, but there seemed to be more hooks into the class than I wanted to deal with. Plus, I don't know what these things do, so I have to know something about them in order to "fake" them.
In the end I decided that we're still largely using the #if scheme to get this done, and the replacement feature I imagined might exist, doesn't. And I'm using the provision in the project file(s) as cited by #Jim G. as it gets the job done and is only a little imperfect. It's good enough.
As #BJ Safdie said here:
Set them in your Compilation Properties or Build options.
You get to the build options by right-clicking the project and selecting
properties from the menu.
Related
Ok, so I was wondering how one would go about creating a program, that creates a second program(Like how most compression programs can create self extracting self excutables, but that's not what I need).
Say I have 2 programs. Each one containing a class. The one program I would use to modify and fill the class with data. The second file would be a program that also had the class, but empty, and it's only purpose is to access this data in a specific way. I don't know, I'm thinking if the specific class were serialized and then "injected" into the second file. But how would one be able to do that? I've found modifying files that were already compiled fascinating, though I've never been able to make changes that didn't cause errors.
That's just a thought. I don't know what the solution would be, that's just something that crossed my mind.
I'd prefer some information in say c or c++ that's cross-platform. The only other language I'd accept is c#.
also
I'm not looking for 3-rd party library's, or things such as Boost. If anything a shove in the right direction could be all I need.
++also
I don't want to be using a compiler.
Jalf actually read what I wrote
That's exactly what I would like to know how to do. I think that's fairly obvious by what I asked above. I said nothing about compiling the files, or scripting.
QUOTE "I've found modifying files that were already compiled fascinating"
Please read and understand the question first before posting.
thanks.
Building an executable from scratch is hard. First, you'd need to generate machine code for what the program would do, and then you need to encapsulate such code in an executable file. That's overkill unless you want to write a compiler for a language.
These utilities that generate a self-extracting executable don't really make the executable from scratch. They have the executable pre-generated, and the data file is just appended to the end of it. Since the Windows executable format allows you to put data at the end of the file, caring only for the "real executable" part (the exe header tells how big it is - the rest is ignored).
For instance, try to generate two self-extracting zip, and do a binary diff on them. You'll see their first X KBytes are exactly the same, what changes is the rest, which is not an executable at all, it's just data. When the file is executed, it looks what is found at the end of the file (the data) and unzips it.
Take a look at the wikipedia entry, go to the external links section to dig deeper:
http://en.wikipedia.org/wiki/Portable_Executable
I only mentioned Windows here but the same principles apply to Linux. But don't expect to have cross-platform results, you'll have to re-implement it to each platform. I couldn't imagine something that's more platform-dependent than the executable file. Even if you use C# you'll have to generate the native stub, which is different if you're running on Windows (under .net) or Linux (under Mono).
Invoke a compiler with data generated by your program (write temp files to disk if necessary) and or stored on disk?
Or is the question about the details of writing the local executable format?
Unfortunately with compiled languages such as C, C++, Java, or C#, you won't be able to just ``run'' new code at runtime, like you can do in interpreted languages like PHP, Perl, and ECMAscript. The code has to be compiled first, and for that you will need a compiler. There's no getting around this.
If you need to duplicate the save/restore functionality between two separate EXEs, then your best bet is to create a static library shared between the two programs, or a DLL shared between the two programs. That way, you write that code once and it's able to be used by as many programs as you want.
On the other hand, if you're really running into a scenario like this, my main question is, What are you trying to accomplish with this? Even in languages that support things like eval(), self modifying code is usually some of the nastiest and bug-riddled stuff you're going to find. It's worse even than a program written completely with GOTOs. There are uses for self modifying code like this, but 99% of the time it's the wrong approach to take.
Hope that helps :)
I had the same problem and I think that this solves all problems.
You can put there whatever code and if correct it will produce at runtime second executable.
--ADD--
So in short you have some code which you can hard-code and store in the code of your 1st exe file or let outside it. Then you run it and you compile the aforementioned code. If eveything is ok you will get a second executable runtime- compiled. All this without any external lib!!
Ok, so I was wondering how one would
go about creating a program, that
creates a second program
You can look at CodeDom. Here is a tutorial
Have you considered embedding a scripting language such as Lua or Python into your app? This will give you the ability to dynamically generate and execute code at runtime.
From wikipedia:
Dynamic programming language is a term used broadly in computer science to describe a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution. These behaviors can be emulated in nearly any language of sufficient complexity, but dynamic languages provide direct tools to make use of them.
Depending on what you call a program, Self-modifying code may do the trick.
Basically, you write code somewhere in memory as if it were plain data, and you call it.
Usually it's a bad idea, but it's quite fun.
We have a large (about 580,000 loc) application which in Delphi 2006 builds (on my machine) in around 20 seconds. When you have build times in seconds, you tend to use the compiler as a tool. i.e. write a little code, build, write some more code and build some more etc etc As we move some of our stuff over to C#, does anyone have a comparison of how long something that size would take to build? I only have small apps and components at the moment, so can't really compare. If things are going to take a lot longer to build, then I may need to change my style! Or is my style just lazy?
For example, if I'm changing the interface of a method call, rather than do a full search on all the app to find out where I need to make changes to calls, I'll use the compiler to find them for me.
Visual Studio 2008 SP1 now has background compilation for C# (it's always had it for VB.NET). Back in my VB days, I often used this to find where something was referenced by changing the name and then seeing where the background compiler said there was an error.
I never worked on anything quite this large. At my last job we had about 60,000 loc spread over about 15 projects and it took about 10 seconds to compile. Maybe someone else can post a slightly larger case study
I used to use the compiler as you describe, but since I've been using ReSharper I do this a lot less.
Also, for things like rename, the refactoring support (both in Visual Studio 2005 upwards and, even better, from ReSharper) mean I don't have to do search + replace to rename things.
One thing you can take advantage of, especially in desktop apps, as I imagine you are dealing with coming from Delphi, is Edit and Continue. This lets you change actual code while you are running in debug mode. You can change just about anything, except for adding class level variables, methods, or new classes, and still continue running without having to recompile your project.
I use only the "Syntax Check" to see if I forgot some typo on the code... And these are much reduced, since I the "Code Proofreader" of GExperts plugin.
Well, compiler doesn't have to be that fast to take advantage of it. Some IDEs support incremental compilation on every file save, or either on-the-fly. This works great.
You can split application in several projects ( by layer and/or module and/or etc... ) and you will compile only project, where do you actualy work.
The last part of your post scares me. I am not familiar with other IDEs but MSDev allows you to find all references to a method - so you don't have to compile just to find all the method calls you broke.
Use whatever works, but it is good you are open to new ways of doing things.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm currently using a simple XML file that contains license information along with the data's signature and public key. So far, this method is working great. However, I'm seeing one rather large security flaw...
When my ASP.NET MVC application starts, it verifies the license and sets the "ValidLicense" bool property accordingly. During each request, this property is checked and an error message is displayed if the license is invalid.
As you can guess, there's absolutely nothing to stop a competent user from simply modifying my assembly to set "ValidLicense" to true regardless of the license's validity. I know this can be done to pretty much any application, but it seems incredibly easy to do with .NET assemblies.
What are some ways that I can stop this from happening, or at least make it a little more difficult to crack the license verification procedure?
I'd rather stay away from assembly encryption and obfuscation systems, if possible. Go ahead and suggest them if you feel that they are good enough to warrant the cost and extra headache, however.
The only way to win is not to play.
The people who are going to steal your stuff (regardless of what protections you put in place), are not the people who are going to pay for it if it's too hard for them to break.
Instead of a simple boolean variable, you could perform a complex calculation every time you need to verify the license and base your logic on the result from that calculation. You do get a perf hit, though. And cracking your assembly wouldn't be that much harder anyway.
You could also employ some more advanced techniques, like dynamic mutation of the code and using the a corresponding mutable function to control the flow of your logic.
However, you should ask yourself does your assembly really contain such precious intelectual property, as to warrant the time and efforts to implement anything like this? It might be more viable and cheaper to go the legal route and battle the potential piracy if and when it occurs.
You can make it a bit more complicated but in the end it will come down to one (or several) booleans: Either you run the code or you don't. Non-obfuscated.NET code is pretty much the same as open source and it is ridiculously easy to crack open.
Even if obfuscation is not a full solution, I think it would make sense to obfuscate, just to prevent fringe amateurs from producing cracked versions.
Of course it won't stop a real cracker who is willing to spend the time, but just by putting the bar a little higher, you can weed out a lot of crackers wannabes.
Obfuscation can be pretty simple to implement for free. If you have a commercial version of Visual Studio, you can use DotFuscator (not with the "Express" editions). I never tried, but I guess it should be simple enough.
Otherwise, you can use Assemblur. (http://www.metapropeller.com/). The free version is a command line application (there is a GUI to create the setting file, but you need to run the settings from the command line).
All in all, it barely takes a couple minutes to obfuscate a simple exe file and it's free
If you want to make your license check a little more challenging, you can make different checks inside various methods, and you can also make sure that the license checking code does not actually output any string directly. (for instance, you do a license check in method A, but you output the error warning from method B, so that when a cracker looks for the license error message, he doesn't land right on the bit of code to be changed).
All it does is raise the bar for wannabe crackers and make things more complex for a real cracker.
Case 1: Non obfuscated .NET application with 1 license check method which output a "not licensed" error message.
Can be cracked in about 5 minutes by anyone who can run reflector.
Case 2: Obfuscated .NET application with a couple different license checks and no obvious string output.
Could take hours for a cracker and prove too hard for a wannabe.
You can get from case 1 to case 2 with about 1 hour of work, without spending a dime. Going beyond that is probably a waste of time (everything can be cracked) but at least, you can weed out the folks who open your application in Reflector just to see if it's going to be easy. If the guy opens the application in reflector and sees something like:
public bool ValidateLicense(string sLicense)
{
string sInvalidLicense = "Your license is not valid";
...
}
Guess what happens next?
//EDIT: In a comment, LC asked:
How do you not have it output any string message but still notify the user? Even if you do a license check and output in two different methods, you'll still have a the binary decision "if(!ValidateLicense(LicenseCode)) {NotifyUserOfInvalidLicense(); throw new LicenseException();}" or something, no?
Put yourself in the shoes of a cracker: You are looking for the License validation code. You are not going to study the whole code just to find it. Instead, you run the application unlicensed: The error message shows up.
You take that error message, you open the assembly in Refactor and you search for a part of that error message.
If that string is located inside "ValidateLicence()", you immediately find the ValidateLicence() function. From there, you only need to locate the return value and change that 1 byte. Done.
If the string is found instead inside "WhatEver()", you still needs to find what methods call "WhatEver()". It might not even be in the same assembly (in which case Refactor will not find it for you). This makes the job harder for your wannabe cracker. He will have to look at that method to see how it validates the code (which it doesn't). He might even be sloppy and change the return value of the wrong method, in which case he introduces a bug (if the method is obfuscated, figuring out what it does is not that simple).
Better yet, don't use a string at all: you can store the error message as a sequence of hex codes, and convert it to string dynamically when you need to display the message. No error string means that the cracker will have to rely on something else to locate your license validation code. And reading through obfuscated code is not fun.
You could also have a fake validation method containing the error message and suppress the warning to make it look like the crack worked.
So, a couple of simple, stupid tricks like these + simple obfuscation are very easy to implement and they can turn a 5 minutes "In and Out" cracking session into weeks of work for the cracker, because not only does he need to find and crack your validation code, but he also has to test to make sure that everything is working and that he didn't just fix a decoy or unwillingly created nasty bugs. Now, he just can't be sure without testing.
In the end, cracking an assembly is just a matter of changing a few bytes, and you can't prevent anyone from changing bytes in your assembly's files. Everything can be cracked.
However you can make it a hell of a lot harder to find which bytes have to be changed, and at the very least, you can avoid having a string that says "the byte you are looking for is right here".
An approach I met when trying to hack a little .NET product was to use an unmanaged .DLL for the licence checking. And not only that, the .DLL also contained a lot of code that was actually used in the software. So, to crack product I actually had to crack the unmanaged .DLL (or make a perfect wrapper). Needless to say, this stopped a wannabe cracker like me. :)
I'm just starting out with C# and to me it seems like Microsoft Called their new system .Net because you have to use the Internet to look everything up to find useful functions and which class they stashed it in.
To me it seems nonsensical to require procedure/functions written and designed to stand alone ( non instantiated static objects) to have their class not also function as their namespace.
That is Why can't I use Write or WriteLine instead of Console.WriteLine ?
Then when I start to get used to the idea that the objects I am using ( like string) know how to perform operations I am used to using external functions to achieve ( like to upper, tolower, substring, etc) they change the rules with numbers, numbers don't know how to convert themselves from one numeric type to another for some reason, instead you have to invoke Convert class static functions to change a double to an int and Math class static functions to achieve rounding and truncating.. which quickly turns your simple( in other languages) statement to a gazillion character line in C#.
It also seems obsessed with strong typing which interferes somewhat with the thought process when I code. I understand that type safety reduces errors , but I think it also increases complexity, sometimes unnecessarily. It would be nice if you could choose context driven types when you wish without the explicit Casting or Converting or ToStringing that seems to be basic necessity in C# to get anything done.
So... Is it even possible to write meaningful code in notepad and use cl with out Internet access? What ref book would you use without recourse to autocomplete and Network access?
Any suggestions on smoothing the process towards grokking this language and using it more naturally?
I think you're suffering a bit from the fact that you've used to working in one way during some years, and now must take time to get yourself comfortable using / developing in a new platform.
I do not agree with you , that MS hasn't been consistent on the fact that a string knows how it should convert itself to another type, and other datatypes (like ints) do not.
This is not true, since strings do not know for themselves how they should be converted to another type as well. (You can use the Convert class to Convert types to other types).
It is however true that every type in .NET has a ToString() method, but, you should not rely on that method to convert whatever you have to a string.
I think you have never worked in an OO language before, and therefore, you're having some difficulties with the paradigm shift.
Think of it this way: it's all about responsabilities and behaviour. A class is (if it is well designed) responsible for doing one thing, and does this one thing good.
There is no excuse to use notepad to code a modern language. SharpDevelop or Visual C# Express provide the functionality to work with C# in a productive way.
And no, due to the complexity, not using the internet as a source of information is also not a good option.
You could buy a book that introduces you to the concepts of the language in a structured way, but to get up-to-date information, the internet is neccessary.
Yes, there are drawbacks in C#, like in any other language. I can only give you the advice to get used to the language. Many of the drawbacks become understandable after that, even if some of them don't become less annoying. I recommend that you ask clear, direct questions with example code if you want to know how some language constructs work or how you can solve specific problems more efficiently. That makes it easier to answer those questions.
For notepad, I have no useful advice, however I would advise you to use one of the free IDE's, Microsofts Express Editions, or Sharp Develop.
The IDE will speed the groking of the language, at which point, you can switch back to notepad.
Reading your post I was thinking that you worked mostly with C or dynamic languages previously. Maybe C# is just a wrong choice for you, there are IronPython, F# and a bunch of other languages that have necessary functionality (like functions outside of classes etc.)
I disagree with you about consistency. In fact there are small inconsistency between some components of .NET, but most part of FW is very consistent and predictable.
Strong typing is a huge factor in low defect count. Dynamic typing plays nice in small/intermediate projects (like scripts, etc). In more or less complex program dynamism can introduce a lot of complexity.
Regarding internet/autocomplete - I can hardly imagine any technology with size of .NET that doesn't require a lot of knowledge sources.
Programming in c# using notepad is like buying a ferrari to drive in dirt roads.
At least use Visual Studio Express Edition. For what you wrote I understand that you come from a non OO background, try to learn the OO concept and try to use it. You will eventually understand most design decisions made for .Net.
http://en.wikipedia.org/wiki/Object-oriented_programming
Oh boy where do i start with you(this will be a long post hahaha), well, lets go little by little:
"Microsoft called their system .NET because you have to use Intenet...", the reason why is called .NET is because the SUITE OF MICROSOFT LANGUAGUES(and now some other ones too like Phyton and Ruby, etc) CAN CALL ANY LIBRARY or DLLs, example you can "NET"(Network OR CALL) a DLL that was built in Visual Basic, F#, C++ from WITHIN C# or from any of those languagues you can also call(or ".NET") C# libraries. OK ONE DOWN!!!
NEXT ONE: "it seems nonsensical to require....to have their class not also function as their namespace", this is because a Namespace can have AS MANY CLASSES AS YOU WISH, and your question:
"That is Why can't I use Write or WriteLine instead of Console.WriteLine ?".
The reason is because: "Console"(System.Console hense the "Using" statement at the beginning of your program) Namespace is where "Write" and "WriteLine" LIVES!!(you can also FULLY qualify it (or "call It"). (all this seems to me that you need to study C# Syntax), ok NEXT:
"when I start to get used to the idea that the objects...", ok in simple words:
C# is a "Strongly Type-Safe language" so that SHOULD-MUST tell you what "you are getting in to" otherwise STAY WITH "WEAK or NO TYPE SAFE LANGUAGES" LIKE PHP or C , etc. this does NOT means is bad it just MEANS IS YOUR JOB TO MAKE SURE, as i tell my students: "IF YOU NEED AN INT THEN DEFINE AN INT INSTEAD LETTING THE COMPILER DO IT FOR YOU OTHERWISE YOU WILL HAVE A LOT OF BAD BUGS", or in other words do YOUR homework BEFORE DESIGNING A PIECE OF SOFTWARE.
Note: C# is IMPLICITY TYPE SAFE language SO IF YOU WANT YOU CAN RUN IT AS UNSAFE so from then it wiLL be your job to make sure, so dont complain later(for being lazy) when bugs arrive AT RUNTIME(and a lot of times when the customer is already using your crappy software).
...and last but not least : Whey do you wan to shoot yourself by using notepad? Studio Express is FREE, even the database SQL SERVER is FREE TOO!!, unless you work for a company I WILL ASK FOR PRO, ETC. all the "extra" stuff is for large companies, teams, etc, YOU CAN DO 99% OF THE STUFF WITH THE FREE VERSIONS(and you can still buy-update to full version once you want to scalate to Distributed Software or a Large Project, or if your software becomes a big hit, Example: if you need millions of queryes or hits PER SECOND from your database or 100 people are working on same project(code) but for the majority of times for 2 or 3 "normal" developers working at home or small office the FREE ONES ARE ENOuGH!!)
cherrsss!!! (PS: Software Developer since the 80's)
I work on a team with about 10 developers. Some of the developers have very exacting formatting needs. I would like to find a pretty printer that I could configure to these specifications and then add to the build processes. In this way no matter how badly other people mess up the format when it is pulled down from source control it will look acceptable.
The easiest solution is for the team lead to mandate a format and everyone use it. The VS defaults are pretty good.
Jeff Atwood did that to us here on Stack Overflow and while I rebelled at first, I got over it :) Makes everything much easier!
Coding standards are definitely something we have. The coding formatting I am talking about is imposed by a grizzled architect that is, lets say, set in his ways and extremely particular. Lets just pretend that we can not address the human factor. I was looking for a way to circumvent the whole human processes.
The visual studio defaults sadly do not address line breaks very well. I am just making this line chopping style up but....
ServiceLocator.Logger.WriteDefault(string.format("{0}{1}"
,foo
,bar)
,Logging.SuperDuper);
another example of formatting visual studio is not too hot at....
if( foo
&& ( bar
|| baz
|| apples
|| oranges)
&& IsFoo()
&& IsBar() ){
}
Visual studio does not play well at all will stuff like this. We are currently using ReSharper to allow for more granularity with formating but it sadly falls sort in many areas.
Don't get me wrong though coding standards are great. The goal of the pretty printer as part of the build process is to get 'perfect' looking code no matter how well people are paying attention or counting their spaces.
The edge cases around code formatting are very solvable since it is a well defined grammar.
As far as the VS defaults go I can only say: BSD style or die!
So all that brings me full circle back to: Is there a configurable pretty printer for C#? As much as lexical analysis and parsing fascinate I have about had my fill making a YAML C# tool chain.
Your issue was the primary intent for creating NArrange (beta). It allows configurable reformatting of C# code and you can use one common configuration file to be shared by the entire team. Since its focus is primarily on reordering members in classes and controlling regions, it is still lacking many necessary formatting options (especially formatting within member code lines).
The normal usage scenario is for each developer to run the tool prior to check-in. I'm not aware of any one running it is part of their build process, but there is no reason why you couldn't, since it is a command-line tool. One idea that I've contemplated is running NArrange on files as part of a pre-commit step. If the original file contents being checked in don't match the NArrange formatted output on the source repository server, then the developer didn't reformat to the rules and a check-in error can be raised.
For more information, see my CodeProject article on Using NArrange to Organize C# Code.
Update 2023-02-25: NArrange appears to have moved to Github. The NArrange site (referenced above) is no longer available although there are copies in web.archive.org
I second Jarrod's answer. If you have 2 developers with conflicting coding preferences, then get the rest of the team to vote, and then get the boss to back the majority decision.
Additionally, the problem with trying to automatically apply a pretty printer like that, is that there will always be exceptional cases where your blanket coding standard is not the best or most readable solution, and you will lose out by squashing them with an automated tool.
Coding Standards are just that, standards. They don't call them Coding Laws or Coding Rules, and there's a good reason for that.