TypeScript Obfuscation - obfuscation

Are there any tools or forks of TypeScript to support public namespace obfuscation? I.e. to turn:
class MyUtil {
print(): void { ... }
}
Into something like:
class xxy {
aab(): void { ... }
}
If not, would be be straight forward to fork the compiler to provide this? Perhaps with some type of class annotation indication what should / shouldn't be obfuscated.
(Obviously public obfuscation has to be used carefully, no good for libraries! But great if used consistently across your project)

I had the exact same question, and it was instantly deleted by SO.
https://github.com/angular/ts-minify
This is exactly the tool you (and I) are looking for, it seems to work pretty well, I needed to comment out a few parts where the the author was taking precautions I don't think are applicable.

I don't believe there is any reason to do this in TypeScript. You can instead use something like Closure Compiler to do the obfuscation on your JavaScript output. Specifically look into Closure's Advanced Compilation settings.

 Not a direct answer! Js obfuscator
https://github.com/javascript-obfuscator/javascript-obfuscator
Plugins:
Webpack plugin: webpack-obfuscator
Webpack loader: obfuscator-loader
Gulp: gulp-javascript-obfuscator
Grunt: grunt-contrib-obfuscator
Rollup: rollup-plugin-javascript-obfuscator
NOTE:
Only obfuscate the code that belongs to you.
It is not recommended to obfuscate vendor scripts and polyfills, since
the obfuscated code is 15-80% slower (depends on options) and the
files are significantly larger.

Related

Kotlin Nested Object Classes

Ok so i'v been starting to learn kotlin for a week now, and i love the language:p
Besides the great utility of extension function, i feel like they lack a proper way of creating namespaces like java utility classes (xxxUtil).
I have recently starting to use this aproach, which im not sure is the right one, and i would like some feedback from Kotlin experienced users.
Is this a valid and proper thing todo:
object RealmDb {
private val realmInstance by lazy{ Realm.getInstance(MainApplication.instance) }
private fun wrapInTransaction(code:() -> Unit){
realmInstance.beginTransaction();
code.invoke()
realmInstance.commitTransaction();
}
object NormaNote{
fun create(...) {...}
fun update(...) {...}
}
}
So, whenever i want to update some NormalNote value to a Realm Database, i do the following:
RealmDb.NormaNote.create(title.text.toString(), note.text.toString())
Is this a common thing to do? Are there better approaches? As i understood, this is singleton nesting, i don't think there's any problem with this, i just don't like to put this common things like DB operations inside classes that need to be instantiated. In old java i opted to static classes
The officially recommended way to create namespaces in Kotlin is to put properties and functions that don't need to be inside classes at the top level of the file, and to use the package statements to create a namespace hierarchy. We see the practice of creating utility classes in Java as a workaround for a deficiency in the language, and not as a good practice to be followed in other languages.
In your example, I would put all of the code in top-level functions and properties.
I don't know about the rest of the code, but I do know that you don't have to call .invoke () on code. The invoke method can always be shortened to a direct call, which in this case would be code ().

Best approach to extend a Camel Route

