How to use MetaTrader4.Manager.Wrapper to listening the event of TradeAdded/TradeClosed/TradeDeleted - metatrader4

I wand to listening the event of TradeAdded/TradeClosed/TradeDeleted ,that's my code:
public partial class Demo : Form
{
public static ConnectionParameters conParam = new ConnectionParameters();
public static ClrWrapper mt;
private void Hedera_Load(object sender, EventArgs e)
{
Login();
}
public void Login()
{
conParam = new ConnectionParameters
{
Login = serverConfig.ManageAccount,
Password = serverConfig.ManagePassword,
Server = serverConfig.ManageServer
};
mt = new ClrWrapper(conParam);
List<UserRecord> users = mt.UsersRequest().ToList();
mt.TradeClosed +=new TradeRecordUpdated(this.MyTradeClosed);
mt.TradeDeleted += new TradeRecordUpdated(this.MyTradeDeleted);
mt.TradeAdded += new TradeRecordUpdated(this.MyTradeAdded);
}
public void MyTradeAdded(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeAdded");
}
public void MyTradeClosed(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeClosed");
}
public void MyTradeDeleted(ClrWrapper mt, TradeRecord tradeRecord)
{
MessageBox.Show("MyTradeDeleted");
}
}
When i trade on the MetaTrader4 client ,I want to get the notify in my C# program.
“UsersRequest” is ok now,but the event does not run.
Where is wrong in my code ?
Can you write an example for me?

Those events are fired only in extended pumping mode. so you have to switch:
public void Login()
{
conParam = new ConnectionParameters
{
Login = serverConfig.ManageAccount,
Password = serverConfig.ManagePassword,
Server = serverConfig.ManageServer
};
mt = new ClrWrapper(conParam);
List<UserRecord> users = mt.UsersRequest().ToList();
mt.TradeClosed +=new TradeRecordUpdated(this.MyTradeClosed);
mt.TradeDeleted += new TradeRecordUpdated(this.MyTradeDeleted);
mt.TradeAdded += new TradeRecordUpdated(this.MyTradeAdded);
metatrader.PumpingSwitchEx();
}
However, after switching into pumping mode, you won't be able to use non pumping methods

Related

netty different channelpool and exception process

I am new to netty and I have a problem using my netty program.
in initConnection method I want to make a different channelpool for each group.
when user group A come in my sendToMessage I want to create channelPool A
like this way user group B come in my sendToMessage I want to create channelPool B and next time if user group A come in again, i will return channelPool A
Is it right to try doing this? Is it possible?
FixedChannelPool error handling
tell me how can I FixedChannelPool error handling? Could I use acquireTimeoutMillis over time.how?
Here is my code
#Service
public class NettyPoolService {
public static final AttributeKey<CompletableFuture<String>> FUTURE = AttributeKey.valueOf("future");
private static final StringDecoder stringDecoder = new StringDecoder(CharsetUtil.UTF_8);
private static final StringEncoder stringEncoder = new StringEncoder(CharsetUtil.UTF_8);
private static ChannelPool channelPool;
private static EventLoopGroup eventLoopGroup;
#Value("${host}")
private String host;
#Value("${port}")
private String port;
#Value("${connection.count}")
private String numberOfConnections;
#Value("${thread.count}")
private String numberOfThreads;
private synchronized void initConnection (String host, int port, int numberOfThreads, int numberOfConnections,String userGroup) {
if ( (channelPool != null) && (eventLoopGroup != null) ) {
return;
}
System.out.println("#############################################");
System.out.println("initConnection start");
eventLoopGroup = new NioEventLoopGroup(numberOfThreads);
Bootstrap bootstrap = new Bootstrap();
bootstrap.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
//bootstrap.option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, 32 * 1024);
//bootstrap.option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, 8 * 1024);
//bootstrap.option(ChannelOption.TCP_NODELAY, true);
bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).remoteAddress(host, port);
int acquireTimeoutMillis = 10000;
int maxPendingAcquires = Integer.MAX_VALUE;
channelPool = new FixedChannelPool(bootstrap,
new AbstractChannelPoolHandler() {
public void channelCreated(Channel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// decoders
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("stringDecoder", stringDecoder);
// encoders
pipeline.addLast("stringEncoder", stringEncoder);
// business logic handler
pipeline.addLast("clientHandler", new ClientPoolHandler(channelPool));
}
},
ChannelHealthChecker.ACTIVE,//eventloop
AcquireTimeoutAction.NEW, //timeout
acquireTimeoutMillis, //
numberOfConnections, //
maxPendingAcquires); //
System.out.println("initConnection End");
System.out.println("#############################################");
}//initConnection
public void sendToMessage(String message,String GroupId) {
System.out.println("=============GroupId=============:"+GroupId);
if (channelPool == null) {
initConnection(host, Integer.parseInt(port.trim()), Integer.parseInt(numberOfThreads.trim()), Integer.parseInt(numberOfConnections.trim()) );
}
final CompletableFuture<String> future = new CompletableFuture<String>();
Future<Channel> channelFuture = channelPool.acquire();
System.out.println("=============channelFuture.get()=============:"+channelFuture.toString());
channelFuture.addListener(new FutureListener<Channel>() {
public void operationComplete(Future<Channel> f) {
if (f.isSuccess()) {
Channel channel = f.getNow();
channel.attr(NettyPoolClientService.FUTURE).set(future);
channel.writeAndFlush(message, channel.voidPromise());
}
}
});
channelFuture.syncUninterruptibly();
}//sendToBnp
}

