Unable install own google chrome extension - asp.net

i want to host my own extension on my asp.net server (it's free web server, so i don't have access to machine.config etc.).
But the point of my problem is here. I put the packaged extension to server and i want use something like this:
protected void Page_Load(object sender, EventArgs e)
{
string file = Request.QueryString["f"];
if (file != null)
{
Response.Write("");
if (file == "0")
{
Response.ContentType = "application/x-chrome-extension";
Response.AddHeader("Content-Disposition", "attachment;filename=RemotePlay_extension.crx");
Response.TransmitFile("~/Extensions/Update/RemotePlay_extension.crx");
}
else
{
Response.ContentType = "application/x-chrome-extension";
Response.AddHeader("Content-Disposition", "attachment;filename=RemotePlay_extension.crx");
Response.TransmitFile("~/Extensions/RemotePlay_extension.crx");
}
}
}
But every time I get this error:
Source of extension manifest:
{
"name": "Remote Play",
"description": "DJ interface to use RP.",
"version": "0.0.0.2",
"update_url": "../Extensions/RemoteChrome_Update.xml",
"permissions": ["tabs", "http://*/*"],
"background": { "scripts": ["background.js"] },
"content_scripts": [{"matches": ["http://*/*"],"js": ["inject.js"]}],
"page_action": {"default_icon": "playico.png", "default_popup": "popup.html"},
"manifest_version": 2
}
What i'm doing wrong? Where is that error?

You can not trigger installation through Page_Load function and headers
You should have a link tag <link rel="chrome-webstore-item"
href="https://chrome.google.com/webstore/detail/apdfllckaahabafndbhieahigkjlhalf">
You can trigger installation through chrome.webstore.install(url, successCallback, failureCallback)
For more information check documentation.

Related

receive error "getTokens does not support retrieving tokens while signed" when try to retrieve data from AWS via API Gateway

