Topshelf TimeoutException - exception

I'm trying to use Topshelf Framework to create a windows service. But when i try to start the service, there is this exception :
" The service failed to start... System.Service.Process.TimeoutException : the waiting period has expired and the operation has not been completed"
This is my code :
public class MyService : ServiceControl
{
private System.Timers.Timer _timer;
public void MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = false;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
Thanks for any help :)

There are several issues I notice:
The current code would make the timer fire only once (you have AutoReset = false)
with TopShelf, the MyService class should look like this:
using System.Timers;
using Topshelf;
namespace TopShelfTestService
{
public class MyService
{
private System.Timers.Timer _timer;
public MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = true;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
}
and the console app/ Program.cs will look like so:
using Topshelf;
namespace TopShelfTestService
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<MyService>(s =>
{
s.ConstructUsing(name => new MyService());
s.WhenStarted((tc, hostControl) => tc.Start(hostControl));
s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host"); //7
x.SetDisplayName("Test Service with TopShelf"); //8
x.SetServiceName("TopShelfTestService");
});
}
}
}

Related

Map fragment doesn't move to current location when Recreated

Greetings to the community. This is my first question, please guide me if I did any mistake.
I have four fragments in my app. An activity(Main Activity) that hosts all the four fragments.
Google Maps Fragment
Fragment two
Fragment three
Fragment four
When the application starts. Maps fragment is loaded and it shows marker at my current location. But when I move from Maps fragment to Fragment two and then came back to Map Fragment it doesn't show my current location
Here is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Fragments
private MapsFragment mapsFragment = new MapsFragment();
private QrScanFragment qrScanFragment = new QrScanFragment();
private SeatsFullFragment seatsFullFragment = new SeatsFullFragment();
private EmergencyFragment emergencyFragment = new EmergencyFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLayouts();
initListeners();
// Maps Fragment Loaded
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
loadFragment(mapsFragment);
}
}
loadFragment(Fragment fragment)
public void loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_container, fragment)
.commit();
}
}
Moving b/w fragments
if (view == mLlMaps) {
if (!mapsFragment.isVisible()) {
loadFragment(mapsFragment);
mTvTitle.setText("Map");
}
mIvMaps.setImageResource(R.drawable.ic_map_pin_2_line_fill);
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
} else if (view == mLlQrScan) {
if (!qrScanFragment.isVisible()) {
loadFragment(qrScanFragment);
mTvTitle.setText("ScanQR");
}
mIvQrScan.setImageResource(R.drawable.ic_baseline_qr_code_scanner_24_fill);
mIvQrScan.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
}
}
MapsFragment.java
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private SupportMapFragment mapFragment;
// To get Current Location of Driver
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
public MapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_maps, container, false);
buildLocationRequest(); // Request for current Location
buildLocationCallback(); // When location is provided
updateLocation(); // Fused Location Provider
// Child Fragment Manager copied from Uber
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
// Request for current Location
private void buildLocationRequest() {
if (locationRequest == null) {
locationRequest = new LocationRequest();
locationRequest.setSmallestDisplacement(50f); // 50m
locationRequest.setInterval(15000); // 15s
locationRequest.setFastestInterval(10000); // 10s
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
// When location result is provided
private void buildLocationCallback() {
if (locationCallback == null) {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),
locationResult.getLastLocation().getLongitude());
// 18f is the radius of circle
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 18f));
}
};
}
}
// Fused Location Provider
private void updateLocation() {
if (fusedLocationProviderClient == null) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "Permission Required", Toast.LENGTH_SHORT).show();
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("EB", "onMapReady: called");
// Check Permission
Dexter.withContext(getContext())
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Toast.makeText(getContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
}
fusedLocationProviderClient.getLastLocation().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
LatLng userLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
// 18f is the radius of circle
mMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(userLatLng, 18f));
}
});
return true;
}
});
// Set Layout - Location Button
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1"))
.getParent())
.findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
//Right Bottom
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 0, 50);
// Move to current Location
buildLocationRequest();
buildLocationCallback();
updateLocation();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(getContext(),
"Permission" + permissionDeniedResponse.getPermissionName() + "wasdenied",
Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
// Change/Parse the Maps Style
try {
boolean success = googleMap.setMapStyle(MapStyleOptions
.loadRawResourceStyle(getContext(), R.raw.uber_maps_style));
if (!success)
Log.e("Error", "Style parsing Error");
} catch (Resources.NotFoundException e) {
Log.e("Error", e.getMessage());
}
}
}

