问:
Android app not sending message to localhost server using sockets
I am implementing a chat application using Nodejs and socket programming. If I send a message from my Android application, it should show connected in my terminal of WebStorm, however nothing is happening.

index.js

```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/',function(req,res){
    res.sendFile(__dirname+'/index.html');
})
io.on('connection',function(socket){
    console.log('one user connected '+socket.id);
    socket.on('message',function(data){
        var sockets = io.sockets.sockets;
        // sockets.forEach(function(sock){
        //  if(sock.id != socket.id)
        //  {
        //  sock.emit('message',data);
        //  }
        //  })
        socket.broadcast.emit('message', data);
        console.log('message '+data);
    })
    socket.on('disconnect',function(){
        console.log('one user disconnected '+socket.id);
    })
})

http.listen(3000,function(){
    console.log('server listening on port 3000');
})
</code>```

index.html

```<code> <!doctype html>
<html>
<head>
    <title>Socket.IO chat</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font: 13px Helvetica, Arial; }
        form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
        form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
        form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
        #messages { list-style-type: none; margin: 0; padding: 0; }
        #messages li { padding: 5px 10px; }
        #messages li:nth-child(odd) { background: #eee; }
    </style>
</head>
<body>
<ul id="messages"></ul>
<form action="">
    <input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io();
</script>
</body>
<h1>Hello Sockets</h1>
</html>
</code>```

ChatFragment.java

```<code>package com.example.admin.chatapp;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ChatFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ChatFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ChatFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private EditText mInputMessageView;
    private RecyclerView mMessagesView;
    private OnFragmentInteractionListener mListener;
    private List<Message> mMessages = new ArrayList<Message>();
    private RecyclerView.Adapter mAdapter;

    private Socket socket;
    {
        try{
            socket = IO.socket("http://192.168.x.x:3000");
        }catch(URISyntaxException e){
            throw new RuntimeException(e);
        }
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ChatFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ChatFragment newInstance(String param1, String param2) {
        ChatFragment fragment = new ChatFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public ChatFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        socket.connect();
        socket.on("message", handleIncomingMessages);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_chat, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);
        mAdapter = new MessageAdapter(mMessages);
        /*try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mMessagesView = (RecyclerView) view.findViewById(R.id.messages);
        mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mMessagesView.setAdapter(mAdapter);

        ImageButton sendButton = (ImageButton) view.findViewById(R.id.send_button);
        mInputMessageView = (EditText) view.findViewById(R.id.message_input);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });

    }

    private void sendMessage(){
        String message = mInputMessageView.getText().toString().trim();
        mInputMessageView.setText("");
        addMessage(message);
        JSONObject sendText = new JSONObject();
        try{
            sendText.put("text",message);
            socket.emit("message", sendText);
        }catch(JSONException e){

        }

    }

    public void sendImage(String path)
    {
        JSONObject sendData = new JSONObject();
        try{
            sendData.put("image", encodeImage(path));
            Bitmap bmp = decodeImage(sendData.getString("image"));
            addImage(bmp);
            socket.emit("message",sendData);
        }catch(JSONException e){

        }
    }

    private void addMessage(String message) {

        mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
                .message(message).build());
        // mAdapter = new MessageAdapter(mMessages);
        mAdapter = new MessageAdapter( mMessages);
        mAdapter.notifyItemInserted(0);
        scrollToBottom();
    }

    private void addImage(Bitmap bmp){
        mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
                .image(bmp).build());
        mAdapter = new MessageAdapter(mMessages);
        mAdapter.notifyItemInserted(0);
        scrollToBottom();
    }
    private void scrollToBottom() {
        mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1);
    }

    private String encodeImage(String path)
    {
        File imagefile = new File(path);
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(imagefile);
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        Bitmap bm = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
        byte[] b = baos.toByteArray();
        String encImage = Base64.encodeToString(b, Base64.DEFAULT);
        //Base64.de
        return encImage;

    }

    private Bitmap decodeImage(String data)
    {
        byte[] b = Base64.decode(data,Base64.DEFAULT);
        Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
        return bmp;
    }
    private Emitter.Listener handleIncomingMessages = new Emitter.Listener(){
        @Override
        public void call(final Object... args){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d("cdcdc", String.valueOf(args[0]));
                    JSONObject data = (JSONObject) args[0];
                    Log.d("cdcdc", String.valueOf(data));
                    String message;
                    String imageText;
                    try {
                        message = data.getString("text").toString();
                        addMessage(message);

                    } catch (JSONException e) {
                        // return;
                    }
                    try {
                        imageText = data.getString("image");
                        addImage(decodeImage(imageText));
                    } catch (JSONException e) {
                        //retur
                    }

                }
            });
        }
    };

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        socket.disconnect();
    }

}
</code>```

To run the index.js file in WebStorm, I type the command

node index.js

which gives me the output as

server listening on port 3000

and when I send a message from my app, nothing happens. The terminal stays as it is. What should I do, and what is causing this.

Update
I changed my android code to

```<code>socket = IO.socket("http://01e42de0.ngrok.io");
</code>```

Using ngrok gives me an error

06-05 20:27:52.578 23204-23204/com.example.admin.chatapp
  E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.admin.chatapp, PID: 23204
                                                                             java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.admin.chatapp/com.example.admin.chatapp.SocketActivity}:
  android.view.InflateException: Binary XML file line #9: Binary XML
  file line #9: Error inflating class fragment
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2728)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                              Caused by: android.view.InflateException: Binary XML file line #9:
  Binary XML file line #9: Error inflating class fragment
                                                                              Caused by: android.view.InflateException: Binary XML file line #9:
  Error inflating class fragment
                                                                              Caused by: java.lang.RuntimeException: java.net.URISyntaxException:
  Illegal character in scheme name at index 0:  http://01e42de0.ngrok.io
                                                                                at com.example.admin.chatapp.ChatFragment.(ChatFragment.java:64)
                                                                                at java.lang.Class.newInstance(Native Method)
                                                                                at android.app.Fragment.instantiate(Fragment.java:622)
                                                                                at android.app.Fragment.instantiate(Fragment.java:593)
                                                                                at
  android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)
                                                                                at
  android.app.FragmentController.onCreateView(FragmentController.java:98)
                                                                                at android.app.Activity.onCreateView(Activity.java:5982)
                                                                                at
  android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
                                                                                at
  android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                                                at
  android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                                                at
  android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at
  com.example.admin.chatapp.SocketActivity.onCreate(SocketActivity.java:22)
                                                                                at android.app.Activity.performCreate(Activity.java:6760)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2681)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                              Caused by: java.net.URISyntaxException: Illegal character in scheme
  name at index 0:  http://01e42de0.ngrok.io
                                                                                at java.net.URI$Parser.fail(URI.java:2856)
                                                                                at java.net.URI$Parser.checkChars(URI.java:3029)
                                                                                at java.net.URI$Parser.checkChar(URI.java:3039)
                                                                                at java.net.URI$Parser.parse(URI.java:3055)
                                                                                at java.net.URI.(URI.java:590)
                                                                                at io.socket.client.IO.socket(IO.java:41)
                                                                                at io.socket.client.IO.socket(IO.java:37)
                                                                                at com.example.admin.chatapp.ChatFragment.(ChatFragment.java:61)
                                                                                at java.lang.Class.newInstance(Native Method)
                                                                                at android.app.Fragment.instantiate(Fragment.java:622)
                                                                                at android.app.Fragment.instantiate(Fragment.java:593)
                                                                                at
  android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)
                                                                                at
  android.app.FragmentController.onCreateView(FragmentController.java:98)
                                                                                at android.app.Activity.onCreateView(Activity.java:5982)
                                                                                at
  android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
                                                                                at
  android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                                                at
  android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                                                at
  android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at
  com.example.admin.chatapp.SocketActivity.onCreate(SocketActivity.java:22)
                                                                                at android.app.Activity.performCreate(Activity.java:6760)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2681)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

