java.lang.NoClassDeffoundError when attempting to use FileFilter - filefilter

My application works on my laptop, but when I attempt to run the app that uses the code for FileFilter I get the NoClassDeffoundError on a production machine. my version is 1.8.0.201 and the prod machine is 1.8.0.121.
FileFilter dirFilter = new FileFilter() {
#Override
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
return false;
}
}
};

Related

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

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

Transaction Per Request Middleware Not working

I am trying to add a middleware so that transaction begins at the beginning of the request and commits or rollbacks depending on the situation. This is my middleware:
public class TransactionPerRequestMiddleware
{
private readonly RequestDelegate next_;
public TransactionPerRequestMiddleware(RequestDelegate next)
{
next_ = next;
}
public async Task Invoke(HttpContext context, AppDbContext dbContext)
{
var is_everything_ok = true;
var transaction = dbContext.Database.BeginTransaction(
System.Data.IsolationLevel.ReadCommitted);
if (context.Response.StatusCode != 200 && is_everything_ok)
{
is_everything_ok = false;
}
await next_.Invoke(context);
if ((context.Response.StatusCode == 200 ||
context.Response.StatusCode == 302) && is_everything_ok)
{
transaction.Commit();
}
else
{
transaction.Rollback();
}
}
}
I registered the above middleware in Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMiddleware<TransactionPerRequestMiddleware>();
}
I have a method in service which performs two database operations one after another.
public void method()
{
databaseOperation1();
databaseOperation2();
}
If exception occurs in databaseOperation2() , databaseOperation1() is not rolling back currently. I am trying to implement Unit Of Work for each web request.
Thanks in advance.

vNext: Console app that uses razor views without hosting

I am creating console application that does some file conversions. These conversions are easily done creating a model from the input file and then executing razor models for the output.
To have this working in the IDE I used Visual Studio 2015 preview and created a vnext console application that uses MVC. (You get razor support out of the box then). To get this all working you need to host the MVC app though, and the cheapest way to do that is hosting is through a WebListener. So I host the MVC app and then call it through "http://localhost:5003/etc/etc" to get the rendered views that construct the output.
But the console app is not supposed to listen to/use a port. It is just a command line tool for file conversions. If multiple instances would run at the same time they would fight to host the pages on the same port. (This could of coarse be prevented by choosing a port dynamically, but this is not what I am looking for)
So my question is how would you get this working without using a port, but using as much of the vnext frameworks as possible.
In short: how can I use cshtml files that I pass models in a console app that does not use a port using the vnext razor engine.
Here is some code I currently use:
Program.cs
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
namespace ConsoleTest
{
public class Program
{
private readonly IServiceProvider _hostServiceProvider;
public Program(IServiceProvider hostServiceProvider)
{
_hostServiceProvider = hostServiceProvider;
}
public async Task<string> GetWebpageAsync()
{
using (var httpClient = new HttpClient())
{
httpClient.BaseAddress = new Uri("http://localhost:5003/home/svg?idx=1");
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
return await httpClient.GetStringAsync("");
}
}
public Task<int> Main(string[] args)
{
var config = new Configuration();
config.AddCommandLine(args);
var serviceCollection = new ServiceCollection();
serviceCollection.Add(HostingServices.GetDefaultServices(config));
serviceCollection.AddInstance<IHostingEnvironment>(new HostingEnvironment() { WebRoot = "wwwroot" });
var services = serviceCollection.BuildServiceProvider(_hostServiceProvider);
var context = new HostingContext()
{
Services = services,
Configuration = config,
ServerName = "Microsoft.AspNet.Server.WebListener",
ApplicationName = "ConsoleTest"
};
var engine = services.GetService<IHostingEngine>();
if (engine == null)
{
throw new Exception("TODO: IHostingEngine service not available exception");
}
using (engine.Start(context))
{
var tst = GetWebpageAsync();
tst.Wait();
File.WriteAllText(#"C:\\result.svg", tst.Result.TrimStart());
Console.WriteLine("Started the server..");
Console.WriteLine("Press any key to stop the server");
Console.ReadLine();
}
return Task.FromResult(0);
}
}
}
Startup.cs
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.AspNet.Routing;
using Microsoft.Framework.ConfigurationModel;
namespace ConsoleTest
{
public class Startup
{
public IConfiguration Configuration { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
//Configure WebFx
app.UseMvc(routes =>
{
routes.MapRoute(
null,
"{controller}/{action}",
new { controller = "Home", action = "Index" });
});
}
}
}
I solved it using the following code:
Program.cs
using System;
using System.Threading.Tasks;
using Microsoft.AspNet.TestHost;
using Microsoft.AspNet.Builder;
using Microsoft.Framework.Runtime.Infrastructure;
namespace ConsoleTest
{
public class Program
{
private Action<IApplicationBuilder> _app;
private IServiceProvider _services;
public async Task<string> TestMe()
{
var server = TestServer.Create(_services, _app);
var client = server.CreateClient();
return await client.GetStringAsync("http://localhost/home/svg?idx=1");
}
public void Main(string[] args)
{
_services = CallContextServiceLocator.Locator.ServiceProvider;
_app = new Startup().Configure;
var x = TestMe();
x.Wait();
Console.WriteLine(x.Result);
Console.ReadLine();
}
}
}
Startup.cs
using Microsoft.AspNet.Builder;
using Microsoft.Framework.DependencyInjection;
using Microsoft.AspNet.Routing;
namespace ConsoleTest
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseServices(services =>
{
// Add MVC services to the services container
services.AddMvc();
});
//Configure WebFx
app.UseMvc(routes =>
{
routes.MapRoute(
null,
"{controller}/{action}",
new { controller = "Home", action = "Index" });
});
}
}
}

