experts.
I need to reload a file when it updated automatically in Liberty. To make it more clear, I want to make a path like "dropins" in liberty, it can automatically detect the change of files or we can scan this folder manually. I need to load the files in this folder when they changed.
I've no idea how to achieve this....
Could anyone here know about it?
Thx!
If you are not averse to writing a Liberty feature (not hard, but requires a little background reading), then you can register a listener for changes to specific files by implementing the com.ibm.wsspi.kernel.filemonitor.FileMonitor interface as a Declarative Service. Once registered as a DS, the Liberty file monitor will invoke your implementation's methods. It invokes onBaseline(Collection<File> baseline) on startup, and onChange(Collection<File> createdFiles, Collection<File> modifiedFiles, Collection<File> deletedFiles) when a change of some sort has occurred.
One implementation might look like this:
#Component(immediate="true", property={"monitor.directories=/path/to/myMonitoredDir"})
public class MyFileMonitor implements FileMonitor {
#Override
public void onBaseline(Collection<File> baseline) {
System.out.println("Initial file state:");
for (File f : baseline) {
System.out.println(f.getName());
}
}
#Override
public void onChange(Collection<File> createdFiles, Collection<File> modifiedFiles, Collection<File> deletedFiles) {
System.out.println("Newly added files:");
for (File f : createdFiles) {
System.out.println(f.getName());
}
System.out.println("Newly deleted files:");
for (File f : deletedFiles) {
System.out.println(f.getName());
}
System.out.println("Modified files:");
for (File f : modifiedFiles) {
System.out.println(f.getName());
}
}
}
Hope this helps,
Andy
Related
I'm trying to migrate my old Visual Studio extension to the new 2022 Studio. Found some fancy solution named 'Community Visual Studio Toolkit', but got some issues. When I use the ProvideAutoLoad attribute for loading my extension when a user opens some solution, I can't get access to the WindowEvents which I need to sign my event handlers. This is the error on debugging: https://snipboard.io/yUXIed.jpg
So this is the code I use, and here I have the error:
[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class MyPackage : ToolkitPackage
{
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.RegisterCommandsAsync();
VS.Events.WindowEvents.ActiveFrameChanged += WindowEvents_ActiveFrameChanged;
}
}
And the thing is my old implementation works with this code:
[ProvideAutoLoad(UIContextGuids80.NoSolution, PackageAutoLoadFlags.BackgroundLoad)]
public sealed class MyPackage : ToolkitPackage
{
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await this.RegisterCommandsAsync();
// Getting `DTE2 dte` trough standard way...
dte.Events.WindowEvents.WindowActivated += WindowEvents_WindowActivated;
}
}
But I don't want to use old kinds of code in the new extension version, so, how to fix this issue in first example of implementation?
Well, I'm not sure about the "perfection" of this solution, but with this line of code added before access to the events - it works.
await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);
Seems like you have to be in main thread to access these events.
I created a Windows Service starting from my .NET Core project following this
After this, I installed correctly it on my working machine and started it.
This is my service class:
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace xxx
{
public class WindowsService
{
static void Main(string[] args)
{
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
using (var service = new Service())
{
ServiceBase.Run(service);
}
}
}
internal class Service : ServiceBase
{
public Service()
{
ServiceName = "...";
}
protected override void OnStart(string[] args)
{
try
{
base.OnStart(args);
Task.Run(() => xxxx);
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
}
}
protected override void OnStop()
{
base.OnStop();
}
protected override void OnPause()
{
base.OnPause();
}
}
}
So, I copied the file and installed it also on a server. Here, when I try to start it, I get:
After this, I start a lot of googling... for example, I tried the following steps :
Go to Start > Run > and type regedit
Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
With the control folder selected, right click in the pane on the right and - select new DWORD Value
Name the new DWORD: ServicesPipeTimeout
Right-click ServicesPipeTimeout, and then click Modify
Click Decimal, type '180000', and then click OK
Restart the computer
The weird point here is that the voice ServicesPipeTimeout didn't exist and I created it. Comparing the server with my working machine, there are also other value not present in the server. They are:
ServicesPipeTimeout
OsBootstatPath
Here the screenshot of regedit from the server:
Are these relevant?
I also tried to reinstall the service, recompile my files... how can I fix this problem? The error appears immediatly, it doesn't wait any timeout!
I had this problem when I switched my project to another location.
When I moved the project, I had copied the files in bin/debug folder too. The issue was resolved after I cleared the debug folder and created a new build.
See if this works!
It's a bit old question but someone may find this useful.
So I had the following code in Program.cs:
builder.SetBasePath(Environment.CurrentDirectory).AddJsonFile("appsettings.json")
Changed it to:
builder.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).AddJsonFile("appsettings.json")
This seemed to fix the problem for me.
The problem with this error is that it is super generic.
Hopefully MS will give us some log in the future.
if you check the windows event viewer under applications it tells you what exactly is the exception that causes this error.
in my case the problem was i published the service in net6 and tried to run it on a pc with net7 installed. apparently it requires the exact major version that was used to publish the app.
How ImageSharp work with Dynamic Images loaded from Database?
Here my controller which get image file:
public async Task<FileResult> GetPhoto([FromQuery] GetFileAttachementInputAsync input)
{
var file = await filesAttachementAppService
.GetFileAsync(new GetFileAttachementInputAsync() { FileId = input.FileId })
.ConfigureAwait(false);
return file != null
? File(new MemoryStream(file.FileDto.FileContent), file.FileDto.ContentType, file.FileDto.FileName)
: null;
}
And this my Html call:
<img src="/PropertyAdministration/GetPhoto?FileId=#item.MainPhotoId&width=554&height=360" alt="" />
I am using ImageSharp as following:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddImageSharp();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
{
app.UseImageSharp();
}
What I am missing here to make this working?
You're not using the middleware nor the services that provide images to the middleware.
For the middleware to work it needs to be able capture an image request. With the default installation this is done by matching the request to an image source in your physical file system in wwwroot.
In your code though you've created an isolated action result returning a stream containing your image which the middleware has no awareness of.
Disclaimer, the following is based on the latest developer build 1.0.0-dev000131 and though unlikely to change could potentially change before final release.
https://www.myget.org/feed/sixlabors/package/nuget/SixLabors.ImageSharp.Web/1.0.0-dev000131
In order to provide images from a custom source you will need to create your own implementation of the IImageProvider and IImageResolver you can use examples in the source to base your implementation from.
Once implemented you will need to register the implementations via dependency injection. This needs to use a more fine grained registration since you are no longer using the defaults.
// Fine-grain control adding the default options and configure all other services. Setting all services is required.
services.AddImageSharpCore()
.SetRequestParser<QueryCollectionRequestParser>()
.SetBufferManager<PooledBufferManager>()
.SetMemoryAllocatorFromMiddlewareOptions()
.SetCacheHash<CacheHash>()
.AddProvider<PhysicalFileSystemProvider>()
/// Add your provider here via AddProvider<T>().
.AddProvider<PhysicalFileSystemProvider>()
.AddProcessor<ResizeWebProcessor>()
.AddProcessor<FormatWebProcessor>()
.AddProcessor<BackgroundColorWebProcessor>();
You should then be able to remove your action result completely and use the IImageProvider and IImageResolver combination to identify the request and return the image.
in my wicket application settings I wish to mount a username parameter on the root like
mountPage (Profile.class, "/${username}") similar to how twitter maps the usernames to its accounts. In wicket this seems to crash the resource location algorithm. In the sense that all css, js files now load with 404.
Is there a work around this?
The code should look like: mountPage (Profile.class, "/${username}"). Note the $ that I've added. This means the named path parameter is mandatory.
Please give more details about the problem if this doesn't solve the issue.
Thanks to martin-g. Override the MountMapper with set the url segments to 1 so it doesn't map to other resources.
public class UsernameMountUrlMapper extends MountedMapper {
public UsernameMountUrlMapper(String mountPath,
Class<? extends IRequestablePage> pageClass) {
super(mountPath, pageClass);
}
#Override
protected boolean urlStartsWithMountedSegments(Url url) {
return url.getSegments().size() == 1 && !url.getPath().equals("favicon.ico") && !url.getPath().equals("oops") && !url.getPath().equals("Index");
}
}
So, I'm working on my first ASP.NET MVC 3 application and one thing I need to do is handle some data that is exported from someone else's system and turn around and import it, on user action, into the system and perform some error checking, etc. on it.
Here's how I have attempted to solve this issue:
I've got a view with a div:
<div>
<span><b>Recipe Data:</b>
<input type="file" name="uploadFile" />
<input type="submit" value="Load" />
</span>
</div>
and that allows me to choose a file and then submit it. Then I've got a controller action that looks like this:
[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
try
{
// attempt to read the file
}
catch (Exception)
{
throw;
}
}
So, when I'm using IE, I can examine the uploadFile parameter and it gives me a path like:
FileName:c:\\Users\\Matt\\Desktop\\TestFiles\\AppleBerry.xml
(which is exactly the full path to the file I picked)
But when I try the same thing in FireFox, that path is stripped off, so uploadFile.FileName is just AppleBerry.xml and the XDocument.Load tries to load it from:
C:\Program Files (x86)\Common files\Microsoft Shared\DevServer\10.0\AppleBerry.xml
So, I'm pretty sure that I'm going about this the wrong way and need some guidance. I need to read in that XML file, preferably via XDocument.Load() and then do some checks and eventually push the records in that xml file into a DB table. The only part I'm having issues with is this file path. Any help you can provide with this would be most appreciated.
Try loading the file directly from the request stream and don't rely on the FileName property because you haven't saved the file on the server yet so it won't find it:
[HttpPost]
public ActionResult Index(HttpPostedFileBase uploadFile)
{
if (uploadFile != null && uploadFile.ContentLength > 0)
{
try
{
// attempt to read the file
var doc = XDocument.Load(uploadFile.InputStream);
// TODO: do something with the XML document
}
catch (Exception)
{
// Make sure you do something more meaningful here
// instead of rethrowing and erasing the stacktrace
throw;
}
}
else
{
// The user didn't upload any file => take respective actions
}
}
The server does not have access to the client's file system so the original path is irrelevant. Furthermore the file is not saved onto the server file system, so you should be loading it from the InputStream property, as per Darin's answer.