答:
by asking you questions on your own question, I think I know what your problem is. Seems like your android device may not be on the same network as your application, and because you're running this on 192.168.x.x, I'm pretty sure this is what your problem is.

Your Android device just can't see your socket application as it's just running in localhost.

To make it accessible to your Android device, you can use a tunnelling application like ngrok. This will make your application available. Get it installed on your computer and run it in a new terminal window as follows:

ngrok http 3000

On that terminal window you will then be given a UR: that is accessible from outside. Copy that URL.

Sample here as image uploads seem broken right now.

Change this line on your code:

socket = IO.socket("http://192.168.1.9:3000");

to your ngrok URL. I.e.

socket = IO.socket("http://fa9910Hf.ngrok.io");

Try again and hopefully you should see the messages coming in.

Body:
I am implementing a chat application using Nodejs and socket programming. If I send a message from my Android application, it should show connected in my terminal of WebStorm, however nothing is happening.

index.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/',function(req,res){
    res.sendFile(__dirname+'/index.html');
})
io.on('connection',function(socket){
    console.log('one user connected '+socket.id);
    socket.on('message',function(data){
        var sockets = io.sockets.sockets;
        // sockets.forEach(function(sock){
        //  if(sock.id != socket.id)
        //  {
        //  sock.emit('message',data);
        //  }
        //  })
        socket.broadcast.emit('message', data);
        console.log('message '+data);
    })
    socket.on('disconnect',function(){
        console.log('one user disconnected '+socket.id);
    })
})

http.listen(3000,function(){
    console.log('server listening on port 3000');
})

index.html

 <!doctype html>

    <title>Socket.IO chat</title>

<form action="">
    <input id="m" autocomplete="off" /><button>Send</button>
</form>

Hello Sockets

ChatFragment.java

package com.example.admin.chatapp;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;

import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ChatFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ChatFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ChatFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private EditText mInputMessageView;
    private RecyclerView mMessagesView;
    private OnFragmentInteractionListener mListener;
    private List<Message> mMessages = new ArrayList<Message>();
    private RecyclerView.Adapter mAdapter;

    private Socket socket;
    {
        try{
            socket = IO.socket("http://192.168.x.x:3000");
        }catch(URISyntaxException e){
            throw new RuntimeException(e);
        }
    }
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ChatFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ChatFragment newInstance(String param1, String param2) {
        ChatFragment fragment = new ChatFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public ChatFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        socket.connect();
        socket.on("message", handleIncomingMessages);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_chat, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context activity) {
        super.onAttach(activity);
        mAdapter = new MessageAdapter(mMessages);
        /*try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }*/

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mMessagesView = (RecyclerView) view.findViewById(R.id.messages);
        mMessagesView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mMessagesView.setAdapter(mAdapter);

        ImageButton sendButton = (ImageButton) view.findViewById(R.id.send_button);
        mInputMessageView = (EditText) view.findViewById(R.id.message_input);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMessage();
            }
        });

    }

    private void sendMessage(){
        String message = mInputMessageView.getText().toString().trim();
        mInputMessageView.setText("");
        addMessage(message);
        JSONObject sendText = new JSONObject();
        try{
            sendText.put("text",message);
            socket.emit("message", sendText);
        }catch(JSONException e){

        }

    }

    public void sendImage(String path)
    {
        JSONObject sendData = new JSONObject();
        try{
            sendData.put("image", encodeImage(path));
            Bitmap bmp = decodeImage(sendData.getString("image"));
            addImage(bmp);
            socket.emit("message",sendData);
        }catch(JSONException e){

        }
    }

    private void addMessage(String message) {

        mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
                .message(message).build());
        // mAdapter = new MessageAdapter(mMessages);
        mAdapter = new MessageAdapter( mMessages);
        mAdapter.notifyItemInserted(0);
        scrollToBottom();
    }

    private void addImage(Bitmap bmp){
        mMessages.add(new Message.Builder(Message.TYPE_MESSAGE)
                .image(bmp).build());
        mAdapter = new MessageAdapter(mMessages);
        mAdapter.notifyItemInserted(0);
        scrollToBottom();
    }
    private void scrollToBottom() {
        mMessagesView.scrollToPosition(mAdapter.getItemCount() - 1);
    }

    private String encodeImage(String path)
    {
        File imagefile = new File(path);
        FileInputStream fis = null;
        try{
            fis = new FileInputStream(imagefile);
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        Bitmap bm = BitmapFactory.decodeStream(fis);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
        byte[] b = baos.toByteArray();
        String encImage = Base64.encodeToString(b, Base64.DEFAULT);
        //Base64.de
        return encImage;

    }

    private Bitmap decodeImage(String data)
    {
        byte[] b = Base64.decode(data,Base64.DEFAULT);
        Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
        return bmp;
    }
    private Emitter.Listener handleIncomingMessages = new Emitter.Listener(){
        @Override
        public void call(final Object... args){
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d("cdcdc", String.valueOf(args[0]));
                    JSONObject data = (JSONObject) args[0];
                    Log.d("cdcdc", String.valueOf(data));
                    String message;
                    String imageText;
                    try {
                        message = data.getString("text").toString();
                        addMessage(message);

                    } catch (JSONException e) {
                        // return;
                    }
                    try {
                        imageText = data.getString("image");
                        addImage(decodeImage(imageText));
                    } catch (JSONException e) {
                        //retur
                    }

                }
            });
        }
    };

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        socket.disconnect();
    }

}

To run the index.js file in WebStorm, I type the command

node index.js

which gives me the output as

server listening on port 3000

and when I send a message from my app, nothing happens. The terminal stays as it is. What should I do, and what is causing this.

Update
I changed my android code to

socket = IO.socket("http://01e42de0.ngrok.io");

Using ngrok gives me an error

