I am developing a windows phone 8 app using sqlite and am trying to check if the database exists and if it doesnt exist,it should be created. but i keep getting the error message "System.windows.shapes.path does not contain a definition for combine". Is there another way to do it or how can i improve it?
public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ContactsManager.sqlite"));//DataBase Name
public App()
{
if (!CheckFileExists("ContactsManager.sqlite").Result)
{
using (var db = new SQLiteConnection(DB_PATH))
{
db.CreateTable<Contacts>();
}
}
}
private async Task<bool> CheckFileExists(string fileName)
{
try
{
var store = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(fileName);
return true;
}
catch
{
}
return false;
}
Do you really need to check if the database exist? I don't know about windows phone, but in Windows, as soon as you try to add a table into a SQLite database, if the database doesn't exist, it creates it. If you are worried about the table existing already, you can use:
CREATE TABLE IF NOT EXISTS tableName(...)
(I tried to ask it as comment but I don't have the reputation)
Why do you have a Path.Combine in a Path.Combine? If Path.Combine is not available with one or two parameter, why not simple concat two strings?
You have it 2x: public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ContactsManager.sqlite"));
you can check by this:
public async Task<bool> isFilePresent(string fileName)
{
return System.IO.File.Exists(string.Format(#"{0}\{1}", ApplicationData.Current.LocalFolder.Path, fileName);
}
#Panagiotis Kanavos's comment was right, you have resolved the Path class using wrong namespace!
Remove
using System.Windows.Shapes; // for silverlite
using Windows.UI.Xaml.Shapes; // for winrt
and add
using System.IO;
Related
Have installed NUGet packages for Xamarin.Forms for PCL. I have 4 projects for Droid, iOS, Win 8.1 and WinPhone 8.1. Tried to connect my database, but encountered trouble: my Win and WinPhone projects don`t see it or return me the wrong path. Followed official Xamarin.Forms forum.
Interface:
public interface ISQLite
{
string GetDatabasePath(string filename);
}
WInPhone Class:
using System.IO;
using Windows.Storage;
using Baumizer.WinPhone;
using Xamarin.Forms;
[assembly: Dependency(typeof(SQLite_WinPhone))]
namespace Baumizer.WinPhone
{
public class SQLite_WinPhone:ISQLite
{
public SQLite_WinPhone() { }
public string GetDatabasePath(string filename)
{
return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
}
}}
This class for selecting info:
public class DataBase
{
SQLiteConnection connection;
public DataBase()
{
connection= new SQLiteConnection(DependencyService.Get<ISQLite>().GetDatabasePath("Database.db"));
}
public IEnumerable<Group> GetGroups()
{
return connection.Query<Group>("SELECT * FROM [Scedule] WHERE [facultyName] =" + "'" + Data.CurrentFaculty + "'");
}
}
It works well on Android. On WinPhone I get exception of SQLite - no such table: Scedule. I open the local directory for emulator where db was - 0Kb.
I put db to Assets and set BuildInAction to Content. What`s wrong? Need help
On forum find this code, putted to OnLaunched(...) in WinPhone App.cs:
if(await ApplicationData.Current.LocalFolder.GetItemAsync(Data.DataBaseName) == null)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync($"Assets\\{Data.DataBaseName}");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
It copies DB if it's not exist, but it is. May be I need to delete DB 0Kb, but I don't know how to do this.
It's work, OnLaunched():
try
{
await ApplicationData.Current.LocalFolder.GetItemAsync("Scedule.db");
}
catch (System.IO.FileNotFoundException)
{
StorageFile databaseFile =
await Package.Current.InstalledLocation.GetFileAsync($"Assets\\{"Scedule.db"}");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
DB was uncorrectly copied. May be there are any another ways.
I've got a Windows 10 UWP application written in C#. I'm using SQLite to store my data locally. The issue I'm experiencing is that the file is never saved and/or retrieved using this code. It should work, but I can't find out what's wrong.
dbExists always evaluates to false, so what am I missing here?
private SQLiteConnection localConn;
private string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "myDatabase.db");
public async void DBInit()
{
bool dbExists = false;
try
{
var store = await ApplicationData.Current.LocalFolder.GetFileAsync(dbPath);
dbExists = true;
}
catch { dbExists = false; }
if (!dbExists)
{
using (localConn = new SQLiteConnection(new SQLitePlatformWinRT(), dbPath))
{
// Create table
localConn.CreateTable<MyTable>();
}
}
else // CURRENTLY NOT FIRING!!
{}
}
Please consider using below code to create and access database file:
StorageFile notesFile = await storageFolder.CreateFileAsync(dbPath, CreationCollisionOption.OpenIfExists);
This will create new file if it does not exists and retrieve it when it is already created.
Please check my blog article to see more about UWP Data Storage:
https://mobileprogrammerblog.wordpress.com/2016/05/23/universal-windows-10-apps-data-storage/
I think you're missing this important piece of code:
SQLiteConnection.CreateFile("mydatabase.sqlite");
Do that first, then create a connection instance referencing the (now) created file.
Also, I'd suggest that you name the db with the .sqlite extension, so that the rest of the team and incoming devs, when then look at the db file artifact, can immediately tell that this is an sqlite database.
EDIT:
The method is a static method. So you would use it like this...
using System.Data.SQLite;
namespace sqlite_sample
{
class Program
{
static void Main(string[] args)
{
SQLiteConnection.CreateFile("sample.db");
}
}
}
The following will not work:
var conn = SQLiteConnection(...);
conn.CreateFile(dbPath); //<-- static methods can't be invoked at the instance level...
I have this piece of code from one of my classes and when i hover over the semicolon next to "//error is here" "} Expected" but all the brackets are closed, i have no idea why its causing this, i tried rebuilding but nothing changes
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite.Net;
using SQLite.Net.Platform.WinRT;
namespace HomeAutomation
{
public class MainCode
{
static string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
static SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), path)
{
conn.CreateTable<User>;//ERROR IS HERE
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
}
You're using an object initiationalization. You don't use semi-colon in it b/c a semi-colon indicates the termination point of a command. You're not allowed to end a statement in the middle of initialization. You would separate each field you're initializing with a comma and then end the statement after the last curly brace.
Edit
It looks like you shouldn't be using object initialization after looking at the code again. This syntax is for initializing property on objects. You need to separate the two statments. I.e.
static SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), path); // End initialization statement
static MainCode()
{
conn.CreateTable<User>;//Initialize in static constructor
}
This conn.CreateTable<User>;//ERROR IS HERE should read
conn.CreateTable<User>();//solved
You forgot the brackets
Not sure if this will help but maybe try:
conn.CreateTable<User>("SELECT somethingHere FROM somewhere");
I think what you've done here to use the keyword static when you should have used using
Looking at what you're trying to achieve I'd suggest your code might need to look something like:
using SQLiteConnection conn = new SQLiteConnection(new SQLitePlatformWinRT(), path)
{
conn.CreateTable<User>();//ERROR IS HERE
}
What have I changed?
I've changed the word static to using and added the brackets to the end of the conn.CreateTable<User>()
Hope this helps!
I'm trying to submit a MapReduce job to HDInsight cluster. In my job I didn't write reduce portion because I don't want to reduce anything. All I want to do is to parse the each filename and append the values to every line in the file. So that I will have all the data needed inside the file.
My code is
using Microsoft.Hadoop.MapReduce;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetMetaDataFromFileName
{
class Program
{
static void Main(string[] args)
{
var hadoop = connectAzure();
//Temp Workaround to Env Variables
Environment.SetEnvironmentVariable("HADOOP_HOME", #"c:\hadoop");
Environment.SetEnvironmentVariable("Java_HOME", #"c:\hadoop\jvm");
var result = hadoop.MapReduceJob.ExecuteJob<MetaDataGetterJob>();
}
static IHadoop connectAzure()
{
//TODO: Update credentials and other information
return Hadoop.Connect(
new Uri("https://sampleclustername.azurehdinsight.net//"),
"admin",
"Hadoop",
"password",
"blobstoragename.blob.core.windows.net", //Storage Account that Log files exists
"AccessKeySample", //Storage Account Access Key
"logs", //Container Name
true
);
}
//Hadoop Mapper
public class MetaDataGetter : MapperBase
{
public override void Map(string inputLine, MapperContext context)
{
try
{
//Get the meta data from name of the file
string[] _fileMetaData = context.InputFilename.Split('_');
string _PublicIP = _fileMetaData[0].Trim();
string _PhysicalAdapterMAC = _fileMetaData[1].Trim();
string _BootID = _fileMetaData[2].Trim();
string _ServerUploadTime = _fileMetaData[3].Trim();
string _LogType = _fileMetaData[4].Trim();
string _MachineUpTime = _fileMetaData[5].Trim();
//Generate CSV portion
string _RowHeader = string.Format("{0},{1},{2},{3},{4},{5},", _PublicIP, _PhysicalAdapterMAC, _BootID, _ServerUploadTime, _LogType, _MachineUpTime);
//TODO: Append _RowHeader to every row in the file.
context.EmitLine(_RowHeader + inputLine);
}
catch(ArgumentException ex)
{
return;
}
}
}
//Hadoop Job Definition
public class MetaDataGetterJob : HadoopJob<MetaDataGetter>
{
public override HadoopJobConfiguration Configure(ExecutorContext context)
{
//Initiate the job config
HadoopJobConfiguration config = new HadoopJobConfiguration();
config.InputPath = "asv://logs#sample.blob.core.windows.net/Input";
config.OutputFolder = "asv://logs#sample.blob.core.windows.net/Output";
config.DeleteOutputFolder = true;
return config;
}
}
}
}
Usually what do you thing the reason of 500 (Server Error) ? Am I suppling to wrong credentials ? Actually I didn't really understand the difference between Username and HadoopUser parameters in Hadoop.Connect method ?
Thank you,
I had approximately same issue in the past (was unable to submit hive job to the cluster with BadGateway response). I have contacted the support team and in my case the problem was in memory leakage at the head node, what means that the problem was not at client's side and it seems to be inherited hadoop problem.
I've solved that stuff by redeploying the cluster.
Have you tried to submit other jobs (simple ones)? If so, than I suggest to have a contact with azure support team or just redeploy the cluster if it's not painful for you.
The full Code can be found here: http://home.htw-berlin.de/~s0531210/eb/DataBaseTest.zip
It is a simple Project with testing Entity Framework.
I have a DLL that allows access to a SQL Server Compact database. This access happens by Enttiy Framework 5.0.
A second project is a console application that accesses this DLL. When calling a class from the DLL to store sample data into the database, the exception is "Error underlying provider Open."
This exception occurs when calling: db.SaveChanges ();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseLibrary
{
public class SLD
{
public SLD()
{
}
public void enterData()
{
using (var db = new SLDDatabaseModelEntitiesContext())
{
for (int i = 0; i < 10; i++)
{
SLDEntity entrysfoo = new SLDEntity();
entrysfoo.Flip = i;
entrysfoo.Slidename = "bla" + i;
db.SLDEntity.Add(entrysfoo);
}
db.SaveChanges(); //DAtanbank speichern
}
}
public SLDEntity getFromDataBase(string wsiname)
{
using (var db = new SLDDatabaseModelEntitiesContext())
{
foreach (var item in db.SLDEntity)
{
if (item.Slidename.Equals(wsiname))
{
return item;
}
}
}
return new SLDEntity();
}
}
}
i hope you guys can help me. I have no clue where the problem is. I searched the internet and i found something about persmission iusses, but the connectionstring is reqiredpermissin=false.
thanks the tip with the connection string worked. The Database was not there where the App.config file from the consoleapp pointed at. but I do not understand why the connection string in the dll, which one also has a App.config File is ignored. If I want, that the connection string is available only in the DLL, Do I have to set the connection string in the DLL manually via a command?