Accessing activity 2 while foreground is activity 1 (either using OOP or Service in XAMARIN)

i code this from a tutorial for locating your location (but I already made some changes)
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Locations;
using System.Collections.Generic;
using Android.Util;
using System.Linq;
using Java.Lang;
using System.Threading.Tasks;
using System;
using Android.Views;
using Android.Content;
namespace LocatorApp
{
[Activity(Label = "Locator", MainLauncher = true, Icon = "#drawable/locator_ico")]
public class LocatorApp : Activity, ILocationListener
{
static readonly string TAG = "X:" + typeof(LocatorApp).Name;
TextView _addressText;
Location _currentLocation;
LocationManager _locationManager;
Address address;
string _locationProvider;
TextView _locationText;
private double latitude = 0;
private double longitude = 0;
public Location getCurrentLocation() { return _currentLocation; }
public double getLatitude() { return latitude; }
public double getLongitude() { return longitude; }
public Address getAddress() { return address; }
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
_addressText = FindViewById<TextView>(Resource.Id.address_text);
_locationText = FindViewById<TextView>(Resource.Id.location_text);
FindViewById<TextView>(Resource.Id.get_address_button).Click += AddressButton_OnClick;
InitializeLocationManager();
}
public void InitializeLocationManager()
{
_locationManager = (LocationManager)GetSystemService(LocationService);
Criteria criteriaForLocationService = new Criteria
{
Accuracy = Accuracy.Coarse,
PowerRequirement = Power.Medium
};
IList<string> acceptableLocationProviders = _locationManager.GetProviders(criteriaForLocationService, true);
if (acceptableLocationProviders.Any())
{
_locationProvider = acceptableLocationProviders.First();
}
else
{
_locationProvider = string.Empty;
}
Log.Debug(TAG, "Using " + _locationProvider + ".");
}
async void AddressButton_OnClick(object sender, EventArgs eventArgs)
{
if (_currentLocation == null)
{
Toast.MakeText(this, "Still waiting for location.", ToastLength.Short).Show();
}
else
{
try
{
var geoUri = Android.Net.Uri.Parse("geo:" + _currentLocation.Latitude + "," + _currentLocation.Longitude);
var mapIntent = new Intent(Intent.ActionView, geoUri);
StartActivity(mapIntent);
}
catch (System.Exception e)
{
Toast.MakeText(this, "Sorry, there is a problem with geomapping.", ToastLength.Short).Show();
}
}
}
async Task<Address> ReverseGeocodeCurrentLocation()
{
try
{
Geocoder geocoder = new Geocoder(this);
IList<Address> addressList =
await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
Address address = addressList.FirstOrDefault();
return address;
}
catch (System.Exception e)
{
throw;
}
return null;
}
void DisplayAddress(Address address)
{
if (address != null)
{
StringBuilder deviceAddress = new StringBuilder();
for (int i = 0; i < address.MaxAddressLineIndex; i++)
{
deviceAddress.Append(address.GetAddressLine(i));
}
// Remove the last comma from the end of the address.
_addressText.Text = "Address: "+deviceAddress.ToString();
}
else
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
}
}
public async void OnLocationChanged(Location location)
{
Toast.MakeText(this, "Location changed.", ToastLength.Short).Show();
_currentLocation = location;
if (_currentLocation == null)
{
_locationText.Text = "Unable to determine your location. Try again in a short while.";
}
else
{
try
{
_locationText.Text = "Location: " + string.Format("{0:f6},{1:f6}", _currentLocation.Latitude, _currentLocation.Longitude);
Address address = await ReverseGeocodeCurrentLocation();
DisplayAddress(address);
var nMgr = (NotificationManager)GetSystemService(NotificationService);
var notification = new Notification(Resource.Drawable.Icon, "Message from LocatorApp");
var pendingIntent = PendingIntent.GetActivity(this, 0, new Intent(this, typeof(LocatorApp)), 0);
notification.SetLatestEventInfo(this, "LocatorApp", "Location changed!", pendingIntent);
nMgr.Notify(0, notification);
}
catch (Java.Lang.Exception e)
{
_addressText.Text = "Unable to determine the address. Try again in a few minutes.";
Toast.MakeText(this, "Error Occured On Geocoder!", ToastLength.Short).Show();
Log.Error(TAG, e.Message);
}
}
}
public void OnProviderDisabled(string provider) { }
public void OnProviderEnabled(string provider) { }
public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
protected override void OnResume()
{
base.OnResume();
if (_locationManager.IsProviderEnabled(_locationProvider))
{
_locationManager.RequestLocationUpdates(_locationProvider, 100, 0, this);
Toast.MakeText(this, _locationProvider.ToString(), ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "There is a problem with "+_locationProvider.ToString()+" provider.", ToastLength.Short).Show();
}
}
protected override void OnPause()
{
base.OnPause();
_locationManager.RemoveUpdates(this);
}
}
}
(i'm just having my experiment)
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method. I instantiated it and can get the variables values but they are null (seems there is no process happened) . What can be a best solution for this.
note: I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
using System;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Util;
using System.Threading;
namespace LocatorApp
{
[Service]
class SimpleService : Service
{
static readonly string TAG = "X:" + typeof(SimpleService).Name;
static readonly int TimerWait = 4000;
Timer _timer;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug(TAG, "OnStartCommand called at {2}, flags={0}, startid={1}", flags, startId, DateTime.UtcNow);
_timer = new Timer(o => { Log.Debug(TAG, "Hello from SimpleService. {0}", DateTime.UtcNow); },
null,
0,
TimerWait);
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
base.OnDestroy();
_timer.Dispose();
_timer = null;
Log.Debug(TAG, "SimpleService destroyed at {0}.", DateTime.UtcNow);
}
public override IBinder OnBind(Intent intent)
{
// This example isn't of a bound service, so we just return NULL.
return null;
}
}
}
I want to know both (OOP way and service way) since not at all time we are required to use the service.
what I want is to run activity B while foreground is in activity A, just like a basic OOP . but my problem is, I don't know how to make it run. I can't also jump to activity B since it has an oncreate method.
You can call Context.StartActivity inside your Activity with following codes:
StartActivity(new Android.Content.Intent(this, typeof(ActivityB)));
And StartActivity will call OnCreate method in ActivityB to create a new instance of ActivityB.
For details about Starting Activities, please refer to Starting Activities and Getting Results.
I am currently looking how to use service for background processing but also i don't know how to run this code after I typed it from a tutorial :( there is only a tutorial for creating a service part but no tutorial for buttons to access it :(
Similar like Activity Context.StartService offers a way to start a Service:
StartService (new Intent (this, typeof(DemoService)));
This will call the OnStartCommand method inside your Service class.
For details about usage of Service, please refer to Implementing a Service.

