How to delete event in Google Calendar using API v3 .NET? - c#

I have this method:
public static void DeleteEvent(CalendarService service, Event eventToDelete, string calendarId = "primary")
{
service.Events.Delete(calendarId, eventToDelete.Id);
}
but it's failing to delete any events from the calendar.
What's am I doing wrong?

What you need to do is Add an .Execute() at the End of the line to execute the delete command, then it will be like the following:
service.Events.Delete(calendarId, eventToDelete.Id).Execute();
You can refer this article as well for more informations

Related

WordPress WooCommerce ASP.net API WebHookHandler: The WebHook request must contain an entity body formatted as HTML Form Data

I am trying to create a WebHookHandler for Webhooks send from WordPress WooCommerce in ASP.NET C#.
I started with creating a ASP.NET C# Azure API App WebApplication Project and adding the relevant references (Microsoft.AspNet.WebHooks.Common, Microsoft.AspNet.WebHooks.Receivers, Microsoft.AspNet.WebHooks.Receivers.WordPress). Added the WebHookConfig, WordPressWebHookHandler and registered the WebHookConfig in the GlobalAsax.
I then published the application as an Azure App Service.
My WordPressWebHookHandler is still the default of the examples and looks like this:
public class WordPressWebHookHandler : WebHookHandler
{
public override Task ExecuteAsync(string receiver, WebHookHandlerContext context)
{
// make sure we're only processing the intended type of hook
if("WordPress".Equals(receiver, System.StringComparison.CurrentCultureIgnoreCase))
{
// todo: replace this placeholder functionality with your own code
string action = context.Actions.First();
JObject incoming = context.GetDataOrDefault<JObject>();
}
return Task.FromResult(true);
}
}
When testing a User Creation WebHook in WooCommerce I can see the request in the log as below.
But unfortunately it is never received while debugging and I see below error.
I am thinking maybe I need a custom WebHook instead of the WordPress specific one as this is a WooCommerce Webhook. Or possibly it is handled wrong in the routing and ends up in another controller.
Any help is much appreciated.
Your WebHookReceiver is wrong
There is a mismatch of expecting HTML Form Data, when in fact it should be expecting JSON.
WordPressWebHookHandler is still the default
This is what is causing your error. If you look at the WordPressWebHookReceiver, the ReceiveAsync() method implementation, calls out to ReadAsFormDataAsync() method, which is not what you want, as your Content-Type is json. So, you want to be doing ReadAsJsonAsync().
Solution: Don't use the WordPressWebHookReceiver and switch it to another one that will call ReadAsJsonAsync().
Looking at the code
I am thinking maybe I need a custom WebHook instead of the WordPress specific one as this is a WooCommerce Webhook.
You had the right idea, so I dug up some of the code to explain exactly why this was happening.
The code block below is the ReceiveAsync() method that is overridden in the WordPressWebHookReceiver. You can see that it is calling the ReadAsFormDataAsync() which is not what you want...
public override async Task<HttpResponseMessage> ReceiveAsync(
string id, HttpRequestContext context, HttpRequestMessage request)
{
...
if (request.Method == HttpMethod.Post)
{
// here is what you don't want to be called
// you want ReadAsJsonAsync(), In short, USE A DIFFERENT RECEIVER.
NameValueCollection data = await ReadAsFormDataAsync(request);
...
}
else
{
return CreateBadMethodResponse(request);
}
}
A quick search through the repository for classes that call the ReadAsJsonAsync() method, shows that the following recievers implement it:
DynamicsCrmWebHookReceiver
ZendeskWebHookReceiver
AzureAlertWebHookReceiver
KuduWebHookReceiver
MyGetWebHookReceiver
VstsWebHookReceiver
BitbucketWebHookReceiver
CustomWebHookReceiver
DropboxWebHookReceiver
GitHubWebHookReceiver
PaypalWebHookReceiver
StripeWebHookReceiver
PusherWebHookReceiver
I assumed that the CustomWebHookReceiver would fit your requirements, so can grab the NuGet here. Otherwise you can implement your own, or derive it from this class, etc.
Configuring a WebHook Recevier
(Copied from the Microsoft Documentation)
Microsoft.AspNet.WebHooks.Receivers.Custom provides support for
receiving WebHooks generated by ASP.NET WebHooks
Out of the box you can find support for Dropbox, GitHub, MailChimp,
PayPal, Pusher, Salesforce, Slack, Stripe, Trello, and WordPress but
it is possible to support any number of other providers
Initializing a WebHook Receiver
WebHook Receivers are initialized by registering them, typically in
the WebApiConfig static class, for example:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
// Load receivers
config.InitializeReceiveGitHubWebHooks();
}
}
There is a problem with the data format that you send in your request. You must use format of HTML Form as your error message said.
Proper POST data format is described here: How are parameters sent in an HTTP POST request?
Don't forget to set Content-Length header and correct Content-Type if your library doesn't do it. Usually the content type is application/x-www-form-urlencoded.
I would like to make some additions to Svek's answer as I now got my Proof-of-concept completed and understand a bit more about the receivers.
His answer pointed me in the right direction, but needs a little addition.
WordpressWebHookReceiver
Can take in Wordpress Webhooks of type HttpPost. This does not work with Woocommerce as Woocommerce sends Json Webhook messages and will fail the HttpPost validation which is build into the WordpressWebHookReceiver class.
CustomWebHookReceiver
Can take in custom ASP.NET Webhooks. The custom ASP.NET webhooks have a specific partner for validation which includes but is not limited to the 'ms-signature'. Even adding the header will not suffice as the signature is also used in a different way from out of the box Woocommerce to encrypt the message. Basically coming to a point that you can't integrate Woocommerce with the CustomWebHookReceiver without changing the Webhook classes of Woocommerce.
GenericWebHookReceiver
This is the receiver you want, which accepts basically a generic set of Json data and will be able to use the "code" query parameter to verify the secret which you can add in the web.config of your asp.net api application. I used this receiver to finish the Proof-of-concept and got both the signature validation as well as the deciphering of the message working right of the bat.
My basic class which I will start to build into a real solution can be viewed below and changes the JObject into a dynamic object in the methods I call from the class. As you can see I have two methods currently added, one for the customer create and one for the order create to call the respective methods which do an insert into Dynamics 365 (former CRM).
public class GenericJsonWebHookHandler : WebHookHandler
{
public GenericJsonWebHookHandler()
{
this.Receiver = "genericjson";
}
public override Task ExecuteAsync(string generator, WebHookHandlerContext context)
{
var result = false;
try
{
// Get JSON from WebHook
var data = context.GetDataOrDefault<JObject>();
if(context.Id != "crcu" && context.Id != "cror")
return Task.FromResult(true);
if (context.Id == "crcu")
{
result = WoocommerceCRMIntegrations.Entities.Contact.CreateContactInCRM(data);
}
else if (context.Id == "cror")
{
result = WoocommerceCRMIntegrations.Entities.Order.CreateOrderInCRM(data);
}
}
catch (Exception ex)
{
result = false;
}
return Task.FromResult(result);
}
}

