Wifi is not detected sometimes on android devices with OS Android 8.1 and above - android-wifi

When a smartphone gets connected to wifi without internet, the job scheduler does not detect the wifi change and onAvailable method is not called sometimes. This issue is observed in android 8.1 OS and above smartphones.
This the code snippet used to detect the wifi connection.
The job is created on launch of the app in the launcher activity.
try {
ComponentName componentName = new ComponentName(this, JobSchedulerWifi.class);
JobInfo jobInfo = new JobInfo.Builder(12, componentName)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.build();
JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("XXX", "Wifi_Job scheduled!"+jobInfo.getId());
} else {
Log.d("XXX", "Wifi_Job not scheduled");
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
public class JobSchedulerService extends JobService {
ConnectivityManager connectivityManager;
ConnectivityManager.NetworkCallback networkCallback;
BroadcastReceiver connectivityChange;
Context cont;
private boolean jobCancelled=false;
#Override
public boolean onStartJob(final JobParameters job) {
Log.d("Job", Build.VERSION.SDK_INT+"Job - Job created"+Build.VERSION_CODES.LOLLIPOP);
cont=this;
connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
cont=this;
connectivityManager.registerDefaultNetworkCallback(networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
// super.onAvailable(network);
WifiManager wifiManager = (WifiManager) cont.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifi = wifiManager.getConnectionInfo();
String wificonnect =wifi.getSSID();
wificonnect = wificonnect.substring(1, wificonnect.length() - 1);
Log.i("job", "Default -> Internet Network Available"+wificonnect);
}

Have you thought about using WorkManger?
WorkManager, part of Android X is supported back to API level 14 and makes detecting and running code on connection change a simple task.
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
val myWorkRequest =
OneTimeWorkRequestBuilder<MyWorker>()
.setConstraints(constraints)
.build()
WorkManager.getInstance(MyApplication.context).enqueue(myWorkRequest)
And the class that will be executed when the connection is detected:
class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
override fun doWork(): Result {
doThis()
return Result.success()
}
private fun doThis() {
Log.d("ASDF", "::onReceive")
}
}
Additional resources:
Current library
Google documentation

Related

Nested Transactions with MySQL and Entity Framework Core

I'm using MySQL with EF Core. I am currently using Pomelo Provider for MySQL. I need to implement Unit Of Work Pattern for transactions. I have a Service which calls two methods in repository. I am not able to implement nested transactions. This is how my method in service looks now:
public void methodA(param)
{
using (TransactionScope tx = new
TransactionScope(TransactionScopeOption.Required))
{
repo1.save(data1);
repo2.save(data2);
tx.complete();
}
}
This is how save method in repo1 is implemented
private readonly UserDbContext appDbContext;
public repo1(UserDbContext _appDbContext)
{
appDbContext = _appDbContext;
}
public void save(User entity)
{
var dbset = appDbContext.Set<User>().Add(entity);
appDbContext.SaveChanges();
}
This is how save method in repo2 is implemented
private readonly UserDbContext appDbContext;
public repo2(UserDbContext _appDbContext)
{
appDbContext = _appDbContext;
}
public void save(UserRole entity)
{
var dbset = appDbContext.Set<UserRole>().Add(entity);
appDbContext.SaveChanges();
}
I am getting the following error while running method in service:
Error generated for warning 'Microsoft.EntityFrameworkCore.Database.Transaction.AmbientTransactionWarning: An ambient transaction has been detected. The current provider does not support ambient transactions. See http://go.microsoft.com/fwlink/?LinkId=800142'. This exception can be suppressed or logged by passing event ID 'RelationalEventId.AmbientTransactionWarning' to the 'ConfigureWarnings' method in 'DbContext.OnConfiguring' or 'AddDbContext'.
This is how I registered UserDbContext in Startup.cs
services.AddDbContext<UserDbContext>(options => options.UseLazyLoadingProxies().UseMySql("Server = xxxx; Database = xxx; Uid = xx;ConnectionReset=True;", b => b.MigrationsAssembly("AssemblyName")));
I even tried adding a middleware which starts transaction at the begining of request and commits/rollbacks during the response . But still I am not able to manage nested transactions.
This is how my middleware looks:
public class TransactionPerRequestMiddleware
{
private readonly RequestDelegate next_;
public TransactionPerRequestMiddleware(RequestDelegate next)
{
next_ = next;
}
public async Task Invoke(HttpContext context, UserDbContext
userDbContext)
{
var transaction = userDbContext.Database.BeginTransaction(
System.Data.IsolationLevel.ReadCommitted);
await next_.Invoke(context);
int statusCode = context.Response.StatusCode;
if (statusCode == 200 || statusCode==302)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
Can anyone help me please?

Try-Catch not working for controller to class library [Debugger Mode]

I am running dotnet core 2.* and as the title mentions I have trouble getting my try catch to work when calling from API. And before anyone comments I am also running middle-ware to catch any exceptions. It too doesn't perform as expected
Addinional Information:
The Two Classes are in different namespaces/projects
Queries.Authentication is static.
They are both in the same solution
Controller:
[AllowAnonymous]
[HttpPost]
public string Login([FromBody] AuthRequest req)
{
// See if the user exists
if (Authenticate(req.username, req.password))
{
try {
// Should Fail Below
UserDetails ud = Queries.Authentication.GetUser(req.username);
} catch (RetrievalException e){ }
catch (Exception e){ } // Exception Still Comes Through
}
}
Queries.Authentication.GetUser Code:
public static class Authentication {
public static UserDetails GetUser (string username)
{
// Some Code
if (details.success)
{
// Some Code
}
else
{
throw new RetrievalException(details.errorMessage); // This is not caught propperly
}
}
}
Retrieval Exception:
public class RetrievalException : Exception
{
public RetrievalException()
{
}
public RetrievalException(String message)
: base(message)
{
}
public RetrievalException(String message, Exception inner)
: base(message, inner)
{
}
}
EDIT: Adding Middleware Code Here as per request:
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(UnauthorizedAccessException))
{
message = "Unauthorized Access";
status = HttpStatusCode.Unauthorized;
}
else if (exceptionType == typeof(NullReferenceException))
{
message = "Null Reference Exception";
status = HttpStatusCode.InternalServerError;
}
else if (exceptionType == typeof(NotImplementedException))
{
message = "A server error occurred.";
status = HttpStatusCode.NotImplemented;
}
else if (exceptionType == typeof(RSClientCore.RetrievalException))
{
message = " The User could not be found.";
status = HttpStatusCode.NotFound;
}
else
{
message = context.Exception.Message;
status = HttpStatusCode.NotFound;
}
context.ExceptionHandled = true;
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)status;
response.ContentType = "application/json";
var err = "{\"message\":\"" + message + "\",\"code\" :\""+ (int)status + "\"}";
response.WriteAsync(err);
}
}
App Config:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} else
{
app.UseExceptionHandler();
}
...
}
Service Config:
public void ConfigureServices(IServiceCollection services)
{
// Add Model View Controller Support
services.AddMvc( config =>
config.Filters.Add(typeof (CustomExceptionFilter))
);
UPDATE: After playing around with it I noticed that even though my program throws the exception, if I press continue the API controller then handles it as if the exception was never thrown (as in it catches it and does what I want). So I turned off the break on Exception setting, this fixed it in debugger mode. However this the break doesn't seem to be an issue when I build/publish the program. This makes me think it is definitely a issue with visual studio itself rather than the code.
When you set ExceptionHandled to true that means you have handled the exception and there is kind of no error anymore. So try to set it to false.
context.ExceptionHandled = false;
I agree it looks a bit confusing, but should do the trick you need.
Relevant notes:
For those who deal with different MVC and API controller make sure you implemented appropriate IExceptionFilter as there are two of them - System.Web.Mvc.IExceptionFilter (for MVC) and System.Web.Http.Filters.IExceptionFilter (for API).
There is a nice article about Error Handling and ExceptionFilter Dependency Injection for ASP.NET Core APIs you could use as a guide for implementing exception filters.
Also have a look at documentation: Filters in ASP.NET Core (note selector above the left page menu to select ASP.NET Core 1.0, ASP.NET Core 1.1,ASP.NET Core 2.0, or ASP.NET Core 2.1 RC1). It has many important notes and explanations why it works as it does.

app certification requirements when returning from tombstoning

I have a page where user can enter his name and attach an image.
When returning from tombstoning state, is it mandatory for my app to restore the image too?
Is it app certification requirement, something without which my app will not pass certification? Or is it a recommended pattern?
same question in the case when I have a pivot for example, is it mandatory to save the index of selected pivot item and restore the selection when activating from tombstoning?
Not necessary:
Is there a popular library \ framework to help me with tombstoning and serializing objects, images, etc?
According to the Technical certification requirements for Windows Phone , the only requirements are :
A Windows Phone app is deactivated when the user presses the Start button or if the device timeout causes the lock screen to engage. A Windows Phone app is also deactivated with it invokes a Launcher or Chooser API.
A Windows Phone OS 7.0 app is tombstoned (terminated) when it is deactivated. A Windows Phone OS 7.1 or higher app becomes Dormant when it is deactivated but can be terminated by the system when resource use policy causes it to tombstone.
When activated after termination, the app must meet the requirements in Section 5.2.1 – Launch time.
As the section 5.2.1 - "Launch time" only concerns startup performance and responsiveness, you don't have a certification requirement for your issue.
However, if the user enters data (attaches images, etc.) and let's say it answer a call, does some other stuff and get's back to the application and then the data he entered was lost... it surely won't appreciate it. That will look more like a defect/bug.
Concerning the serialization of your state, I recommend you to use binary serialization as the performance is at least 10x better than using Json, Xml or any other format.
Personally, I implement a custom interface, IBinarySerializable to my "state" related classes and use this BinaryWriter extensions class to help writing the serialization code:
using System.IO;
namespace MyCompany.Utilities
{
public interface IBinarySerializable
{
void Write(BinaryWriter writer);
void Read(BinaryReader reader);
}
}
using System;
using System.Collections.Generic;
using System.IO;
namespace MyCompany.Utilities
{
public static class BinaryWriterExtensions
{
public static void Write<T>(this BinaryWriter writer, T value) where T : IBinarySerializable
{
if (value == null)
{
writer.Write(false);
return;
}
writer.Write(true);
value.Write(writer);
}
public static T Read<T>(this BinaryReader reader) where T : IBinarySerializable, new()
{
if (reader.ReadBoolean())
{
T result = new T();
result.Read(reader);
return result;
}
return default(T);
}
public static void WriteList<T>(this BinaryWriter writer, IList<T> list) where T : IBinarySerializable
{
if (list == null)
{
writer.Write(false);
return;
}
writer.Write(true);
writer.Write(list.Count);
foreach (T item in list)
{
item.Write(writer);
}
}
public static List<T> ReadList<T>(this BinaryReader reader) where T : IBinarySerializable, new()
{
bool hasValue = reader.ReadBoolean();
if (hasValue)
{
int count = reader.ReadInt32();
List<T> list = new List<T>(count);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
T item = new T();
item.Read(reader);
list.Add(item);
}
return list;
}
}
return null;
}
public static void WriteListOfString(this BinaryWriter writer, IList<string> list)
{
if (list == null)
{
writer.Write(false);
return;
}
writer.Write(true);
writer.Write(list.Count);
foreach (string item in list)
{
writer.WriteSafeString(item);
}
}
public static List<string> ReadListOfString(this BinaryReader reader)
{
bool hasValue = reader.ReadBoolean();
if (hasValue)
{
int count = reader.ReadInt32();
List<string> list = new List<string>(count);
if (count > 0)
{
for (int i = 0; i < count; i++)
{
list.Add(reader.ReadSafeString());
}
return list;
}
}
return null;
}
public static void WriteSafeString(this BinaryWriter writer, string value)
{
if (value == null)
{
writer.Write(false);
return;
}
writer.Write(true);
writer.Write(value);
}
public static string ReadSafeString(this BinaryReader reader)
{
bool hasValue = reader.ReadBoolean();
if (hasValue)
return reader.ReadString();
return null;
}
public static void WriteDateTime(this BinaryWriter writer, DateTime value)
{
writer.Write(value.Ticks);
}
public static DateTime ReadDateTime(this BinaryReader reader)
{
var int64 = reader.ReadInt64();
return new DateTime(int64);
}
}
}