Sharing video and photo in metro apps through share charm

i am trying to take a picture and video from within the app and trying to share it through share charm but i am having a problem doing that. After i take the pic ,the share charm says it has trouble sharing the image. This is my code .Can anybody please let me know what i am doing wrong.
namespace Temp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Page1 : Page
{
private StorageFile _photo; // Photo file to share
private StorageFile _video; // Video file to share
private async void OnCapturePhoto(object sender, TappedRoutedEventArgs e)
{
var camera = new CameraCaptureUI();
var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
_photo = file;
DataTransferManager.ShowShareUI();
}
}
private async void OnCaptureVideo(object sender, TappedRoutedEventArgs e)
{
var camera = new CameraCaptureUI();
camera.VideoSettings.Format = CameraCaptureUIVideoFormat.Wmv;
var file = await camera.CaptureFileAsync(CameraCaptureUIMode.Video);
if (file != null)
{
_video = file;
DataTransferManager.ShowShareUI();
}
}
void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
var request = args.Request;
if (_photo != null)
{
request.Data.Properties.Description = "Component photo";
var reference = Windows.Storage.Streams.RandomAccessStreamReference.CreateFromFile(_photo);
request.Data.Properties.Thumbnail = reference;
request.Data.SetBitmap(reference);
_photo = null;
}
else if (_video != null)
{
request.Data.Properties.Description = "Component video";
List<StorageFile> items = new List<StorageFile>();
items.Add(_video);
request.Data.SetStorageItems(items);
_video = null;
}
}
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
DataTransferManager.GetForCurrentView().DataRequested += OnDataRequested;
}
}
In order for your app to share, you must set the Title of the DataPackagePropertySet and at least one of the "SetXXX" methods. If you do not, you'll see the following message when trying to share "There was a problem with the data from ."
So add request.Data.Properties.Title = "Title_of_photo_or_video"; in OnDataRequested event.

