Is there any way to run the PHP code on the c# app
since I'm working on an application that requires to implement of this site's API
but there is no documentation except for PHP, so is there any way I can use this piece of code in a c# application or convert this code in C# if that is possible.
public $api_url = 'https://smm-bomb.com/api/v2'; // API URL
public $api_key = ''; // Your API key
public function order($data) { // add order
$post = array_merge(array('key' => $this->api_key, 'action' => 'add'), $data);
return json_decode($this->connect($post));
}
One option is to rewrite the call using C#, check docs if needed.
Another one is to made your custom php-api which wrap initial call.
Then from C# just use your php-api. Postman can be a useful tool to check your custom php-api and also for C# code generation
---custom php-api---
--update to fit https://smm-bomb.com/api--
<?php
class Api
{
public $api_url = 'https://smm-bomb.com/api/v2'; // API URL
public $api_key = '4a99333333333333333dummy'; // Your API key
...
//just copy-paste from example
}
//from-docs, create an instance an invoke any methods
//since it's a self contained class no imports required
//main
$api = new Api();
$services = $api->services(); # return all services
$out = [];
//mainly here will be the return of api-call
$out["mykey"]="myvalue";
//output as json whatever wanted
$out["listServices"]=$services;
echo json_encode($out);
?>
//sample output
//{"mykey":"myvalue"}
This piece of code should be accessible via link eg: https://yoursite/custom-api (for security purpose can use a token on query-string. /custom-api?key=123mykey ->trivial approach)
Use PostMan to check and see code-generation
Related
When writing Javascript code within a Razor/cshtml file, one may write code as follows:
if (lSelectedID == "#(Globals.MyGlobalVariable)") {
...
}
where Globals.MyGlobalVariable is a C# variable.
If Globals.MyGlobalVariable==123, then the resulting Javascript on the client will be
if (lSelectedID == "123") {
...
}
The above is very handy. But how to do the same in Typescript? I.e. how to insert a C# global variable (or result of C# function call or whatever) into typescript before the typescript file is transformed to Javascript?
It's not best practice to include JavaScript and CSS directly into your CSTHML. Rather you should have them in their own file and reference them in your view.
If your JavaScript is going to need some value from C# then you should store it by using data attribute in your HTML elements.
Example:
<span id="myGlobalVariable" data-value="123456">MyGlobalVariable</span>
Then in your TypeScript get data you have set in your View
let myGlobalVariable = document.getElementById("myGlobalVariable").dataset.value;
if (lSelectedID == myGlobalVariable) {
}
I think the easiest thing to do here would be to replicate your global variables in Typescript on the client side. This is how I've done it for my last two projects.
So on the server side you would have:
// C#
public class Globals()
{
public int GlobalNum {get;} = 0;
public string GlobalString {get;} = "123";
}
And on the client side, in Typescript it would be:
// Typescript
export enum Globals{
GlobalNum = 0;
GlobalString = "123";
}
Now you can forget about the difficulty of trying to connect Razor (which renders server-side) to your Typescript (which executes on the client side), while still having a clear and obvious set of globals to refer to.
You code can then become:
// Typescript
if (lSelectedID == Globals.GlobalString) {
//...
}
The only thing you need to keep in mind is that your global variables exist in two places - once on the server side and once on the client side.
Typescript demands that you replicate a lot of your server-side classes on the client side anyway, for receiving fetch response data properly, for example, so the addition of a Globals class/enum should not be too much of a break from the norm.
I'm trying to create a REST Webservice, not sure to create a separate WebAPI or just add a WCF Service.
public class FirstService : Reactor, IFirstService
{
const string StateFilename = "DetectedEvent.bin";
public string Reset()
{
string stateFile = Path.Combine(App.StoragePath, StateFilename);
if (File.Exists(stateFile))
{
File.Delete(stateFile);
}
return "Reset Completed";
}
}
I am trying to write a webservice for deleting a file and that call I would be doing using Powershell Invoke-RestMethod
The DetectedEvent.bin is located in remote server.
I have already created a C# class library i.e. custom Seq.App.FirstOfType but now I want to create a REST webservice by which wen called can delete a file.
I am using Seq App, Seq has a storagePath which it stores all data, which I want to delete it.
Please someone can let me know how should I go forward i.e should I create new project i.e. WEBAPI and attach it to current solution or I should create a WCF service application.
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);
}
}
I have seen many links on how to make a web-api using PHP, and all of the examples would put each "function" in a different file. I once helped my friend develop an asp.net C# web api where a single file would contain multiple functions.
Can this be done in PHP? i.e can a single PHP file contain multiple functions that a web-api can call? If so can you kindly give me an example of how it is done, or refer me to a link where this is explained?
Thank you for your time.
Use a framework to build your API, don't reinvent the wheel.
If you must, you need to find a "discriminator", or how you know what kind of request has to end up at which function.
You can do so using the HTTP verb, the URL, HTTP headers and whatnot. Frameworks do this for you, so you only have to write the code you're interested in.
Again, if you must, you can do something like this:
<?php
function DoPost()
{
// ...
}
function DoPut()
{
// ...
}
function DoGet()
{
// ...
}
function Main()
{
switch ($_SERVER['REQUEST_METHOD'])
{
case 'GET':
return DoGet();
case 'PUT':
return DoPut();
case 'POST':
return DoPost();
}
}
Main();
?>
I have a silver-light based web application.I am using ScriptObject to connect and call method in java script and in turn java script interact with plugin. All the function call from c# to java script was synchronous.now Now I am trying to use web socket server for replacement for plugin.
Now I am just changing the code of the methods in java script file to interact with web socket server.
Since web Socket call are asynchronous in nature I am not able to implement the call from c# to java script and return value.
Now I wanted call callback from java script to c# code.Is this is possible ?
Please suggest how to solve this problem.
It's possible.
You annotate a class like this:
public class MyScriptableManagedType {
[ScriptableMember()]
public string MyToUpper(string str) {
return str.ToUpper();
}
[ScriptableMember()]
public string Name { get; set; }
}
put it in the page's scope of javascript objects:
MyScriptableManagedType smt = new MyScriptableManagedType();
HtmlPage.RegisterScriptableObject("mySLapp", smt);
Then you can use it from javascript like so:
var slCtl = null;
function pluginLoaded(sender,args){
slCtl = sender.getHost();
alert(slCtl.Content.mySLapp.MyToUpper("Test String"));
}
The function pluginLoaded has to be registered with the silverlight plugin to be called on load.
Take from and more details at:
http://msdn.microsoft.com/en-us/library/cc221414(v=vs.95).aspx