How to create a singleton class which runs when ASP.NET WEB FORMS starts (without dependency on the user login) - webforms

I have an ASP.NET web form application hosted on IIS.
In the app, I have a code snippet that should make some work on the background from the moment the application starts.
The problem is when I have created the singleton class and initialize it from Global.asax ->
Application_Start(), The code runs only when the first user is connecting to the site.
How can I set it to run without any dependency from the user side?
Any Idea?
The singleton class example:
public sealed class SingeltonBackgroundWork
{
private static SingeltonBackgroundWork updater = null;
private static Timer timer;
private SingeltonBackgroundWork()
{
//Milliseconds * Seconds * Minutes
timer = new Timer(1000 * 60 * 10);
timer.Elapsed += new ElapsedEventHandler(OnElapsed);
timer.AutoReset = true;
timer.Enabled = true;
}
private void OnElapsed(object sender, ElapsedEventArgs e)
{
//DO SOME WORK
}
public static void InitProcess()
{
if (updater == null)
{
updater = new SingeltonBackgroundWork();
}
}
}
Global.asax Application_Start():
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
SingeltonBackgroundWork.InitProcess();
}

Related

How to fix " Admob offline performance problem"?

Help please. I have created a script to add a resume funtion for users by seeing an reward base ad from Admob in unity. It works fine when user is online. but performance is too slow (not playable) when user device is in offline mode.
When the script is disable game works fine in both online and offline.
The problem maybe in RequestRewardBasedVideo() funtion.
using System;
using UnityEngine;
using GoogleMobileAds.Api;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class RewardAdResume : MonoBehaviour
{
private string app_id = "....................";
private RewardBasedVideoAd rewardBasedVideo;
public rewdResume RewdResume;
public bool adClosed;
public Text txt2;
public GameObject ops;
public GameObject rw1;
public GameObject rw2;
public GameObject rw3;
public bool opsld;
public GameObject opsLdImg;
// Start is called before the first frame update
void Start()
{
//on publish enable
//MobileAds.Initialize(app_id);
adClosed = false;
opsld = false;
this.RequestRewardBasedVideo();
}
void Update()
{
if (adClosed)
{
if (rewdResume.resumes)
{
txt2.text = adClosed + " Rewarded " + rewdResume.resumes;
RewdResume.resume();
rewdResume.resumes = false;
}
else
{
roverCore.adclosed = true;
}
adClosed = false;
}
if (opsld) {
opsLdImg.GetComponent<Image>().fillAmount += Time.deltaTime * 0.2f;
if (opsLdImg.GetComponent<Image>().fillAmount == 1) {
roverCore.adclosed = true;
ops.SetActive(false);
rw1.SetActive(true);
rw2.SetActive(true);
rw3.SetActive(true);
opsld = false;
}
}
}
private void RequestRewardBasedVideo()
{
string adUnitId = "ca-app-pub-3940256099942544/5224354917";
this.rewardBasedVideo = RewardBasedVideoAd.Instance;
// Called when an ad request has successfully loaded.
rewardBasedVideo.OnAdLoaded += HandleRewardBasedVideoLoaded;
// Called when an ad request failed to load.
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoFailedToLoad;
// Called when an ad is shown.
rewardBasedVideo.OnAdOpening += HandleRewardBasedVideoOpened;
// Called when the ad starts to play.
rewardBasedVideo.OnAdStarted += HandleRewardBasedVideoStarted;
// Called when the user should be rewarded for watching a video.
rewardBasedVideo.OnAdRewarded += HandleRewardBasedVideoRewarded;
// Called when the ad is closed.
rewardBasedVideo.OnAdClosed += HandleRewardBasedVideoClosed;
// Called when the ad click caused the user to leave the application.
rewardBasedVideo.OnAdLeavingApplication += HandleRewardBasedVideoLeftApplication;
// Create an empty ad request.
AdRequest adRequest = new AdRequest.Builder().AddTestDevice("2077ef9a63d2b398840261c8221a0c9b").Build();
// Load the rewarded video ad with the request.
this.rewardBasedVideo.LoadAd(adRequest, adUnitId);
}
public void UserOptToWatchAd()
{
if (rewardBasedVideo.IsLoaded())
{
roverCore.showChanceTimeout = false;
rewardBasedVideo.Show();
}
else {
ops.SetActive(true);
rw1.SetActive(false);
rw2.SetActive(false);
rw3.SetActive(false);
opsld = true;
//roverCore.adclosed = true;
}
}
#region rewd event
public void HandleRewardBasedVideoLoaded(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoLoaded event received");
}
public void HandleRewardBasedVideoFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
this.RequestRewardBasedVideo();
}
public void HandleRewardBasedVideoOpened(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoOpened event received");
}
public void HandleRewardBasedVideoStarted(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoStarted event received");
}
public void HandleRewardBasedVideoClosed(object sender, EventArgs args)
{
adClosed = true;
}
public void HandleRewardBasedVideoRewarded(object sender, Reward args)
{
rewdResume.resumes = true;
}
public void HandleRewardBasedVideoLeftApplication(object sender, EventArgs args)
{
MonoBehaviour.print("HandleRewardBasedVideoLeftApplication event received");
}
#endregion
private void OnDisable()
{
// Called when an ad request has successfully loaded.
rewardBasedVideo.OnAdLoaded -= HandleRewardBasedVideoLoaded;
// Called when an ad request failed to load.
rewardBasedVideo.OnAdFailedToLoad -= HandleRewardBasedVideoFailedToLoad;
// Called when an ad is shown.
rewardBasedVideo.OnAdOpening -= HandleRewardBasedVideoOpened;
// Called when the ad starts to play.
rewardBasedVideo.OnAdStarted -= HandleRewardBasedVideoStarted;
// Called when the user should be rewarded for watching a video.
rewardBasedVideo.OnAdRewarded -= HandleRewardBasedVideoRewarded;
// Called when the ad is closed.
rewardBasedVideo.OnAdClosed -= HandleRewardBasedVideoClosed;
// Called when the ad click caused the user to leave the application.
rewardBasedVideo.OnAdLeavingApplication -= HandleRewardBasedVideoLeftApplication;
}
}
rewardBasedVideo.OnAdFailedToLoad += HandleRewardBasedVideoFailedToLoad;
public void HandleRewardBasedVideoFailedToLoad(object sender, AdFailedToLoadEventArgs args)
{
this.RequestRewardBasedVideo();
}
When user device is offline, rewarded ad will fail to load almost every sec. So, you will send a lot of requests. That may cause FPS drops.
If i were you, i would start a coroutine for requesting a new rewarded video and wait at least 30 sec. to request a new rewarded ad.