NullPointerException error on Implementing Location API on J2me

I am trying to implement jsr-179 APi into Nokia Symbian phone for periodic location update using setLocationListener through J2me. In emulator it is working fine. While I installed Midlet on the device nokia 5230, it is given NullPointerException and the application is automatically terminating. What might be possible causes?
Below is my class, I am instantiating object for this class on a form in netbeans
class MovementTracker implements LocationListener {
LocationProvider provider;
Location lastValidLocation;
UpdateHandler handler;
boolean done;
public MovementTracker() throws LocationException
{
done = false;
handler = new UpdateHandler();
new Thread(handler).start();
//Defining Criteria for Location Provider
/*
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(500);
*/
//you can place cr inside getInstance
provider = LocationProvider.getInstance(null);
//listener,interval,timeout,int maxAge
//Passing -1 selects default interval
// provider.setLocationListener(MovementTracker.this, -1, -1, -1);
provider.setLocationListener(MovementTracker.this, -1, 30000, 30000);
}
public void locationUpdated(LocationProvider provider, Location location)
{
handler.handleUpdate(location);
batteryLevel = System.getProperty("com.nokia.mid.batterylevel");
sn = System.getProperty("com.nokia.mid.networksignal");
localTime = System.currentTimeMillis();
Send_Location();
}
public void providerStateChanged(LocationProvider provider, int newState)
{
}
class UpdateHandler implements Runnable
{
private Location updatedLocation = null;
// The run method performs the actual processing of the location
public void run()
{
Location locationToBeHandled = null;
while (!done)
{
synchronized(this)
{
if (updatedLocation == null)
{
try
{
wait();
}
catch (Exception e)
{
// Handle interruption
}
}
locationToBeHandled = updatedLocation;
updatedLocation = null;
}
// The benefit of the MessageListener is here.
// This thread could via similar triggers be
// handling other kind of events as well in
// addition to just receiving the location updates.
if (locationToBeHandled != null)
processUpdate(locationToBeHandled);
}
try
{
Thread.sleep(10000); //Sleeps for 10 sec & then sends the data
}
catch (InterruptedException ex)
{
}
}
public synchronized void handleUpdate(Location update)
{
updatedLocation = update;
notify();
}
private void processUpdate(Location update)
{
latitude = update.getQualifiedCoordinates().getLatitude();
longitude = update.getQualifiedCoordinates().getLongitude();
altitude = update.getQualifiedCoordinates().getAltitude();
}
}
}
public MovementTracker() throws LocationException
...
I have not written any code for handling LocationException.
No code is very dangerous practice, just search the web for something like "java swallow exceptions".
It is quite possible that because of implementation specifics Nokia throws LocationException where emulator does not throw it. Since you don't handle exception this may indeed crash you midlet at Nokia - and you wouldn't know the reason for that because, again, you have written no code to handle it.
How can I catch that exception?
The simplest thing you can do is to display an Alert with exception message and exit the midlet after user reads and dismisses alert