06-05 20:27:52.578 23204-23204/com.example.admin.chatapp
  E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.admin.chatapp, PID: 23204
                                                                             java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.admin.chatapp/com.example.admin.chatapp.SocketActivity}:
  android.view.InflateException: Binary XML file line #9: Binary XML
  file line #9: Error inflating class fragment
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2728)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                              Caused by: android.view.InflateException: Binary XML file line #9:
  Binary XML file line #9: Error inflating class fragment
                                                                              Caused by: android.view.InflateException: Binary XML file line #9:
  Error inflating class fragment
                                                                              Caused by: java.lang.RuntimeException: java.net.URISyntaxException:
  Illegal character in scheme name at index 0:  http://01e42de0.ngrok.io
                                                                                at com.example.admin.chatapp.ChatFragment.(ChatFragment.java:64)
                                                                                at java.lang.Class.newInstance(Native Method)
                                                                                at android.app.Fragment.instantiate(Fragment.java:622)
                                                                                at android.app.Fragment.instantiate(Fragment.java:593)
                                                                                at
  android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)
                                                                                at
  android.app.FragmentController.onCreateView(FragmentController.java:98)
                                                                                at android.app.Activity.onCreateView(Activity.java:5982)
                                                                                at
  android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
                                                                                at
  android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                                                at
  android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                                                at
  android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at
  com.example.admin.chatapp.SocketActivity.onCreate(SocketActivity.java:22)
                                                                                at android.app.Activity.performCreate(Activity.java:6760)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2681)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                              Caused by: java.net.URISyntaxException: Illegal character in scheme
  name at index 0:  http://01e42de0.ngrok.io
                                                                                at java.net.URI$Parser.fail(URI.java:2856)
                                                                                at java.net.URI$Parser.checkChars(URI.java:3029)
                                                                                at java.net.URI$Parser.checkChar(URI.java:3039)
                                                                                at java.net.URI$Parser.parse(URI.java:3055)
                                                                                at java.net.URI.(URI.java:590)
                                                                                at io.socket.client.IO.socket(IO.java:41)
                                                                                at io.socket.client.IO.socket(IO.java:37)
                                                                                at com.example.admin.chatapp.ChatFragment.(ChatFragment.java:61)
                                                                                at java.lang.Class.newInstance(Native Method)
                                                                                at android.app.Fragment.instantiate(Fragment.java:622)
                                                                                at android.app.Fragment.instantiate(Fragment.java:593)
                                                                                at
  android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2302)
                                                                                at
  android.app.FragmentController.onCreateView(FragmentController.java:98)
                                                                                at android.app.Activity.onCreateView(Activity.java:5982)
                                                                                at
  android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:36)
                                                                                at
  android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:777)
                                                                                at
  android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
                                                                                at android.view.LayoutInflater.rInflate(LayoutInflater.java:858)
                                                                                at
  android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:821)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:518)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:426)
                                                                                at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
                                                                                at
  android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
                                                                                at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                                at
  com.example.admin.chatapp.SocketActivity.onCreate(SocketActivity.java:22)
                                                                                at android.app.Activity.performCreate(Activity.java:6760)
                                                                                at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                                                                at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2681)
                                                                                at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2814)
                                                                                at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1527)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6290)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


来源: stackexchange

问:
Replace special charachter '´' in C
I have a string to parse and it maybe contains the symbol "& acute;" depends on user data. So i want to eliminate this symbole and replace it with '.
Example :

Before --> Won´t Get Fooled Again
After  --> Won't Get Fooled Again

This is my try but it dosen't work in any way ..

```<code>int main()
{

  char* permenant="Won´t Get Fooled Again";
  char* s=permenant;
  for ( ; *s && *s != '&'; s++) ;
  printf("found '&' character \n"); // ---> OK
  printf("s=%s \n",s);              // ---> OK
  if (*(s+1) == 'a' && *(s+2) == 'c' && *(s+3) == 'u' && *(s+4) == 't'  && *(s+5) == 'e'  && *(s+6) == ';') // ---> OK
  {
     *s='\'';   //---> NO also if *s='a'; segmentation fault !!
     while(*(s+7)!='\0')
     {
          *(s+1)=*(s+7);
          s++;
          printf("the next character is -> %c \n", *(s+7));
     }// ---> Segmentation fault also if i remove *s='\''

   }
  printf("permenant=%s \n",permenant);

return 0;

}
</code>```

答:
You may want to have a look at

```<code>char *strstr(const char *haystack, const char *needle)
</code>```

It returns the pointer to the first time that needle shows up in haystack. Just take the return pointer and write your replacement character to it.

PS: It is part of <string.h>

ContentLicense: CC BY-SA 3.0

Title: Replace special charachter '´' in C

Body:
I have a string to parse and it maybe contains the symbol "& acute;" depends on user data. So i want to eliminate this symbole and replace it with '.
Example :

Before --> Won´t Get Fooled Again
After  --> Won't Get Fooled Again

This is my try but it dosen't work in any way ..

int main()
{

  char* permenant="Won´t Get Fooled Again";
  char* s=permenant;
  for ( ; *s && *s != '&'; s++) ;
  printf("found '&' character \n"); // ---> OK
  printf("s=%s \n",s);              // ---> OK
  if (*(s+1) == 'a' && *(s+2) == 'c' && *(s+3) == 'u' && *(s+4) == 't'  && *(s+5) == 'e'  && *(s+6) == ';') // ---> OK
  {
     *s='\'';   //---> NO also if *s='a'; segmentation fault !!
     while(*(s+7)!='\0')
     {
          *(s+1)=*(s+7);
          s++;
          printf("the next character is -> %c \n", *(s+7));
     }// ---> Segmentation fault also if i remove *s='\''

   }
  printf("permenant=%s \n",permenant);

return 0;

}

Body:
You may want to have a look at

char *strstr(const char *haystack, const char *needle)

It returns the pointer to the first time that needle shows up in haystack. Just take the return pointer and write your replacement character to it.

PS: It is part of <string.h>


问:
Google People API not returning all photo sources
Getting a person through the Google People API does not seem to return profile sources that are connected using a phone number, as opposed to an email address.

I have several contacts that when viewed through Google Contacts have a photo coming from their connected Google+ profile, stated to have been found via the contact's phone number. However when requesting the contacts through Google People the photo or source (the Google+ profile) is not returned in the response.

When doing the same for contacts where the profile is stated to have been found via an email address the photo and profile is returned in the response.

How do I get a contact's photo when the photo comes from a Google+ profile connected via a phone number?

答: Looks like there was a bug with getting profile data connected through phones, that should be fixed now.</p>


问:
Remove redundant spaces when render inside a
 tag
I'd like to render a paragraph without redundant spaces. For example:

```<code><p>There are cars, dogs, computers and houses!</p>
</code>```

I have written the following code:

```<code>var objects = new List<string> { "cars", "dogs", "computers", "houses" };

<p>
    There are
    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            @:and
        }
        else if (i > 0)
        {
            @:,
        }
        @objects[i]
    }
    !
<p>

@* This code will be rendered incorrectly by the browser like *@
<p>There are cars , dogs , computers and houses!</p>
</code>```