Background Service Location Changed Not Fired Xamarin Android

I need to retrieve the real-time location of the device, I had implement ILocationListener in my Service Class as I want this to run even after the app is in the background or closed I have referred - this
and it seems not working for me even if I change my device location the location change event is not fired
My Service Class with Implemented ILocationListener
[Service]
public class LocationService : Service, ILocationListener
{
public event EventHandler<LocationChangedEventArgs> LocationChanged = delegate { };
public event EventHandler<ProviderDisabledEventArgs> ProviderDisabled = delegate { };
public event EventHandler<ProviderEnabledEventArgs> ProviderEnabled = delegate { };
public event EventHandler<StatusChangedEventArgs> StatusChanged = delegate { };
public LocationService()
{
}
// Set our location manager as the system location service
protected LocationManager LocMgr = Android.App.Application.Context.GetSystemService ("location") as LocationManager;
readonly string logTag = "LocationService";
IBinder binder;
public override void OnCreate ()
{
base.OnCreate ();
Log.Debug (logTag, "OnCreate called in the Location Service");
}
// This gets called when StartService is called in our App class
[Obsolete("deprecated in base class")]
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug (logTag, "LocationService started");
return StartCommandResult.Sticky;
}
// This gets called once, the first time any client bind to the Service
// and returns an instance of the LocationServiceBinder. All future clients will
// reuse the same instance of the binder
public override IBinder OnBind (Intent intent)
{
Log.Debug (logTag, "Client now bound to service");
binder = new LocationServiceBinder (this);
return binder;
}
// Handle location updates from the location manager
public void StartLocationUpdates ()
{
//we can set different location criteria based on requirements for our app -
//for example, we might want to preserve power, or get extreme accuracy
var locationCriteria = new Criteria();
locationCriteria.Accuracy = Accuracy.NoRequirement;
locationCriteria.PowerRequirement = Power.NoRequirement;
// get provider: GPS, Network, etc.
var locationProvider = LocMgr.GetBestProvider(locationCriteria, true);
Log.Debug (logTag, string.Format ("You are about to get location updates via {0}", locationProvider));
// Get an initial fix on location
LocMgr.RequestLocationUpdates(locationProvider, 2000, 0, this);
Log.Debug (logTag, "Now sending location updates");
}
public override void OnDestroy ()
{
base.OnDestroy ();
Log.Debug (logTag, "Service has been terminated");
// Stop getting updates from the location manager:
LocMgr.RemoveUpdates(this);
}
My Binder Class
public class LocationServiceBinder : Binder
{
public LocationService Service
{
get { return this.service; }
} protected LocationService service;
public bool IsBound { get; set; }
// constructor
public LocationServiceBinder (LocationService service)
{
this.service = service;
}
}
public class LocationServiceConnection : Java.Lang.Object, IServiceConnection
{
public event EventHandler<ServiceConnectedEventArgs> ServiceConnected = delegate {};
public LocationServiceBinder Binder
{
get { return this.binder; }
set { this.binder = value; }
}
protected LocationServiceBinder binder;
public LocationServiceConnection (LocationServiceBinder binder)
{
if (binder != null) {
this.binder = binder;
}
}
// This gets called when a client tries to bind to the Service with an Intent and an
// instance of the ServiceConnection. The system will locate a binder associated with the
// running Service
public void OnServiceConnected (ComponentName name, IBinder service)
{
// cast the binder located by the OS as our local binder subclass
LocationServiceBinder serviceBinder = service as LocationServiceBinder;
if (serviceBinder != null) {
this.binder = serviceBinder;
this.binder.IsBound = true;
Log.Debug ( "ServiceConnection", "OnServiceConnected Called" );
// raise the service connected event
this.ServiceConnected(this, new ServiceConnectedEventArgs () { Binder = service } );
// now that the Service is bound, we can start gathering some location data
serviceBinder.Service.StartLocationUpdates();
}
}
// This will be called when the Service unbinds, or when the app crashes
public void OnServiceDisconnected (ComponentName name)
{
this.binder.IsBound = false;
Log.Debug ( "ServiceConnection", "Service unbound" );
}
}
public class ServiceConnectedEventArgs : EventArgs
{
public IBinder Binder { get; set; }
}
My MainActivity
public class MainActivity : Activity
{
readonly string logTag = "MainActivity";
// make our labels
TextView latText;
TextView longText;
TextView altText;
TextView speedText;
TextView bearText;
TextView accText;
#region Lifecycle
//Lifecycle stages
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Log.Debug (logTag, "OnCreate: Location app is becoming active");
SetContentView (Resource.Layout.Main);
// This event fires when the ServiceConnection lets the client (our App class) know that
// the Service is connected. We use this event to start updating the UI with location
// updates from the Service
App.Current.LocationServiceConnected += (object sender, ServiceConnectedEventArgs e) => {
Log.Debug (logTag, "ServiceConnected Event Raised");
// notifies us of location changes from the system
App.Current.LocationService.LocationChanged += HandleLocationChanged;
//notifies us of user changes to the location provider (ie the user disables or enables GPS)
App.Current.LocationService.ProviderDisabled += HandleProviderDisabled;
App.Current.LocationService.ProviderEnabled += HandleProviderEnabled;
// notifies us of the changing status of a provider (ie GPS no longer available)
App.Current.LocationService.StatusChanged += HandleStatusChanged;
};
latText = FindViewById<TextView> (Resource.Id.lat);
longText = FindViewById<TextView> (Resource.Id.longx);
altText = FindViewById<TextView> (Resource.Id.alt);
speedText = FindViewById<TextView> (Resource.Id.speed);
bearText = FindViewById<TextView> (Resource.Id.bear);
accText = FindViewById<TextView> (Resource.Id.acc);
altText.Text = "altitude";
speedText.Text = "speed";
bearText.Text = "bearing";
accText.Text = "accuracy";
// Start the location service:
App.StartLocationService();
}
protected override void OnPause()
{
Log.Debug (logTag, "OnPause: Location app is moving to background");
base.OnPause();
}
protected override void OnResume()
{
Log.Debug (logTag, "OnResume: Location app is moving into foreground");
base.OnResume();
}
protected override void OnDestroy ()
{
Log.Debug (logTag, "OnDestroy: Location app is becoming inactive");
base.OnDestroy ();
// Stop the location service:
App.StopLocationService();
}
#endregion
#region Android Location Service methods
///<summary>
/// Updates UI with location data
/// </summary>
public void HandleLocationChanged(object sender, LocationChangedEventArgs e)
{
Android.Locations.Location location = e.Location;
Log.Debug (logTag, "Foreground updating");
// these events are on a background thread, need to update on the UI thread
RunOnUiThread (() => {
latText.Text = String.Format ("Latitude: {0}", location.Latitude);
longText.Text = String.Format ("Longitude: {0}", location.Longitude);
altText.Text = String.Format ("Altitude: {0}", location.Altitude);
speedText.Text = String.Format ("Speed: {0}", location.Speed);
accText.Text = String.Format ("Accuracy: {0}", location.Accuracy);
bearText.Text = String.Format ("Bearing: {0}", location.Bearing);
});
}
public void HandleProviderDisabled(object sender, ProviderDisabledEventArgs e)
{
Log.Debug (logTag, "Location provider disabled event raised");
}
public void HandleProviderEnabled(object sender, ProviderEnabledEventArgs e)
{
Log.Debug (logTag, "Location provider enabled event raised");
}
public void HandleStatusChanged(object sender, StatusChangedEventArgs e)
{
Log.Debug (logTag, "Location status changed, event raised");
}
#endregion
}
the above public void HandleLocationChanged(object sender, LocationChangedEventArgs e) {}
never get fired on my device location change

