pass array of numbers from ajax to controller

I know this is a popular topic and I’ve tried all of the solutions I could find already out there to no avail. I’ve used all the solutions included for this questions: Pass a List from javascript to controller. I’ve simplified my test to ridiculously simple. I get into the controller but my controller input param is {int[0]}. I confirmed my array data looks good in the JavaScript and ajax call.

Can anyone please tell me what I am missing?

JavaScript Code

var selectedIds = [];
selectedIds.push(565);
selectedIds.push(573);
selectedIds.push(571);
// selectedIds = [565, 573, 571]

$.ajax({
    type: "POST",
    traditional: true,
    dataType: "json",
    data: { "ids": JSON.stringify(selectedIds) },
    //data: { "ids": selectedIds},
    //data: { ids: selectedIds},
    url: "api/services/getbuildingsbyid",
    success: function (result) {
        return result;
    }
});

Controller Code

[HttpPost]
public bool GetBuildingsById(int[] ids)
{
    var lookAtIds = ids;     // {int[0]}
    return true;
}


Source: stackoverflow-javascript

Base 6 Given a sequence of distinct numbers

Problem : Base 6

Given a sequence of distinct numbers a1, a2, ….. an, an inversion occurs if there are indices i aj .

For example, in the sequence 2 1 4 3 there are 2 inversions (2 1) and (4 3).

The input will be a main sequence of N positive integers. From this sequence, a Derived Sequence will be obtained using the following rule. The output is the number of inversions in the derived sequence.

Rule for forming derived sequence
An integer may be represented in base 6 notation. In base 6, 10305 is 1×64 + 3×62 + 5 =1409. Note that none of the digits in that representation will be more than 5.

The sum of digits in a base 6 representation is the sum of all the digits at the various positions in the representation. Thus for the number 1409, the representation is 10305, and the sum of digits is 1+0+3+0+5=9. The sum of digits may be done in the decimal system, and does not need to be in base 6

The derived sequence is the sum of the digits when the corresponding integer is represented in the base 6 form number will be expressed in base 6, and the derived sequence is the sum of the digits of the number in the base 6 representation.

Input Format:

The first line of the input will have a single integer, which will give N.

The next line will consist of a comma separated string of N integers, which is the main sequence
Output Format:

The number of inversions in the derived sequence formed from the main sequence.
Constraints:

N <= 50

Integers in sequence <= 107

Sample Input and Output

SNo. Input Output
1
5

55, 53, 88, 27, 33

2
2
8
120,21,47,64,72,35,18,98

11

Explanation for example 1:
The number of integers is 5, as specified in the first line. The given sequence is 55, 53, 88, 27, 33.

The base6 representation is 131, 125, 224, 43, 53 The derived sequence is 5,8,8,7,8 (corresponding to the sum of digits). The number of inversions in this is 2, namely (8, 7), (8, 7)

Explanation for example 2:
The base 6 representation of this is 320,33,115,144,200,55,30,242, and the derived sequence (sum of digits) is 5,6,7,9,2,10,3,8. The number of inversions is 11 (5,2), (5,3),(6,2) (6,3), (7,2), (7,3) (9,2),(9,3) (9,8),(10,3), (10,8)
Note:

Please do not use package and namespace in your code. For object oriented languages your code should be written in one class.
Note:

Participants submitting solutions in C language should not use functions from / as these files do not exist in gcc
Note:

For C and C++, return type of main() function should be int.


Source: stackoverflow-php

Get datetime in two different timezone

I have date time stored in document db database as

“myDate”: “2017-06-27T15:44:35.6752016+09:30”,

and my property in C# to store that datetime is below

public DateTime MYDate{ get; set; }

On my screen user can click a button which will save the information in a text file. Now information that I want to store in that text file is MyDate value as a string and another version of MyDate as a string also. This another version of MyDate can be of a different timezone. For example, I create MyDate in Australia, Melbourne now lets say I moved to America and when I click that button on client I am passing DateTimeOffset information and want to see that original date and another version in AmericanTime equivalent time. How would I solve this issue?


Source: stackoverflow-javascript

C# WebSockets and JavaScript sync time

