Error 404 when creating a calendar with Google Calendar Api v3 using c# .net - http-status-code-404

I am trying to create a calendar using Google Calendar API v3 if it does not already exist. My implementation successfully retrieves all my calendars and events and can change calendars, but I am struggling with adding a new calendar. This is what I do in order to try to add a new calendar for the user:
...
var calendarService = new CalendarService(_authenticator);
var calendarId = "com.somedomain.somename.1234"; // Some random ID
try {
calendarManager.GetCalendar(calendarId); // No calandar found
} catch(GoogleCalandarServiceProxyException e){
// Ok, so far so good, calendar not found (that is correct) and I am here
var someCalendar = new Google.Apis.Calendar.v3.Data.CalendarListEntry {
Summary = "Some summary!",
Description = "A calendar descr.",
AccessRole = "writer",
BackgroundColor = "#E7323C",
Id = calendarId
};
calendarService.CalendarList.Insert(someCalendar).Fetch(); // Fetch to execute
}
Request generated:
insert # https://www.googleapis.com/calendar/v3/users/me/calendarList?alt=json&prettyPrint=true
RequestError:
Google.Apis.Request.RequestErrorNotFound[404]Errors [Message[Not Found]Location[-] Reason[notFound] Domain[global]]]
Weird thing is that doing a GET at https://www.googleapis.com/calendar/v3/users/me/calendarList?alt=json&prettyPrint=true does not return something, so it should be there.
I hope that there is some awesome guy/girl out there which knows what to do! I'm completely stuck.
Update
Seems like I am receiving the same 404 error on CalendarList Google Api Explorer also:
Url:
https://developers.google.com/google-apps/calendar/v3/reference/calendarList/insert
Request:
POST https://www.googleapis.com/calendar/v3/users/me/calendarList?key={YOUR_API_KEY}
Content-Type: application/json
Authorization: Bearer ya29.AHES6ZQTj-D6uIMOWr_AoFYVvfefsEGcVvLvvMf4aKhgrdvQE25aVw
X-JavaScript-User-Agent: Google APIs Explorer
{
"id": "hastalavista"
}
Response:
404 Not Found
- Show headers - { "error": { "errors": [ {
"domain": "global",
"reason": "notFound",
"message": "Not Found" } ], "code": 404, "message": "Not Found" } }
Does anyone know whether Google have changed the URL for this resource? And if yes, how I change the Google Calendar Api v3 to use the updated url ...?

Okey, my bad:
You can't create a calendar with your own identifier, the purpose of CalendarListEntry.Insert() is to insert a created Calendar into the list of calendars
So to create a new calendar one has to:
Insert a new Calendar: https://developers.google.com/google-apps/calendar/v3/reference/calendars/insert
(DO NOT add id as paramater, this will be automatically created)
Insert the ID of the calendar created in step 1 and insert it into the calendarList: https://developers.google.com/google-apps/calendar/v3/reference/calendarList/insert

I'm still totally confused as to Google's distinction between a Calendar and a CalendarList since the data seems to overlap. Why is a calendar considered a "secondary" calendar.

The next code dit the trick for me, The mentioned reference is Java not .Net and, as usual ther e are some anoying differences...
private bool createCalendar()
{
// use Google.Apis.Calendar
Calendar calendar = new Calendar();
calendar.Summary = "MyNewCalendar";
calendar.Description = "Your new Calendar";
calendar.Location = "Aadorp";
calendar.TimeZone = "Europe/Amsterdam";
try
{
// Not inserting in CalendarList but in Calendar!
calendarService.Calendars.Insert(calendar).Execute();
}
catch (Exception exception)
{
MessageBox.Show(exception.Message);
return false;
}
return true;
}

Related

Unable to read or right data to/ from Firestore SwiftUI

