C# fileSystemWatcher, Adding File names into Listbox Problem - filesystemwatcher

I'm using fileSystemWatcher for new files in to folder then I add their file names to a listbox. Program can dedect new files successfully but I'm facing problem adding file names into listbox since it adds same file names a couple of times if multiple files added into folder at same time. My codes are herebelow.
File Names : 1,2,3,4,
Listbox output: 2,3,2,3,2,3,4,1,2,3,4
void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
folderlist.Items.Add(file.Name);
}
}

Instead of finding the reason of the problem, I found a solution to avoid problem. I just checked whether item is already exist in the listbox. If not, add into listbox.
void watcher_FileCreated(object sender, FileSystemEventArgs e)
{
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
if (!folderlist.Items.Contains(file.Name))
{
folderlist.Items.Add(file.Name);
}
}
}

Related

How to debug FileSystemWatcher c#

Can someone explain how I debug this?
I have built a windows service which monitors a folder and when a file is created in that folder, it moves that newly created file to another folder. Pretty simple and works. I am trying to pad it out now with out features and I'm starting to get generic IOExpections thrown in event viewer, so I want to try and debug. But the issue I am having is when to create the new file in the directory during debugging.
This is my code so far
which line should I stop at during stepping through, place my new file in the directory and then continue debugging so that it picks up the created file?
public void OnDebug()
{
OnStart(null);
}
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
protected override void OnStart(string[] args)
{
string pathToWatch = ConfigurationManager.AppSettings["DirectoryToWatch"];
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = pathToWatch;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Created += new FileSystemEventHandler(FileCreated);
watcher.EnableRaisingEvents = true;
}
private void FileCreated(object source, FileSystemEventArgs e)
{
try
{
DateTime dt = File.GetCreationTime(e.FullPath);
File.Move(e.FullPath.ToString(), ConfigurationManager.AppSettings["DirectoryToMoveTo"] + e.Name + dt.ToString());
LogEvent($"New file found and moved \n {e.FullPath.ToString()}");
}
catch (IOException ex)
{
LogEvent(ex.ToString());
}
}
You can start by adding a breakpoint inside the function FileCreated.
I suggest you add a breakpoint at
DateTime dt = File.GetCreationTime(e.FullPath);
When you create a new file in the directory being watched, the FileSystemWatcher gets notified and the function FileCreated is called.
I also suggest you to log the destination path for your move. Just to make sure it's a valid path.

Using property files in Web Applications [duplicate]

This question already has answers here:
How to get properties file from /WEB-INF folder in JSF?
(3 answers)
Closed 7 years ago.
I'm developing a web application(this is my first time) and pretty confused about using property files. I don't know where to put the property files.
The problem is that i have put it under the WEB_INF folder. And when i test run it as a Java Application to check whether Database connections are working according to the properties in the property file it is working without any problem.
But when i run it in a Server as a Web Application it fails to load the properties file saying it could not find the file in the path specified. I tried using every possible path i could give and changing the file directories within the whole project. But I kept getting the same error.
Then i changed my class again from scratch thinking there's some kind of a bug withing my code where i load the properties file. And it seems that it could not find the file either when deployed as a Web App. But my test application works fine. Where do i put this file and how do i use it. I have read #BalusC's answer in this thread https://stackoverflow.com/a/2161583/2999358 but i have no idea why this happens. Can someone help me on this?
I'm using Tomcat 8, Eclipse IDE and building on JSF framework.
Class where i load my properties file
public class ConfigCache {
private static final File FILE = new File("./WebContent/WEB-INF/conf/config.properties");
private static final Properties PROPERTIES = new Properties();
public static final String JDBC_DRIVER = ConfigCache.getProperty("db.driverName");
public static final String DATABASE_URL = ConfigCache.getProperty("db.url");
public static final String DATABASE_USERNAME = ConfigCache.getProperty("db.user");
public static final String DATABASE_PASSWORD = ConfigCache.getProperty("db.pass");
public ConfigCache() {
}
public static String getProperty(String key) {
if (PROPERTIES.isEmpty()) {
loadProperties();
}
Object value;
return (value = PROPERTIES.get(key)) == null ? "" : value.toString();
}
private static void loadProperties() {
if (!FILE.exists()) {
throw new IllegalArgumentException("The 'config.properties' has not been found.");
}
try {
FileInputStream fis = null;
try {
fis = new FileInputStream(FILE);
PROPERTIES.load(fis);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (IOException exp) {
System.out.println("IOException #" + ConfigCache.class + " # loadProperties() : " + exp);
}
}
} catch (Exception exp) {
System.out.println("Exception #" + ConfigCache.class + " # loadProperties() : " + exp);
}
}
}
Folder Structure
Try With this.
put the property in src folder.
Your file is in the WEB-INF directory. This means it's part of the war and reachable as part of the class path. That's perfectly ok, since it makes it portable and independant of the web container installation (e.g. Tomcat).
You can load any file in the class path as a resource:
getClass().getResourceAsStream("/conf/config.properties")
This means you can write your code like this:
private static void loadProperties() {
InputStream is = getClass().getResourceAsStream("/conf/config.properties");
PROPERTIES.load(fis);
}
(Error handling omitted)
You can explode (unzip) your war/ear file and see the contents or folder structure of it and find why your code doesnt work. The reason is that the folder WebContent doesnt exist in your ear/war , but does exist only when run via eclipse. This is the reason why its always better to follow the solution provided in the link posted so that you can retrieve the porperty files from classpath. The below code fetches your property file in eclipse but not in the server.
private static final File FILE = new File("./WebContent/WEB-INF/conf/config.properties");
Contents of WAR file (from JournelDev), it contains WEB-INF directory but there would be no WebContent directory above it

