I'm a beginner programmer. I have a database file (MyDatabase.sdf) in my windows phone mango app. What I am trying to accomplish is copy and convert the MyDatabase.sdf file as MyDatabaseBackup.txt in isolated storage and then upload it to skydrive as backup. Since skydrive doesn't support .sdf files to be uploaded some people have suggested this conversion method and have got it to work.
So I am trying to do the same but I'm unable to copy the .sdf file to .txt file in isolated storage. Here's my code...
//START BACKUP
private void Backup_Click(object sender, RoutedEventArgs e)
{
if (client == null || client.Session == null)
{
MessageBox.Show("You must sign in first.");
}
else
{
if (MessageBox.Show("Are you sure you want to backup? This will overwrite your old backup file!", "Backup?", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
UploadFile();
}
}
public void UploadFile()
{
if (skyDriveFolderID != string.Empty) //the folder must exist, it should have already been created
{
this.client.UploadCompleted
+= new EventHandler<LiveOperationCompletedEventArgs>(ISFile_UploadCompleted);
infoTextBlock.Text = "Uploading backup...";
dateTextBlock.Text = "";
using (AppDataContext appDB = new AppDataContext(AppDataContext.DBConnectionString))
{
appDB.Dispose();
}
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists("MyDatabase.sdf"))
{
myIsolatedStorage.CopyFile("MyDatabase.sdf", "MyDatabaseBackup.txt"); //This is where it goes to the catch statement.
}
this.client.UploadAsync(skyDriveFolderID, fileName, true, readStream , null);
}
}
catch
{
MessageBox.Show("Error accessing IsolatedStorage. Please close the app and re-open it, and then try backing up again!", "Backup Failed", MessageBoxButton.OK);
infoTextBlock.Text = "Error. Close the app and start again.";
dateTextBlock.Text = "";
}
}
}
private void ISFile_UploadCompleted(object sender, LiveOperationCompletedEventArgs args)
{
if (args.Error == null)
{
infoTextBlock.Text = "Backup complete.";
dateTextBlock.Text = "Checking for new backup...";
//get the newly created fileID's (it will update the time too, and enable restoring)
client = new LiveConnectClient(session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(getFiles_GetCompleted);
client.GetAsync(skyDriveFolderID + "/files");
}
else
{
this.infoTextBlock.Text =
"Error uploading file: " + args.Error.ToString();
}
}
Here's how I am creating the database in my app.xaml.cs file.
// Specify the local database connection string.
string DBConnectionString = "Data Source=isostore:/MyDatabase.sdf";
// Create the database if it does not exist.
using (AppDataContext appDB = new AppDataContext(AppDataContext.DBConnectionString))
{
if (appDB.DatabaseExists() == false)
{
//Create the database
appDB.CreateDatabase();
appDB.SubmitChanges();
}
}
Some have suggested that make sure "no processes/functions/threads have the sdf file open."
I tried to that in the UploadFile() method but I am not entirely sure if I did it correctly.
Can someone please give some code help on these two issues. Thanks for the help!
First, create the local copy using File.Copy method as shown below, then upload the .txt file:
File.Copy (Path.Combine ([DbFileDir], MyDatabase.sdf), Path.Combine ([SomeLocalDir], MyDatabaseBackup.txt), true)
Note: you have to have proper access rights to the original/new local folders.
Hope this will help. Rgds,
Related
I have installed SenseNet version 6.5 (Code from codeplex). Wanted to upload the files in content repositry using Sensenet Client API, unfortunately it is not working with bulk upload.
string [] fileEntries = Directory.GetFiles(#"C:\Users\conyna\Downloads\Chirag");
foreach (string fileName in fileEntries)
{
using (Stream fs = File.OpenRead(fileName))
{
string fn = Path.GetFileName(fileName);
Task<SenseNet.Client.Content> x = SenseNet.Client.Content.UploadAsync("/Root/Sites/Default_Site/workspaces/(apps)/DocumentLibrary", fn, fs);
}
}
There are two problems with the code above:
you have to 'await' for async methods. Currently you start the task with the UploadAsync method, but you do not wait for it to finish, which casuses problems, because the file stream closes immediately after starting the upload task. Please upload files in an async way (of course you'll have to make your caller method async too, but that is the point of using an async api):
await Content.UploadAsync(...)
You may also consider using the Importer class in the client, it is able to import full directory structures.
You are trying to upload into an (apps) folder, which is not a correct target, that was designed to contain applications (mostly pages). It would be better if you uploaded into a document library in a workspace, for example:
/Root/Sites/Default_Site/workspaces/Document/SampleWorkspace/DocumentLibrary
We created a small application with SN ClientLibrary. I think, you can use this application/information/code.
This application can upload entire folders via Client Libray. Please check it out my Github repository: https://github.com/marosvolgyiz/SNClientLibraryUploader
There is relevant upload method:
public async Task Upload()
{
try
{
Console.WriteLine("Initilization...");
ClientContext.Initialize(new[] { sctx });
Console.WriteLine("Upload Started");
//Is Parent exists
var content = await Content.LoadAsync(Target);
if (content != null)
{
//Uploading files
var tasks = new List<Task>();
foreach (var file in Files)
{
string fileTargetFolder = Target + file.DirectoryName.Replace(Source, "").Replace(BaseDirectory, "").Replace("\\", "/");
var fileTargetContentFolder = await Content.LoadAsync(fileTargetFolder);
if (fileTargetContentFolder == null)
{
if (CreateFolderPath(Target, file.DirectoryName.Replace(Source, "")))
{
fileTargetContentFolder = await Content.LoadAsync(fileTargetFolder);
Console.WriteLine("#Upload file: " + file.FullName);
tasks.Add(Content.UploadAsync(fileTargetContentFolder.Id, file.Name, file.OpenRead()));
LoggerClass.LogToCSV("File uploaded", file.Name);
}
else
{
LoggerClass.LogToCSV("File target folder does not exist or you do not have enough permission to see! File can not be uploaded. ", file.Name);
}
}
else
{
Console.WriteLine("#Upload file: " + file.FullName);
tasks.Add(Content.UploadAsync(fileTargetContentFolder.Id, file.Name, file.OpenRead()));
LoggerClass.LogToCSV("File uploaded", file.Name);
}
}
await Task.WhenAll(tasks);
}
else
{
Console.WriteLine("Target does not exist or you do not have enough permission to see!");
LoggerClass.LogToCSV("Target does not exist or you do not have enough permission to see!");
}
Console.WriteLine("Upload finished.");
}
catch (Exception ex)
{
LoggerClass.LogToCSV(ex.Message);
}
}
I hope my answer is helpful to you.
Br,
maros
I am developing a plugin using org.sonarsource.sonarqube:sonar-plugin-api:6.3. I am trying to access a file in my resource folder. The reading works fine in unit testing, but when it is deployed as a jar into sonarqube, it couldn't locate the file.
For example, I have the file Something.txt in src/main/resources. Then, I have the following code
private static final String FILENAME = "Something.txt";
String template = FileUtils.readFile(FILENAME);
where FileUtils.readFile would look like
public String readFile(String filePath) {
try {
return readAsStream(filePath);
} catch (IOException ioException) {
LOGGER.error("Error reading file {}, {}", filePath, ioException.getMessage());
return null;
}
}
private String readAsStream(String filePath) throws IOException {
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath)) {
if (inputStream == null) {
throw new IOException(filePath + " is not found");
} else {
return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
}
}
}
This question is similar with reading a resource file from within a jar. I also have tried with /Something.txt and Something.txt, both does not work.If I put the file Something.txt in the classes folder in sonarqube installation folder, the code will work.
Try this:
File file = new File(getClass().getResource("/Something.txt").toURI());
BufferredReader reader = new BufferedReader(new FileReader(file));
String something = IOUtils.toString(reader);
Your should not use getContextClassLoader(). see Short answer: never use the context class loader!
Managed to download .zip file to my filesystem on mobile phone. But after a while realised I can't find a way how to unzip that file. As I tried with:
https://github.com/plrthink/react-native-zip-archive
https://github.com/remobile/react-native-zip
First one dies immidiately after requiring, getting error "Cannot read property 'unzip' of undefined" (followed instructions carefully)
And the second one dies because it's dependant on codrova port to react native which also doesn't work.
Any suggestions or way to solve these problems?
Using react-native 0.35, testing on Note4 with android 5.1.1.
I did manage in the end solve my problem:
using react-native-zip-archive
the solution was to change code inside:
RNZipArchiveModule.java file which is inside module
The changes that needed to be applied are written in this comment:
https://github.com/plrthink/react-native-zip-archive/issues/14#issuecomment-261712319
So credits to hujiudeyang for solving problem.
go to this direction :
node_modules\react-native-zip-archive\android\src\main\java\com\rnziparchive\RNZipArchiveModule.java
and replace this codes instead of unzip method
public static void customUnzip(File zipFile, File targetDirectory) throws IOException {
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = zis.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " +
dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
/* if time should be restored as well
long time = ze.getTime();
if (time > 0)
file.setLastModified(time);
*/
}
} finally {
zis.close();
}
}
//**************************
#ReactMethod
public void unzip(final String zipFilePath, final String destDirectory, final String charset, final Promise promise) {
new Thread(new Runnable() {
#Override
public void run() {
try {
customUnzip(new File(zipFilePath ) , new File(destDirectory));
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
I have the following code for saving image in mongodb:
public static void insertImage() throws Exception {
String newFileName = "mkyong-java-image";
File imageFile = new File("c:\\JavaWebHosting.png");
GridFS gfsPhoto = new GridFS(db, "photo");
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
gfsFile.setFilename(newFileName);
gfsFile.save();
}
And I got this from this link:
link for code
But when I use that I get the following error and I do not know how to fix it ... Can anyone help?
Exception in thread "main" java.lang.NullPointerException
at com.mongodb.gridfs.GridFS.<init>(GridFS.java:97)
for more explanation the error is at exactly this line:
GridFS gfsPhoto = new GridFS(db, "photo");
Update:
Here is the code for creating db connection
public static DB getDBConnection() {
// If it's not connected to the database, make connection
if (db == null) {
initialize();
makeConnections();
}
return db;
}
private static void makeConnections() {
MongoCredential credential = MongoCredential.createMongoCRCredential(dbUser, dbName, dbPass.toCharArray());
MongoClient mongoClient;
try {
mongoClient = new MongoClient(new ServerAddress(dbHost, Integer.parseInt(dbPort)), Arrays.asList(credential));
db = mongoClient.getDB(dbName);
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
Update:
String newFileName = "mkyong-java-image";
File imageFile = new File("D:/1.jpg");
db = MongoDB.getDBConnection();
collection = db.getCollection("test");
// create a "photo" namespace
GridFS gfsPhoto = new GridFS(db, "photo");
// get image file from local drive
GridFSInputFile gfsFile = gfsPhoto.createFile(imageFile);
// set a new filename for identify purpose
gfsFile.setFilename(newFileName);
// save the image file into mongoDB
gfsFile.save();
// print the result
DBCursor cursor = gfsPhoto.getFileList();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
// get image file by it's filename
GridFSDBFile imageForOutput = gfsPhoto.findOne(newFileName);
// save it into a new image file
imageForOutput.writeTo("D:\\JavaWebHostingNew.jpg");
// remove the image file from mongoDB
// gfsPhoto.remove(gfsPhoto.findOne(newFileName));
System.out.println("Done");
I have an application for Windows CE 5 that uses Ado.net to backup/Restore the database I do simple copy.
Before restoring a database from a backup I use SqlCeEngine to verify that the database is OK and fix it if not. This works fine but when I restore large database after few times I get verify method returns false and the repair functions throw an exception
Could not load sqlcecompact30.dll. Operation has been aborted.
This happens now for every database file I want to restore until I exit the application.
Could not find the reason if I remove the test and repair everything is working OK and the database is OK but I want to check if the database is corrupted before restoring it.
I use the following CAB files to install the SQL on the PDA (iPAQ 310).
sqlce30.ppc.wce5.armv4i.CAB
sqlce30.repl.ppc.wce5.armv4i.CAB
Visual Studio 2005
Microsoft SQL server 2005 compact
Microsoft ssql Client 2.0
This is the code for verify and repair:
private static SqlCeEngine CreateEngine(string DBFileName)
{
return new SqlCeEngine("Data Source = '" + DBFileName + "'");
}
static public bool CheckDB(string DBFileName)
{
SqlCeEngine engine = null;
try
{
FileInfo file = new FileInfo(DBFileName);
if (file.Exists)
{
engine = CreateEngine(DBFileName);
return engine.Verify();
}
}
catch
{
}
finally
{
if (engine != null)
{
engine.Dispose();
}
}
return false;
}
static public bool RepairDB(string DBFileName)
{
SqlCeEngine engine = null;
try
{
FileInfo file = new FileInfo(DBFileName);
if (file.Exists)
{
engine = CreateEngine(DBFileName);
engine.Repair(null, RepairOption.RecoverCorruptedRows);
return engine.Verify();
}
}
catch (Exception ex)
{
Ness300Logger.Logger.Log("Repair failed: " + ex.Message);
}
finally
{
if (engine != null)
{
engine.Dispose();
}
}
return false;
}