I have events which occur in a C# based application which run on a timer. However, I can’t seem to ever get both server and clients time to sync with one another to show a count down to which the event is going to end.

I am used web sockets to communicate with the client. Here are some of the things which I have done in attempt to achieve a sync but either the client or server is out of sync as timer either finishes before or after rarely ever at the same time.

Sending time in second

I send a simply message like start-timer;100 which triggers 100 seconds. Then I use something like this

function setTimer(type, expire)
        {
            if(cycleTimers[type] == undefined) {
                cycleTimers[type] = {};
            }

            var d = new Date();
            d.setSeconds(d.getSeconds() + expire);

            cycleTimers[type].time = d;
            if(cycleTimers[type].interval != undefined) {
                clearInterval(cycleTimers[type].interval);
            }

            cycleTimers[type].interval = setInterval(function() {

                var time = Math.abs((new Date() - cycleTimers[type].time) / 1000);

                var minutes = ("00" + Math.floor(time / 60)).slice(-2);
                var seconds = ("00" + Math.floor(time % 60)).slice(-2);

                $(".timer-cycle").html(minutes + ":" + seconds);
                $(".timer-cycle").show();

                if(time <= 0) {
                    clearInterval(cycleTimers[type].interval);
                    $(".timer-cycle").hide();
                }
            }, 500);
        }

The reason for type, is that in the end I would like to run multiple timers and show the time left on the clients screen. However, for purpose of this example it isn’t needed.

Time in seconds with interval

I have send the time in seconds above but instead of converting it to a date I attempted to just use an interval of 1000 and decrease the seconds remaining by one on each cycle. This didn’t work either.

Unix time stamp

I also attempted to convert date time from c# to a timestamp and send it to client for expire time but they were completely different to one another.

C#

this.ExpireTime = DateTime.UtcNow.AddSeconds(Seconds);
socket.SendTimer(Seconds);

I run a task which executes every 500ms to check if this.Expired is less than current date if so then stop cycle. This works fine on emulator as I write to console the time at each tick.


Source: stackoverflow-javascript

node.js addon call javascript function failed

I want to call a javascript function(which is in the test.js) from my C++ addon by name but not pass it as an argument in the FunctionCallbackInfo<Value> object. Version of my node.js is 6.10.2.

test.js:

function callme(msg)
{
    console.log(msg);
}
const addon = require('./build/Debug/addon11');
addon.StartRun();

addon.cc:

#include<node.h>

namespace demo
{
    using v8::FunctionCallbackInfo;
    using v8::Isolate;
    using v8::Local;
    using v8::Object;
    using v8::String;
    using v8::Value;
    using v8::Exception;
    using v8::Function;
    using v8::Context;
    using v8::HandleScope;
    using v8::MaybeLocal;

    void Method(const FunctionCallbackInfo<Value>& args)
    {
        Isolate* isolate = Isolate::GetCurrent();
        HandleScope scope(isolate);
        Local<Context> context = isolate->GetCurrentContext();
        Local<Object> global = context->Global();
        if (global.IsEmpty() || global->IsNull())
        {
            return;
        }
        MaybeLocal<Value> mbValue = global->Get(String::NewFromUtf8(isolate, "callme"));
        if (mbValue.IsEmpty())
        {
            isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "can't find the function callme!")));
            return;
        }
        Local<Value> vTmp = mbValue.ToLocalChecked();
        if (!vTmp->IsFunction())
        {
            return;//it will retun here
        }
        Local<Function> callFunc = Local<Function>::Cast(vTmp);
        Local<Value> argv[] = { String::NewFromUtf8(isolate, "call from c++") };
        callFunc->Call(Null(isolate), 1, argv);
    }

    void init(Local<Object> exports)
    {
        NODE_SET_METHOD(exports, "StartRun", Method);
    }

    NODE_MODULE(addon11, init)
}

when I debug the code it returns here:

        Local<Value> vTmp = mbValue.ToLocalChecked();
        if (!vTmp->IsFunction())
        {
            return;//it will retun here
        }


Source: stackoverflow-javascript

PHP COM and C# "Out" and boolean Parameters