issue:
console show "getTokens does not support retrieving tokens while signed-" error.
step:
1. run app with Android studio
2. log in AWS ( my app use amplify drop-in UI )
3. retrieve data from AWS via API Gateway --> result OK ( able to retrieve)
4. log out and log in again
5. retrieve data from AWS via API Gateway --> result NG ( show above error)
note:
my configuration file include: Cognito User pool and Identity pool. this is auto generate after keyin " amplify add auth" at CLI.
if i deleted Cognito Identity pool from configuration file, issue not happen.
May i know why ?
my configuration file:
{
"UserAgent": "aws-amplify-cli/0.1.0",
"Version": "1.0",
"IdentityManager": {
"Default": {}
},
"CredentialsProvider": {
"CognitoIdentity": {
"Default": {
"PoolId": "xxx",
"Region": "us-east-2"
}
}
},
"CognitoUserPool": {
"Default": {
"PoolId": "us-east-2_xxx",
"AppClientId": "xxx",
"AppClientSecret": "xxx",
"Region": "us-east-2"
}
}
}
sign-in code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_authentication);
AWSMobileClient.getInstance().initialize(getApplicationContext(), new Callback<UserStateDetails>() {
#Override
public void onResult(UserStateDetails userStateDetails) {
switch (userStateDetails.getUserState()) {
case SIGNED_IN:
Intent i = new Intent(Authentication.this, AvailableFlavor.class);
break;
case SIGNED_OUT:
showSignIn();
break;
default:
AWSMobileClient.getInstance().signOut();
showSignIn();
break;
}
}
#Override
public void onError(Exception e) {
}
});
}
private void showSignIn() {
try {
AWSMobileClient.getInstance().showSignIn(this,
SignInUIOptions.builder().nextActivity(LoginSuccess.class)
.build());
} catch (Exception e) {
// Log.e(TAG, e.toString());
}
}
}
I guess the end of the error is "getTokens does not support retrieving tokens while signed-"...out?
I had a similar error, please check if your identity poolId is correct (even if you're not using a guest access or if you only want to use the user pool functionality) in app -> src -> res -> raw -> amplifyconfiguration.json & awsconfiguration.json. You can find your poolId in your AWS console -> cognito -> manage identity pools -> click on your pool -> click on Sample code.:

Chrome App - Cannot read property 'connect' of undefined

I'm working on a Raspberry pi 3, I have a webpage that sends text data to a Chrome App, and everything works fine up to here.
After that the Chrome App should send that data to the serial port and here appears the error:
Error in event handler for runtime.onMessageExternal: TypeError: Cannot read property 'connect' of undefined
The problem could be that this is not a Chrome App, it's an Extension and it can't use this API cause only Chrome Apps have access to the hardware, but I followed this guide to make my first Chrome App (https://developer.chrome.com/apps/first_app), so maybe there's something i didn't understand or a step that i missed.
Here's my code, thanks in advance for the help!
manifest.json
{
"name": "Send serial data",
"description": "App to send serial data.",
"version": "1.0",
"manifest_version": 2,
"app": {
"background": {
"scripts": ["background.js"]
}
},
"icons": { "16": "img-16.png", "128": "img-128.png" },
"externally_connectable" : {
"matches": ["*://localhost/*"]
}
}
background.js
var msg ;
function openSend(data) {
var onConnect ;
onConnect = function(connectionInfo) {
_this.connectionId = connectionInfo.connectionId;
}
chrome.serial.connect("/dev/ttyAMA0", {bitrate: 115200}, onConnect);
chrome.serial.send(connectionId, convertStringToArrayBuffer(data), function(sendInfo) {
if(sendInfo.error) $.modal('<div id="title">Unable to send data: ' + sendInfo.error + '</div>')
});
}
chrome.runtime.onMessageExternal.addListener((message, sender, sendResponse) => {
console.log(message.data);
msg = message.data ;
openSend(msg);
});
Solved, i just forgot to put this line of code in my manifest.json:
"permissions":["serial"],

Why assert in #PactVerification?

I don't understand the use of assert in #PactVerification. To me it seams more like a complicated way of saying 1 == 1. For example:
import static org.assertj.core.api.Assertions.assertThat;
public class PactConsumerDrivenContractUnitTest {
#Rule
public PactProviderRuleMk2 mockProvider
= new PactProviderRuleMk2("test_provider", "localhost", 8080, this);
#Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
return builder
.given("test GET ")
.uponReceiving("GET REQUEST")
.path("/")
.method("GET")
.willRespondWith()
.body("{\"condition\": true, \"name\": \"tom\"}")
}
#Test
#PactVerification()
public void givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody() {
//when
ResponseEntity<String> response
= new RestTemplate().getForEntity(mockProvider.getUrl(), String.class);
//then
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
}
}
So first in "createPact" we state
body("{\"condition\": true, \"name\": \"tom\"}")
Then in givenGet_whenSendRequest_shouldReturn200WithProperHeaderAndBody annotated #PactVerification we do this
assertThat(response.getBody()).contains("condition", "true", "name", "tom");
But why? We just said that! As far as I can see the assertion does not show up in the generated Pact file. It seams to fill no purpose?
In addition to that, I thought that the idea of contract testing was to reduce the need for integration test since they can break for example if test data changes. But here we still depend on test data. If there are no "Tom" in the Provider, then the test will fail. I primarily wanted to test if the contract is broken, not if the test data has changed.
The example given is a contrived one. In real life using Pact, you wouldn't do this. Your PactVerification would invoke a collaboration method/class/thing which is responsible for the external call to the service you are mocking.
So your assertions are then on what the collaborating function is doing.
Eg. A User Service might create an object with certain properties, that you know only are populated by that external call.
Testing assertions in your #PactVerification test method is not mandatory, yet still it might be very helpful. E.g. you may make a typo in your JSON body string and you wont be able to catch it in your test and it will break provider's pipeline. Assertions in this case have nothing to do with generated Pact file, they play role of a guard that checks in the end if the contract you have just defined (RequestResponsePact) matches all your expectations (assertions).
Also it is worth mentioning that your consumer contract tests should break only if provider tries to release a change that makes your expectations broken. And this is consumer's responsibility to write good contract tests. In your example you have defined following expectation:
#Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
return builder
.given("test GET ")
.uponReceiving("GET REQUEST")
.path("/")
.method("GET")
.willRespondWith()
.body("{\"condition\": true, \"name\": \"tom\"}")
}
This contract will be satisfied as long as condition == true and name == tom. This is over-specification of a response. You could define more flexible response with PactDslJsonBody DSL instead:
#Pact(consumer = "test_consumer")
public RequestResponsePact createPact(PactDslWithProvider builder) {
final DslPart body = new PactDslJsonBody()
.stringType("name", "tom")
.booleanType("condition", true);
return builder
.given("test GET ")
.uponReceiving("GET REQUEST")
.path("/")
.method("GET")
.willRespondWith()
.body(body)
.toPact();
}
This fragment will generate Pact file like:
{
"provider": {
"name": "providerA"
},
"consumer": {
"name": "test_consumer"
},
"interactions": [
{
"description": "GET REQUEST",
"request": {
"method": "GET",
"path": "/"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json; charset=UTF-8"
},
"body": {
"condition": true,
"name": "tom"
},
"matchingRules": {
"body": {
"$.name": {
"matchers": [
{
"match": "type"
}
],
"combine": "AND"
},
"$.condition": {
"matchers": [
{
"match": "type"
}
],
"combine": "AND"
}
}
}
},
"providerStates": [
{
"name": "test GET "
}
]
}
],
"metadata": {
"pact-specification": {
"version": "3.0.0"
},
"pact-jvm": {
"version": "3.5.10"
}
}
}
The main difference is that this Pact file uses matchingRules to test if:
type of condition field is boolean
type of name field is String
For strings you can also use PactDslJsonBody.stringMatcher(name, regex, value) method if needed. It allows you to define regular expression that will be tested using current field value.

Elasticsearch - Get locale specific date in Groovy script