Azure Webjob trigger on insert or update record in table

I want to get trigger on insertion or updation of any record in Azure table storage. For that I have created a azure webjob with below method...
public static async Task ReadTableEntity(
[QueueTrigger("inputqueue")] Contact contactInQueue,
[Table("Contact", "ContactId", "CityId")] Contact contactInTable, TextWriter logger)
{
logger.WriteLine("triggered");
}
But above method is not called after any record in table updated or new record inserted.
I want to get above method called on insert or update any record in table.
Please correct me where I am wrong.
This trigger isn't working like you are expecting it to. For that to be the case, it would need to be some type of "Table Trigger," which does not exist.
From the docs :
Some of the code snippets show the Table attribute used in functions that are called manually, that is, not by using one of the trigger attributes.
In laymen terms:
There is nothing listening for you making any changes to your Storage Tables. You need to trigger this call after you Insert or Update your Table Storage records.
In your Web Job, you could add something like this (from the documentation) to trigger your method :
public class Program
{
static void Main(string[] args)
{
JobHost host = new JobHost();
host.Call(typeof(Program).GetMethod("CreateQueueMessage"), new { value = "Hello world!" });
}
[NoAutomaticTrigger]
public static void CreateQueueMessage(
TextWriter logger,
string value,
[Queue("outputqueue")] out string message)
{
message = value;
logger.WriteLine("Creating queue message: ", message);
}
}
As I known, there is a similar issue about Azure WebJobs Table Trigger. Also, someone has posted a feature request issue Add Trigger for Azure Table Storage. I would report this feature request, you could try to follow this tutorial to build your own binding extensions or follow Mark C.'s solution to manually trigger the insert/update record in Azure Table Storage for a workaround.

