Can you please tell me what is the wrong with the below code for programmatically inserting the pageview in google analytics.
Code is not inserting pageview.
var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com");
request.Method = "POST";
// the request body we want to send
var postData = new Dictionary<string, string>
{
{ "v", "1" },
{ "tid", "UA-XXXXXX-1" },
{ "cid", "555" },
{ "t", "pageview" },
{"dh","www.pomroofing.com"},
{ "dp", "/phone/123/456/789/1" },
{ "dt", "homepage" },
};
var postDataString = postData
.Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
HttpUtility.UrlEncode(next.Value)))
.TrimEnd('&');
// set the Content-Length header to the correct value
request.ContentLength = Encoding.UTF8.GetByteCount(postDataString);
// write the request body to the request
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(postDataString);
}
try
{
var webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
throw new HttpException((int)webResponse.StatusCode,
"Google Analytics tracking did not return OK 200");
}
}
catch (Exception ex)
{
// do what you like here, we log to Elmah
// ElmahLog.LogError(ex, "Google Analytics tracking failed");
}
please help, or is there any api for this.
Try testing your full request string directly into a Browser. A short request like that can also be sent with a GET.
Check real-time reports to see if its showing up or not. (I tested this)
http://www.google-analytics.com/collect?v=1&tid=UA-XXXX-X&cid=555&t=pageview&dh=www.pomroofing.com&dp=/phone/123/456/789/1&dt=homepage
No there is no API for this.
BTW you are missing /collect in the url :)
Related
I created a Google Sheet that uses a Google Script to generate short URLs via Firebase API.
This is the code in the Google Script
function URLShortener(longURL) {
var body = {
"dynamicLinkInfo": {
"domainUriPrefix": "https://go.example.com",
"link" : longURL
},
"suffix": {
"option": "SHORT"
}
};
var key = 'xxxxxxx'
var url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=" + key;
var options = {
'method': 'POST',
"contentType": "application/json",
'payload': JSON.stringify(body),
};
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
var obj = data["shortLink"];
return obj;
Logger.log(obj)
}
The script works and it generates URLs similar to https://go.example.com/Xdka but these link redirect to https://example.com/Xdka instead of the actual URL that is sent, e.g. https://example.com/final_url.
If I try to generate these short links from the Firebase dashboard the same happens.
Did I misunderstand how these short URLs work or am I missing something?
I am trying to POST an image taken from the camera to Microsoft Cognitive Service's Face API (using the Face - Detect method). However, when I try it returns the 'Response 415':
{
"error": {
"code": "BadArgument",
"message": "Invalid Media Type."
}
}
Here is my code for this method:
final bytes = image.readAsBytesSync();
var uri = Uri.parse("https://australiaeast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false");
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile.fromBytes('url', bytes, contentType: new MediaType('image', 'jpeg'));
request.headers['Ocp-Apim-Subscription-Key'] = "9c261636281d42c0947d89fe3982df73";
request.headers['Content-Type'] = "application/octet-stream";
request.files.add(multipartFile);
var response = await request.send();
print(request);
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
}
I used the Flutter Image Picker plugin to take the picture and get it to show up fine on the screen. All other operations I've tried with Microsoft Cognitive Services work fine - it is only uploading this image that is giving me problems.
I think you don't need a MultipartRequest but just a Request and assign the bodyBytes property:
final bytes = image.readAsBytesSync();
var uri = Uri.parse("https://australiaeast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=false");
var request = new http.Request("POST", uri)
..headers['Ocp-Apim-Subscription-Key'] = "9c261636281d42c0947d89fe3982df73"
..headers['Content-Type'] = "application/octet-stream"
..bodyBytes = bytes;
var response = await request.send();
print(request);
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
I am using a webhook and c# to fulfill my logic within an Action.
I have subscribed to two intents, and have captured the "UpdateUserId".
Here is the notification payload
{
"customPushMessage": {
"target": {
"userId": "ABwppHFW6M9ASVqbKFBigM8N0mgssCJmPlwarmgzil_Nk_YsdZ1evzTAggEh0aEsctjOIYg2uHc8n7KfzNuHLuJoirXW",
"intent": "NotificationIntent",
"argument": {
"rawText": "Notification Argument Raw Text",
"textValue": "Notification Argument Text Value",
"name": "Notification Argument"
},
"locale": "en-US"
},
"userNotification": {
"title": "Notification Title",
"text": "Notification Text"
}
}
}
I am sending my notification using the following code blocks
private static async Task<string> GetAccessTokenFromJsonKeyAsync(string jsonKeyFilePath, params string[] scopes)
{
using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))
{
return await GoogleCredential
.FromStream(stream) // Loads key file
.CreateScoped(scopes) // Gathers scopes requested
.UnderlyingCredential // Gets the credentials
.GetAccessTokenForRequestAsync(); // Gets the Access Token
}
}
public async Task<HttpResponseMessage> SendNotificationMessage(ProactiveMessage proactiveMessage)
{
try
{
var accessToken = await GetAccessTokenFromJsonKeyAsync("key.json", "https://www.googleapis.com/auth/actions.fulfillment.conversation");
var serialized = JsonConvert.SerializeObject(proactiveMessage);
var payload = "{\"customPushMessage\": " + serialized + "}";
// Wrap our JSON inside a StringContent which then can be used by the HttpClient class
var httpContent = new StringContent(payload, Encoding.UTF8, "application/json");
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var httpResponseMessage = await _httpClient.PostAsync($"{_hostUrl}", httpContent);
Console.WriteLine(httpResponseMessage.IsSuccessStatusCode ? "Successfully sent notification message." : $"Failed to send notification message with {httpResponseMessage.StatusCode}.");
return httpResponseMessage;
}
catch (Exception ex)
{
Debug.WriteLine($"Google Assistant Service: Failed to send notification message with exception: {ex.Message}");
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
}
The method returns a 200 Response. However, a notification never shows up on my phone.
I am not sure what my next steps for debugging are.
Since notifications are stil not public, is this a common issue?
I had the same issue. I received 200 status code but no notifications arrived at the target device.
I tried it again in approximately 2 days and it worked with no problems and have been working ever since.
The only explanation I could come up with is that there is some configuration running in the background.
I'm working on creating a Flutter application that works with LIFX. I'm trying to follow their instructions here, but I'm having issues adding a header to my HTTP GET request.
TestHttpGet() async {
var httpClient = new HttpClient();
var header = "Bearer $token"; //token hidden
var url = 'https://api.lifx.com/v1/lights/all/state';
String result;
try {
var request = await httpClient.getUrl(Uri.parse(url));
request.headers.set("Authorization", header);
var response = await request.close();
if (response.statusCode == HttpStatus.OK) {
var json = await response.transform(UTF8.decoder).join();
print(json);
var data = JSON.decode(json);
result = data['brightness'].toString();
} else {
result =
'Error getting response:\nHttp status ${response.statusCode}';
}
} catch (exception) {
result = 'Failed parsing response';
}
This returns with Error getting response: Http status 404. I've tried various ways of request.headers .set .add [HttpHeaders.Authorization] = "header" all return with a 404. Any advice would be appreciated.
You can pass a Map<String, String> to the http.get call as the headers parameter like this:
await httpClient.get(url, headers: {
'Authorization': 'Bearer $token',
});
In order to set headers you can't set the entire variable since it is set as final. What you need to do is set the value of the individual array items which are also known as the individual "headers" in this case.
For example :
http.Request request = http.Request('GET', uri);
request.headers['Authorization'] = 'Bearer $token';
I believe dart makes all the fields of a HttpHeader to lowercase.
https://github.com/flutter/flutter/issues/16665
The argument for that is because "Field names are case-insensitive". (otherwise it is not HTTP compliant)
https://www.rfc-editor.org/rfc/rfc2616#section-4.2
Let me know if you found a workaround for this.
I am developing calendar api client and I have problem with reminder - they do not work...
I create event like this:
Event gEvent = new Event()
{
Summary = "Reminder test",
Location = "Reminder test",
Start = new EventDateTime()
{
DateTime = new DateTime(2014, 12, 14, 21, 0, 0),
},
End = new EventDateTime()
{
DateTime = new DateTime(2014, 12, 14, 22, 0, 0),
},
Reminders = new Event.RemindersData()
{
UseDefault = false,
Overrides = new List<EventReminder>()
{
new EventReminder()
{
Method = "email",
Minutes = 15
},
new EventReminder()
{
Method = "email",
Minutes = 30
},
new EventReminder()
{
Method = "email",
Minutes = 45
},
}
}
};
Event simpleEvent = calService.Events.Insert(gEvent, strCalendarID).Execute();
This code works and in my google calendar GUI is really created my event, but if I click on editing event - I can not see my reminders, there are only default reminders.
Why? What I am doing wrong?
Thanks for all answers
Today I attempted send request from code with JSON. My method look like this:
private static void CreateSimpleEvent(string strAccessToken, string strCalendarID, string strApiKey)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format("https://www.googleapis.com/calendar/v3/calendars/{0}/events?sendNotifications=false&fields=reminders&key={1}", strCalendarID, strApiKey));
request.Method = "POST";
request.ContentType = "application/json";
request.UserAgent = "TestCalendarApi2";
request.Headers.Add("Authorization", "Bearer " + strAccessToken);
string strJson = #"{
'end': {
'dateTime': '2014-12-19T15:30:00.000Z',
'timeZone': 'Europe/Prague'
},
'start': {
'dateTime': '2014-12-19T14:30:00.000Z',
'timeZone': 'Europe/Prague'
},
'reminders': {
'useDefault': false,
'overrides': [
{
'method': 'email',
'minutes': 13
}
]
}
}";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(strJson);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
Method proceeded OK and in google calendar was created event, but reminders are still missing when I use AccessToken from ServiceAccountCredential object :(. When I use AccessToken generated in Apis explorer (https://developers.google.com/apis-explorer/#p/calendar/v3/) - reminders are working.
Problem is, that in Apis explorer I must turn on OAuth2 and after that I must grand acess...
Is there any way, how to grand access from code?
Thanks for all answers.
The problem with reminders while using a service account to manage events in Google Calendar is that the service account is practically a virtual user with its own Google Calendar. The event reminders are set per user, so you would be only able to see the reminders if you'd manage to log in to Google Calendar as your service account. The users who share the calendar with the service account only see the event details but they have to set their own reminders.
Same issue here, event inserted without any reminders.
Sending same request via API explorer successfully inserted event with reminders.
My JSON data:
{
"end":{
"dateTime":"2015-01-19T01:20:00.000",
"timeZone":"Europe\/Minsk"
},
"reminders":{
"useDefault":false,
"overrides":[
{
"method":"sms",
"minutes":"30"
},
{
"method":"email",
"minutes":"60"
}
]
},
"start":{
"dateTime":"2015-01-19T01:15:00.000",
"timeZone":"Europe\/Minsk"
},
"summary":"New event",
"start_date":"2015-01-19 01:15",
"end_date":"2015-01-19 01:20"
}