I’m connecting through PHP “COM” to an API that is compatible with C#,C++ etc.
I have successfully made connection with the application and trying to use “out” parameters through COM and getting a “type mismatch” error. Is the “out” parameter and is supposed to house the response and then the false. I’m not sure if it fails on that or if it fails on the false.. but either way I can’t get this to work.

the C# example looks like this:

Dim aViews As Array = Nothing
vault.GetVaultViews(aViews, False)

the php code looks like this:

$this->aviews = array();      
try {

         $this->epdm->GetVaultViews($this->aviews, False );

   } catch (Exception $e) {

        echo 'Caught exception: ',  $e->getMessage(), "n";

 }

I get the following returned errors:
Caught exception: Parameter 1: Type mismatch.

Hope someone can help!


Source: stackoverflow-php

Translating PHP http request into C# .NET

I have written this code in PHP to make a HTTP request to my server to retrieve my data:

<?php


$client_secret= '';
$data= array(

'email' => '**********',

'password' => '******',

'client_id' => '*******'
);

$api_url='******';

$json_data=json_encode($data);

$signature_string = md5($json_data . $client_secret); 


$post_data = 'signature='.$signature_string.'&data='.urlencode($json_data);

$curl = curl_init($api_url); 
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1);

curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($curl, CURLOPT_POST, 1); 

curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);

$result = curl_exec($curl); 

print_r($result);


curl_close($curl); 

?> 

And this works good. Data is returned in JSON format. Now I’m trying to do exactly the same thing but in .NET

I have managed to recreate in .NET C# exactly the same postData parameter as in PHP, but I’m not sure how to pass it in C# with the request itself… So I’ve decided to use .NET’s restsharp library to make the request like this:

  public void GetResponse()
        {
            string client_secret = "*****";

            var serializer = new JavaScriptSerializer();
            string json_data = serializer.Serialize(new { email = "*****", password = "*****", client_id = "*****" });

            var signature_string = CalculateMD5Hash(json_data + client_secret).ToLower();

            var postData = "signature=" + signature_string + "&data=" + Server.UrlEncode(json_data);
            var client = new RestClient("mysite.com");
            var request = new RestRequest(Method.POST);
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            request.AddHeader("cache-control", "no-cache");
            request.AddParameter("application/x-www-form-urlencoded", "signature="+signature_string, ParameterType.RequestBody);
            request.AddParameter("application/x-www-form-urlencoded", "data=" +json_data, ParameterType.RequestBody);

            IRestResponse response = client.Execute(request);

        }

Please note in C# and in PHP variables:

$post_data 

and 

var postdata

are exactly identical. Now I just don’t know how to pass them alongside the request because the server always responds me that request data was empty..

What am I doing wrong here?


Source: stackoverflow-php

overload null in api restful methods ajax

I am creating a UI for a content production area on a company intranet. I created the middleware API in a previous project. This is my first tie using RESTful methods (and I’m fairly new to Javascript and jquery in the first place)

When I call my debugging local api from the jquery.ajax the JSON objet is not beig passed properly on my GET method.

In the C# API
[ActionName(“THING”)]
[HttpGet()]
public string GetThing(object json)
{
GetData getData;
if (json == null)
return null;
else if (json is string && (json as string).StartsWith(“{“))
getData = JsonConvert.DeserializeObject(json as string);
else
return null;
ItemReturn retVAl = new ItemReturn();

[logic to use JSON]

return retVal;

in the web page

loadThings: function (thingNumber, showBool) {
                showBool = (showBool === true);
                $.ajax({
                    type: "GET",
                    dataType: "json",
                    data: '{ "GetData" : {"ThingNumber":"' + thingNumber + '","Show": ' + showBool + '}}',
                    url: "http://localhost:11422/api/THING/THING/GetThing",
                    contentType: "application/json; charset=utf-8",

                    success: function (result) {

[logic to display things]

}

I can hit my breakPoint in GetThing fine, hat all work, but I can’t seem to figure out why the object (json) in my overload is coming in null. I know it’s something in the javascript, my unit tests work fine and my JavaScript is getting me to my breakpoint in the method, I just need to overloaded JSON object to actually b passed in


Source: stackoverflow-javascript