MarkdownSharp errors in a Windows 8 app - c#

I was trying to play with MardownSharp in a Windows 8 app. But I'm getting errors in the Mardown.cs file. It doesn't have System.Configuration and RegexOptions.Compiled.

You have two issues here.
System.Configuration is not one of the .NET namespaces available
for Windows Store applications. The good news is that it seems
to be used only in one of the overloaded constructors of the
Markdown class:
public Markdown(bool loadOptionsFromConfigFile)
Comment out that constructor (and the using statement). You could
rewrite that constructor to make use of app local storage which
would allow analogous functionality to a config file but not with
quite the same implementation. I suspect you may not be using that
overload anyway
The code makes heavy use of the Compiled flag for regular
expressions, which also isn't supported in this context. You should
be able to safely remove all references to that flag.
With those modifications I was able to at least compile the code, I didn't take it further.

Related

UWP debug/release error with ntdll.dll

I'm writing a UWP program to detect colors from LEDs, this program runs on a Raspberry Pi 3 with Windows 10 IoT with attached display.
What the program does is take a reference image with the LED turned off, then take a image from the LED turned on.
Both images are converted to the same pixelformat and then are cropped to a smaller size, in which only the LED is shown (both the reference and the lighted LED).
Then those picture parts are converted to grayscale wich is followed by creating a difference picture of the two, so that only pixels that changed from the reference to the lighted LED are shown.
To do so I use the NuGet-Package portable.AForge.imaging. The code is shown below.
LEDBildNeu = LEDBild.Clone(PixelFormat.Format24bppRgb);
ReferenzbildNeu = Referenzbild.Clone(PixelFormat.Format24bppRgb);
Crop cropping = new Crop(new System.Drawing.Rectangle(Convert.ToInt32(x), Convert.ToInt32(y), 100, 100));
CroppedLED = cropping.Apply(LEDBildNeu);
CroppedReferenz = cropping.Apply(ReferenzbildNeu);
Grayscale grayscale = new Grayscale(0.2125, 0.7154, 0.0721);
GrayscaleReferenz = grayscale.Apply(CroppedReferenz);
GrayscaleLED = grayscale.Apply(CroppedLED);
Difference difference = new Difference(GrayscaleReferenz);
Differenzbild = difference.Apply(GrayscaleLED);
This code works fine as long as im in debug mode, all of the functions are working.
However when i change to release mode, i get this error while building:
1>C:\Users\morsch.nuget\packages\microsoft.net.native.compiler\1.7.2\tools\Microsoft.NetNative.targets(697,5): warning : MCG : warning MCG0007: Unresolved P/Invoke method 'ntdll.dll!memcpy' for method 'System.Byte* AForge.SystemTools.memcpy(System.Byte*, System.Byte*, System.Int32)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisify those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
1>C:\Users\morsch.nuget\packages\microsoft.net.native.compiler\1.7.2\tools\Microsoft.NetNative.targets(697,5): warning : MCG : warning MCG0007: Unresolved P/Invoke method 'ntdll.dll!memset' for method 'System.Byte* AForge.SystemTools.memset(System.Byte*, System.Int32, System.Int32)'. Calling this method would throw exception at runtime. Please make sure the P/Invoke either points to a Windows API allowed in UWP applications, or a native DLL that is part of the package. If for some reason your P/Invoke does not satisify those requirements, please use [DllImport(ExactSpelling=true) to indicate that you understand the implications of using non-UWP APIs.
When I run the code in release mode and get to the part where the difference picture is created, I get the exception
System.TypeLoadException: 'Unresolved P/Invoke method 'memcpy!ntdll.dll' from this method. Please look for this method in build warnings for more details.'
According to this 'memset' and 'memcpy' are not supported by UWP. My questions now are:
Why does the program run in debug mode without any problems even when those two entry points are not supported, but as soon as i turn to release mode i get the exceptions?
Is there a workaround for the problem?
I already tried to use
[DllImport("ntdll.dll", EntryPoint = "memset")]
and
[DllImport("ntdll.dll", EntryPoint = "memcpy")]
But either I did it wrong or it just don't work that way.
I know I could just program a workaround in which I check the pixels manually and create a new image, but I wanted to solve that problem if possible.
Finding the correct combination of directives can be a very frustrating and time consuming process. Here is additional information that I received from Microsoft via email, hope this helps:
Helpful links:
https://devblogs.microsoft.com/dotnet/net-native-deep-dive-dynamic-features-in-static-code/
https://learn.microsoft.com/en-us/dotnet/framework/net-native/runtime-directives-rd-xml-configuration-file-reference
https://learn.microsoft.com/en-us/dotnet/framework/net-native/runtime-directive-policy-settings
The analysis we do to get your application ready to be ahead of time compiled is quite extensive. We need to generate code for various generic types, reflection callable wrappers, serialization information, marshalling stubs etc etc. In come cases (as you could imagine) we end up generating more than is strictly necessary due to run away combinatorics. It’s completely possible that some fiddling with our heuristics can get you application to a place where it compiles without any loss of functionality.
Practically speaking, there’s two ways to manipulate the behavior of the compiler. One is through some of our compiler flags available through dropping elements into your csproj. The other is making edits to your applications Properties\Default.rd.xml file.
Compiler flags
There are a wide range of flags available but here’s a couple that may help out:
<ShortcutGenericAnalysis>true</ShortcutGenericAnalysis> - Can help stop runaway analysis of generic types and reduce overall generation requirements.
<UseDotNetNativeSharedAssemblyFrameworkPackage>false</UseDotNetNativeSharedAssemblyFrameworkPackage> - Eliminates one of the linking boundaries the compiler has to fight with. I actually suspect turning this off will make things worse not better but whole program optimizers are hard to reason about but rebuilds are cheap enough to try.
Runtime Directives
There’s lots of reading above but the tl;dr is that this file is read by the compiler and can contain lots of hints about what we want it to do or ignore etc. The overall syntax of the file is also included in the reading above but I don’t think we’re very clear about the one special directive that’s include by default:
<Assembly Name="*Application*" Dynamic="Required All" />
This directive says: “Please save/generate enough information so that all user types can be inspected and created via reflection.” Where ‘user types’ means any type in an assembly that isn’t signed with the .NET key token. So, basically everything that isn’t explicitly .NET Framework. This in leads to lots of bloat but also makes it so most folks don’t ever have to think about these things. In cases where we don’t have enough information, you’ll get runtime exceptions like MissingMetadataException or TypeLoadException or NullReferenceException. Each instance will require a bit of code inspection and fiddling with directives to get patched up. This can be an annoying a fragile process. All that said, the analysis engine is quite sophisticated and you’ll get lots and lots of things ‘for free’ without the special directive or any hassle. It’s entirely possible that your app runs great with just a little bit of tweaking.
Okay, the goal now is to remove this directive but still have a working application. There’s two approaches that have tradeoffs, so I’ll describe both and let you decide if either methodology suits you. Roughly here’s what the two workflows look like:
Start from nothing.
a. Remove the special Application directive
b. Build the app
c. If the build fails, email us, else…
d. Test the app and see if you hit any runtime errors
e. If you do you’ll need to look at the error location and see if adding some directives can help then head back to (b).
f. If you find no errors, you’re done! Hooray!
Start from everything
a. Remove the special Application directive
b. Get a list of the full set of dlls for your project, for example by inspecting here: obj[architecture]\Release\ilc\in
c. For each dll, add a Dynamic directive. They’ll look like: <Assembly Name="ASSEMBLYNAMEWITHOUTEXTENTION" Dynamic="Required All"/>
d. Comment out some subset of these libraries
e. Build the app
f. If the build fails again in RHBIND go to (d)
g. Test the app and see if you hit any runtime errors
h. If you do you’ll need to look at the error location and see if adding some directives can help then head back to (e)
i. If you find no errors, you’re done! Hooray!
I found a solution which worked:
Instead of downloading the portable.AForge package with NuGet i downloaded the portable.AForge from GitHub.
Find the .cs-file called SystemTools.cs (located in AForge/Sources/Core/).
Open it with any .cs editing porgram, now search for all code like
#if !MONO
...
#else
and remove it.
This clears the use of memcpu() or memset() from ntdll.dll.
Save the SystemTools.cs, create the library and add the AForge-Package manually to the application.
After the change it worked without any problems.

C# .NET security how to prevent program to load

I've 2 .NET c# application without any security features. I wanted to implement a security mechanism myself which i will describe below, and i would like your comments if this is would work or there are things which i dont know.
So, when i need to run MyApp, i run AuthenticationAPP, this app will ask me for a security code.
IF code is correct -> load MyApp;
ELSE -> do not load app
What i was wondering is if there is a method to bypass this kind of mechanism and therefore transforming my authenticaitonAPP in uselessAPP very easly or if those methods are hard to implement.
thank you for any ideas/clarification.
You need to prevent the .net runtime from loading and executing any of the assemblies in MyApp. To ensure that you need to specify code permissions for your assemblies.
The code permissions has to check for a condition that can only be set correctly by AuthentificationAPP. It could something as simple as an encrypted call parameter from AuthentificationAPP to MyApp.
Then you have to make sure that your code can't be reverse engineered by a third party. So you have to look into code obfuscation and signing.
I think you can add code permissions on assembly level. So it could be that all you need is to add a single source file with assembly level code permissions and call context verification to each of you 1000 programs and the recompile those.
There exist different wrapping protection solutions like VMProtect, ASProtect, Armadillo etc.
Maybe they will fit your task.

P/Invoke dynamic DLL search path

I have an existing app which P/Invokes to a DLL residing in the same directory as the app itself.
Now (due to the fact that Canon produces one of the crappiest API's around) I need to support two versions of this API and determine at run-time which one I should use (old or new). Since the DLLs have the same name (the first one loads other DLLs with same names so just renaming the first one won't help me) I must keep them in different directories.
Hence my question: what options do I have to control what directory the DLL given in a DllImport declaration uses?
I guess I can start out by trying any of these two ideas:
1) Use "SetDllDirectory" to set my desired directory before doing the first P/Invoke and then reset it afterwards.
2) Load the desired DLL manually using "LoadLibraryEx" and hope that that will do the trick.
But are there any more ".NET:ish way" to try out first?
UPDATE: I realize that I can stuff all access to the DLLs in two separate .Net assemblies and then place each one of them in a separate directory with the corresponding API files. Then I can load the proper .Net assembly dynamically and the loading of the correct DLL whould happen automatically. Any reason that shouldn't work?
I can think of one: how would I go about debugging this stuff? It is possible to tell Visual Studio that an assembly (contained in my solution) shall be placed in a subdirectory and debugged from there?
My condolences, I've seen one of the APIs and it was indeed shockingly bad. The bigger problem is that you'll need to be able to convince Windows to find the DLL. They won't be in your .exe directory so the default won't work. Using SetDllDirectory() would work, using Environment.CurrentDirectory does too. LoadLibrary cannot work, the P/Invoke marshaller will use LoadLibrary itself.
If it is at all an option, you can use different names for the two P/Invoke declarations, using different arguments for the DllImport() constructor and using the EntryPoint attribute. Doesn't sound like that will fly.
I think 2nd option will work, but it will require to write a lot of code to manage dll loading in .net.
First one might work also, but i either don't like it.
Here is my suggestion: you can specify full path (and may be relative) in DllImport [DllImport(#"C:\dll\a32.dll"]
Your first option (P/Invoke with SetDllDirectory) is the option I personally prefer. Unfortunately, there isn't a ".NETish" way to handle loading native DLLs...which does make sense.
Starting with .NET Core 3.0, and also works with .NET 5 & .NET 6, you can use NativeLibrary.Load(string) to dynamically load DLLs at runtime, and use via P/Invoke normally.
Check this answer for more details: https://stackoverflow.com/a/69958827/211672

ORM and .NET Code Protectors

We are about to use Code Protectors (Obsfucation as well as Native Compilation), I assume ORMs will be dependent little bit on Reflection and I am worried will Obsfucation and Native Compilation protection techniques create any problems?
Has anyone tried successful ORM and Code Protection for any good desktop application? We are having WPF Desktop Application.
Our primary language for development is C# and we are using our custom ORM but I want to evaluate any commercial ORM or ADO.NET EF etc as well.
Question is not about what is Code Protection and which one I should use, I am trying to ask about the effect of protection on ORM.
If your code is using Reflection, most probably the obfuscated assembly will not work. You will need to exclude from obfuscation those entities referenced by their original name. Take a look at Crypto Obfuscator which will analyze your code during obfuscation and show all methods and line numbers where potentially breaking methods (such as Reflection ) are called. This is a huge timer-saver since it pinpoints the exact location and helps determine the properties/classes you need to exclude from renaming.
Try .Net Reactor. Available at http://www.eziriz.com/
Its a LOT cheaper than some of the others around, and it can do a lot more. You can also disable certain options (like obfuscation, to preserve the use of reflection) and only have certain options enabled like ILDASM Suppression, which will still protect the code.
Cheers
Redgate acquired Smart Assembly not too long ago, which is what I'd look at if I had a need to do this.
A while ago I trialed CodeViel to look at obfuscating/encrypting code with some degree of success. I think if you’re serious about doing this it’s not as simple as dropping an assembly in one end and it popping out a protected assembly. You will have to consider portions of your code (ie Namespaces, Classes, Methods, Fields, Properties, Structures, Events, and Resources) which are only to be used internally, and those that need to be exposed to other resources and libraries. In the case I was looking at I was able to encrypt (or use native compilation) to hide some method implementations, but left the class definition (name, methods, properties untouched). In some cases I left whole namespaces untouched as they contained only simple POCO objects required by other libraries.
It really seems to be a careful case by case basis as to what strategy you use where, some internals you could obfuscate to make decompilation/reverse engineering hard and that would be enough. Other cases you could use the encryption/native compilation to simply hide a method implementation. And you will also get cases where you are excluding portions of an assembly from being touched at all. Most of these programs will give you some recommended defaults and options that you can start from, but you will need to tweak and change these until you can produce results that protect your core IP but don't restrict your end users.

How to use reflection to create a "reflection machine"

OK so that title sucks a little but I could not think of anything better (maybe someone else can?).
So I have a few questions around a subject here. What I want to do is create a program that can take an object and use reflection to list all its properties, methods, constructors etc. I can then manipulate these objects at runtime to test, debug and figure out exactly what some of my classes / programs are doing whilst they are running, (some of them will be windows services and maybe installed on the machine rather than running in debug from VS).
So I would provide a hook to the program that from the local machine (only) this program could get an instance of the main object and therefore see all the sub objects running in it. (for security the program may need to be started with an arg to expose that hook).
The "reflection machine" would allow for runtime manipulation and interrogation.
Does this sound possible?
Would the program have to provide a hook or could the "reflection machine" take an EXE and (if it knew all the classes it was using), create an object to use?
I know you can import DLL's at runtime so that it knows about all sorts of classes, but can you import individual classes? I.E. Say I have project 'Y' that is not compiled to a DLL but I want to use the "reflection machine" on it, can I point at that directory and grab the files to be able to reference those classes?
EDIT: I would love to try and develop it my self but I already have a long list of projects I would like to do and have already started. Why reinvent the wheel when there is already a great selection to choose from.
Try looking at Crack.NET. It is used to do runtime manipulation and interrogation on WPF/WinForms but the source is available and might be a good start if it already doesn't meet your needs.
It sound as if Corneliu Tusnea's Hawkeye might be close to what you're looking for runtime interrogation of objects/properties/etc. He calls it the .NET Runtime Object Editor. I'm not sure if the homepage I linked to above or the CodePlex project is the best place to start.
It's a bit out of date now, I think, but there's an earlier version of it on CodeProject where you can see the source code for how and what he did.
Powershell actually does nearly all of this, if I properly understand what you are saying.
See this answer on how to build a "reflection engine".
All you need to do is to drop that set of machinery in the your set of available
runtime libraries and it does what you want, I think.
(It might not be as easy as I've made it sound in practice).
My guess is you'll also want a runtime compiler, so that you can
manufacture instrumented/transformed variants of the program under inspection
to collect the runtime data you want. You may find that such
machinery provide static analysis results that let you avoid
doing the runtime analysis in many cases.

Categories

Resources