Create .db file in SD-CARD after checking its existence in blackberry? - file

I am working to create a db file in my application. Now I want to create the .db file on application installation just one time.
When I open the app, it just check for the existence of the file.
How can we check for a .db file in sdcard and if it exists before installation than to delete the file.

You can check if file exists or not using following code
FileConnection fileConnection = (FileConnection)Connector.open("file:///SDCard/foldername/" + "databasename.db");
boolean result=fileConnection.exists();
if(result)
{
//database available
}else{
//database not available
}
and next you want to check this when application first time instalation using
CodeModuleListener listner=new CodeModuleListener() {
public void modulesDeleted(String[] moduleNames) {
// TODO Auto-generated method stub
}
public void modulesAdded(int[] handles) {
// TODO Auto-generated method stub
//here you can check if database available or not if available then delete
try{
URI myURI = URI.create("file:///SDCard/foldername/" + "database_name.db");
DatabaseFactory.delete(myURI);
}catch (Exception e) {
// TODO: handle exception
}
}
public void moduleDeletionsPending(String[] moduleNames) {
// TODO Auto-generated method stub
}
};
CodeModuleManager.addListener(this.getApplication(), listner);

Related

In VS Installer Project, Commit() is not working properly

Using the Visual Studio Installer Project, I included the initial setup project in Install and Commit in Custom Actions that will perform the downloading of the cabinet file under the Windows\Temp\Target Folder folder. Consequently, the zip file will be unzipped.
I used async/await for the first time in DownloadCatalog(), but the zip file wasn't properly downloaded, even though the directory was created. I assumed the installing process stopped the downloading process. I then changed it.
I created the installation file without async. Then I ran it, but the result was the same. This code works fine when running it in an independent project. Do you have any suggestions?
namespace IntialSetupApp
{
[RunInstaller(true)]
public partial class IntialInstallApp : System.Configuration.Install.Installer
{
private readonly string temp = #"C:\Windows\Temp\Target Folder\";
private readonly string zipUrl = #"https://thank.you/so.much";
private readonly string catalog = #"C:\Windows\Temp\Target Folder\whateverXML.xml";
public IntialInstallApp()
{
InitializeComponent();
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
Directory.CreateDirectory(temp);
DownloadCatalog();
}
private Task DownloadCatalog()
{
try
{
string fileName = Path.Combine(temp, "ZippedCab.cab");
Uri uri = new Uri(url);
using (WebClient client = new WebClient())
{
client.DownloadFile(uri, fileName);
}
UnzipFile(fileName);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return Task.FromResult(true);
}
private Task UnzipFile(string filePath)
{
try
{
CabInfo cab = new CabInfo(filePath);
cab.Unpack(temp);
return Task.FromResult(true);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return Task.FromResult(false);
}
}
}
+Update
With the above code, I created the console project independently, and it created the folder and completed downloading the file. Therefore, it seems that installer prevents modifying other folders. Is there any workaround way?
The reason was The request was aborted: Could not create SSL/TLS secure channel., so I updated the code with this. Then it works fine.

zipme implementation in codenameone

I want to apply unzipping the file using zipme cn1 library (codenameone library). Is there any examples on how to do it? Can anyone give me the starting point? So far I have tried the following code but I am not sure where to keep dataName.zip file in the project and the folder to keep all the files after unzipping.
#Override
protected void beforeMain(Form f) {
net.sf.zipme.ZipEntry dataZE;
InputStream isData = getClass().getResourceAsStream("/" + "dataName" + ".zip");
StringBuffer sbData = new StringBuffer();
ZipInputStream dataZIS = new ZipInputStream(isData);
try {
while ((dataZE = dataZIS.getNextEntry()) != null) {
//how to extract the zip file in a separate folder...
dataZIS.closeEntry();
}
} catch (IOException ex) {
System.out.println("zip exception");
}
}
The above code gives following error:
cannot find symbol
InputStream isData = getClass().getResourceAsStream("");
symbol: method getResourceAsStream(String)
One more thing, why cant I use the following to get the zip file as in core java
ZipInputStream zis = new ZipInputStream(new FileInputStream("C:\\abc.zip"));
// it gives "FileInputStream: cannot find symbol"
How can I extract the zip file in a separate folder?
You should use Display.getInstance().getResourceAsStream().
FileInputStream isn't supported in Codename One which uses FileSystemStorage. The FileInputStream and File API's assume many things about the underlying OS that aren't always true.

Best practices for file system of application data JavaFX

I am trying to build an inventory management system and have recently asked a question about how to be able to store images in a package within my src file. I was told that you should not store images where class files are stored but have not been told what the best practices are for file systems. I have created a new page that allows the user to input all the data about a new part that they are adding to the system and upload an image associated with the part. When they save, everything worked fine until you try to reload the parts database. If you 'refresh' eclipse and then update the database, everything was fine because you could see the image pop into the package when refreshed. (All database info was updated properly as well.
I was told not to store these types of 'new' images with the program files but to create a separate file system to store these types of images. Is there a best practice for these types of file systems? My confusion is when the program gets saved where ever it is going to be saved, I can't have it point to an absolute path because it might not be saved on a C drive or K drive and I wouldn't want an images folder just sitting on the C drive that has all of the parts images for anyone to mess with. Please give me some good resources on how to build these file systems. I would like the images folder 'packaged' with the program when I compile it and package all the files together, I have not been able to find any good information on this, thanks!
To answer this question, probably not in the best way, but works pretty well.
I ended up making another menuItem and menu that you can see at the top 'Image Management', where it lets the user set the location that they would like to save all the images as well as a location to back up the images. it creates the directory if it is not there or it will save over the images if the directory is already there. This menu will only appear if the user has admin privileges. I would think that this could be set up with an install wizard, but I have no idea how to make one, where it only runs on installation. I am also going to add an autosave feature to save to both locations if a backup location has been set. This is the best way I can think of managing all the parts images, if anyone has some good input, please let me know. I considered a server, but think that is too much for this application and retrieving images every time the tableView populates would take a lot of time. If interested the code I used is:
public class ImageDirectoryController implements Initializable{
#FXML private AnchorPane imageDirectory;
#FXML private Label imageDirLbl, backupLbl;
#FXML private Button setLocationButton, backupButton;
#FXML private TextField imageDirPathTxtField;
Stage window;
String image_directory;
#Override
public void initialize(URL location, ResourceBundle resources) {
// TODO Auto-generated method stub
}
public void setImageDirectory(String image_address, String backup_address) {
imageDirLbl.setText(image_address);
backupLbl.setText(backup_address);
}
#FXML
public void setLocationButtonClicked () {
String imagesPath = imageDirPathTxtField.getText() + "tolmarImages\\";
File files = new File(imagesPath + "asepticImages");
File generalFiles = new File(imagesPath + "generalImages");
File facilitiesFiles = new File(imagesPath + "facilitiesImages");
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to set this location?");
if(answer) {
if (!files.exists()) {
if (files.mkdirs() && generalFiles.mkdirs() && facilitiesFiles.mkdirs()) {
JOptionPane.showMessageDialog (null, "New Image directories have been created!", "Image directory created", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog (null, "Failed to create multiple directories!", "Image directory not created", JOptionPane.INFORMATION_MESSAGE);
}
}
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = ?";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, imageDirPathTxtField.getText());
myStmt.setInt(2, 1);
myStmt.executeUpdate();
myStmt.close();
imageDirPathTxtField.clear();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#FXML
public void backupButtonClicked () {
String backupStatus = null;
if (backupLbl.getText().equals("")&& !imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!imageDirPathTxtField.getText().equals("")) {
backupStatus = imageDirPathTxtField.getText();
} else if (!backupLbl.getText().equals("")){
backupStatus = backupLbl.getText();
} else {
JOptionPane.showMessageDialog(null, "You must create a directory.", "No directory created", JOptionPane.INFORMATION_MESSAGE);
return;
}
boolean answer = ConfirmBox.display("Set Image", "Are you sure you want to backup the images?");
if(answer) {
DBConnection dBC = new DBConnection();
Connection con = dBC.getDBConnection();
String updateStmt = "UPDATE image_address SET image_address = ? WHERE rowid = 2";
try {
PreparedStatement myStmt = con.prepareStatement(updateStmt);
myStmt.setString(1, backupStatus);
myStmt.executeUpdate();
myStmt.close();
String source = imageDirLbl.getText() + "tolmarImages";
File srcDir = new File(source);
String destination = backupStatus + "tolmarImages";
File destDir = new File(destination);
try {
FileUtils.copyDirectory(srcDir, destDir);
JOptionPane.showMessageDialog(null, "Images copied successfully.", "Images copied", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

Windows Phone 8.1 | How to determine if file exists in local folder?

How to determine if file exists in local folder (Windows.Storage.ApplicationData.Current.LocalFolder)
on Windows Phone 8.1?
Unfortunately there is no direct method for now to check if file exists. You can try to use one of two methods:
get a file, and if exception is thrown then it means that file doesn't exist,
list all files and check if there is one with searched filename
A simple extension methods can look like this:
public static class FileExtensions
{
public static async Task<bool> FileExists(this StorageFolder folder, string fileName)
{
try { StorageFile file = await folder.GetFileAsync(fileName); }
catch { return false; }
return true;
}
public static async Task<bool> FileExist2(this StorageFolder folder, string fileName)
{ return (await folder.GetFilesAsync()).Any(x => x.Name.Equals(fileName)); }
}
Then you can use them like this:
bool isFile = await ApplicationData.Current.LocalFolder.FileExists("myfile.txt");
The second method can be little faster in case the file doesn't exist and there are few files in a folder, hence the exception is not being thrown.

Silverlight file upload - file is in use by another process (Excel, Word)

all. I have a problem with uploading of the file in Silverlight application. Here is a code sample. In case when this file is opened in other application (excel or word for example) it fails to open it, otherwise it's working fine. I'm using OpenFileDialog to choose the file and pass it to this function.
private byte[] GetFileContent(FileInfo file)
{
var result = new byte[] {};
try
{
using (var fs = file.OpenRead())
{
result = new byte[file.Length];
fs.Read(result, 0, (int)file.Length);
}
}
catch (Exception e)
{
// File is in use
}
return result;
}
Is there any way i can access this file or should i just notify the user that the file is locked?
You should notify the user that the file is currently in use by another program. If another program has the file open with a lock that does allow a shared read there is no way to bypass this lock.

Resources