BackgroundWorker example

Could you please provide an example how to use background worker.
I have created Background worker follow the instruction provided in documentation for asp.net boilerplate. Inherit my class from
public class ContactValidationBackgroundWorker : BackgroundWorkerBase, ITransientDependency
Override Start method and put into non-blocking Task.Run(MyMethod). Then I add wait instruction into Overrided method WaitToStop, add like myTask.Wait();
This method starts , but it block performing main process of work.
I'm using Asp.net(boilerplate) core + Angular (SPA)
I added it into Application Services layer.
public class MakeInactiveUsersPassiveWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
{
private readonly IRepository<User, long> _userRepository;
public MakeInactiveUsersPassiveWorker(AbpTimer timer, IRepository<User, long> userRepository)
: base(timer)
{
_userRepository = userRepository;
Timer.Period = 5000; //5 seconds (good for tests, but normally will be more)
}
[UnitOfWork]
protected override void DoWork()
{
using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var oneMonthAgo = Clock.Now.Subtract(TimeSpan.FromDays(30));
var inactiveUsers = _userRepository.GetAllList(u =>
u.IsActive &&
((u.LastLoginTime < oneMonthAgo && u.LastLoginTime != null) || (u.CreationTime < oneMonthAgo && u.LastLoginTime == null))
);
foreach (var inactiveUser in inactiveUsers)
{
inactiveUser.IsActive = false;
Logger.Info(inactiveUser + " made passive since he/she did not login in last 30 days.");
}
CurrentUnitOfWork.SaveChanges();
}
}
}
Read => https://aspnetboilerplate.com/Pages/Documents/Background-Jobs-And-Workers
public partial class MainWindow : Window
{
//defining the backgroundworker
private BackgroundWorker bgworker = new BackgroundWorker();
public MainWindow()
{
InitializeComponent();
initializeBackgroundWorker();
}
private void initializeBackgroundWorker()
{
bgworker.DoWork += MyBackgroundWorker_DoWork;
}
private void MyBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
//method you want to execute in the backgroundWorker
MyMethod();
}
private void Mouse_Enter(object sender, MouseEventArgs e)
{
//call the backgroundWorker and execute it
//This will execute the method simultaneouly with other methods
//without blocking the UI
bgworker.RunWorkerAsync();
}
private void MyMethod()
{
//your method's code
}
}
The above code shows how to define, initialize and execute a backgroundWorker in a WPF or winform application using C#.
Refer to the inline comments in the code to understand what each part of code does.