We have lots of routes which do common stuff. I would like to move that stuff into a Base Route and add/overwrite functionality (e.g. adding system dependent headers, doing system dependent enrichments, etc) in the extension.
What is a good approach for that? Would it make sense to use the AdviceWithRouteBuilder since I saw only examples where it is used in unit tests?
Are there other ideas?
Thanks
Yusuf
You can do "sub routes". I have found them very useful for doing common tasks.
Create something like this inside a "CommonRoutes" route builder:
// Example
from("direct:extractCommonMetadata")
.setHeader("orderid").xpath("/data/orderid")
.setHeader("customer").xpath("/data/customer")
from("direct:enrichWithCommonStuff")
.enrich("foo:baz")
Then you can simply do this in your various routes:
from("foo:bar")
.inOut("direct:extractCommonMetadata")
.inOut("direct:enrichWithCommonStuff
.foo("bar")
from("bar:foo")
.inOut("direct:extractCommonMetadata")
.to("the little house on the hill");
The overhead of using the direct protocol is very low and a good way to break out common functionality.
If you use Java then its just java, and you can create a base RouteBuilder class, and do some shared stuff in the configure method, and call super.configure() from extended classes.

Is ReactiveUI Production Ready?

I've been looking into the feasability of using Reactive UI in production code. Some of the features are really appealing, but I have concerns about taking a dependency on this library. These include:
Whacky naming and conventions. For example, protected members starting with lower case, and the RaiseAndSetIfChanged method depends on your private member beginning with an underscore. I understand Paul Betts (ReactiveUI author) has a Ruby background, so I guess that's where the odd naming stems from. However, this will cause a real issue for me, since standard naming (as per Stylecop) is enforced throughout my project. Even if it wasn't enforced, I'd be concerned by the resultant inconsistency in naming that this will cause.
Lack of documentation/samples. There is some documentation and a lonely sample. However, the documentation is just a series of (old) blog posts and the sample is based on V2 of the library (it's now on V4).
Odd design, in parts. For example, logging is abstracted so as not to take a dependency on a specific logging framework. Fair enough. However, since I use log4net (and not NLog) I will need my own adapter. I think that will require me to implement IRxUIFullLogger, which has a metric crapload of methods in it (well over 50). I would have thought a far better approach would be to define a very simple interface and then provide extension methods within ReactiveUI to facilitate all the requisite overloads. In addition, there's this weird IWantsToRegisterStuff interface that the NLog assembly depends on, that I won't be able to depend on (because it's an internal interface). I'm hoping I don't need that...
Anyway, my concern here is the overall design of the library. Has anyone been bitten by this?
I'm already using MVVM Light extensively. I know Paul did a blog post where he explains you can technically use both, but my concern is more around maintainability. I suspect it would be horribly confusing having both intermingled in one's code base.
Does anyone have hands-on experience with using Reactive UI in production? If so, are you able to allay or address any of my above concerns?
Let's go through your concerns piece by piece:
#1. "Whacky naming and conventions."
Now that ReactiveUI 4.1+ has CallerMemberName, you don't have to use the conventions at all (and even then, you can override them via RxApp.GetFieldNameForPropertyFunc). Just write a property as:
int iCanNameThisWhateverIWant;
public int SomeProperty {
get { return iCanNameThisWhateverIWant; }
set { this.RaiseAndSetIfChanged(ref iCanNameThisWhateverIWant, value); }
}
#2. Lack of documentation/samples
This is legit, but here's some more docs / samples:
http://docs.reactiveui.net/ (this is the official ReactiveUI documentation, a work in progress but definitely where you want to start)
https://github.com/reactiveui/ReactiveUI.Samples
https://github.com/reactiveui/RxUI_QCon
https://github.com/play/play-windows
#3. "I would have thought a far better approach would be to define a very simple interface and then provide extension methods within ReactiveUI to facilitate all the requisite overloads"
Implement IRxUILogger instead, it has a scant two methods :) ReactiveUI will fill in the rest. IRxUIFullLogger is only there if you need it.
"In addition, there's this weird IWantsToRegisterStuff interface "
You don't need to know about this :) This is only for dealing with ReactiveUI initializing itself so that you don't have to have boilerplate code.
"I suspect it would be horribly confusing having both intermingled in one's code base."
Not really. Just think of it as "MVVM Light with SuperPowers".
I am answering as someone who has used ReactiveUI in a few production systems, has had issues with the way RxUI does stuff, and has submitted patches to try and fix issues I've had.
Disclaimer: I don't use all the features of RxUI. The reason being I don't agree with the way those features have been implemented. I'll detail my changes as I go.
Naming. I thought this was odd too. This ended up being one of the features I don't really use. I use PropertyChanged.Fody to weave in the change notification using AOP. As a result my properties look like auto properties.
Doco. Yes there could be more. Especially with the newer parts like routing. This possibly is a reason why I don't use all of RxUI.
Logging. I've had issues with this in the past. See pull request 69. At the end of the day I see RxUI as a very opinionated framework. If you don't agree with that opinion you can suggest changes, but that's all. Opinionated does not make it bad.
I use RxUI with Caliburn Micro. CM handles View-ViewModel location and binding, Screen and Conductors. I don't use CM's convention binding. RxUI handles Commands, and ViewModel INPC code, and allows me to react to property changes using Reactive instead of the traditional approaches. By keeping these things separate I find it much easier to mix the two together.
Does any of these issues have anything to do with being production ready? Nope. ReactiveUI is stable, has a decently sized user base, problems get solved quickly in the google group and Paul is receptive to discussion.
I use it in production and so far RxUI has been perfectly stable. The application has had problems with stability, some to do with EMS, others with an UnhandledException handler that was causing more problems than it was solving, but I've not had any problems with the ReactiveUI part of the application. However, I have had issues regarding the ObservableForProperty not firing at all, which I may have used incorrectly and did work consistently (incorrectly) in my test code as well as in the UI at run time.
-1. Paul explains that the _Upper is due to using reflection to get at the private field in your class. You can either use a block such as below to deal with the StyleCop and Resharper messages, which is easy to generate (from the Resharper SmartTag)
/// <summary>The xxx view model.</summary>
public class XXXViewModel : ReactiveObject
{
#pragma warning disable 0649
// ReSharper disable InconsistentNaming
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. ReactiveUI field.")]
private readonly bool _IsRunning;
[SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1306:FieldNamesMustBeginWithLowerCaseLetter",
Justification = "Reviewed. ReactiveUI field.")]
private string _Name;
....
or change your properties from the full
/// <summary>Gets or sets a value indicating whether is selected.</summary>
public bool IsSelected
{
get { return _IsSelected; }
set { this.RaiseAndSetIfChanged(x => x.IsSelected, value); }
}
to its component parts such as
/// <summary>Gets or sets a value indicating whether is selected.</summary>
public bool IsSelected
{
get { return _isSelected; }
set
{
if (_isSelected != value)
{
this.RaisePropertyChanging(x => x.IsSelected);
_isSelected = value;
this.RaisPropertyChanged(x=>x.IsSelected);
}
}
}
This pattern is also useful where you don't actually supply a "simple" property accessor, but may require a more derived variant where setting one value affects multiple others.
-2. Yes the documentation isn't ideal but I found that after Rx, picking up the RxUI samples was quite easy. I also note that the jumps from 2->4 seem to have all come with the changes to support Windows 8/Windows 8 Phone, and having picked up ReactiveUI for a Windows Store App then the DotNet 4.5 support is excellent. i.e. use of [CallerName] now means that you simply this.RaiseAndSetIFChanged(value) no need for the expression.
-3. I haven't any feedback on the logging side as I've not elected to use it.
-4. I've not mixed and matched with others frameworks either.
There's also a list of other contributors to ReactiveUI 4.2 at http://blog.paulbetts.org/index.php/2012/12/16/reactiveui-4-2-is-released/, including Phil Haack.

JUnit 4 PermGen size overflow when running tests in Eclipse and Maven2

I'm doing some unit tests with JUnit, PowerMock and Mockito. I have a lot of test classes annotated with #RunWith(PowerMockRunner.class) and #PrepareForTest(SomeClassesNames) to mock final classes and more than 200 test cases.
Recently I've run into a problem of a PermGen space overflow when I run my entire test suite in Eclipse or Maven2. When I run my test one by one then each of them succeeds.
I did some research about that, however none of the advice helped me (I have increased PermGenSize and MaxPermSize). Recently I've found out that there is one class that contains only static methods and each method returns object mocked with PowerMockito. I'm wondering whether it is a good practice and maybe this is the origin of the problem because static variables are being shared between unit tests?
Generally speaking is it a good practice to have a static class with a lot of static methods which returns static mocked objects?
I am getting PermGen errors from Junit in Eclipse too. But I am not using any mocking libs like Mockito nor EasyMock. However, my code base is large and my Junit tests are using Spring-Test (and are intense and complex test cases). For this, I need to truly increase the PermGen for all of my Junit tests.
Eclipse applies the Installed JRE settings to the Junit runs - not the eclipse.ini settings. So to change those:
Window > Preferences > Java > Installed JRE's
select the default JRE, Edit... button
add to Default VM Arguments: -XX:MaxPermSize=196m
This setting will allow Junit tests to run the more intense TestCases in Eclipse, and avoid the OutOfMemoryError: PermGen. This should also be low risk because most simple Junit tests will not allocate all of that memory.
As #Brice says, the problems with PermGen will be coming from your extensive use of mocked objects. Powermock and Mockito both create a new class which sits between the class being mocked and your test code. This class is created at runtime and loaded into PermGen, and is (practically) never recovered. Hence your problems with the PermGen space.
To your question:
1) Sharing of static variables is considered a code smell. It's necessary in some cases, but it introduces depdendencies between tests. Test A needs to run before test B.
2) Usage of static methods to return a mocked object isn't really a code smell, it's a attern which is often used. If you really can't increase your permgen space, you have a number of options:
Use a pool of mocks, with PowerMock#reset() when the mock is put back into the pool. This would cut down on the number of creations you're doing.
Secondly, you said that your classes are final. If this is changeable, then you could just use an anonymous class in the test. This again cuts down on the amount of permgen space used:
Foo myMockObject = new Foo() {
public int getBar() { throw new Exception(); }
}
Thirdly, you can introduce an interface (use Refactor->Extract Interface in Eclipse), which you then extend with an empty class which does nothing. Then, in your class, you do similar to the above. I use this technique quite a lot, because I find it easier to read:
public interface Foo {
public int getBar();
}
public class MockFoo implements Foo {
public int getBar() { return 0; }
}
then in the class:
Foo myMockObject = new MockFoo() {
public int getBar() { throw new Exception(); }
}
I have to admit I'm not a particular fan of mocking, I use it only when necessary, I tend to either extend the class with an anonymous class or create a real MockXXX class. For more information on this point of view, see Mocking Mocking and Testing Outcomes. by Uncle Bob
By the way, in maven surefire, you can always forkMode=always which will fork the jvm for each test class. This won't solve your Eclipse problem though.
First : Mockito is using CGLIB to create mocks, and PowerMock is using Javassist for some other stuff, like removing the final markers, Powermock also loads classes in a new ClassLoader. CGLIB is known for eating the Permanent Generation (just google CGLIB PermGen to find relevant results on the matter).
It's not a straight answer as it depends on details of your project :
As you pointed there is static helper class, I don't know if holds static variables with mocks as well, I don't know the details of your code, so this is pure guess, and other readers that actually knows better might correct me.
It could be the ClassLoader (and at least some of his childrens) that loaded this static class might be kept alive across tests - it might be because of statics (which lives in the Class realm) or because of some reference somewhere - that means that if the ClassLoader still lives (i.e. not garbage collected) his loaded classes are not discarded i.e. the classes including the generated ones are still in the PermGen.
These classes might also be huge in size, if you have a lot of these classes to be loaded this might be relevant to have higher PermGen values, especially since Powermock needs to reload classes in a new Classloader for each tests.
Again I don't know the details of your project, so I'm just guessing, but your permanent generation issue might be caused either due to point 1 or point 2, or even both.
Anyway generally speaking I would say yes : having a static class that might return static mocked object does look like a bad practice here, as it usually is in production code. If badly crafted it can leads to ClassLoader's leak (this is nasty!).
In practice I've seen running hundreds of tests (with Mockito only) without ever changing memory parameters and without seeing the CGLIB proxies being unloaded, and I'm not using static stuff appart the ones from the Mockito API.
If you are using a Sun/Oracle JVM you can try these options to track what's happening :
-XX:+TraceClassLoading and -XX:+TraceClassUnloading or -verbose:class
Hope that helps.
Outside the scope of this question :
Personnaly I don't like using to use Powermock anyway, I only use it in corner cases e.g. for testing unmodifiable legacy code. Powermock is too intrusive imho, it has to spawn for each test a new classloader to perform its deeds (modifying the bytecode), you have to heavily annotate the test classes to be able to mock, ...
In my opinion for usual development all these little inconvenience outweight the benefit of the hability to mock finals. Even Johan the author of Powermock, once told me he was recommanding Mockito instead and keeping Powermock for some specific purpose.
Don't get me wrong here: Powermock is a fantastic piece of technology, that really help when you have to deal with (poorly) designed legacy code that you cannot change. But not for the every day developpement, especially if praticing TDD.

