Precompile protobuf-net Type Model for compact framework - compact-framework

I am deserializing thousands of objects on compact framework (3.5) and it is slow. Taking the devices 20+ seconds to finish. I found that it's done by reflection, instead of compile-and-run like non compact counterpart.
So I thought, could I pre-compile and generate a type model dll first?
So I did the following:
Extract all the Contract class to a smart device dll (it references Protobuf-net CF3.5 Dll)
Create a desktop 3.5 console application, referencing Protobuf-net "Desktop" Dll and the Contract Dll created above.
class Program
{
static void Main(string[] args)
{
var bb = TypeModel.Create();
foreach (var t in Assembly.GetAssembly(typeof(My.ContractX)).GetTypes())
{
var contract = t.GetCustomAttributes(typeof (ProtoBuf.ProtoContractAttribute), false);
if (contract.Length > 0)
{
bb.Add(t, true);
}
}
bb.Compile("My.TypeModel", "My.Serialization.dll");
}
}
Back to the device project, reference the Contract DLL, the generated My.Serialization.dll, and Protobuf-net CF3.5 Dll.
Instead of using the default model, modified it to deserialize with the model constructed by "new TypeModel()"
It actually compiles correctly. I look at the generated dll in the Reflector, it's as expected.
Except that upon running, it throws MissingMethodException. However exactly what is missing is missing because compact framework doesn't report that.
My bet is because the generated My.Serialization.dll actually refers to the "Desktop" dll, but some method is missing.
So back to my question, how could I achieve type model pre-generation to be used in compact framework? Or could I get performance boost by doing something else?

Good news, I suspect. I've spent quite insane amounts of time working on the issue of cross-compilation (ok, I've been mainly driven by people asking about WP7 and WinRT), culminating in a brand new cross-platform precompiler.
This already does what your code does, i.e. it looks for all the [ProtoContract] types in the input assembly/assemblies. I honestly haven't tried it for CF, but I'm very hopeful. I would genuinely love to hear how you get on. The only reason I haven't tested it against CF is that my external drive with my VS2008 VM died-a-death.
Usage:
precompile {some path}\YourCFDto.dll –o:MySerializer.dll –t:MySerializer
Note: at the moment you would need to build "precompile" from source, but if this is an issue, I can get around to publishing it.
If you have any problems whatsoever, please let me know.

Related

Razor view errors while Migrating from core 2.2 to 3.1

After doing the general upgrade steps for the migration. My razor had 100's of errors suddenly after removing Microsoft.AspNetCore.All. These error were not consistent, these were general compiler errors.
Some combination of
IDE1007 C# The name does not exist in the current context.
CS0111 C# Type already defines a member called with the same parameter types
CS0538 C# in explicit interface declaration is not an interface
CS0116 C# A namespace cannot directly contain members such as fields
or methods
CS8107 C# Feature is not available in C# 7.0. Please use
language version 9.0 or greater.
Just all over the place stuff, and this was all working perfectly in 2.2
I was able to fix this. What I found was that we had few places in the code where we were using # inside a razor block, this used to work fine but breaks in core 3.1. I am assuming that the process of generating the classes by Razor SDK was failing because I was also getting errors in index.g.cshtml.cs.
We probably had this issue in 5 files at most but we were getting 500+ build errors. Very frustrating, so adding this answer because I was not able to find any similar answer anywhere.
Example of bad code, notice the extra # inside {}.
#{ var replacements = new string[] { #Model.TotalItemsInCart.ToString() };}

Debugging an obfuscated .NET core application with DotPeek