How can I remove the spaces inside the
 tag?

答:
You can create the string outside or inside of the paragraph using a code block like so. Then, just throw it in your

Outside

```<code>@{
    var objects = new List<string> { "cars", "dogs", "computers", "houses" };
    string myObjs = "";

    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            myObjs += " and";
        }
        else if (i > 0)
        {
            myObjs += ",";
        }

        myObjs += " " + objects[i];
    }
}

<p>There are @myObjs.Trim()!</p>
</code>```

Inside

```<code><p>There are
@{
    var objects = new List<string> { "cars", "dogs", "computers", "houses" };
    string myObjs = "";

    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            myObjs += " and";
        }
        else if (i > 0)
        {
            myObjs += ",";
        }

        myObjs += " " + objects[i];
    }
}
@myObjs.Trim()!</p>
</code>```

Title: Remove redundant spaces when render inside a <p> tag

Body:
I'd like to render a paragraph without redundant spaces. For example:

There are cars, dogs, computers and houses!

I have written the following code:

var objects = new List<string> { "cars", "dogs", "computers", "houses" };

    There are
    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            @:and
        }
        else if (i > 0)
        {
            @:,
        }
        @objects[i]
    }
    !

@* This code will be rendered incorrectly by the browser like *@

There are cars , dogs , computers and houses!

How can I remove the spaces inside the
 tag?

Body:
You can create the string outside or inside of the paragraph using a code block like so. Then, just throw it in your <p></p>

Outside

@{
    var objects = new List<string> { "cars", "dogs", "computers", "houses" };
    string myObjs = "";

    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            myObjs += " and";
        }
        else if (i > 0)
        {
            myObjs += ",";
        }

        myObjs += " " + objects[i];
    }
}

<p>There are @myObjs.Trim()!</p>

Inside

<p>There are
@{
    var objects = new List<string> { "cars", "dogs", "computers", "houses" };
    string myObjs = "";

    for (var i = 0; i < objects.Count; ++i)
    {
        if (objects.Count > 1 && i == objects.Count - 1)
        {
            myObjs += " and";
        }
        else if (i > 0)
        {
            myObjs += ",";
        }

        myObjs += " " + objects[i];
    }
}
@myObjs.Trim()!</p>


问:
Twilio Synch token in ColdFusion
ColdFusion being as obscure as it is, Twilio doesn't have any SDKs for it. I'm trying to give Synch a go; I'm not getting the JSON request for the access token correct. Trying to mimic what is done by their node.js example here, I thought I could just output the JSON to the page on token.cfm:

```<code>    {
        "identity":"#Username#",
        "token":["#AccountSID#","#APPSID#","#SECRET#"]
    }
</code>```

This is called from index.cfm:

```<code><script src="js/jquery.js"  ></script>
<script src="https://media.twiliocdn.com/sdk/js/sync/releases/0.5.7/twilio-sync.min.js"></script>

<script>
    function fetchAccessToken(handler) {
      // We use jQuery to make an Ajax request to our server to retrieve our
      // Access Token
      $.getJSON('token.cfm', function(data) {
          // The data sent back from the server should contain a long string, which
          // is the token you'll need to initialize the SDK. This string is in a format
          // called JWT (JSON Web Token) - more at http://jwt.io
          console.log(data.token);

          // Since the starter app doesn't implement authentication, the server sends
          // back a randomly generated username for the current client, which is how
          // they will be identified while sending messages. If your app has a login
          // system, you should use the e-mail address or username that uniquely identifies
          // a user instead.
          console.log(data.identity);

          handler(data);
      });
    }

    $(document).ready(function()
    {
        fetchAccessToken(initializeSync);

        function initializeSync(tokenResponse) {
          var syncClient = new Twilio.Sync.Client(tokenResponse.token);

          // Use syncClient here
        }
    });

</script>
</code>```

The response I receive is

```<code>{code: 400, message: "Unable to process JSON"}
code:
400
message:
"Unable to process JSON"
</code>```

Can I accomplish this? Or, alternately, can the token be built by JavaScript alone?

答:
Your JS is a very roundabout way of writing this:

```<code>$(function() {
    $.get('token.cfm').done(function (response) {
        var syncClient = new Twilio.Sync.Client(response.token);
        // ... use syncClient here
    });
});
</code>```

but this still requires that the response is actually parseable as JSON.

If your CFM page just contains this:

```<code><cfoutput>
{
    "identity":"#Username#",
    "token":["#AccountSID#","#APPSID#","#SECRET#"]
}
</cfoutput>
</code>```

then this almost certainly produces syntactically wrong JSON. Don't do that.

JSON is to be produced from a data structure and a serialization function, that's no different in ColdFusion than in any other language.

```<code><cfset AccountSID = "...">
<cfset APPSID  = "...">
<cfset SECRET = "...">

<cfset tokenData = {
    "identity" = Username,
    "token" = [AccountSID, APPSID, SECRET]
}>

<cfcontent type="application/json"><cfoutput>#SerializeJSON(tokenData)#</cfoutput>
</code>```

There are other, nicer ways of creating JSON responses, most prominently CF components with functions annotated with the "json" returnformat, but doing it manually like above is enough for a one-off.

Title: Twilio Synch token in ColdFusion

Body:
ColdFusion being as obscure as it is, Twilio doesn't have any SDKs for it. I'm trying to give Synch a go; I'm not getting the JSON request for the access token correct. Trying to mimic what is done by their node.js example here, I thought I could just output the JSON to the page on token.cfm:

    {
        "identity":"#Username#",
        "token":["#AccountSID#","#APPSID#","#SECRET#"]
    }

This is called from index.cfm:

The response I receive is

{code: 400, message: "Unable to process JSON"}
code:
400
message:
"Unable to process JSON"

Can I accomplish this? Or, alternately, can the token be built by JavaScript alone?

Body:
Your JS is a very roundabout way of writing this:

$(function() {
    $.get('token.cfm').done(function (response) {
        var syncClient = new Twilio.Sync.Client(response.token);
        // ... use syncClient here
    });
});

but this still requires that the response is actually parseable as JSON.

If your CFM page just contains this:

<cfoutput>
{
    "identity":"#Username#",
    "token":["#AccountSID#","#APPSID#","#SECRET#"]
}
</cfoutput>

then this almost certainly produces syntactically wrong JSON. Don't do that.

JSON is to be produced from a data structure and a serialization function, that's no different in ColdFusion than in any other language.

<cfset AccountSID = "...">
<cfset APPSID  = "...">
<cfset SECRET = "...">

<cfset tokenData = {
    "identity" = Username,
    "token" = [AccountSID, APPSID, SECRET]
}>

<cfcontent type="application/json"><cfoutput>#SerializeJSON(tokenData)#</cfoutput>

There are other, nicer ways of creating JSON responses, most prominently CF components with functions annotated with the "json" returnformat, but doing it manually like above is enough for a one-off.