J2ME connect localhost nullpointerexception 0

I am trying to connect localhost and insert data into database through j2me application.but when I am connecting the server it shows there is a nullpointerexception 0 error.
this is midlet code
import java.io.DataOutputStream;
import java.io.InputStream;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.*;
public class Midlet_1 extends MIDlet implements CommandListener {
Display mdDisplay;
Form mForm;
StringItem messageitem;
Command exit, connectCommand;
public Midlet_1() {
mForm = new Form("My Counter midlet");
messageitem = new StringItem(null, "");
exit = new Command("Exit", Command.EXIT, 0);
connectCommand = new Command("Connect", Command.SCREEN, 0);
mForm.append(messageitem);
mForm.addCommand(exit);
mForm.addCommand(connectCommand);
mForm.setCommandListener(this);
}
public void startApp() {
mdDisplay = Display.getDisplay(this);
mdDisplay.setCurrent(mForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
if (c == exit) {
notifyDestroyed();
} else if (c == connectCommand) {
Form waitform = new Form("Waiting");
mdDisplay.setCurrent(waitform);
Thread t = new Thread() {
public void run() {
connect();
}
};
t.start();
}
}
private void connect() {
try {
HttpConnection hs = null;
InputStream in = null;
String url = "localhost:8080/testweb/src/save";
hs.setRequestProperty("User-Agent", "Profile/MIDP-2.0,Configuration/CLDC-2.0");
hs.setRequestProperty("Content-Language", "en-US");
hs.setRequestMethod(HttpConnection.POST);
DataOutputStream ds = hs.openDataOutputStream();
ds.writeUTF("nam56");
ds.writeUTF("67");
ds.writeUTF("0716522549");
ds.flush();
ds.close();
in = hs.openInputStream();
int connectlength = (int) hs.getLength();
byte[] raw = new byte[connectlength];
int length = in.read(raw);
// int ch;
// StringBuffer sb=new StringBuffer();
// while((ch=in.read())!=-1){
// sb.append((char)ch);
// }
in.close();
hs.close();
String s = new String(raw, 0, length);
messageitem.setText(s);
} catch (Exception e) {
messageitem.setText(e.toString());
System.out.println(e);
}
mdDisplay.setCurrent(mForm);
}
}
and this is servlet code
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
DataInputStream in=new DataInputStream(request.getInputStream());
String name=in.readUTF();
String id=in.readUTF();
String contt=in.readUTF();
Connection c=DBcon.setconConnection();
Statement s=c.createStatement();
s.executeUpdate("insert into details values('"+id+"','"+name+"''"+contt+"')");
out.print("successfullllll");
} finally {
out.close();
}
}
please check this out.....
This might work only if you are running an emulator on the same machine as the server. Try to replace locahost by 127.0.0.1.
In your connect() method, I can see that you initialized hs as null then you called setRequestProperty. Try to initialize hs properly before calling its methods.

