How can i check the connection off/on using ionic3 - ionic-framework

with what i can replace " Network.connection"? it's no more valid !! please i need help
import { Network } from '#ionic-native/network';
isOnline(): boolean {
if(this.onDevice && Network){
return Network.connection!== Connection.NONE;
} else {
return navigator.onLine;
}
}

Check the documentation for the plugin: https://ionicframework.com/docs/native/network/
But in your case it seems to work with
return this.network.type != 'none';
After injecting the plugin of course.

Related

Exposing all RevenueCat PurchasesErrorCode codes in flutter

I need to trap all of the listed PurchasesErrorCode error codes in my Flutter app so I can respond to them accordingly.
Currently I can only trap "userCancelled", for everything else I can only report the information returned in the standard PlatformException code, message and details properties, without knowing what they will contain.
try {
// Code to make purchase..
} on PlatformException catch (e) {
if (!(e.details as Map)["userCancelled"]) {
// Here I need a comprehensive switch statement so I can
// retry where appropriate/control what messages the user sees
String reason = '';
(e.details as Map).forEach((k,v) => reason += '$k => $v');
showError(context, 'Error', '${e.code} : ${e.message}');
} else {
showError(context, 'Purchase Cancelled', 'Your purchase was not completed, you have not been charged.');
}
}
These codes are exposed in IOS/Swift and Android/Kotlin but I can't get them in Flutter/Dart - what am I missing?
I developed the RevenueCat Flutter plugin and I created an issue on GitHub some time ago to track this (https://github.com/RevenueCat/purchases-flutter/issues/3). I am sorry there is some room for improvement in our Flutter error handling.
When we send the platform exceptions we pass the error code as an String:
result.error(error.getCode().ordinal() + "", error.getMessage(), userInfoMap);
Too bad we can't just pass an int as the first parameter and we have to pass a String, I guess we could pass it in the userInfoMap. But for now, since we are not providing the enum with the error codes yet, you would have to do something like this in your code:
enum PurchasesErrorCode {
UnknownError,
PurchaseCancelledError,
StoreProblemError,
PurchaseNotAllowedError,
PurchaseInvalidError,
ProductNotAvailableForPurchaseError,
ProductAlreadyPurchasedError,
ReceiptAlreadyInUseError,
InvalidReceiptError,
MissingReceiptFileError,
NetworkError,
InvalidCredentialsError,
UnexpectedBackendResponseError,
ReceiptInUseByOtherSubscriberError,
InvalidAppUserIdError,
OperationAlreadyInProgressError,
UnknownBackendError,
InsufficientPermissionsError
}
try {
} on PlatformException catch (e) {
PurchasesErrorCode errorCode = PurchasesErrorCode.values[int.parse(e.code)];
switch (errorCode) {
case PurchasesErrorCode.UnknownError:
case PurchasesErrorCode.PurchaseCancelledError:
case PurchasesErrorCode.StoreProblemError:
// Add rest of cases
}
}
When you do e.details, you also get access to a readableErrorCode containing the name of the error code; and an underlyingErrorMessage, that can hopefully help you debug any issue.
I hope that helps
The issue mentioned on the previous answer was solved, after version 1.0.0 you can handle like this:
try {
PurchaserInfo purchaserInfo = await Purchases.purchasePackage(package);
} on PlatformException catch (e) {
var errorCode = PurchasesErrorHelper.getErrorCode(e);
if (errorCode == PurchasesErrorCode.purchaseCancelledError) {
print("User cancelled");
} else if (errorCode == PurchasesErrorCode.purchaseNotAllowedError) {
print("User not allowed to purchase");
}
}

Why ionic Network Plugin is not working after upgrading.?

This code was working fine till upgrade to ionic 3.4.
now in serve command shows :
Property 'connection' does not exist on type 'Navigator'.
I've replaced this code Network.connection with navigator.connection but still the same result.
export class NetworkService {
onDevice: boolean;
constructor(public platform: Platform , private Network: Network){
this.onDevice = this.platform.is('cordova');
}
isOnline(): boolean {
if(this.onDevice && Network.connection){
return Network.connection !== Connection.NONE;
} else {
return navigator.onLine;
}
}
isOffline(): boolean {
if(this.onDevice && Network.connection){
return Network.connection === Connection.NONE;
} else {
return !navigator.onLine;
}
}
}
The wrapper around that plugin has changed and doesn't expose a 'connection' property. Instead you need to use 'type' property. Full example available on the ionic documentation here.

How to write to log from vscode extension?

I am attempting to develop an extension with a language-server for VSCode. I am trying to figure out how to write text to log from language-server part of the extension. console.log produces nothing
Just as an update, you can use vscode.window.createOutputChannel to create the output container and then write to it with the appendLine method.
//Create output channel
let orange = vscode.window.createOutputChannel("Orange");
//Write to output.
orange.appendLine("I am a banana.");
Just open vscode and go to menu "Help"->"Toggle Developer Tools" and the console is displayed on rigth window.
On server side try using connection.console.log.
// Create a connection for the server. The connection uses
// stdin / stdout for message passing
let connection: IConnection = createConnection(process.stdin, process.stdout);
connection.console.log(`Console test.`);
The message with show in Debug console on client side.
For client side simple console.log works well for me.
You have to set an outputChannelName property on the client options inside the client extension code:
let clientOptions: LanguageClientOptions = {
outputChannelName: 'XYZ Language Server',
};
Once you've done that you can use console.log() and it will be shown in the VSCode extension output panel.
The Language Server Protocol supports logging, use the notification window/logMessage to send log messages from the server, VS Code will display the server's log in the output panel, in the channel corresponding to the language client that started the server.
Thanks guys!
export let config: any = {};
export function getConfig() {
//debug
config.debug = workspace.getConfiguration().get('VBI.debug');
config.debugToChannel = workspace.getConfiguration().get('VBI.debugToChannel'); //Instead into dev-tools-console
return config;
}
/**
* #param cat Type String --> define Cathegory [info,warn,error]
* #param o Rest Parameter, Type Any --> Data to Log
*/
export let info = vscode.window.createOutputChannel("VBI-Info");
export function log(cat: string, ...o: any) {
function mapObject(obj: any) {
switch (typeof obj) {
case 'undefined':
return 'undefined';
case 'string':
return obj;
case 'number':
return obj.toString;
case 'object':
let ret: string = '';
for (const [key, value] of Object.entries(obj)) {
ret += (`${key}: ${value}\n`);
}
return ret;
default:
return obj; //function,symbol,boolean
}
}
if (config.debug) {
if (config.debugToChannel) {
switch (cat.toLowerCase()) {
case 'info':
info.appendLine('INFO:');
o.map((args: any) => {
info.appendLine('' + mapObject(args));
});
info.show();
return;
case 'warn':
info.appendLine('WARN:');
o.map((args: any) => {
info.appendLine('' + mapObject(args));
});
info.show();
return;
case 'error':
let err:string='';
info.appendLine('ERROR: ');
//err += mapObject(cat) + ": \r\n";
o.map((args: any) => {
err += mapObject(args);
});
info.appendLine(err);
vscode.window.showErrorMessage(err);//.replace(/(\r\n|\n|\r)/gm,"")
info.show();
return;
default:
info.appendLine('INFO-Other:');
info.appendLine(mapObject(cat));
o.map((args: any) => {
info.appendLine('' + mapObject(args));
});
info.show();
return;
}
}
else {
switch (cat.toLowerCase()) {
case 'info':
console.log('INFO:', o);
return;
case 'warn':
console.log('WARNING:', o);
return;
case 'error':
console.log('ERROR:', o);
return;
default:
console.log('log:',cat, o);
return;
}
}
}
}
tests:
import * as func from './functions';
import { config } from './functions';
func.getConfig();
let text = `debugToChannel:${config.debugToChannel}\n`;
func.log('info','vbi-format',text);
func.log('warn','vbi-format',text);
func.log('error','vbi-format',text);

Form not redirecting correctly Wicket

private void setDefaultResponsePageIfNecessary() {
if(!continueToOriginalDestination()) {
if(session.getRoles().equals("ROLE_ADMIN")){
setResponsePage(SearchForCapacity.class);
System.out.println("Role for Admin:" + session.getRoles());
} else if (session.getRoles().equals("ROLE_USER"));
setResponsePage(HomePage.class);
System.out.println("Role for User: " + session.getRoles());
}
}
Hi all, this extract is from my login class which works fine except it wont redirect to the correct page. I can print the roles to the console so for admin it will print ROLE_ADMIM etc. The problem is no matter what the role it always navigates to the same page (HomePage), does anyone know why this is? thanks.
The else if statement is terminated by a ; instead of opening a block with {.
private void setDefaultResponsePageIfNecessary() {
if(!continueToOriginalDestination()) {
if(session.getRoles().equals("ROLE_ADMIN")){
setResponsePage(SearchForCapacity.class);
System.out.println("Role for Admin:" + session.getRoles());
} else if (session.getRoles().equals("ROLE_USER")) {
setResponsePage(HomePage.class);
System.out.println("Role for User: " + session.getRoles());
}
}
}
You should also use getRoles().contains() instead of getRoles().equals().

how to detect response content-type in asp.net mvc

I've wrote very simple minification/compression handler that minify css and js by indicating request type (Request.RawUrl.EndsWith("css" || "js")), but i don't know an approach to indicate which response type is html and then minify that as HTML-content because in mvc isn't extension to checking.
thanks in advance ;)
If you wrote an HTTP handler to compress static resources it's up to you to set up the Content-Type header based on the file type:
if (Request.RawUrl.EndsWith("css"))
{
Response.ContentType = "text/css";
}
else if (Request.RawUrl.EndsWith("js"))
{
Response.ContentType = "text/javascript";
}
Btw I would recommend you to minify/compress your static resources in advance and rely on the web server's gzip compression and client caching. I would avoid writing such handlers if it's not education purposes.
hm..., i think you misunderstood my goal/problem. here are my handler:
public void ProcessRequest(HttpContext context)
{
if (Preferences.EnableHtmlMinification && **IfResponseContentIsHtml**)
{
//Do minify here
}
if (Preferences.EnableHtmlCompression && **IfResponseContentIsHtml**)
{
acceptEncoding = acceptEncoding.ToLower(CultureInfo.InvariantCulture);
if (acceptEncoding.Contains("gzip"))
{
response.Filter = new HtmlCompressStream(response.Filter, CompressionMode.Compress, HtmlCompressStream.CompressionType.GZip);
response.AddHeader("Content-encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
response.Filter = new HtmlCompressStream(response.Filter, CompressionMode.Compress, HtmlCompressStream.CompressionType.Deflate);
response.AddHeader("Content-encoding", "deflate");
}
}
else
{
response.Filter = new HtmlCompressStream(response.Filter, CompressionMode.Compress, HtmlCompressStream.CompressionType.None);
}
}