I've setup Firestore DB and wanted to test it. However I was unable neither read or wright data to it. Here is what console shows on connection status to Firebase.
Debug Console:
2020-11-19 17:58:49.802849+0300 Demo [813:165300] 6.34.0 - [Firebase/Analytics][I-ACS023007] Analytics v.60900000 started
2020-11-19 17:58:49.803819+0300 Demo [813:165300] 6.34.0 - [GoogleUtilities/AppDelegateSwizzler][I-SWZ001014] App Delegate does not conform to UIApplicationDelegate protocol.
2020-11-19 17:58:49.804498+0300 Demo [813:165300] 6.34.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see https://help.apple.com/xcode/mac/8.0/#/dev3ec8a1cb4)
2020-11-19 17:58:50.586054+0300 Demo [813:165306] 6.34.0 - [Firebase/Analytics][I-ACS800023] No pending snapshot to activate. SDK name: app_measurement
2020-11-19 17:58:51.138985+0300 Demo [813:165306] 6.34.0 - [Firebase/Analytics][I-ACS023012] Analytics collection enabled
2020-11-19 17:58:51.139362+0300 Demo [813:165306] 6.34.0 - [Firebase/Analytics][I-ACS023220] Analytics screen reporting is enabled. Call +[FIRAnalytics logEventWithName:FIREventScreenView parameters:] to log a screen view event. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO (boolean) in the Info.plist
2020-11-19 17:58:51.850205+0300 Demo [813:165012] [AXRuntimeCommon] This class 'SwiftUI.AccessibilityNode' is not a known serializable element and returning it as an accessibility element may lead to crashes
Also Firebase it self shows that I had some reads in stats.
I stuck and don't understand what important part I didn't do in order to start implementing Firebase use. Will appreciate any help or suggestion.!
I used several methods to initiate Firebase in SwiftUI.
This one:
import SwiftUI
import Firebase
#main
struct DemoApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL(perform: { url in
Auth.auth().canHandle(url)
})
}
}
Also tried with DelegateAdaptor:
#main
struct DemoApp: App {
#UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
appDelegate
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
print("Application is starting up. ApplicationDelegate didFinishLaunchingWithOptions.")
return true
}
}
To test writing to:
func letE() {
let db = Firestore.firestore()
db.collection("wine").addDocument(data: ["Cool" : 2017])
}
And to fetch an array
private var db = Firestore.firestore()
func fetchData() {
db.collection("collection").document("document")
.addSnapshotListener { documentSnapshot, error in
guard let document = documentSnapshot else {
print("Error fetching document: \(error!)")
return
}
guard let data = document.data()!["array name"] else {
print("Document data was empty.")
return
}
print(data)
}
And like this:
func getData(){
db.collection("skills").getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
print("\(document.documentID) => \(document.data())")
}
}
Hello, Peter! I was trying to come to solving this problem from different angels but still no luck.
Basically I am trying to perform wright operation
It goes like this
#main
struct DemoApp: App {
init() {
FirebaseApp.configure()
}
var body: some Scene {
WindowGroup {
ContentView()
.onOpenURL(perform: { url in
Auth.auth().canHandle(url)
})
}
}
}
func addData() {
//
let db = Firestore.firestore()
//
db.collection("wine").addDocument(data: ["Test":100])
}
Then i press Build.
From my understanding that already should create collection "Wine" with autogenerated Document with contains field "Test" with value "100"
But once again nothing happens on the firebase side.
The Debug console
2021-01-26 16:22:21.907902+0300 Demo [27616:342494] 6.34.0 - [Firebase/Analytics][I-ACS023007] Analytics v.60900000 started
2021-01-26 16:22:21.908067+0300 Demo [27616:342494] 6.34.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see https://help.apple.com/xcode/mac/8.0/#/dev3ec8a1cb4)
2021-01-26 16:22:21.934626+0300 Demo [27616:342498] 6.34.0 - [GoogleUtilities/AppDelegateSwizzler][I-SWZ001014] App Delegate does not conform to UIApplicationDelegate protocol.
2021-01-26 16:22:21.979114+0300 Demo [27616:342490] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
2021-01-26 16:22:21.994921+0300 Demo [27616:342490] 6.34.0 - [Firebase/Analytics][I-ACS800023] No pending snapshot to activate. SDK name: app_measurement
2021-01-26 16:22:22.000217+0300 Demo [27616:342490] 6.34.0 - [Firebase/Analytics][I-ACS023012] Analytics collection enabled
2021-01-26 16:22:22.000724+0300 Demo [27616:342490] 6.34.0 - [Firebase/Analytics][I-ACS023220] Analytics screen reporting is enabled. Call +[FIRAnalytics logEventWithName:FIREventScreenView parameters:] to log a screen view event. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO (boolean) in the Info.plist
2021-01-26 16:22:22.032550+0300 Demo [27616:342197] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x60000341ce60 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7fb0e7d16480]-(6)-[_UIModernBarButton:0x7fb0e7d0a710'Skills'] (active)>",
"<NSLayoutConstraint:0x60000341ceb0 'CB_Trailing_Trailing' _UIModernBarButton:0x7fb0e7d0a710'Skills'.trailing <= _UIButtonBarButton:0x7fb0e7d10cb0.trailing (active)>",
"<NSLayoutConstraint:0x60000341dc20 'UINav_static_button_horiz_position' _UIModernBarButton:0x7fb0e7d16480.leading == UILayoutGuide:0x600002e54ee0'UIViewLayoutMarginsGuide'.leading (active)>",
"<NSLayoutConstraint:0x60000341dc70 'UINavItemContentGuide-leading' H:[_UIButtonBarButton:0x7fb0e7d10cb0]-(0)-[UILayoutGuide:0x600002e54e00'UINavigationBarItemContentLayoutGuide'] (active)>",
"<NSLayoutConstraint:0x60000347eda0 'UINavItemContentGuide-trailing' UILayoutGuide:0x600002e54e00'UINavigationBarItemContentLayoutGuide'.trailing == _UINavigationBarContentView:0x7fb0e7e0f7e0.trailing (active)>",
"<NSLayoutConstraint:0x60000341e3f0 'UIView-Encapsulated-Layout-Width' _UINavigationBarContentView:0x7fb0e7e0f7e0.width == 0 (active)>",
"<NSLayoutConstraint:0x60000347e9e0 'UIView-leftMargin-guide-constraint' H:|-(0)-[UILayoutGuide:0x600002e54ee0'UIViewLayoutMarginsGuide'](LTR) (active, names: '|':_UINavigationBarContentView:0x7fb0e7e0f7e0 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000341ce60 'BIB_Trailing_CB_Leading' H:[_UIModernBarButton:0x7fb0e7d16480]-(6)-[_UIModernBarButton:0x7fb0e7d0a710'Skills'] (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
The changed Debug Console outcome presented is because I've setup authorised access and it does work. I can create user and then perform login with crated login and password. All users do show up on the Firebase console.