Libgdx make getStatuscode called once only in update()

I'm developing an app but when I try to getstatuscode of httprequest
in order to know Which of the gameend overlay to call the status code is called multiple times so how do I call it just once
public void update(float dt) {
for (NewPhysicsActor baseEnemyOthers: balloonList) {
if (baseEnemyOthers.getY() < 250) {
removeList.add(baseEnemyOthers);
gameFailed();
}
}
}
public void gameFailed() {
HttpRequest request = new HttpRequest(HttpMethods.GET);
request.setUrl("https://www.google.com");
Gdx.net.sendHttpRequest(request, new HttpResponseListener() {
#Override
public void handleHttpResponse(HttpResponse httpResponse) {
HttpStatus status = httpResponse.getStatus();
if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) {
togglePaused();
watchVideoOverlay.setVisible(isPaused());
} else {
togglePaused();
levelFailedOverlay.setVisible(isPaused());
}
}
#Override
public void failed(Throwable t) {
togglePaused();
levelFailedOverlay.setVisible(isPaused());
}
#Override
public void cancelled() {
togglePaused();
levelFailedOverlay.setVisible(isPaused());
}
});
}
if I off my data connection everything works perfectly
but when it's on the problem continues. Watchoverlay() is called on and off continuously without stop

Flex, pushing message, ServiceAdapter, BlazeDS

I have Flex 3.6A + BlazeDS + java6 webapp.
I want to push message from server that must be intercepted by the client (.mxml page). Googlin around I manage to build the follow example:
public class TestMessaging extends ServiceAdapter {
private String previousMsg = "";
private volatile boolean running;
private Message createTestMessage() {
AsyncMessage msg = new AsyncMessage();
msg.setDestination("RandomDataPush");
msg.setClientId(UUIDUtils.createUUID());
msg.setMessageId(UUIDUtils.createUUID());
msg.setBody(BarValues.STATUS);
return msg;
}
#Override
public void start(){
super.start();
Thread messageSender = new Thread(){
public void run(){
running = true;
while(running){
sendMessageToClients(createTestMessage());
secondsToSleep(3);
}
}
};
messageSender.start();
}
/**
* #see flex.messaging.services.ServiceAdapter#stop()
*/
#Override
public void stop(){
super.stop();
running = false;
}
public void sendMessageToClients(Message msg) {
if (!msg.getBody().equals(previousMsg)) {
previousMsg = msg.getBody().toString();
((MessageService) getDestination().getService()).pushMessageToClients(msg, false);
}
}
#Override
public Object invoke(Message message) {
if (message.getBody().equals("stop")) {
running = false;
} else if (message.getBody().equals("start")) {
start();
}
return null;
}
private void secondsToSleep(int seconds) {
try{
Thread.sleep(seconds * 1000);
}catch(InterruptedException e){
System.out.println("TestServiceAdapter Interrupted while sending messages");
e.printStackTrace();
}
}
}
In the .mxml I have:
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="100%" height="100%" creationComplete="init()">
<mx:Script>
<![CDATA[
private function messageHandler(message:IMessage):void {
randomNumbers = message.body as String;
if (randomNumbers == null) {
var msg:AsyncMessage = new AsyncMessage();
msg.body = "stop";
producer.send(msg);
} else Alert.show(randomNumbers.toString());
}
private function init():void {
var msg:AsyncMessage = new AsyncMessage();
msg.body = "stop";
producer.send(msg);
consumer.subscribe();
}
private function start():void {
var msg:AsyncMessage = new AsyncMessage();
msg.body = "start";
producer.send(msg);
consumer.subscribe();
}
private function handleFault(event:MessageFaultEvent):void {
Alert.show(event.faultString);
}
private function ack(event:MessageAckEvent):void {
if (event.message.body != null) {
randomNumbers = event.message.body as String;
Alert.show(randomNumbers.toString());
}
}
<mx:Producer id="producer" destination="RandomDataPush" acknowledge="ack(event)"/>
<mx:Consumer id="consumer" destination="RandomDataPush" message="messageHandler(event.message)" />
</mx:Application>
Problems are:
1) Whitout a thread I can't manage to push messages
2) The thread starts automatically when I alunch the application. To prevent this I send the "stop" when the init() method of the flex page is called (but is really orrible)
What I want to do is: when a java query is executed (or a complex elaboration starts) I want to start the service and send messages calling manually the sendMessageToClients method (without thread if is it possible) and, when the query or the elaboration ends, stop the service.
Can you help me?
Thanks all