I need to update existing documents of a particular type with a new field. This new field should be set to the local day name of a date given by a datetime field in the document. The date time field is in the format yyyy-MM-dd'T'HH:mm:ss, is in UTC but has no explicit timezone code.
I'd like to do this with Groovy but have no Java experience. I'm guessing I need to:
1) Set the datetime to UTC locale
2) Convert to local locale (set to Europe/London) in this case
3) Get the day name from converted date and set new field (dayname) value with it
If I use the following update_by_query:
POST /myindex/_update_by_query
{
"script": {
"inline": "ctx._source.dayname = Some_function(ctx._source.datetime)"
},
"query": {
"term": {
"_type": "myDocType"
}
}
}
Is there a simple way to do this with a some Groovy functions (replacing Some_function above).
Any hints would be very much appreciated!
UPDATE - Thanks to tim_yates i have the following Sense console code:
POST /rating/_update_by_query
{
"script": {
"inline": "ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime, java.util.TimeZone.getTimeZone('UTC')).format('EEEE', java.util.TimeZone.getTimeZone('Europe/London'))"
},
"query": {
"term": {
"_type": "transaction"
}
}
}
Unfortunately this generates the following error message:
{
"error": {
"root_cause": [
{
"type": "script_exception",
"reason": "failed to run inline script [ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime, java.util.TimeZone.getTimeZone('UTC')).format('EEEE', java.util.TimeZone.getTimeZone('Europe/London'))] using lang [groovy]"
}
],
"type": "script_exception",
"reason": "failed to run inline script [ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime, java.util.TimeZone.getTimeZone('UTC')).format('EEEE', java.util.TimeZone.getTimeZone('Europe/London'))] using lang [groovy]",
"caused_by": {
"type": "missing_property_exception",
"reason": "No such property: java for class: 1209ff7fb16beac3a71ff2a276ac2225f7c4505b"
}
},
"status": 500
}
Though it does work if I remove reference to the getTimeZone - exact Sense console code as follows:
POST /rating/_update_by_query
{
"script": {
"inline": "ctx._source.day = Date.parse(\"yyyy-MM-dd'T'HH:mm:ss\", ctx._source.datetime).format('EEEE')"
},
"query": {
"term": {
"_type": "transaction"
}
}
}
I'm not sure why the getTimeZone method is failing. I've tried "TimeZone.getTimeZone" instead of "java.util.TimeZone.getTimeZone"
The Groovy code (for Java 7) you will need is going to be very similar to this:
Date.parse("yyyy-MM-dd'T'HH:mm:ss", ctx._source.datetime, TimeZone.getTimeZone('UTC'))
.format('EEEE', TimeZone.getTimeZone("Europe/London"))
OK, a bit more research allowed me to understand that tim_yates answer was correct, we just needed to whitelist the Java class required. We did this via:
nano $JAVA_HOME/lib/security/java.policy
and adding:
permission org.elasticsearch.script.ClassPermission "java.util.TimeZone";
...then restart the ES services.
Note this whitelists the class for all users, not just the ES user. See:
https://www.elastic.co/guide/en/elasticsearch/reference/2.2/modules-scripting-security.html

Data passed via Segment API does not show up on Google Analytics

I am using Segment.com .NET APIs to pass data to Google Analytics. But even after 3 to 4 days The data has not appeared on Google. Nor I can see data in the Debugger section of Segment's Account Dashboard.
I wonder what is happening? Is there any special configuration to be done at Google side for the data to appear ? or is there anything else I am missing.
Following is the code used.
Analytics.Initialize("pOAM4 Some-KEY PrAC",new Config().SetAsync(false));
Analytics.Client.Identify("BillGates", new Segment.Model.Traits() {
{ "name", uname },
{ "email", uemail },
{ "friends", counter }
});
Analytics.Client.Track("BillGates", "Purchased Item", new Segment.Model.Properties() {
{ "Item", itemcounter},
{ "revenue", 39.95 },
{ "shipping", "2-day" }
});
Analytics.Client.Track("BillGates", "Logged Out", new Segment.Model.Properties() {} );
I am executing them several times.... and I expect something to appear on Google Analytics Dashboard, but its bank.
Any help from anyone who have used Segment.com APIs ?
If your data isn't getting to the Segment debugger, that means that something is probably wrong in your implementation, either API keys or improperly formatted code and I'd recommend using the logging that's built into this lib, you can use it like so.
using Segment;
Segment.Logger.Handlers += Logging_Handler;
void Logging_Handler(Level level, string message, Dict args)
{
if (args != null)
{
foreach (string key in args.Keys) {
message += String.Format(" {0}: {1},", "" + key, "" + args[key]);
}
}
Console.WriteLine(String.Format("[Analytics] [{0}] {1}", level, message));
}
The one thing that jumps out to me is that you're calling new Segment.Model.Properties() in your .Track() and new Segment.Model.Traits() in your .Identify().
I've always used new Properties() in .Track() and new Traits() in .Identify() like so
Analytics.Client.Identify("<<userId>>", new Traits() {
{ "name", "#{ user.name }" },
{ "email", "#{ user.email }" },
{ "friends", 29 }
});
Analytics.Client.Track("<<userId>>", "Purchased Item", new Properties() {
{ "revenue", 39.95 },
{ "shipping", "2-day" }
});
The code for this lib is all open-source and available on github here and the Segment docs are pretty thorough as well.
Good luck!

Resources