using existing SqlCe database in windows phone - windows-phone-7

I have a SqlCe database which i made for another project. Now i want to use it for a windows phone project. My database structure is
I copied my database into my project folder and set it's build action as "content" and copy to output directory as "copy always".
In my main page i used this:
private const string Con_String = #"isostore:/mydb.sdf";
public MainPage()
{
InitializeComponent();
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
using (mTableDatabaseContext context = new mTableDatabaseContext(Con_String))
{
if (!context.DatabaseExists())
{
context.CreateDatabase();
}
if (!iso.FileExists("mydb.sdf"))
{
MoveReferenceDatabase();
}
}
}
public static void MoveReferenceDatabase()
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
using (Stream input = Application.GetResourceStream(new Uri("mydb.sdf", UriKind.Relative)).Stream)
{
using (IsolatedStorageFileStream output = iso.CreateFile("mydb.sdf"))
{
byte[] readBuffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = input.Read(readBuffer, 0, readBuffer.Length)) > 0)
{
output.Write(readBuffer, 0, bytesRead);
}
}
}
}
and my mTableDatabaseContext class is like that:
public class mTableDatabaseContext:DataContext
{
public mTableDatabaseContext(string connectionString): base(connectionString)
{
}
public Table<dic> my_dics
{
get
{
return this.GetTable<dic>();
}
}
public Table<learn_table> my_learn_tables
{
get
{
return this.GetTable<learn_table>();
}
}
}
But i cant use my database and copy of my database cant be performed???
What can i do to do this??
How can i do this?? Can anyone help me??

You should use
private const string Con_String = #"Data Source=isostore:/mydb.sdf";
instead of
private const string Con_String = #"isostore:/mydb.sdf";

Related

Xamarin Forms save image from an url into device's gallery

I am working on Xamarin Forms (with iOS and Android). What I want to do is to allow users to download image from an url by using DependencyService. I tried run in IOS emulator and the image did save into the emulator but does not show up in the gallery.
Appreciate help in that and following is my code:
In ViewModel:
public void DownloadImage()
{
IFileService fileSvc = DependencyService.Get<IFileService>();
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData(ImgUrl);
Stream stream = new MemoryStream(bytes);
fileSvc.SavePicture(DateTime.Now.ToString(), stream, "temp");
}
In Xamarin.iOS
public void SavePicture(string name, Stream data, string location = "temp")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string imageFilename = Path.Combine(documentsPath, "Images", location);
Directory.CreateDirectory(imageFilename);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
In Xamarin.Droid
public void SavePicture(string name, Stream data, string location = "temp")
{
var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
documentsPath = Path.Combine(documentsPath, "Images", location);
Directory.CreateDirectory(documentsPath);
string filePath = Path.Combine(documentsPath, name);
byte[] bArray = new byte[data.Length];
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (data)
{
data.Read(bArray, 0, (int)data.Length);
}
int length = bArray.Length;
fs.Write(bArray, 0, length);
}
}
If you Want to save image into Gallery, please follow the code below.
Firstly, create Create the IMediaService Interface in PCL.
public interface IMediaService
{
void SaveImageFromByte(byte[] imageByte,string filename);
}
Then implement this interface in Platform-specific
Xamarin.Android Project
public class MediaService : IMediaService
{
Context CurrentContext => CrossCurrentActivity.Current.Activity;
public void SaveImageFromByte(byte[] imageByte, string filename)
{
try
{
Java.IO.File storagePath = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures);
string path = System.IO.Path.Combine(storagePath.ToString(), filename);
System.IO.File.WriteAllBytes(path, imageByte);
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(path)));
CurrentContext.SendBroadcast(mediaScanIntent);
}
catch (Exception ex)
{
}
}
}
implement this interface in Platform-specific
Xamarin.iOS Project
public class MediaService : IMediaService
{
public void SaveImageFromByte(byte[] imageByte,string fileName)
{
var imageData = new UIImage(NSData.FromArray(imageByte));
imageData.SaveToPhotosAlbum((image, error) =>
{
//you can retrieve the saved UI Image as well if needed using
//var i = image as UIImage;
if (error != null)
{
Console.WriteLine(error.ToString());
}
});
}
}
For accessing the CurrentContext Install the NuGet Package (Plugin.CurrentActivity) from NuGet Package Manager, also check for the external storage permission.

SQLite support for Universal Windows App