PayPal doesn't capture payment after subscription is created - React

We are using PayPal in order to enable subscription in our platform.
I set up the product and plans inside PayPal and integrated the "PayPal Smart Buttons" using the "react-smart-payment-buttons" package (https://github.com/erksch/react-smart-payment-buttons).
I managed to create the subscription successfully but the first payment is not captured immediately or at all.
When I'm using the PayPal Subscription API in order the see when will be the next billing cycle, it shows a timestamp that has already passed.
For example, this is part of the JSON I got from the API:
"billing_info": {
"outstanding_balance": {
"currency_code": "USD",
"value": "0.0"
},
"cycle_executions": [
{
"tenure_type": "REGULAR",
"sequence": 1,
"cycles_completed": 0,
"cycles_remaining": 12,
"current_pricing_scheme_version": 1
}
],
"next_billing_time": "2019-07-01T10:00:00Z",
"failed_payments_count": 0
},
"auto_renewal": false,
"create_time": "2019-07-01T15:34:02Z"
}
As you can see, the next_billing_time value is before the create_time which doesn't make sense.
What I already did:
After the user approves the subscription, I'm getting the ID of the order and also the subscription. When trying to capture the payment by using the PayPal Payments API and the order id I got, I'm getting back an error.
I checked the status of the created subscription and it shows ACTIVE.
createSubscription(data, actions) {
let plan_id = process.env.REACT_APP_PAY_PAL_BASIC_PLAN_ID;
return actions.subscription.create({
plan_id
});
}
onApprove(data, actions) {
const Http = new XMLHttpRequest();
let url = process.env.REACT_APP_UPGRADE_USER_URL;
Http.open("POST", url);
Http.setRequestHeader("x-access-token", this.state.token);
Http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
Http.send(`plan=${this.state.plan}&subscriptionId=${data.subscriptionID}`);
}
I'll be happy if someone can assist me with this problem.
Thanks in advance.

Submitting Data to Google Analytics from WPF