问:
Is there a UI component kit for react-native like ionic framework?
I am playing around with a small app in react-native and I was wondering if there is a ready to use set of components that look like iOS's components. Somewhat like ionic-framework provides for Angular? Or am I missing something that is already in react-native that I can use?

To clarify I am referring to things like:

答: Another on looks promising to me if you want to keep consistency between web and native app Ant Design Mobile from Ant Design</p>


问:
MVC .NET Core web API XML or JSON
I would like to create a web application that returns data in the form of XML or JSON, how do I go about doing this?

The model:

```<code>namespace ReturningJSONandXML.Models
{
    public class SomeImportantInformation
    {
        public int ID { get; set; }
        public string Information { get; set; }
    }
}
</code>```

The controller:

```<code>namespace ReturningJSONandXML.Controllers
{
    public class GetInfoController : Controller
    {
        // GET: /<controller>/
        public List<SomeImportantInformation> Get()
        {
            List<SomeImportantInformation> ImportantInfo = new List<SomeImportantInformation>();
            ImportantInfo.Add(new SomeImportantInformation { ID = 0, Information = "Awesome info" });
            ImportantInfo.Add(new SomeImportantInformation { ID = 1, Information = "Some other interesting info" });
            return ImportantInfo;
        }
    }
}
</code>```

I would like to return an XML and JSON file...

What are the best practice's I should be using here?

答:
The framework takes care of this automatically for you so that you don't have to reinvent the wheel. The answer is quoted below.

But to make it simpler: Unless you specify an Accept header, the API will serialize the response as JSON. If you specify, for example, 'application/xml' it will return XML.

As MSDN Says:

Content negotiation (conneg for short) occurs when the client
specifies an Accept
header. The
default format used by ASP.NET Core MVC is JSON. Content negotiation
is implemented by ObjectResult. It's also built into the status code
specific action results returned from the helper methods (which are
all based on ObjectResult). You can also return a model type (a
class you've defined as your data transfer type) and the framework
will automatically wrap it in an ObjectResult for you.

...

Content negotiation only takes place if an Accept header appears
in the request. When a request contains an accept header, the
framework will enumerate the media types in the accept header in
preference order and will try to find a formatter that can produce a
response in one of the formats specified by the accept header. In case
no formatter is found that can satisfy the client's request, the
framework will try to find the first formatter that can produce a
response (unless the developer has configured the option on
MvcOptions to return 406 Not Acceptable instead). If the request
specifies XML, but the XML formatter has not been configured, then the
JSON formatter will be used. More generally, if no formatter is
configured that can provide the requested format, then the first
formatter that can format the object is used. If no header is given,
the first formatter that can handle the object to be returned will be
used to serialize the response. In this case, there isn't any
negotiation taking place - the server is determining what format it
will use.

From MSDN -- Current version and version at time of quote.

Title: MVC .NET Core web API XML or JSON

Body:
I would like to create a web application that returns data in the form of XML or JSON, how do I go about doing this?

The model:

namespace ReturningJSONandXML.Models
{
    public class SomeImportantInformation
    {
        public int ID { get; set; }
        public string Information { get; set; }
    }
}

The controller:

namespace ReturningJSONandXML.Controllers
{
    public class GetInfoController : Controller
    {
        // GET: /<controller>/
        public List<SomeImportantInformation> Get()
        {
            List<SomeImportantInformation> ImportantInfo = new List<SomeImportantInformation>();
            ImportantInfo.Add(new SomeImportantInformation { ID = 0, Information = "Awesome info" });
            ImportantInfo.Add(new SomeImportantInformation { ID = 1, Information = "Some other interesting info" });
            return ImportantInfo;
        }
    }
}

I would like to return an XML and JSON file...

What are the best practice's I should be using here?

ContentLicense: CC BY-SA 4.0


问:
StreamWriter: Starting and ending on a specific line number
I would like to ask some tips and help on a reading/writing part of my C#.

Situation:

I have to read a CSV file; - OK

If the CSV file name starts with "Load_", I want to write on another CSV the data from line 2 to the last one;

If the CSV file name starts with "RO_", I want to write on 2 different CSVs, 1 with the line 1 to 4 and the other 4 to the last one;

What I have so far is:

```<code>    public static void ProcessFile(string[] ProcessFile)
    {

        // Keeps track of your current position within a record
        int wCurrLine = 0;

        // Number of rows in the file that constitute a record
        const int LINES_PER_ROW = 1;
        int ctr = 0;
        foreach (string filename in ProcessFile)
        {

            var sbText = new System.Text.StringBuilder(100000);
            int stop_line = 0;
            int start_line = 0;

            // Used for the output name of the file
            var dir = Path.GetDirectoryName(filename);
            var fileName = Path.GetFileNameWithoutExtension(filename);
            var ext = Path.GetExtension(filename);
            var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\"));

            var lineCount = File.ReadAllLines(@filename).Length;

            string outputname = folderbefore + "output\\" + fileName;

            using (StreamReader Reader = new StreamReader(@filename))
            {

                if (filename.Contains("RO_"))
                {
                    start_line = 1;
                    stop_line = 5;
                }
                else
                {
                    start_line = 2;
                    stop_line = lineCount;
                }

                ctr = 0;
                while (!Reader.EndOfStream && ctr < stop_line)
                {
                    // Add the text
                    sbText.Append(Reader.ReadLine());

                    // Increment our current record row counter
                    wCurrLine++;

                    // If we have read all of the rows for this record
                    if (wCurrLine == LINES_PER_ROW)
                    {
                        // Add a line to our buffer
                        sbText.AppendLine();
                        // And reset our record row count
                        wCurrLine = 0;
                    }
                    ctr++;

                } // end of the while
            }

            int total_lenght = sbText.Length
            // When all of the data has been loaded, write it to the text box in one fell swoop
            using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
            {
                Writer.Write.(sbText.);
            }

        } // end of the foreach

    } // end of ProcessFile
</code>```

I was thinking about using the IF/ELSE: "using (StreamWriter Writer = new StreamWriter(dir + "\" + "output\" + fileName + "_out" + ext))" part. However, I am not sure how to pass, to StreamWriter, to only write from/to a specific line number.

Any Help is welcome! If I am missing some information, please, let me know (I am pretty new on stackoverflow).

Thank you.

答:
Code is way too complicated</p>

```<code>using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication57
{
    class Program
    {
        static void Main(string[] args)
        {

        }
        public static void ProcessFile(string[] ProcessFile)
        {
            foreach (string filename in ProcessFile)
            {

                // Used for the output name of the file
                var dir = Path.GetDirectoryName(filename);
                var fileName = Path.GetFileNameWithoutExtension(filename);
                var ext = Path.GetExtension(filename);
                var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\"));

                var lineCount = File.ReadAllLines(@filename).Length;

                string outputname = folderbefore + "output\\" + fileName;

                using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
                {

                    int rowCount = 0;
                    using (StreamReader Reader = new StreamReader(@filename))
                    {
                        rowCount++;
                        string inputLine = "";
                        while ((inputLine = Reader.ReadLine()) != null)
                        {

                            if (filename.Contains("RO_"))
                            {
                                if (rowCount <= 4)
                                {
                                    Writer.WriteLine(inputLine);
                                }
                                if (rowCount == 4) break;
                            }
                            else
                            {
                                if (rowCount >= 2)
                                {
                                    Writer.WriteLine(inputLine);
                                }
                            }

                        } // end of the while
                        Writer.Flush();
                    }
                }

            } // end of the foreach

        } // end of ProcessFile

    }

}
</code>```

Body:
I would like to ask some tips and help on a reading/writing part of my C#.

Situation:

I have to read a CSV file; - OK

If the CSV file name starts with "Load_", I want to write on another CSV the data from line 2 to the last one;

If the CSV file name starts with "RO_", I want to write on 2 different CSVs, 1 with the line 1 to 4 and the other 4 to the last one;

What I have so far is:

    public static void ProcessFile(string[] ProcessFile)
    {

        // Keeps track of your current position within a record
        int wCurrLine = 0;

        // Number of rows in the file that constitute a record
        const int LINES_PER_ROW = 1;
        int ctr = 0;
        foreach (string filename in ProcessFile)
        {

            var sbText = new System.Text.StringBuilder(100000);
            int stop_line = 0;
            int start_line = 0;

            // Used for the output name of the file
            var dir = Path.GetDirectoryName(filename);
            var fileName = Path.GetFileNameWithoutExtension(filename);
            var ext = Path.GetExtension(filename);
            var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\"));

            var lineCount = File.ReadAllLines(@filename).Length;

            string outputname = folderbefore + "output\\" + fileName;

            using (StreamReader Reader = new StreamReader(@filename))
            {

                if (filename.Contains("RO_"))
                {
                    start_line = 1;
                    stop_line = 5;
                }
                else
                {
                    start_line = 2;
                    stop_line = lineCount;
                }

                ctr = 0;
                while (!Reader.EndOfStream && ctr < stop_line)
                {
                    // Add the text
                    sbText.Append(Reader.ReadLine());

                    // Increment our current record row counter
                    wCurrLine++;

                    // If we have read all of the rows for this record
                    if (wCurrLine == LINES_PER_ROW)
                    {
                        // Add a line to our buffer
                        sbText.AppendLine();
                        // And reset our record row count
                        wCurrLine = 0;
                    }
                    ctr++;

                } // end of the while
            }

            int total_lenght = sbText.Length
            // When all of the data has been loaded, write it to the text box in one fell swoop
            using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
            {
                Writer.Write.(sbText.);
            }

        } // end of the foreach

    } // end of ProcessFile

I was thinking about using the IF/ELSE: "using (StreamWriter Writer = new StreamWriter(dir + "\" + "output\" + fileName + "_out" + ext))" part. However, I am not sure how to pass, to StreamWriter, to only write from/to a specific line number.

Any Help is welcome! If I am missing some information, please, let me know (I am pretty new on stackoverflow).

Thank you.

Body:
Code is way too complicated

using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ConsoleApplication57
{
    class Program
    {
        static void Main(string[] args)
        {

        }
        public static void ProcessFile(string[] ProcessFile)
        {
            foreach (string filename in ProcessFile)
            {

                // Used for the output name of the file
                var dir = Path.GetDirectoryName(filename);
                var fileName = Path.GetFileNameWithoutExtension(filename);
                var ext = Path.GetExtension(filename);
                var folderbefore = Path.GetFullPath(Path.Combine(dir, @"..\"));

                var lineCount = File.ReadAllLines(@filename).Length;

                string outputname = folderbefore + "output\\" + fileName;

                using (StreamWriter Writer = new StreamWriter(dir + "\\" + "output\\" + fileName + "_out" + ext))
                {

                    int rowCount = 0;
                    using (StreamReader Reader = new StreamReader(@filename))
                    {
                        rowCount++;
                        string inputLine = "";
                        while ((inputLine = Reader.ReadLine()) != null)
                        {

                            if (filename.Contains("RO_"))
                            {
                                if (rowCount <= 4)
                                {
                                    Writer.WriteLine(inputLine);
                                }
                                if (rowCount == 4) break;
                            }
                            else
                            {
                                if (rowCount >= 2)
                                {
                                    Writer.WriteLine(inputLine);
                                }
                            }

                        } // end of the while
                        Writer.Flush();
                    }
                }

            } // end of the foreach

        } // end of ProcessFile

    }

}


问:
Generating random numbers with Swift
I need to generate a random number.

It appears the arc4random function no longer exists as well as the arc4random_uniform function.

The options I have are arc4random_stir(),   arc4random_buf(UnsafeMutablePointer<Void>, Int), and   arc4random_addrandom(UnsafeMutablePointer<UInt8>, Int32).

I can't find any docs on the functions and no comments in the header files give hints.

答:
My implementation as an Int extension. Will generate random numbers in range from..<to

```<code>public extension Int {
    static func random(from: Int, to: Int) -> Int {
        guard to > from else {
            assertionFailure("Can not generate negative random numbers")
            return 0
        }
        return Int(arc4random_uniform(UInt32(to - from)) + UInt32(from))
    }
}
</code>```

Title: Generating random numbers with Swift

Body:
My implementation as an Int extension. Will generate random numbers in range from..<to

public extension Int {
    static func random(from: Int, to: Int) -> Int {
        guard to > from else {
            assertionFailure("Can not generate negative random numbers")
            return 0
        }
        return Int(arc4random_uniform(UInt32(to - from)) + UInt32(from))
    }
}


问:
How to Preload 'Realm' DB into iOS swift3?
I am trying to implement Realm database in my app , I have realm database with some Preloaded data into it . I have searched through many stack overflow resources but didn't get any success.

So far now , I have done following steps :

Copy the Realm File into my app's bundle

Added following code in the app delegate :

```<code>path = Bundle.main.path(forResource: "data", ofType: "realm")
var config = Realm.Configuration(fileURL: NSURL(fileURLWithPath:      path!))
config.readOnly = true

// Open the Realm with the configuration
let realm = try! Realm(configuration: config)
</code>```

But this doesn't work , Please provide some solution to it .

Note : I don't want to migrate my database.

Thanks in advance

答:
The piece of code below works perfectly for me to load a preloaded Realm instance during the first launch of my app:</p>

```<code>let defaultPath = Realm.Configuration.defaultConfiguration.fileURL?.path
let path = Bundle.main.path(forResource: "default", ofType: "realm")
if !FileManager.default.fileExists(atPath: defaultPath!), let bundledPath = path {
    do {
        try FileManager.default.copyItem(atPath: bundledPath, toPath: defaultPath!)
    } catch {
        print("Error copying pre-populated Realm \(error)")
    }
}
</code>```

Body:
I am trying to implement Realm database in my app , I have realm database with some Preloaded data into it . I have searched through many stack overflow resources but didn't get any success.

So far now , I have done following steps :

Copy the Realm File into my app's bundle

Added following code in the app delegate :

path = Bundle.main.path(forResource: "data", ofType: "realm")
var config = Realm.Configuration(fileURL: NSURL(fileURLWithPath:      path!))
config.readOnly = true

// Open the Realm with the configuration
let realm = try! Realm(configuration: config)

But this doesn't work , Please provide some solution to it .

Note : I don't want to migrate my database.

Thanks in advance

Body:
The piece of code below works perfectly for me to load a preloaded Realm instance during the first launch of my app:

let defaultPath = Realm.Configuration.defaultConfiguration.fileURL?.path
let path = Bundle.main.path(forResource: "default", ofType: "realm")
if !FileManager.default.fileExists(atPath: defaultPath!), let bundledPath = path {
    do {
        try FileManager.default.copyItem(atPath: bundledPath, toPath: defaultPath!)
    } catch {
        print("Error copying pre-populated Realm \(error)")
    }
}


问:
jQuery menu with sub menu trigger
I am trying to create a trigger for an HTML menu which when clicked will toggle sub menus. The problem with the following code is when you click the trigger (class="open") it toggles all the submenu items at once. I'd like the trigger to toggle one sub menu at a time using jQuery. Here is my code:

HTML

```<code><ul>
 <li class="menu-item-has-children">Item 1</li>
   <a class="open">+</a>
   <ul class="sub-menu">
     <li>Sub Item 1</li>
     <li>Sub Item 2</li>
     <li class="menu-item-has-children">Sub Item 3</li>
     <a class="open">+</a>
       <ul class="sub-menu">
         <li>Sub Sub Item 1</li>
         <li>Sub Sub Item 2</li>
         <li>Sub Sub Item 3</li>
         <li>Sub Sub Item 4</li>
         <li>Sub Sub Item 5</li>
      </ul>
   <li>Sub Item 4</li>
   <li>Sub Item 5</li>
</ul>
</code>```

JQUERY

```<code>$(document).ready(function() {
  $('.open').click(function () {
    $('li.menu-item-has-children').parent().closest('.sub-menu').toggle();
  });
});
</code>```

CSS

```<code>ul li {
  list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
 }
 .sub-menu {
  display:none;
 }
</code>```

VIEW THE JS FIDDLE HERE

Thank you :)

答:
other option is to create another class for your sub-menu.

$(document).ready(function() {
 $('.open').click(function () {
  $('li.menu-item-has-children').parent().closest('.sub-menu').toggle();
  });

  $('.open-sub1').click(function () {
  $('.sub-menu1').toggle();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul li {
 list-style-type:none;
}
.open, .open-sub1 {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
}
.sub-menu, .sub-menu1 {
  display:none;
}</code>```

Item 1

    +

Sub Item 1

Sub Item 2

Sub Item 3

        +

Sub Sub Item 1

Sub Sub Item 2

Sub Sub Item 3

Sub Sub Item 4

Sub Sub Item 5

Sub Item 4

Sub Item 5

```

Title: jQuery menu with sub menu trigger

Body:
I am trying to create a trigger for an HTML menu which when clicked will toggle sub menus. The problem with the following code is when you click the trigger (class="open") it toggles all the submenu items at once. I'd like the trigger to toggle one sub menu at a time using jQuery. Here is my code:

HTML

Item 1

   +

Sub Item 1

Sub Item 2

Sub Item 3

     +

Sub Sub Item 1

Sub Sub Item 2

Sub Sub Item 3

Sub Sub Item 4

Sub Sub Item 5

Sub Item 4

Sub Item 5

JQUERY

$(document).ready(function() {
  $('.open').click(function () {
    $('li.menu-item-has-children').parent().closest('.sub-menu').toggle();
  });
});

CSS

ul li {
  list-style-type:none;
}
.open {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
 }
 .sub-menu {
  display:none;
 }

VIEW THE JS FIDDLE HERE

Thank you :)

Body:
other option is to create another class for your sub-menu.

$(document).ready(function() {
 $('.open').click(function () {
  $('li.menu-item-has-children').parent().closest('.sub-menu').toggle();
  });

  $('.open-sub1').click(function () {
  $('.sub-menu1').toggle();
  });
});

ul li {
 list-style-type:none;
}
.open, .open-sub1 {
  width:20px;
  height:20px;
  background-color:red;
  color:#fff;
  display:block;
  cursor:pointer;
  text-align:center;
}
.sub-menu, .sub-menu1 {
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li class="menu-item-has-children">Item 1</li>
    <a class="open">+</a>
    <ul class="sub-menu">
      <li>Sub Item 1</li>
      <li>Sub Item 2</li>
      <li class="menu-item-has-children">Sub Item 3</li>
        <a class="open-sub1">+</a>
        <ul class="sub-menu1">
          <li>Sub Sub Item 1</li>
          <li>Sub Sub Item 2</li>
          <li>Sub Sub Item 3</li>
          <li>Sub Sub Item 4</li>
          <li>Sub Sub Item 5</li>
        </ul>
      <li>Sub Item 4</li>
      <li>Sub Item 5</li>
    </ul>
</ul>


问:
QMetaType::convert failed
I'm trying to use QMetaType::convert to convert a QJsonValue to another dynamic type. At first, I tested the following code with the dynamic type setting to QString, the conversion was failed.

```<code>QJsonValue value("test");
QString string;
if (!QMetaType::convert(&value, QMetaType::QJsonValue, &string, QMetaType::QString))
{
    qDebug() << "failed";
}
</code>```

Then, I found this static method to check whether the meta system has a registered conversion between two meta types.

```<code>qDebug() << QMetaType::hasRegisteredConverterFunction(QMetaType::QJsonValue, QMetaType::QString);
</code>```

unfortunately, the result was false. Maybe QJsonValue is so complex that the conversion from QJsonValue to QString is not supported. Finally, I tried this, and the result was still false:

```<code>qDebug() << QMetaType::hasRegisteredConverterFunction(QMetaType::Int, QMetaType::Int);
</code>```

It's odd, seems to be, Qt dose not implement the converter functions between basic meta types. And, users can't use QMetaType::registerConverter to register converter function between two basic meta types.

I still can't believe that Qt dosen't implement conversions between basic meta types, is there any initializtion or .pro setting I missed?

答:
I guess you have the QMetaType system and the QVariant class to encapsulate Qt data types on the one hand, and QJsonValue to encapsulate a value in JSON on the other hand.

QMetaType::convert can deal with QVariant data only. What you can do is to extract the QVariant from your QJsonValue and then use the QMetaType system to convert your data you know being a QString.

```<code>// Your code
QJsonValue value("test");
QString string ;
if (!QMetaType::convert(&value, QMetaType::QJsonValue, &string, QMetaType::QString))
{
    qDebug() << "failed";
}

// Extract the QVariant data
QVariant variant = value.toVariant() ;

// Two way to test conversion between QVariant and a type
qDebug() << "canConvert template:" << variant.canConvert<QString>() << endl
         << "canConvert parameter:" << variant.canConvert( QMetaType::QString ) ;
if( variant.canConvert<QString>() )
{
   // Convert using QVariant methods
   qDebug() << "QVariant toString:" << variant.toString() ;

   // Convert Using QJsonValue methods
   qDebug() << "QJsonValue toString:" << value.toString() ; // It's just a string representation of the data, not the actual data
}
</code>```

outputs :

```<code> failed
 canConvert template: true
 canConvert parameter: true
 QVariant toString: "test"
 QJsonValue toString: "test"
</code>```

PS: the QJsonValue::Type : String is different from the QVariant::Type : String (QMetaType::QString) so there is no relationship between them.

Title: QMetaType::convert failed

Body:
I'm trying to use QMetaType::convert to convert a QJsonValue to another dynamic type. At first, I tested the following code with the dynamic type setting to QString, the conversion was failed.

QJsonValue value("test");
QString string;
if (!QMetaType::convert(&value, QMetaType::QJsonValue, &string, QMetaType::QString))
{
    qDebug() << "failed";
}

Then, I found this static method to check whether the meta system has a registered conversion between two meta types.

qDebug() << QMetaType::hasRegisteredConverterFunction(QMetaType::QJsonValue, QMetaType::QString);

unfortunately, the result was false. Maybe QJsonValue is so complex that the conversion from QJsonValue to QString is not supported. Finally, I tried this, and the result was still false:

qDebug() << QMetaType::hasRegisteredConverterFunction(QMetaType::Int, QMetaType::Int);

It's odd, seems to be, Qt dose not implement the converter functions between basic meta types. And, users can't use QMetaType::registerConverter to register converter function between two basic meta types.

I still can't believe that Qt dosen't implement conversions between basic meta types, is there any initializtion or .pro setting I missed?

Body:
I guess you have the QMetaType system and the QVariant class to encapsulate Qt data types on the one hand, and QJsonValue to encapsulate a value in JSON on the other hand.

QMetaType::convert can deal with QVariant data only. What you can do is to extract the QVariant from your QJsonValue and then use the QMetaType system to convert your data you know being a QString.

// Your code
QJsonValue value("test");
QString string ;
if (!QMetaType::convert(&value, QMetaType::QJsonValue, &string, QMetaType::QString))
{
    qDebug() << "failed";
}

// Extract the QVariant data
QVariant variant = value.toVariant() ;

// Two way to test conversion between QVariant and a type
qDebug() << "canConvert template:" << variant.canConvert<QString>() << endl
         << "canConvert parameter:" << variant.canConvert( QMetaType::QString ) ;
if( variant.canConvert<QString>() )
{
   // Convert using QVariant methods
   qDebug() << "QVariant toString:" << variant.toString() ;

   // Convert Using QJsonValue methods
   qDebug() << "QJsonValue toString:" << value.toString() ; // It's just a string representation of the data, not the actual data
}

outputs :

 failed
 canConvert template: true
 canConvert parameter: true
 QVariant toString: "test"
 QJsonValue toString: "test"

PS: the QJsonValue::Type : String is different from the QVariant::Type : String (QMetaType::QString) so there is no relationship between them.


问:
Pass parameters from nunit3-console to TestFixture constructor, not to TestMethod
I have a problem with executing test from nunit3-console. I need to pass parameters to TestFixture constructor, but i want to call an specific Test.
In my fixture i have two different constructors and one method without arguments. Now i call this cdm:

nunit3-console --params username=u1;password=p1 --test namespace.class.Test1 Tests.dll

I think, now nunit try to pass this 2 parameters to my test, but i want to pass it into constructor, which have

[TestFixtureSource(typeof(TestFixtureSource), "GetParameters")]

When i call an cmd with --where "class='TestFixtureClassName'"clause parameters are passed into testfixture constructor, but it runs all tests inside this fixture.

In example

```<code>namespace TestNamespace
{
[TestFixtureSource("GetTestFixtureSource")]
public class TestFixture
{
private int _a;
private int _b;
TestFixture()
{
_a = 8;
_b = 10;
}
TestFixture(int a, int b)
{
_a = a;
_b = b;
}
[Test]
public void Test()
{
//test1 body
}
[Test]
public void Test2()
{
//test2 body
}
[Test]
public void Test3()
{
//test3 body
}
}
}
</code>```

Now in command prompt i call this line:

nunit3-console --params a=80;b=100 --test TestNamespace.TestFixture.Test Tests.dll

Result of this line is that selenium tries to find method Test with 2 arguments. But when u call nunit-console like this:

nunit3-console --params a=80;b=100 --where class='TestFixture' Tests.dll

It finds suitable constructor with 2 arguments and call it, but runs all Tests inside this Fixture.
Now, what i want to achieve is run single test, but pass --params to suitable constructor of TestFixture.

Hope now i presented it more clearly for you.

答:
Your description could use a bit more code to make clear what you are doing.

However, from what you say, it sounds as if the run parameters are being passed and used in the fixture constructor without problem. Am I misunderstanding something?

Which tests get run is an entirely separate matter. If you use a --where clause that specifies the class name, then you are telling the runner to run all the tests in that class. But your description says there is only one test method. Please make your problem clearer in your description by showing what you are doing in the test code, what you hope will happen and what actually happens.

As you see... I started to answer but realized I don't understand the problem, so you can consider this as a long comment. I'll answer after you update the question.

Body:
I have a problem with executing test from nunit3-console. I need to pass parameters to TestFixture constructor, but i want to call an specific Test.
In my fixture i have two different constructors and one method without arguments. Now i call this cdm:

nunit3-console --params username=u1;password=p1 --test namespace.class.Test1 Tests.dll

I think, now nunit try to pass this 2 parameters to my test, but i want to pass it into constructor, which have

[TestFixtureSource(typeof(TestFixtureSource), "GetParameters")]

When i call an cmd with --where "class='TestFixtureClassName'"clause parameters are passed into testfixture constructor, but it runs all tests inside this fixture.

In example

namespace TestNamespace
{
[TestFixtureSource("GetTestFixtureSource")]
public class TestFixture
{
private int _a;
private int _b;
TestFixture()
{
_a = 8;
_b = 10;
}
TestFixture(int a, int b)
{
_a = a;
_b = b;
}
[Test]
public void Test()
{
//test1 body
}
[Test]
public void Test2()
{
//test2 body
}
[Test]
public void Test3()
{
//test3 body
}
}
}

Now in command prompt i call this line:

nunit3-console --params a=80;b=100 --test TestNamespace.TestFixture.Test Tests.dll

Result of this line is that selenium tries to find method Test with 2 arguments. But when u call nunit-console like this:

nunit3-console --params a=80;b=100 --where class='TestFixture' Tests.dll

It finds suitable constructor with 2 arguments and call it, but runs all Tests inside this Fixture.
Now, what i want to achieve is run single test, but pass --params to suitable constructor of TestFixture.

Hope now i presented it more clearly for you.