I am using Xamarin Forms to develop an app and using SQlite to store the user details. Just started with windows(Windows 10). Does SQLite has support for UWP, I have referred some sites and its saying it does support. but when I am trying, the connection is always null.
The code i am using:
public SQLite.Net.SQLiteConnection GetConnection()
{
var sqliteFilename = "Sample.db3";
string path = Path.Combin(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
if (!File.Exists(path))
{
File.Create(path + sqliteFilename);
}
var plat = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
var conn = new SQLite.Net.SQLiteConnection(plat,path);
return conn;
}
}
Any help or suggestion would be much appreciated.
Note: I have installed the SQLite.Net-PCL and added reference to SQLite for Universal App Platform
Inside your App.cs I have a static variable called:
public static LocalDatabase Database { get; private set; }
public App()
{
Database = new LocalDatabase();...
}
And then you can access your Database class on any place of your controller like: App.Database
For reference LocalDatabase class will contain:
public class LocalDatabase
{
static readonly object locker = new object ();
static SQLiteConnection database;
string DatabasePath {
get {
const string sqliteFilename = "LocalDatabaseSQLite.db3";
#if __IOS__
string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder
string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder
var path = Path.Combine (libraryPath, sqliteFilename);
#else
#if __ANDROID__
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
#else
// WinPhone
var path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, sqliteFilename); ;
#endif
#endif
return path;
}
}
public LocalDatabase ()
{
database = new SQLiteConnection (DatabasePath);
database.CreateTable<UserSQLModel> ();
//All your create tables...
}
}

RadEditor.ImageManager not inserting image on clicking Insert

I have a radEditor control with the ImageManager enabled. this feature worked fine within our last version we had (2011 version) but now with the version we have, the image manager does not insert the image selected. Below is my radEditor html tag:
<telerik:RadEditor ID="txtRTE"
SpellCheckSettings-AllowAddCustom="false"
ToolsFile="~/SimpleRTEEditorTools.xml"
OnClientLoad="HandleRTEClientLoad"
ExternalDialogsPath="~/RadControls/EditorDialogs/"
runat="server"
Height="200"
Skin="Default"
EditModes="Design"
AllowScripts="false"
StripFormattingOptions="All">
<ImageManager ViewPaths=".." UploadPaths=".." SearchPatterns="*.jpg,*.gif,*.png" EnableImageEditor="False" ViewMode="Grid" />
I am editing the ViewPaths and uploadPaths within the code behind's page_load method:
txtRTE.ImageManager.ViewPaths = paths;
txtRTE.ImageManager.UploadPaths = paths;
txtRTE.ImageManager.ContentProviderTypeName = typeof(FolderContentProvider).AssemblyQualifiedName;
We implemented our own content provider as seen below:
public class FolderContentProvider : FileBrowserContentProvider
{
private string ROOT_DIRECTORY_FULL_PATH =
//Path to record documents folder
System.Configuration.ConfigurationManager.AppSettings[Constants.RECORD_DOC_ROOT_FOLDER_APP_KEY].ToString() +
//folder containing images
Constants.Record_DOC_FORM_TEXT_IMAGE_FOLDER + "\\" +
//to get Record ID
((MyAppPrincipal)System.Threading.Thread.CurrentPrincipal).Record.ID;
public string RootDirectory
{
get
{
return ROOT_DIRECTORY_FULL_PATH;
}
private set
{
}
}
private PathPermissions fullPermissions = PathPermissions.Read | PathPermissions.Upload;
private DirectoryItem[] GetSubDirectories(string path)
{
//we have only one directory no sub directories
//no need to go to file system to find that out
return new DirectoryItem[0];
}
private string GetDirectoryFullPath(string path)
{
return RootDirectory;
}
private FileItem[] GetFiles(string path)
{
string[] filesFullName = Directory.GetFiles(RootDirectory);
ArrayList files = new ArrayList();
for (int i = 0; i < filesFullName.Length; i++)
{
string fullPath = filesFullName[i];
System.IO.FileInfo currentFile = new System.IO.FileInfo(fullPath);
if (IsAlowedFileExtension(currentFile.Extension))
{
string url = string.Format("{0}?path={1}", HttpContext.Current.Request.ApplicationPath + "/app/FormTextImageHandler.ashx", currentFile.Name);
files.Add(new FileItem(
currentFile.Name, //file name
currentFile.Extension, //extension
currentFile.Length, //size
string.Empty,//currentFile.FullName, //location
url, //url
string.Empty,//tag
fullPermissions//permissions
));
}
}
return (FileItem[])files.ToArray(typeof(FileItem));
}
private bool IsAlowedFileExtension(string Extension)
{
if (Extension.Equals(".gif", StringComparison.InvariantCultureIgnoreCase))
return true;
if (Extension.Equals(".jpg", StringComparison.InvariantCultureIgnoreCase))
return true;
if (Extension.Equals(".png", StringComparison.InvariantCultureIgnoreCase))
return true;
return false;
}
public FolderContentProvider(HttpContext context, string[] searchPatterns, string[] viewPaths, string[] uploadPaths, string[] deletePaths, string selectedUrl, string selectedItemTag)
: base(context, searchPatterns, viewPaths, uploadPaths, deletePaths, selectedUrl, selectedItemTag)
{
}
public override string DeleteFile(string path)
{
//we do not allow removing files
return null;
}
public override string DeleteDirectory(string path)
{
//we don't have any sub directories
//and moreover we don't give delete rights
return null;
}
public override string StoreFile(Telerik.Web.UI.UploadedFile file, string path, string name, params string[] arguments)
{
int fileLength = (int)file.InputStream.Length;
byte[] content = new byte[fileLength];
file.InputStream.Read(content, 0, fileLength);
string fullPath = RootDirectory +"\\"+ name;
FileStream fileStream = new FileStream(fullPath, FileMode.OpenOrCreate);
fileStream.Write(content, 0, content.Length);
fileStream.Flush();
fileStream.Close();
return string.Empty;
}
public override DirectoryItem ResolveDirectory(string path)
{
DirectoryItem[] directories = new DirectoryItem[0];
FileItem[] files = this.GetFiles(RootDirectory);
DirectoryItem dir = new DirectoryItem("Images", string.Empty, RootDirectory, string.Empty, fullPermissions, files, directories);
return dir;
}
public override DirectoryItem ResolveRootDirectoryAsTree(string path)
{
//we don't have any subdirectories - everythinng is in the same folder
DirectoryItem[] directories = new DirectoryItem[0];
FileItem[] files = this.GetFiles(RootDirectory);
DirectoryItem root = new DirectoryItem("Images", string.Empty, "Images\\", string.Empty, fullPermissions, files, directories);
return root;
}
public override bool CanCreateDirectory
{
get
{
return false;
}
}
public override string CreateDirectory(string path, string name)
{
return null;
}
public override string StoreBitmap(Bitmap bitmap, string url, ImageFormat format)
{
return null;
}
public override Stream GetFile(string url)
{
return null;
}
public override string GetPath(string url)
{
return RootDirectory;
}
public override string GetFileName(string url)
{
return null;
}
[Obsolete]
public override DirectoryItem[] ResolveRootDirectoryAsList(string path)
{
return null;
}
public override bool CheckWritePermissions(string folderPath) {
return true;
}
}
Any idea's why the old version was able to insert into the field, but the new version is not?
The FileBrowserProvider API could be changed between the old and new versions. That why my suggestion is to examine the code of the following demo http://demos.telerik.com/aspnet-ajax/editor/examples/dbfilebrowsercontentprovider/defaultcs.aspx that works as expected and compare it with the code of your custom solution.
If you have any customized dialogs you may need to copy the EditorDialogs folder from the new installation that you are using and customize them from scratch.
Best regards,
Rumen