Android Service binding with MvvmCross

I am developing xamarin.Android app in MvvmCross. I want to call a service even when the App is backgrounded and a user is logged in. The problem is, I want to call this service within every say 2 hours whether the app is in foreground or background, just the user of the App needs to be logged in.
Intent loggedintent = new Intent(this,typeof(DeviceLoginHelper));
loggedintent.PutExtra("LoggedIn", true);
StartService(loggedintent);
I have written an android service:
[Service]
public class DeviceLoginHelper : IntentService
{
protected override void OnHandleIntent(Intent intent)
{
try
{
if(intent.HasExtra("LoggedIn"))
{
}
}
catch(Exception ex) { }
}
}
But how can I implement a timer? Where do I initialise and handle event to the timer. And when timer is elapsed when should I call ?
public override void OnDestroy()
{
try
{
base.OnDestroy();
}
catch(Exception ex){}
}
and when a user loges out i want to stop this service. Where do I put the call StopService() in MvvmCross
I would not use a Timer. Instead you should configure the AlarmManager.
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
private static AlarmManager alarmMgr;
private static PendingIntent alarmIntent;
public const int NOTIFICATION_ID = 1;
public const int IDLE_TIME_MS = 30 * 1000; // 30-seconds (update here)
private NotificationManager mNotificationManager;
Notification.Builder builder;
public override void OnReceive(Context context, Intent intent)
{
// Do something when alarm triggers (here I'm building notification)
BuildNotification(context);
// reschedule alarm
ScheduleAlarm(IDLE_TIME_MS);
}
public static Context ApplicationContext { get; set; }
public static void ScheduleAlarm(int milliseconds)
{
if (milliseconds == 0) return;
alarmMgr = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
var intent = new Intent(ApplicationContext, typeof(AlarmReceiver));
alarmIntent = PendingIntent.GetBroadcast(ApplicationContext, 0, intent, 0);
alarmMgr.Set(AlarmType.ElapsedRealtimeWakeup,
SystemClock.ElapsedRealtime() + milliseconds, alarmIntent);
}
private void BuildNotification(Context context)
{
mNotificationManager = (NotificationManager)context.GetSystemService(Context.NotificationService);
var contentIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainView)), 0);
var message = $"Time is up";
var mBuilder = new Notification.Builder(context)
.SetAutoCancel(true)
.SetPriority(NotificationCompat.PriorityMax)
.SetDefaults(NotificationDefaults.All)
.SetContentTitle("Time is up")
.SetStyle(new Notification.BigTextStyle()
.BigText(message))
.SetContentText(message)
.SetSmallIcon(Resource.Drawable.ic_launcher);
mBuilder.SetContentIntent(contentIntent);
mNotificationManager.Notify(NOTIFICATION_ID, mBuilder.Build());
}
}
In your startup code, simply call:
AlarmReceiver.ApplicationContext = context;
AlarmReceiver.ScheduleAlarm(timeInMs);