MvvmCross: NotImplementedException calling EnsureFolderExists method of IMvxFileStore

I'm developing my first Windows Store App, using MvvmCross framework and I have a problem with images management. In particular I have the following simple ViewModel in my PCL project, and a Store project with a button bound with AddPictureCommand.
public class FirstViewModel : MvxViewModel
{
IMvxPictureChooserTask _pictureChooserTask;
IMvxFileStore _fileStore;
public FirstViewModel(IMvxPictureChooserTask pictureChooserTask, IMvxFileStore fileStore)
{
_pictureChooserTask = pictureChooserTask;
_fileStore = fileStore;
}
private byte[] _pictureBytes;
public byte[] PictureBytes
{
get { return _pictureBytes; }
set
{
if (_pictureBytes == value) return;
_pictureBytes = value;
RaisePropertyChanged(() => PictureBytes);
}
}
public ICommand AddPictureCommand
{
get { return new MvxCommand(() =>
{
_pictureChooserTask.ChoosePictureFromLibrary(400, 95, pictureAvailable, () => { });
}); }
}
private void pictureAvailable(Stream stream)
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
PictureBytes = memoryStream.ToArray();
GenerateImagePath();
}
private string GenerateImagePath()
{
if (PictureBytes == null) return null;
var RandomFileName = "Image" + Guid.NewGuid().ToString("N") + ".jpg";
_fileStore.EnsureFolderExists("Images");
var path = _fileStore.PathCombine("Images", RandomFileName);
_fileStore.WriteFile(path, PictureBytes);
return path;
}
}
The problem is that the method _fileStore.EnsureFolderExists("Images");
gives me the an "NotImplementedException" with message: "Need to implement this - doesn't seem obvious from the StorageFolder API".
Has anyone already seen it before?
Thank you
This not implemented exception is documented in the wiki - see https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#File
It should be fairly straightforward to implement these missing methods if they are required. Indeed I know of at least 2 users that have implemented these - but sadly they've not contributed them back.
to implement them, just
fork (copy) the code from https://github.com/MvvmCross/MvvmCross/blob/v3/Plugins/Cirrious/File/Cirrious.MvvmCross.Plugins.File.WindowsStore/MvxWindowsStoreBlockingFileStore.cs
implement the missing methods using the winrt StorageFolder apis
in your Store UI project, don't load the File plugin - so comment out or remove the File bootstrap class.
during setup, register your implementation with ioc using Mvx.RegisterType - e.g.:
protected override void InitializeFirstChance()
{
base.InitializeFirstChance();
Cirrious.CrossCore.Mvx.RegisterType<IMvxFileStore, MyFileStore>();
}
For more on using ioc, see https://github.com/MvvmCross/MvvmCross/wiki/Service-Location-and-Inversion-of-Control
For more on customising the setup sequence, see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup
Following Stuart's suggestions I've implemented the following methods for Windows 8 Store App:
public bool FolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
return false;
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in FolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
return true;
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
public void EnsureFolderExists(string folderPath)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
}
catch (FileNotFoundException)
{
var localFolder = ToFullPath(string.Empty);
var storageFolder = StorageFolder.GetFolderFromPathAsync(localFolder).Await();
storageFolder.CreateFolderAsync(folderPath).Await();
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in EnsureFolderExists - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - doesn't seem obvious from the StorageFolder API");
//var folder = StorageFolder.GetFolderFromPathAsync(ToFullPath(folderPath)).Await();
}
The third method we need to implement is DeleteFolder(string folderPath, bool recursive). Unfortunately StorageFolder method "DeleteFolder" doesn't have a "recursive" parameter. So I should implement DeleteFolder ignoring it:
public void DeleteFolder(string folderPath, bool recursive)
{
try
{
var directory = ToFullPath(folderPath);
var storageFolder = StorageFolder.GetFolderFromPathAsync(directory).Await();
storageFolder.DeleteAsync().Await();
}
catch (FileNotFoundException)
{
//Folder doesn't exist. Nothing to do
}
catch (Exception ex)
{
MvxTrace.Trace("Exception in DeleteFolder - folderPath: {0} - {1}", folderPath, ex.ToLongString());
throw ex;
}
//throw new NotImplementedException("Need to implement this - See EnsureFolderExists");
}
or I should check if the folder is empty before to delete it if "recursive" equals false.
Better implementations are welcomed.

Detect maintenance mode scom agent (aka MOM)

Is there a way programatically to find out if the SCOM agent is in Maintenance Mode.
This could be done by calling cmdlets.
Add-PSSnapin Microsoft.EnterpriseManagement.OperationsManager.Client
Get-Agent
Add Reference to
System.Management.Automation.dll
public class ExecuteCmdlet
{
public static InitialSessionState state;
public static RunspacePool pool;
static ExecuteCmdlet()
{
Console.WriteLine("Creating Initial State");
state = InitialSessionState.CreateDefault();
try
{
PSSnapInException ex = null;
state.ImportPSSnapIn("Microsoft.EnterpriseManagement.OperationsManager.Client", out ex);
}
catch { }
pool = RunspaceFactory.CreateRunspacePool(state);
pool.SetMinRunspaces(3);
pool.SetMaxRunspaces(10);
pool.Open();
}
public static Collection<PSObject> Execute(string cmd)
{
PowerShell gpc = PowerShell.Create();
// Specify the runspace to use and add commands.
gpc.RunspacePool = pool;
gpc.AddCommand(cmd);
return gpc.Invoke();
}
}