uploading photo to a webservice with mvvmcross and mono touch

What I want to do is simply to upload a photo to a webservice using mono touch/mono droid and mvvmcross, hopefully in a way so I only have to write the code once for both android and IOS :)
My initial idea is to let the user pick an image (in android using an intent) get the path for the image. Then use MvxResourceLoader resourceLoader to open an stream from the path and then use restsharp for creating a post request with the stream.
However I already hit a wall, when the user picks an image the path is e.g. "/external/images/media/13". this path results in a file not found exception when using the MvxResourceLoader resourceLoader.
Any ideas to why I get the exception or is there an better way to achieve my goal?
This is how I ended up doinging it - thank you stuart and to all the links :)
public class PhotoService :IPhotoService, IMvxServiceConsumer<IMvxPictureChooserTask>,IMvxServiceConsumer<IAppSettings>
{
private const int MaxPixelDimension = 300;
private const int DefaultJpegQuality = 64;
public void ChoosePhotoForEventItem(string EventGalleryId, string ItemId)
{
this.GetService<IMvxPictureChooserTask>().ChoosePictureFromLibrary(
MaxPixelDimension,
DefaultJpegQuality,
delegate(Stream stream) { UploadImage(stream,EventGalleryId,ItemId); },
() => { /* cancel is ignored */ });
}
private void UploadImage(Stream stream, string EventGalleryId, string ItemId)
{
var settings = this.GetService<IAppSettings>();
string url = string.Format("{0}/EventGallery/image/{1}/{2}", settings.ServiceUrl, EventGalleryId, ItemId);
var uploadImageController = new UploadImageController(url);
uploadImageController.OnPhotoAvailableFromWebservice +=PhotoAvailableFromWebservice;
uploadImageController.UploadImage(stream,ItemId);
}
}
public class PhotoStreamEventArgs : EventArgs
{
public Stream PictureStream { get; set; }
public Action<string> OnSucessGettingPhotoFileName { get; set; }
public string URL { get; set; }
}
public class UploadImageController : BaseController, IMvxServiceConsumer<IMvxResourceLoader>, IMvxServiceConsumer<IErrorReporter>, IMvxServiceConsumer<IMvxSimpleFileStoreService>
{
public UploadImageController(string uri)
: base(uri)
{
}
public event EventHandler<PhotoStreamEventArgs> OnPhotoAvailableFromWebservice;
public void UploadImage(Stream stream, string name)
{
UploadImageStream(stream, name);
}
private void UploadImageStream(Stream obj, string name)
{
var request = new RestRequest(base.Uri, Method.POST);
request.AddFile("photo", ReadToEnd(obj), name + ".jpg", "image/pjpeg");
//calling server with restClient
var restClient = new RestClient();
try
{
this.ReportError("Billedet overføres", ErrorEventType.Warning);
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
//upload successfull
this.ReportError("Billedet blev overført", ErrorEventType.Warning);
if (OnPhotoAvailableFromWebservice != null)
{
this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = base.Uri });
}
}
else
{
//error ocured during upload
this.ReportError("Billedet kunne ikke overføres \n" + response.StatusDescription, ErrorEventType.Warning);
}
});
}
catch (Exception e)
{
this.ReportError("Upload completed succesfully...", ErrorEventType.Warning);
if (OnPhotoAvailableFromWebservice != null)
{
this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = url });
}
}
}
//method for converting stream to byte[]
public byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
}
Try:
Issues taking images and showing them with MvvmCross on WP
Need an example of take a Picture with MonoDroid and MVVMCross
https://github.com/Redth/WshLst/ - uses Xam.Mobile for it's picture taking