kryonet client, send message to server without open a new connection

I'm saying i'm not a programmer but a guy who has been learning to program with java for a while. I hope to find the solution to my problem here. I'm trying to program my home automation system and remote control and to do this, I chose to use Kryonet. My problem is that every time I send the data to the server, the client opens a new connection. It's been 3 weeks since googlo and I try to figure out how to do it but with no results.
Every help is seriously appreciated. This is my code. Thank you.
This code work in my home network.
Sorry for my english...
public class MainActivity extends AppCompatActivity {
Button button;
String IP = "";
EditText editText;
TextView textView;
EditText editText3;
public static String msg_response;
public static String msg_request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Handler handler = new MyHandler();
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
editText3 = (EditText) findViewById(R.id.editText3);
textView = (TextView) findViewById(R.id.textView);
int MY_PERMISSIONS_REQUEST_INTERNET = 1;
int MY_PERMISSIONS_REQUEST_ACCESS_NETWORK_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.INTERNET},
MY_PERMISSIONS_REQUEST_INTERNET);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_NETWORK_STATE},
MY_PERMISSIONS_REQUEST_ACCESS_NETWORK_STATE);
int MY_PERMISSIONS_REQUEST_ACCESS_WIFY_STATE = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_WIFI_STATE},
MY_PERMISSIONS_REQUEST_ACCESS_WIFY_STATE);
textView.setText(msg_response);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
msg_request = valueOf(editText3.getText().toString());
} catch (Exception e) {
e.printStackTrace();
}
MyThread myThread = new MyThread(handler);
myThread.start();
}
});
}
private class MyHandler extends Handler {
#Override
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
if (bundle.containsKey("msg da server")) {
String msgin = bundle.getString("msg da server");
textView.setText(msgin);
}
}
}
class MyThread extends Thread {
private Handler handler;
public MyThread(Handler handler) {
this.handler = handler;
}
public void run() {
System.out.println("MyThread running");
Client client = new Client();
client.start();
Kryo kryoClient = client.getKryo();
kryoClient.register(SampleRequest.class);
kryoClient.register(SampleResponse.class);
try {
client.connect(5000, "192.168.0.101", 54555, 54666);
} catch (IOException e) {
e.printStackTrace();
}
client.addListener(new Listener() {
public void received(Connection connection, Object object) {
if (object instanceof SampleResponse) {
SampleResponse response = (SampleResponse) object;
System.out.println(response.text);
msg_response = response.text.toString();
invia_activity(msg_response);
}
}
});
SampleRequest request = new SampleRequest();
request.text = msg_request;
client.sendTCP(request);
}
private void invia_activity(String invia) {
Message msg = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("msg da server", "" + invia);
msg.setData(b);
handler.sendMessage(msg);
}
}
}
I dont have an direct solution, but i have an tutorial for it. I used the same one. So there the connections keeps open, and you can send as many packets as you need. Its without audio, but the code works well. After that you can experiment with the code. It works fine for me. This is the tutorial
I hope i can help you with this.
EDIT:
Maybe you can make an
public static Connection conn;
and you could use that object again and again as your connection to the server.

Resources