Eclipse API: How to schedule a job that joins with another recently scheduled job?

More specifically, how do I create an IResource and then immediately delete an IResource that was created within the first IResource?
I am creating an IProject, and the Eclipse API automatically creates a ".project" IFile within the IProject. I want to delete the ".project" file that is inside the recently created IProject. Here's is my attempt, to give an idea:
project.create(null);
// Remove the .project file that was created with the IProject.
// Do I need a separate thread here, that waits until the project
// has been created?
IResource file = project.findMember(".project");
file.delete(false, null);
I believe that I am running into a race condition, correct? I think the solution would be to have findMember and delete methods wait until my project has been created (ie I want findMember and delete to "join" with the thread invoked by create). Is this the right approach?
Extra information
If interested, and to provide some context, this question is related to my efforts in the open source project Solstice. Specifically, I am addressing this issue where we are replicating the developer's workspace in real time. I am working on the ResourceSynchronizer that receives messages about changes in the developer's workspace and replicates those changes in the copy workspace. Thus, it receives a message to add an IProject, and then it receives another message to add the corresponding ".project". Since the IProject addition automatically adds the ".project", I am trying to remove the ".project" immediately after adding the IProject. If I try to add an ".project" when it already exists, a warning is generated. Thus, I am trying to avoid this warning.
Thank you.
If you have an existing .project file you can use it to create the project like this:
IWorkspace workspace = ResourcesPlugin.getWorkspace();
// Read the existing project file - this does not have to be in the workspace
IPath path = new Path(existingProjectFile);
IProjectDescription projectDesc = workspace.loadProjectDescription(path);
// Make sure project location is the default in the workspace
projectDesc.setLocation(null);
// Create 'handle' to project
IProject project = workspace.getRoot().getProject(projectName);
// Create the project using the existing description data
project.create(projectDesc, progress monitor);
The project.create should really be done in a WorkspaceModifyOperation.
My solution to the original post is below, which schedules a job to create an IProject, then joins and schedules another job to delete the .project. From what I have learned, this works because when Eclipse creates a new project, it does the following:
It creates the top-level directory for the project,
fires an ADDED event for the project.
It creates a .project file inside the project folder,
fires an ADDED event for the .project file.
// Create "FamilyMember" so each job will be recognized as being in the
// same "family". In this case, use the same "lastName".
private class FamilyMember extends Job
{
private String lastName;
public FamilyMember(String firstName, String lastName)
{
super(firstName + " " + lastName);
this.lastName = lastName;
}
#Override
protected IStatus run(#Nullable IProgressMonitor monitor)
{
// Take care of family business
return Status.OK_STATUS;
}
#Override
public boolean belongsTo(Object family) {
return lastName.equals(family);
}
}
In another method, do the following:
final IProject project = (IProject) resource; // Project to be created.
// Need to create a project that does not have a .project file.
// To do so, create a project, then delete its .project file.
Job createProjectJob = new FamilyMember("Create", "SyncProject")
{
#Override
protected IStatus run(#Nullable IProgressMonitor monitor)
{
try
{
ResourceUtility.createProject(project);
}
catch (CoreException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return Status.OK_STATUS;
}
};
// This job deletes the .project file from the final project defined above.
Job deleteProjectFileJob = new FamilyMember("Delete", "SyncProject")
{
#Override
protected IStatus run(#Nullable IProgressMonitor monitor)
{
try
{
project.findMember(".project").delete(false, null);
}
catch (CoreException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return Status.OK_STATUS;
}
};
// Schedule and join the jobs.
IJobManager manager = Job.getJobManager();
createProjectJob.schedule();
try
{
manager.join("SyncProject", null);
deleteProjectFileJob.schedule();
}
catch (OperationCanceledException | InterruptedException e)
{
SolsticeClient.getLogger().logWarning("Exception during project without .project creation: "
+ e);
}
The following links were also used:
http://www.eclipse.org/articles/Article-Concurrency/jobs-api.html
http://help.eclipse.org/indigo/ntopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/core/runtime/jobs/IJobManager.html

How to open file(Display), Which is stored in directory in c# when click on link button in gridview

How to open file(Display), Which is stored in directory in c# when click on link button in gridview.
In my application i am storing documents in directory.
I am displaying those documents path in gridview, Now i want to open particular document in new window or radwindow when click on link button of particular row.
My Code is.
protected void ImgBtnView_Click(object sender, EventArgs e)
{
try
{
GridViewRow clickedRow = ((ImageButton)sender).NamingContainer as GridViewRow;
Label lblID = (Label)clickedRow.FindControl("lblFileName");
string strDoc_FileName = lblID.Text.ToString();
filePath = lblID.Text.ToString();
// code to open file here ?
}
catch { }
}
here filePath is geting location of file. Now i want to open that file in radwindow..Thanks

VSTO Excel: Restore ListObject data source when reopening a file

I am working on an Excel 2010 template project. In my template I have many sheets with static ListObject controls in each of them. To initialize my ListObject, I bind a BindingList<MyCustomType> so it generates a column for each of my MyCustomType public properties. It is really handy because when the user some rows in the ListObject, it automatically fills up my BindingList instance. I added a button in the Excel ribbon so that the program can validate and commit these rows through an EDM. This is how I bind my data to the ListObject in the startup event handler of one of my Excel sheet.
public partial class MyCustomTypesSheet
{
private BindingList<MyCustomType> myCustomTypes;
private void OnStartup(object sender, System.EventArgs e)
{
ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData;
BindingList<MyCustomType> customTypes = new BindingList<MyCustomType>();
myCustomTypeTable.SetDataBinding(customTypes);
}
// Implementation detail...
}
Now my issue is that it is very likely that the user of this template will enter these rows in many sessions. It means that he will enter data, save the file, close it, reopen it, enter some new rows and eventually try to commit these rows when he thinks he is done. What I noticed is that when the Excel file created from the template is reopened, the DataSource property of my ListObject controls is null. Which means I have no way to get back the data from the ListObject into a BindingList<MyCustomType>. I have been searching and I found no automatic way to do that and I don't really want to make a piece of code that would crawl through all of the columns to recreate my MyCustomType instances. In an ideal world I would have done like this.
private void OnStartup(object sender, System.EventArgs e)
{
ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData;
BindingList<MyCustomType> customTypes = null;
if (myCustomTypeTable.DataSource == null) // Will always be null and erase previous data.
{
customTypes = new BindingList<MyCustomType>();
myCustomTypeTable.SetDataBinding(customTypes);
}
else
{
customTypes = myCustomTypeTable.DataSource as BindingList<MyCustomType>;
}
}
I have been doing a lot of research on this but I was not able to find a solution so I hope some of your can help me to resolve this issue.
Thanks.
As a last solution I decided that I would serialize my object list in XML and then add it as a XML custom part to my Excel file on save. But when I got into MSDN documentation to achieve this, I found out that there was 2 ways to persist data: XML custom part and data caching. And actually data caching was exactly the functionality I was looking for.
So I have been able to achieve my goal by simply using the CachedAttribute.
public partial class MyCustomTypesSheet
{
[Cached]
public BindingList<MyCustomType> MyCustomTypesDataSource { get; set; }
private void OnStartup(object sender, System.EventArgs e)
{
ExcelTools.ListObject myCustomTypeTable = this.MyCustomTypeData;
if (this.MyCustomTypesDataSource == null)
{
this.MyCustomTypesDataSource = new BindingList<MyCustomType>();
this.MyCustomTypesDataSource.Add(new MyCustomType());
}
myCustomTypeTable.SetDataBinding(this.MyCustomTypesDataSource);
}
private void InternalStartup()
{
this.Startup += new System.EventHandler(OnStartup);
}
}
It works like a charm. You can find more information about data caching in MSDN documentation.

Resources