Xamarin/Mvvmcross: Open a different view controller when a iOS push notification is received

I have found this question asked using Objective-c but I am unable to translate it into C#
e.g.
open-specific-view-when-opening-app-from-notification
Basically I want to do this:
public override void ReceivedRemoteNotification (UIApplication application, NSDictionary userInfo)
{
string alert = (aps[new NSString("alert")] as NSString).ToString();
Debug.WriteLine ("I want to open a specific ViewController and pass in my alert");
}
I am actually using mvvmcross to manage my View navigation. So ideally I want to somehow implement this navigation using mvvmcross. In mvvmcross I would navigate to my ViewControler by doing this:
this.ShowViewModel<SpecificControllerViewModel>();
Thanks
if you look to the parameters of ShowViewModel(), it has a way to pass values to the view-model
this is described here along with examples
You can achieve that in few ways.
You could use a custom message. A view-model can register to receive the message and you send it from the ReceivedRemoteNotification Read here about messenger in MvvmCross.
Or, you can call ShowViewModel. If you look to how ShowViewModel is implemented here, it uses a IMvxViewDispatcher singleton service, so you could have the following utility method:
static void ShowViewModel<T>(object parameter) where T : IMvxViewModel
{
var viewDispatcher = Mvx.Resolve<IMvxViewDispatcher>();
var request = MvxViewModelRequest.GetDefaultRequest(typeof(T));
request.ParameterValues = ((object)parameter).ToSimplePropertyDictionary();
viewDispatcher.ShowViewModel(request);
}
I posted about this on my blog here.
I think the 2nd way can work even in the case when the notification is received when app is not running (received by FinishedLaunching)

How to use google analytics for win phone

I have a win phone and I got a new requirement to put google analytic to log app events.
I added everything I found over net but my client saying that he is not seeing any log. So what I using is
GoogleAnalytics.EasyTracker.GetTracker().SetStartSession(true);
Used this line of code on app startup. And than
public void SendEvent(string category, string action, string label, int value)
{
GoogleAnalytics.EasyTracker.GetTracker().SendEvent(category, action, label, value);
}
this method to log events. Is there something wrong I am doing?

How to manipulate a header and then continue with it in C#?

I want to replace an old ISAPI filter that ran on IIS6. This filter checks if the request is of a special kind, then manipulates the header and continues with the request. Two headers are added in the manipulating method that I need for calling another special ISAPI module.
So I have ISAPI C++ code like:
DWORD OnPreProc(HTTP_FILTER_CONTEXT *pfc, HTTP_FILTER_PREPROC_HEADERS *pHeaders)
{
if (ManipulateHeaderInSomeWay(pfc, pHeaders))
{
return SF_STATUS_REQ_NEXT_NOTIFICATION;
}
return SF_STATUS_REQ_FINISHED;
}
I now want to rewrite this ISAPI filter as a managed module for the IIS7. So I have something like this:
private void OnMapRequestHandler(HttpContext context)
{
ManipulateHeaderInSomeWay(context);
}
And now what? The request seems not to do what it should?
I already wrote an IIS7 native module that implements the same method. But this method has a return value with which I can tell what to do next:
REQUEST_NOTIFICATION_STATUS CMyModule::OnMapRequestHandler(IN IHttpContext *pHttpContext, OUT IMapHandlerProvider *pProvider)
{
if (DoSomething(pHttpContext))
{
return RQ_NOTIFICATION_CONTINUE;
}
return RQ_NOTIFICATION_FINISH_REQUEST;
}
So is there a way to send my manipulated context again?
I finally found it. As I stated in the comments I add two headers to the request that are needed by my DLL that finally handles the request. The url header contains the path to the DLL. So I have to do a redirect to that DLL.
This is done with the following code:
private void OnMapRequestHandler(HttpContext context)
{
ManipulateHeaderInSomeWay(context);
string url = context.Request.Header["url"]; // path of the DLL
// now this is the important call!
context.Server.TransferRequest(url, true);
}

Categories

Resources