LocalSettings and background tasks WP 8.1

How to change values in Windows.Storage.ApplicationData.Current.LocalSettings with background task. I use such code like back ground task:
namespace MainTask
{
public sealed class Task :IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
var storage = Windows.Storage.ApplicationData.Current.LocalSettings;
int i = (int)storage.Values["var"];
i++;
storage.Values["val"] = i;
_deferral.Complete();
}
}
}
Background task started and there is in livecycle events in debugger and it reads the storage. But Values["val"] does not change.
namespace MainTask
{
public sealed class Task :IBackgroundTask
{
public void Run(IBackgroundTaskInstance taskInstance)
{
BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();
var storage = Windows.Storage.ApplicationData.Current.LocalSettings;
int i = (int)storage.Values["var"];
i++;
storage.Values.Remove("val");
storage.Values.Add("val", i);
_deferral.Complete();
}
}
}

Binding views to ICommand.CanExecute

Is it somehow possible to bind view properties to ICommand.CanExecute?
I'd for example like to be able to do something like this in a touch view:
this
.CreateBinding(SignInWithFacebookButton)
.For(b => b.Enabled)
.To((SignInViewModel vm) => vm.SignInWithFacebookCommand.CanExecute)
.Apply();
I've already read How to use CanExecute with Mvvmcross, but unfortunately it skips the questions and instead just proposes another implementation.
One way of doing this is to use your own custom button inheriting from UIButton.
For Android, I've got an implementation of this to hand - it is:
public class FullButton : Button
{
protected FullButton(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
Click += OnClick;
}
public FullButton(Context context) : base(context)
{
Click += OnClick;
}
public FullButton(Context context, IAttributeSet attrs) : base(context, attrs)
{
Click += OnClick;
}
public FullButton(Context context, IAttributeSet attrs, int defStyle) : base(context, attrs, defStyle)
{
Click += OnClick;
}
private IDisposable _subscription;
private object _commandParameter;
public object CommandParameter
{
get { return _commandParameter; }
set
{
_commandParameter = value;
UpdateEnabled();
}
}
private ICommand _command;
public ICommand Command
{
get { return _command; }
set
{
if (_subscription != null)
{
_subscription.Dispose();
_subscription = null;
}
_command = value;
if (_command != null)
{
var cec = typeof (ICommand).GetEvent("CanExecuteChanged");
_subscription = cec.WeakSubscribe(_command, (s, e) =>
{
UpdateEnabled();
});
}
UpdateEnabled();
}
}
private void OnClick(object sender, EventArgs eventArgs)
{
if (Command == null)
return;
if (Command.CanExecute(CommandParameter))
Command.Execute(CommandParameter);
}
private void UpdateEnabled()
{
Enabled = ShouldBeEnabled();
}
private bool ShouldBeEnabled()
{
if (_command == null)
return false;
return _command.CanExecute(CommandParameter);
}
}
and this can be bound as:
<FullButton
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Show Detail"
local:MvxBind="Command ShowDetailCommand; CommandParameter CurrentItem" />
For iOS, I'd expect the same type of technique to work... inheriting from a UIButton and using TouchUpInside instead of Click - but I'm afraid I don't have this code with me at the moment.