Encrypting and Decrypting Isolated Storage File

I want to encrypt and decrypt the isolated storage file.
The Microsoft site took me here
While using Isolated Storage on the emulator, it can persist only until the emulator is running.
There is no way to get the physical location of the Isolated Storage.
I hope the above statements of mine are correct.
Now, I want to know how can I encrypt the Isolated Storage file ?
Taking the example provided by Microsoft, (application name is GasMileage)
here is the code
namespace CodeBadger.GasMileage.Persistence
{
public class IsolatedStorageGateway
{
private const string StorageFile = "data.txt";
private readonly XmlSerializer _serializer;
public IsolatedStorageGateway()
{
_serializer = new XmlSerializer(typeof (Notebook));
}
public Notebook LoadNotebook()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var stream = GetStorageStreamForReading(store))
using (var reader = new StreamReader(stream))
{
return reader.EndOfStream
? new Notebook()
: (Notebook) _serializer.Deserialize(reader);
}
}
}
public NotebookEntry LoadEntry(Guid guid)
{
var notebook = LoadNotebook();
return notebook.Where(x => x.Id == guid).FirstOrDefault();
}
public void StoreEntry(NotebookEntry entry)
{
var notebook = LoadNotebook();
AssignId(entry);
RemoveExistingEntryFromNotebook(notebook, entry);
Console.WriteLine(entry);
notebook.Add(entry);
WriteNotebookToStorage(notebook);
}
public void DeleteEntry(NotebookEntry entry)
{
var notebook = LoadNotebook();
RemoveExistingEntryFromNotebook(notebook, entry);
WriteNotebookToStorage(notebook);
}
private void WriteNotebookToStorage(Notebook notebook)
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var stream = GetStorageStreamForWriting(store))
{
_serializer.Serialize(stream, notebook);
}
}
private static void AssignId(NotebookEntry entry)
{
if (entry.Id == Guid.Empty) entry.Id = Guid.NewGuid();
}
private static void RemoveExistingEntryFromNotebook(Notebook notebook, NotebookEntry entry)
{
var toRemove = notebook.Where(x => x.Id == entry.Id).FirstOrDefault();
if (toRemove == null) return;
notebook.Remove(toRemove);
}
private static IsolatedStorageFileStream GetStorageStreamForWriting(IsolatedStorageFile store)
{
return new IsolatedStorageFileStream(StorageFile, FileMode.Create, FileAccess.Write, store);
}
private static IsolatedStorageFileStream GetStorageStreamForReading(IsolatedStorageFile store)
{
return new IsolatedStorageFileStream(StorageFile, FileMode.OpenOrCreate, FileAccess.Read, store);
}
}
Now I want to know, How to encrypt the data.txt given in the context.
On Application load, decrypt the file and on application termination, it should encrypt.
Can someone help me on this ?
The ProtectedData class will encrypt/decrypt a byte array for storing on isolated storage. You can supply your own additional entropy, but by default:
In Silverlight for Windows Phone, both the user and machine credentials are used to encrypt or decrypt data
For more information, see How to: Encrypt Data in a Windows Phone Application

Resources