Using Moq at Blend design time

This might be a bit out there, but suppose I want to use Moq in a ViewModel to create some design time data, like so:
public class SomeViewModel
{
public SomeViewModel(ISomeDependency dependency)
{
if (IsInDesignMode)
{
var mock = new Mock<ISomeDependency>();
dependency = mock.Object; // this throws!
}
}
}
The mock could be set up to do some stuff, but you get the idea.
My problem is that at design-time in Blend, this code throws an InvalidCastException, with the message along the lines of "Unable to cast object of type 'Castle.Proxies.ISomeDependencyProxy2b3a8f3188284ff0b1129bdf3d50d3fc' to type 'ISomeDependency'." While this doesn't necessarily look to be Moq related but Castle related, I hope the Moq example helps ;)
Any idea why that is?
Thanks!
I'm having a similar issue, except that the cast is coming from a dynamically generated assembly (Blend_RuntimeGeneratedTypesAssembly) type that is masquerading as one of my types.
For no apparent reason.
Which is driving me CRAZY.
I used to think that I needed to do this sort of trick but after much experiementing and searching about, discovered that Blend 4 now can create design time sample datacontexts based on an existing class.
This effectively gives you a dummy class that looks just like your VM class so that you can add your binding etc.
It works well enough that this is the technique we now recommend.
A possible disadvantage with this is that if you need your real VM to perform some sort of interactivity then the proxy of course can't do that - you'd have to manually change values, or swap to another design time object. But in practice, I've rarely encountered this scenario. Most of the time, you set the state of the VM and then take ages getting the look right.
Update: released on github: https://github.com/GeniusCode/GeniusCode.Components.DynamicDuck
I also ran into a similar problem when trying to use castle to mock viewmodels at design time. We wrote our own msil duck / mock library, and it works well for that purpose.
I blogged about it here: http://blogs.geniuscode.net/JeremiahRedekop/?p=255
We are working to release the library under MS-PL and deploy on GitHub.

Resources