I am hunting for a possible logic bomb in the code deployed to production by our vendor software factory.
For sake of curiosity of the readers, here is a brief recap. The application stopped working with an infinite wait at some point. Decompiling the obfuscated code, I found an odd Thread.sleep that should never be in an MVC API, where the amount is computed by difference of the current ticks to a value computed somehow. I.e.
private long SomeFunction(long param) {
if (param > 0)
Thread.Sleep(param);
return param;
}
private long GetSomeLongValue() {
//Simplified. There is a lot of long to string and back
return SomeFunction(Manipulate(DateTime.Now.Ticks - GetMysteryNumber()));
}
private long Manipulate(long param){
if (param < 0)
return param;
else
# Compute a random number of days between 0 and param / 86400000,
# and return its milliseconds value, always positive
}
And by running experiments with system clock, I found that there is a magic DateTime.Now value when the application works (before) and stops (right after one second). The experiment was consistent and repeatable.
Back to the question
I have done all this work using JetBrains DotPeek. This was done by looking at the code: human static analysis.
The problem is that what I have called SomeMysteryFunction is too well obfuscated that I really can't get any clue about what it does. I have the full code but I would like to take another approach.
I'd like to exercise that function and try to see if it returns consistent values that may be equal to the guilty timestamp. The function depends on the result of GetCallingAssembly method, so that will be a pain in the back.
I thought about running some sort of Program.cs or unit test that exploits the obfuscated function by reflection, but I'd like to debug using DotPeek. Why?
Disassembly can be a mess
I tried Telerik, but I had a lot more success with DotPeek decompiling async methods not in their StateMachine representation
I have never done this in my work experience. I just need to be sure about this being intentional or not.
How do I set up a test bed environment so that I can debug into a linked DLL decompiled by DotPeek?
This post In the Jungle of .NET Decompilers explains all .NET Decompilers that are worth to use.
Definitely the free and OSS tool dnSpy is the one you want to use for that sort of hacking[I'd like to exercise that function] scenarios.

Any alternative to shim feature provided in Microsoft fake framework?

I am wondering is there any alternative lib to the shim feature provided in Microsoft fake framework since it is only supported in ultimate version?
There are three frameworks to my knowledge that allow you to mock non virtual methods and sealed classes like Fakes' Shims. There are
Microsofts' Moles or Fakes
Teleriks JustMock
TypeMocks
They are all commercial because they use the Profiling API, which is very hairy and poorly documented, so coding them is a real pain.
And for the record I'm all for fakes. Most code that people are working on is legacy code. One of the Pragmatic Programmer's rules of refactoring is make sure that you have unit test coverage before any refactorings to avoid regression. This makes Fakes and similar frameworks super useful, especially when the legacy code was not written for test-ability.
Prig hasn't been updated to work with VS 2017, but Pose does, and works really well for what I needed it for (basic shimming of Environment.UserName, and DateTime.Now and similar), and has a really nice interface:
// Create shims. They only apply within this isolate block.
var dateTimeShim = Shim.Replace(() => DateTime.Now)
.With(() => new DateTime(2010, 1, 1));
var usernameShim = Shim.Replace(() => Environment.UserName)
.With(() => "john.wick");
// Shims are only active within an Isolate block - and you
// have to pass all shims you want to be active.
PoseContext.Isolate(() =>
{
// Run your test - shims are active at this point.
RunTest();
}, dateTimeShim, usernameShim);
EDIT
I should note that I get lots of errors when doing fairly basic tests - really scary errors like "Common Language Runtime detected an invalid program.", and "JIT Compiler encountered an internal limitation." so caveat emptor.
An open source alternative is Prig. MIT licenced and still active - but slightly behind with VS IDE

Mono compatibility with bool Type.op_Equality (Type, Type)

I am considering changing from VS2010 to Mono and as such I ran my assemblies through MoMA to see how much difficulties I may have with the transition. On the generated report I found that I continually get this error:
bool Type.op_Equality (Type, Type) Implement it properly once 4.0 impl details are known.
I checked the class status pages and have seen that bool Type.op_Equality is listed as being a TODO in both 4.5 and 4.0 in mscorlib.dll (system namespace) with it awaiting impl details. which brings me to my question:
Does anyone know if/when implementation details will be available? Or if I ignore this TODO, will my code still work?
I haven't heard about any bugs related to Mono's implementation of Type.op_Equality (which doesn't mean there aren't any of course).
The only way to actually know if your code will work is to try it out on mono. MoMA is just a guide, not an oracle, and as such it lists potential issues (with a varying degree of seriousness).
For any particular code in Mono it is also possible to check the source code to see if the message you get in MoMA affects you or not.
For instance: https://github.com/mono/mono/blob/master/mcs/class/corlib/System/Type.cs#L482.

Example of a simple ASP.NET MVC + NHibernate + Fluent with proper session handling?

I'm new to all of these technologies. I would like to see a simple (not over the top) example of how you would set up a project with these technologies. The most important being the proper NHibernate session handling (using HttpContext). Or we can build off of what I already have.
I've seen several examples of one piece or another but nothing with all of these technologies mixed. I'm having a tough time tying them together.
Right now I have an NHibernateHelper class (<-- see the pastebin link) that someone provided me as an example. I've modified it slightly. I think I need to do some stuff in my Global.asax.cs file but I'm not sure exactly what. I need to somehow initialize the NHibernateHelper by passing its constructor an Assembly... but what kind of Assembly? This is where I get really lost. What am I missing?
In your example, The Assembly parameter is the Assembly that contains all Mapping files (hbm.xml) or Mapping classes (fluent nhibernate).
I'do like to recommend you to read this Tutorial. This is how i usually do, create a new HttpModule that opens a new session once per request and binds it to the web context. At the end of the request the session is closed. This is another example of the same implementation,
although the post is written in pt-BR, the code is in english.