Implementation of simple Java IDE using Runtime Process and JTextArea

I am developing a simple Java IDE like Netbeans/Eclipse. My GUI includes two JTextArea component, one used as a TextEditor where the end user can type in his programs and the other used as an output window.
I am running the users programs by invoking the windows command prompt through Java Runtime and Process classes. I am also catching the IO streams of the process using the methods getInputStream(), getErrorStream(), getOutputStream().
If the program contains only the statements to print something onto the screen, I am able to display the output on the output window(JTextArea). But if it includes statements to read input from the user, then it must be possible for the user to type the expected input value via the output window and it must be sent to the process just as in Netbeans/Eclipse.
I also checked the following link
java: work with stdin/stdout of process in same time
Using this code, I am able to display only the statements waiting for input and not simple output statements. Also, only a single line is displayed on the output window at a time.
It would be great if anybody can help me to resolve this issue.
Thanks
Haleema
I've found the solution with little modification to the earlier post java: work with stdin/stdout of process in same time
class RunFile implements Runnable{
public Thread program = null;
public Process process = null;
private JTextArea console;
private String fn;
public RunFile(JTextArea cons,String filename){
console = cons;
fn=filename;
program = new Thread(this);
program.start();
}
#Override
public void run() {
try {
String commandj[] = new String[4];
commandj[0] = "cmd";
commandj[1]="/C";
commandj[2]="java";
commandj[3] = fn;
String envp[] = new String[1];
envp[0]="path=C:/Program Files (x86)/Java/jdk1.6.0/bin";
File dir = new File("Path to File");
Runtime rt = Runtime.getRuntime();
process = rt.exec(commandj,envp,dir);
ReadStdout read = new ReadStdout(process,console);
WriteStdin write = new WriteStdin(process, console);
int x=process.waitFor();
console.append("\nExit value: " + process.exitValue() + "\n");
}
catch (InterruptedException e) {}
catch (IOException e1) {}
}
}
class WriteStdin implements Runnable{
private Process process = null;
private JTextArea console = null;
public Thread write = null;
private String input = null;
private BufferedWriter writer = null;
public WriteStdin(Process p, JTextArea t){
process = p;
console = t;
writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
write = new Thread(this);
write.start();
console.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyTyped(java.awt.event.KeyEvent e){
//save the last lines for console to variable input
if(e.getKeyChar() == '\n'){
try {
int line = console.getLineCount() -2;
int start = console.getLineStartOffset(line);
int end = console.getLineEndOffset(line);
input = console.getText(start, end - start);
write.resume();
} catch (BadLocationException e1) {}
}
}
});
console.addCaretListener(new javax.swing.event.CaretListener() {
#Override
public void caretUpdate(CaretEvent e) {
console.setCaretPosition(console.getDocument().getLength());
throw new UnsupportedOperationException("Not supported yet.");
}
});
console.addFocusListener(new java.awt.event.FocusAdapter() {
#Override
public void focusGained(java.awt.event.FocusEvent e)
{
console.setCaretPosition(console.getDocument().getLength());
}
});
}
#Override
public void run(){
write.suspend();
while(true){
try {
//send variable input in stdin of process
writer.write(input);
writer.flush();
} catch (IOException e) {}
write.suspend();
}
}
}
class ReadStdout implements Runnable{
public Thread read = null;
private BufferedReader reader = null;
private Process process = null;
private JTextArea console = null;
public ReadStdout(Process p,JTextArea t){
process = p;
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
console = t;
read = new Thread(this);
read.start();
}
public void run() {
String line;
try {
while((line = reader.readLine())!=null)
console.append(line+"\n");
}catch (IOException e) {}
}
}