I am trying to send data to Google Analytics from a WPF application. I can't find any resource online which clearly defines how to do that. I know that there are numerous NuGet packages available, but I'm not sure which to use, nor how to implement them. I also know that there are some third-party "helper" libraries available (see Using Google Analytics from a .NET desktop application), which I'm not interested in. It also looks like most instructions online are showing how to "pull" data from GA, not how to push. Not looking for "maybe"'s or workarounds but what the normal straightforward way to do this is. This shouldn't be complicated. Just need a "Hello World".
Can you please point me in the right direction? Thanks,
This worked for me:
var request = (HttpWebRequest)WebRequest.Create("http://www.google-analytics.com/collect");
request.Method = "POST";
// the request body we want to send
var postData = new Dictionary<string, string>
{
{ "v", "1" }, //analytics protocol version
{ "tid", "UA-XXXXXXXX-X" }, //analytics tracking property id
{ "cid", "XXXX"}, //unique user identifier
{ "t", "event" }, //event type
{ "ec", category },
{ "ea", action },
};
var postDataString = postData
.Aggregate("", (data, next) => string.Format("{0}&{1}={2}", data, next.Key,
Uri.EscapeDataString(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);
}
var webResponse = (HttpWebResponse)request.GetResponse();
if (webResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception($"Google Analytics tracking did not return OK 200. Returned: {webResponse.StatusCode}");
}

AngularJS web API not working with strings

At the moment what I am trying to do is to return a list of strings from my web API, but I was getting this error 'No 'Access-Control-Allow-Origin' header is present on the requested resource.'
After struggling for a while I have realised it's because it will only allow me to return a list of integers and not a list of strings.
Here are the two methods (one of which would obviously be commented out).
public IEnumerable<string> Get(int userId)
{
IEnumerable<string> listOfFormGroups = new List<string>() { "Form Group 1", "Form Group 2", "Form Group 3" };
return listOfFormGroups;
}
public IEnumerable<int> Get(int id)
{
IEnumerable<int> listOfRoles = new List<int>() { 1, 2, 3 };
return listOfRoles;
}
The top method throws the error, but the second method returns fine.
my angular service
this.get = function (userId) {
return $http.get(toApiUrl('formgroup/') + userId);
}
my angular controller calling the service,
var promiseGet = formGroupService.get(1);
promiseGet.then(function (result) {
$scope.FormGroups = result.data
},
function (errorResult) {
$log.error('Unable to get users form groups. An error has occurred. :', errorResult);
});
If you look at the default WebApiConfig, it looks like this:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I believe the integer version is working because you called the param id as stated in the config. The string one you have is trying to map to id, seeing userId as the only parameter and not mapping it correctly. I believe that is your error.
Change your method to look like this:
public IEnumerable<string> Get(int id)
{
IEnumerable<string> listOfFormGroups = new List<string>() { "Form Group 1", "Form Group 2", "Form Group 3" };
return listOfFormGroups;
}
peinearydevelopment's answer may be correct, but there is another interesting part of the question. The No 'Access-Control-Allow-Origin' message is a CORS error message (a cross origin request). In general, a script is limited to making AJAX requests to the same URL origin that it came from.
My guess that part of the problem is coming from the fact that toApiUrl() creates a URL that is of a different domain than the script came from.
There are ways around this, but it requires changes on the server side. See the documentation on how to do this.
It does't have any problem. You can call it by having below url.
I have already tested it and its working fine.
http://localhost:52257/api/temp/Get?userId=3
// please use your domain or localhost....
So in your case you can go with,
return $http.get(toApiUrl('formgroup/Get?userId=3'));

Implementation of Paypal in single page application

I am currently working on a game, which will consist out of an API-based backend, along with a web frontend (which is a single page app, in AngularJS) and on several mobile devices (using Cordova). I am planning on serving the SPA over the main domain name, along with a CDN. The SPA (and homepage) will all be static HTML/Javascript/CSS files, so the only part which is dynamic is the api. The domain name for the "main server" hosting the static sites will be in the style of example.com, the one for the api will be api.example.com
I am wondering how I can integrate Paypal into this scenario though. The internet doesn't seem to offer much advice on how to integrate it into S.P.A's like this...or my google-fu could be off. Thanks for the replies.
Below is how I am handling the situation,
I have a button to say pay with paypal and onClick I open a new window -> window.open("/paypalCreate", width = "20px", height = "20px");
and I capture this get request "/paypalCreate" in my node.js server and call create method which looks liek below
exports.create = function (req, res) {
//Payment object
var payment = {
//fill details from DB
};
//Passing the payment over to PayPal
paypal.payment.create(payment, function (error, payment) {
if (error) {
console.log(error);
} else {
if (payment.payer.payment_method === 'paypal') {
req.session.paymentId = payment.id;
var redirectUrl;
for (var i = 0; i < payment.links.length; i++) {
var link = payment.links[i];
if (link.method === 'REDIRECT') {
redirectUrl = link.href;
}
}
res.redirect(redirectUrl);
}
}
});
};
This redirects user to paypal and once user confirms or cancels payment, the redirect urls are called. And in the success redirect url I capture the payment details into the databse and render a html in this opened window with the confirmation.
exports.execute = function (req, res) {
var paymentId = req.session.paymentId;
var payerId = req.param('PayerID');
// 1. if this is executed, then that means the payment was successful, now store the paymentId, payerId and token into the database
// 2. At the close of the popup window open a confirmation for the reserved listing
var details = {"payer_id": payerId};
paypal.payment.execute(paymentId, details, function (error, payment) {
if (error) {
console.log(error);
} else {
//res.send("Hell yeah!");
res.render('paypalSuccess', {payerId: payerId, paymentId: paymentId});
}
});
};
Once the user closes the opened window in which paypal was being handled the orginal SPA window will be refreshed and thus getting the payment details from the DB and here you can handle the SPA in whatever way you want.
I know that this is a dirty hack, but like you I couldnt find a better way. Please let me know if this works for you or if you have a found a better way to do tihs.
cheers,
Chidan

Resources