How to identify a component is spark or mx - actionscript-3

I need to check the component is spark or mx I have tried with checking is IVisualElementContainer
But both spark and mx component are fall into IVisualElementContainer my code sample are as follows
displayMessage(vidbox, 'videbox removed');
public function displayMessage(messageParent:*, message:String, fontSize:String = "30"):void {
messageLabel.text = message;
if(messageParent is IVisualElementContainer)
messageParent.addElement(messageLabel);
else
messageParent.addChild(messageLabel);
}
any helps are highly appreciated

There is getQualifiedClassName which returns "the fully qualified class name of an object.", so then you can check if class name starts with "mx." or "spark.".
Code sample:
var fullClassName:String = getQualifiedClassName(messageParent).toLowerCase();
if(fullClassName.indexOf("spark.") == 0)
{
//spark comp
messageParent.addElement(messageLabel);
}
else if(fullClassName.indexOf("mx.") == 0)
{
// mx comp
messageParent.addChild(messageLabel);
}
else
{
// other
}

Related

Blazor WASM Passing value from server to the client dynamically

I've made an application with Blazor WebAssembly with a 5min timer in a BackgroundService into my SERVER.
Now, everytime a second change I would like to notify my client to update the timer on the CLIENT page. (it's a Component)
I was wondering if there was a solution to call a CLIENT C# Method from my SERVER by using a SERVICE between this two ?
Do you have any suggestion ?
I've already created the shared SERVICE but I don't know how I can call my CLIENT C# method from my Service automatically.
ps : I've already trying to pass my values from my SERVER to a SERVICE who call a JAVASCRIPT function (with IJSRuntime) who will call my C# function to update the timer. But actually my Js function seems to not working.
[My Background Task]
`
// A 5min timer who create a Draw every 5min and update it when count is at 0
public async Task ClockCountDownAsync()
{
if (secTime == 0 && minTime != 0)
{
if (minTime == 5)
{
Draw newDraw = new Draw();
_unitOfWork.Draws.Add(newDraw);
await _unitOfWork.Complete();
}
minTime = minTime - 1;
secTime = 59;
}
else if (secTime != 0)
{
secTime = secTime - 1;
}
else if(minTime == 0 && secTime == 0)
{
await DrawAndAddNumbers();
minTime = 5;
secTime = 0;
}
int[] timeTab = new int[] { minTime, secTime };
_timerService.GetTimeFromCounter(timeTab);
}
`
[My Client Function]
`
public async Task UpdateTimer(int[] timeTab)
{
minTime = timeTab[0];
secTime = timeTab[1];
await InvokeAsync(StateHasChanged);
}
`
[The function in a Service shared who is called by the SERVER who need to call the function from my CLIENT]
`
public void GetTimeFromCounter(int[] timeTab)
{
// UpdateTimer(timeTab);
}
`

Custom ThingsBoard widget: set gauge value property

I need to edit the "Speed gauge" widget to show zero value when certain condition is met. This action should be executed in the onDataUpdated() function.
This widget inherits methods from the "TbAnalogueRadialGauge" class, which contains an update() method. If I'm not wrong, this would be its implementation:
update() {
if (this.ctx.data.length > 0) {
const cellData = this.ctx.data[0];
if (cellData.data.length > 0) {
const tvPair = cellData.data[cellData.data.length -
1];
const value = tvPair[1];
if (value !== this.gauge.value) {
this.gauge.value = value;
}
}
}
}
TbAnalogueRadialGauge extends TbAnalogueGauge. TbAnalogueGauge exends TbBaseGauge, where update() is implemented.
It seems to access the this.gauge.value property to update the gauge value. However, when I try to access this property from widget development IDE, it turns out to be undefined.
self.onDataUpdated = function() {
self.ctx.gauge.update();
console.log(self.ctx.gauge.value) // output: undefined
}
Does anyone have any ideas about how to access this property?
You need the following
self.ctx.gauge.gauge.value

how to unit test subscription to a BehaviourSubject in angular

I have a UserManagementService which exposes an Observable of a BehaviourSubject.
this.userSignInState$ = this.signInStateSubject.asObservable();
I subscribe to userSignInState in a nav component.
constructor(public userManagementService: UserManagementService, private fb:FormBuilder, private helper:HelperService) {
this.userSignInStateSubscription = this.userManagementService.userSignInState$.subscribe(
(result:Result)=> {
console.log("In nav - result from user signin state ",result);
let subscribed:UserSigninState = result.additionalInfo;
console.log("new user signin state received:", subscribed);
this.userLoggedIn = subscribed.isSignedIn;
if(subscribed.isSignedIn && subscribed['additional-info'] !== ''){
this.profile = JSON.parse(subscribed['additional-info']) as UserProfileAPI
}
if(!subscribed.isSignedIn && subscribed['additional-info'] !== ''){
// let error:ServerResponseAPI = JSON.parse(subscribed['additional-info']) as ServerResponseAPI
//let errorMessage:string = this.helper.userFriendlyErrorMessage(error);
this.navEvent.emit(new NavContext(subscribed['additional-info']));
}
},
(error:ServerResponseAPI)=>{
console.log("got error from the Observable: ",error);
let errorMessage:string = this.helper.userFriendlyErrorMessage(error);
this.navEvent.emit(new NavContext(errorMessage));
// this.userloggedIn =false;
},
()=>{ //observable complete
console.log("observable completed")
//this.userloggedIn =false;
});
}
I want to unit test nav. The spec should test that the component subscribes to userSignInState$ and handles Result correctly. How do I do this? As this is a unit test, I don't want to use the real UserManagementService
I wrote the following spec
fit('should subscribe to user sign in state observable',()=>{
let userManagementService = TestBed.get(UserManagementService);
let navComponent:NavComponentComponent = component;
console.log('component is ',navComponent);
navComponent.userLoggedIn = false;
let dummyUserProfile = new UserProfileAPI(new User('fn','ln','test#test.com'));
userManagementService.signInStateSubject.next(new Result('success',(new UserSigninState(true,JSON.stringify(dummyUserProfile ))).toString));
expect(navComponent.userLoggedIn).toBe(true)
});
but I got error Expected undefined to be true.
I don't understand why userLoggedIn is undefined. I have declared it in the nav class
export class NavComponentComponent implements OnInit {
userLoggedIn:boolean;
...
}
I set it in ngOnInit.
ngOnInit(){
this.userLoggedIn = false;
...
}
I also moved the subscription logic to ngOnInit but that doesn't work either and gives the same result.
The issue was with the way I was creating Result. I should have not used .toString with userSignInState. From another question I posted in SO, "reference to .toString without () is just a reference to that function, so if you log that you get the code for that function." Also, "toString() will not work as userSignInState doesn't have a meanigful string representation and is defaulting to [object Object]". I removed toString and the code worked as additional-info is of type any

Can I stop Angular.js’s json filter from excluding properties that start with $?

Angular.js has a handy built-in filter, json, which displays JavaScript objects as nicely formatted JSON.
However, it seems to filter out object properties that begin with $ by default:
Template:
<pre>{{ {'name':'value', 'special':'yes', '$reallyspecial':'Er...'} | json }}</pre>
Displayed:
{
"name": "value",
"special": "yes"
}
http://plnkr.co/edit/oem4HJ9utZMYGVbPkT6N?p=preview
Can I make properties beginning with $ be displayed like other properties?
Basically you can't. It is "hard-coded" into the filter's behaviour.
Nonetheless, it is quite easy to build a custom JSON filter that behaves identically with the Angular's one but not filtering out properties starting with '$'.
(Scroll further down for sample code and a short demo.)
If you take a look at the 1.2.15 version source code, you will find out that the json filter is defined like this:
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
So, it uses the toJson() function (the second parameter (true) means: format my JSON nicely).
So, our next stop is the toJson() function, that looks like this:
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
This function makes use of the "native" JSON.stringify() function, passing a custom replacer function (toJsonReplacer).
The toJsonReplacer() function handles some special cases: It checks if the key starts with $ and ignores it if it does (this is what we want to change) and it checks if the value is either a Window, a Document or a Scope object (in which case it converts it to a descriptive string in order to avoid "Converting circular structure to JSON" errors).
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
For the sake of completeness, the two functions that check for Window and Scope look like this:
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
Finally, all we need to do is to create a custom filter that uses the exact same code, with the sole difference that our toJsonReplacer() won't filter out properties starting with $.
app.filter('customJson', function () {
function isWindow(obj) {
return obj &&
obj.document &&
obj.location &&
obj.alert &&
obj.setInterval;
}
function isScope(obj) {
return obj &&
obj.$evalAsync &&
obj.$watch;
}
function toJsonReplacer(key, value) {
var val = value;
if (isWindow(value)) {
val = '$WINDOW';
} else if (value && (document === value)) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
function toJson(obj, pretty) {
if (typeof obj === 'undefined') { return undefined; }
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
return function(object) {
return toJson(object, true);
};
});
See, also, this short demo.
* The downside is that your custom JSON filter will not benefit from further improvement/enhancement of Angular's json filter, so you'll have to re-define your's to incorporate changes. Of course, for such a basic and simple filter like this, one should'nt expect frequent or extensive changes, but that doesn't mean there aren't going to be any.

How to hide library source code in Google way?

For instance, I have a library and I would like to protect the source code to being viewed. The first method that comes to mind is to create public wrappers for private functions like the following
function executeMyCoolFunction(param1, param2, param3) {
return executeMyCoolFunction_(param1, param2, param3);
}
Only public part of the code will be visible in this way. It is fine, but all Google Service functions look like function abs() {/* */}. I am curious, is there an approach to hide library source code like Google does?
Edit 00: Do not "hide" a library code by using another library, i.e. the LibA with known project key uses the LibB with unknown project key. The public functions code of LibB is possible to get and even execute them. The code is
function exploreLib_(lib, libName) {
if (libName == null) {
for (var name in this) {
if (this[name] == lib) {
libName = name;
}
}
}
var res = [];
for (var entity in lib) {
var obj = lib[entity];
var code;
if (obj["toSource"] != null) {
code = obj.toSource();
}
else if (obj["toString"] != null) {
code = obj.toString();
}
else {
var nextLibCode = exploreLib_(obj, libName + "." + entity);
res = res.concat(nextLibCode);
}
if (code != null) {
res.push({ libraryName: libName, functionCode: code });
}
}
return res;
}
function explorerLibPublicFunctionsCode() {
var lstPublicFunctions = exploreLib_(LibA);
var password = LibA.LibB.getPassword();
}
I don't know what google does, but you could do something like this (not tested! just an idea):
function declarations:
var myApp = {
foo: function { /**/ },
bar: function { /**/ }
};
and then, in another place, an anonymous function writes foo() and bar():
(function(a) {
a['\u0066\u006F\u006F'] = function(){
// here code for foo
};
a['\u0062\u0061\u0072'] = function(){
// here code for bar
};
})(myApp);
You can pack or minify to obfuscate even more.
Edit: changed my answer to reflect the fact that an exception's stacktrace will contain the library project key.
In this example, MyLibraryB is a library included by MyLibraryA. Both are shared publicly to view (access controls) but only MyLibraryA's project key is made known. It appears it would be very difficult for an attacker to see the code in MyLibraryB:
//this function is in your MyLibraryA, and you share its project key
function executeMyCoolFunction(param1, param2, param3) {
for (var i = 0; i < 1000000; i++) {
debugger; //forces a breakpoint that the IDE cannot? step over
}
//... your code goes here
//don't share MyLibraryB project key
MyLibraryB.doSomething(args...);
}
but as per the #megabyte1024's comments, if you were to cause an exception in MyLibraryB.doSomething(), the stacktrace would contain the project key to MyLibraryB.