Castle Windsor Singleton Instantiated On Each Call To Resolve

I'm using Castle Windsor 2.5.3 in an ASP.NET 4.0 Web Application (not ASP.NET MVC)
I have an interceptor which is being used to intercept calls to a data access component. The interceptor depends on a cache manager. The cache manager is used by the interceptor to avoid calling the data access component if the cache manager has the required data.
Even though the cache manager is registered as a Singleton, it is being instantiated multiple times. I can prove this with a debug message or a hit-count breakpoint in its default constructor.
A new requirement is for the cache to be clearable on demand, so I thought it would be a simple matter of resolving the Cache Manager and calling EmptyCache. What is happening is that the container is creating a new instance of the Cache Manager on which the call to EmptyCache has no effect (since the new cache manager has no cached data). Here is the code in the web page for clearing the cache:
protected void flushButton_Click(object sender, EventArgs e)
{
ICacheManager cacheManager = null;
try
{
cacheManager = Global.Container.Resolve<ICacheManager>();
cacheManager.EmptyCache();
resultLabel.Text = "Cache has been flushed";
}
catch (Exception ex)
{
resultLabel.Text = "An error occurred. The reason given was: " + ex.Message;
}
finally
{
if (cacheManager != null)
Global.Container.Release(cacheManager);
}
}
When I hover over the Container in Visual Studio and drill into the Components, the CacheManager is marked as Singleton. How can this be happening?
My Cache Manager is registered like this:
public class WindsorComponentInstaller : IWindsorInstaller
{
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
Component.For(typeof(Data.Common.Cache.ICacheManager))
.ImplementedBy(typeof(Data.Common.Cache.CacheManager))
.LifeStyle.Singleton
);
container.Register(
Component.For<Data.Common.CachingInterceptor>()
);
}
}
The Cache Manager interface looks like this:
public interface ICacheManager
{
object CacheItem(string cacheKey, DateTime absoluteExpiration, CacheItemPriority priority, Func<object> itemProvider);
object CacheItem(string cacheKey, TimeSpan slidingExpiration, CacheItemPriority priority, Func<object> itemProvider);
void EmptyCache();
}
The interceptor looks like this:
public class CachingInterceptor : IInterceptor
{
private ILogger logger = NullLogger.Instance;
private ICacheManager cacheManager;
public CachingInterceptor(ICacheManager cacheManager)
{
this.cacheManager = cacheManager;
}
public ILogger Logger
{
set
{
if (value != null) logger = value;
}
}
public void Intercept(IInvocation invocation)
{
try
{
string cacheItemKey = MakeCacheItemKey(invocation);
//Debug.WriteLine("Cache Key: {0}", cacheItemKey);
TimeSpan lifespan = TimeSpan.Parse("00:20:00");
bool cacheHit = true;
object result = cacheManager.CacheItem(cacheItemKey, lifespan, CacheItemPriority.Low,
() =>
{
invocation.Proceed();
//Debug.WriteLine(String.Format("populate-the-cache callback was invoked and returned a {0}", invocation.ReturnValue ?? "null"));
cacheHit = false;
return invocation.ReturnValue;
}
);
logger.DebugFormat("Interceptor {0} Cache Hit: {1}", (invocation.Method.Name ?? "null"), cacheHit.ToString());
invocation.ReturnValue = result;
}
catch (Exception ex)
{
logger.Error("Intercept Error", ex);
}
}
private string MakeCacheItemKey(IInvocation invocation)
{
StringBuilder sb = new StringBuilder();
sb.Append(invocation.InvocationTarget);
sb.Append("|" + invocation.MethodInvocationTarget.Name);
sb.Append("|" + invocation.MethodInvocationTarget.ReturnType);
foreach (ParameterInfo pi in invocation.MethodInvocationTarget.GetParameters())
sb.Append("|" + pi.ParameterType.ToString());
foreach (var arg in invocation.Arguments)
{
sb.Append("|");
sb.Append(arg ?? "null");
}
return sb.ToString();
}
}
The data components are registered like this:
public void Install(IWindsorContainer container, IConfigurationStore store)
{
string connStr = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;
container.Register(
Component.For<IActualCostsVersusBudgetDataProvider>()
.ImplementedBy<ActualCostsVersusBudgetDataProvider>()
.DependsOn(Property.ForKey("connectionString").Eq(connStr))
.LifeStyle.Transient
.Interceptors(InterceptorReference.ForType<CachingInterceptor>())
.Anywhere
);
/* Many calls to .Register omitted */
}
The business objects that depend on data providers are registered like this:
public void Install(IWindsorContainer container, IConfigurationStore store)
{
container.Register(
AllTypes.FromThisAssembly()
.Where(t => t.Name.EndsWith("Manager"))
.Configure(c => c.LifeStyle.Transient)
);
}
The container is initialized like this in global.asax:
public static IWindsorContainer Container { get; private set; }
public Global()
{
Container = BootstrapContainer();
}
private IWindsorContainer BootstrapContainer()
{
WindsorContainer container = new WindsorContainer();
container.AddFacility<LoggingFacility>(f => f.LogUsing(LoggerImplementation.Log4net).WithAppConfig());
container.Install(
new Data.Common.Installers.WindsorComponentInstaller(),
new Data.Installers.WindsorComponentInstaller(),
new Business.Installers.WindsorComponentInstaller()
);
return container;
}