Encrypting and Decrypting Isolated Storage File - windows

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

Related

Download and open picture from url/http [Android Xamarin App]

Hello, would any of you send a working code to download a photo from a given http address on android Xamarin c #?
First, I need to create a new folder for my application files.
My goal is to download the file from the internet to my Android folder (saving this file with its original name is best).
The next step is to display the image from that folder in "ImageView". It is also important that there are permissions in android and I do not fully understand it.
Could any of you send it to me or help me understand it and explain the topic?
*Actually i have this code:
string address = "https://i.stack.imgur.com/X3V3w.png";
using (WebClient webClient = new WebClient())
{
webClient.DownloadFileCompleted += WebClient_DownloadFileCompleted;
webClient.DownloadFile(address, Path.Combine(pathDire, "MyNewImage1.png"));
//System.Net.WebException: 'An exception occurred during a WebClient request.'
}
Loading image from url and display in imageview.
private void Btn1_Click(object sender, System.EventArgs e)
{
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
imagen.SetImageBitmap(imageBitmap);
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
SavePicture("ImageName.jpg", imageBytes, "imagesFolder");
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
download image and save it in local storage.
private void SavePicture(string name, byte[] data, string location = "temp")
{
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
documentsPath = System.IO.Path.Combine(documentsPath, "Orders", location);
Directory.CreateDirectory(documentsPath);
string filePath = System.IO.Path.Combine(documentsPath, name);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
int length = data.Length;
fs.Write(data, 0, length);
}
}
you need to add permission WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in AndroidMainfeast.xml, then you also need to Runtime Permission Checks in Android 6.0.
private void checkpermission()
{
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the writeexternalstorage.
}
else
{
// writeexternalstorage permission is not granted. If necessary display rationale & request.
}
if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
{
// We have permission, go ahead and use the ReadExternalStorage.
}
else
{
// ReadExternalStorage permission is not granted. If necessary display rationale & request.
}
}

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.

Error "Must set UnitOfWorkManager before use it"

I'm developing the service within ASP.NET Boilerplate engine and getting the error from the subject. The nature of the error is not clear, as I inheriting from ApplicationService, as documentation suggests. The code:
namespace MyAbilities.Api.Blob
{
public class BlobService : ApplicationService, IBlobService
{
public readonly IRepository<UserMedia, int> _blobRepository;
public BlobService(IRepository<UserMedia, int> blobRepository)
{
_blobRepository = blobRepository;
}
public async Task<List<BlobDto>> UploadBlobs(HttpContent httpContent)
{
var blobUploadProvider = new BlobStorageUploadProvider();
var list = await httpContent.ReadAsMultipartAsync(blobUploadProvider)
.ContinueWith(task =>
{
if (task.IsFaulted || task.IsCanceled)
{
if (task.Exception != null) throw task.Exception;
}
var provider = task.Result;
return provider.Uploads.ToList();
});
// store blob info in the database
foreach (var blobDto in list)
{
SaveBlobData(blobDto);
}
return list;
}
public void SaveBlobData(BlobDto blobData)
{
UserMedia um = blobData.MapTo<UserMedia>();
_blobRepository.InsertOrUpdateAndGetId(um);
CurrentUnitOfWork.SaveChanges();
}
public async Task<BlobDto> DownloadBlob(int blobId)
{
// TODO: Implement this helper method. It should retrieve blob info
// from the database, based on the blobId. The record should contain the
// blobName, which should be returned as the result of this helper method.
var blobName = GetBlobName(blobId);
if (!String.IsNullOrEmpty(blobName))
{
var container = BlobHelper.GetBlobContainer();
var blob = container.GetBlockBlobReference(blobName);
// Download the blob into a memory stream. Notice that we're not putting the memory
// stream in a using statement. This is because we need the stream to be open for the
// API controller in order for the file to actually be downloadable. The closing and
// disposing of the stream is handled by the Web API framework.
var ms = new MemoryStream();
await blob.DownloadToStreamAsync(ms);
// Strip off any folder structure so the file name is just the file name
var lastPos = blob.Name.LastIndexOf('/');
var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1);
// Build and return the download model with the blob stream and its relevant info
var download = new BlobDto
{
FileName = fileName,
FileUrl = Convert.ToString(blob.Uri),
FileSizeInBytes = blob.Properties.Length,
ContentType = blob.Properties.ContentType
};
return download;
}
// Otherwise
return null;
}
//Retrieve blob info from the database
private string GetBlobName(int blobId)
{
throw new NotImplementedException();
}
}
}
The error appears even before the app flow jumps to 'SaveBlobData' method. Am I missed something?
Hate to answer my own questions, but here it is... after a while, I found out that if UnitOfWorkManager is not available for some reason, I can instantiate it in the code, by initializing IUnitOfWorkManager in the constructor. Then, you can simply use the following construction in your Save method:
using (var unitOfWork = _unitOfWorkManager.Begin())
{
//Save logic...
unitOfWork.Complete();
}

Change Content Type for files in Azure Storage Blob

I use only Microsoft Azure Storage and no other Azure products/services. I upload files to my storage blob via ftp type client (GoodSync), and I need to change the content type of all the files based on their file extension after they are already in the Blob. I have looked around and have not found out how to do this without having one of their VPS with PowerShell. What are my options and how do I accomplish this? I really need step by step here.
I recently had the same issue so I created a simple utility class in order to "fix" content type based on file's extension. You can read details here
What you need to do is parse each file in your Azure Storage Containers and update ContentType based on a dictionary that defines which MIME type is appropriate for each file extension.
// Connect to your storage account
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
// Load Container with the specified name
private CloudBlobContainer GetCloudBlobContainer(string name)
{
CloudBlobClient cloudBlobClient = _storageAccount.CreateCloudBlobClient();
return cloudBlobClient.GetContainerReference(name.ToLowerInvariant());
}
// Parse all files in your container and apply proper ContentType
private void ResetContainer(CloudBlobContainer container)
{
if (!container.Exists()) return;
Trace.WriteLine($"Ready to parse {container.Name} container");
Trace.WriteLine("------------------------------------------------");
var blobs = container.ListBlobs().ToList();
var total = blobs.Count;
var counter = 1;
foreach (var blob in blobs)
{
if (blob is CloudBlobDirectory) continue;
var cloudBlob = (CloudBlob)blob;
var extension = Path.GetExtension(cloudBlob.Uri.AbsoluteUri);
string contentType;
_contentTypes.TryGetValue(extension, out contentType);
if (string.IsNullOrEmpty(contentType)) continue;
Trace.Write($"{counter++} of {total} : {cloudBlob.Name}");
if (cloudBlob.Properties.ContentType == contentType)
{
Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (skipped)");
continue;
}
cloudBlob.Properties.ContentType = contentType;
cloudBlob.SetProperties();
Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (reset)");
}
}
_contentTypes is a dictionary that contains the appropriate MIME type for each file extension:
private readonly Dictionary _contentTypes = new Dictionary()
{
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg" }
};
Full list of content types and source code can be found here.
Here you are a refreshed version for latest Azure.Storage.Blobs SDK. I'm using .Net 5 and console app.
using Azure.Storage.Blobs.Models;
using System;
using System.Collections.Generic;
using System.IO;
var contentTypes = new Dictionary<string, string>()
{
{".woff", "font/woff"},
{".woff2", "font/woff2" }
};
var cloudBlobClient = new BlobServiceClient("connectionstring");
var cloudBlobContainerClient = cloudBlobClient.GetBlobContainerClient("fonts");
await cloudBlobContainerClient.CreateIfNotExistsAsync();
var blobs = cloudBlobContainerClient.GetBlobsAsync();
await foreach (var blob in blobs)
{
var extension = Path.GetExtension(blob.Name);
contentTypes.TryGetValue(extension, out var contentType);
if (string.IsNullOrEmpty(contentType)) continue;
if (blob.Properties.ContentType == contentType)
{
continue;
}
try
{
// Get the existing properties
var blobClient = cloudBlobContainerClient.GetBlobClient(blob.Name);
var properties = await blobClient.GetPropertiesAsync();
var headers = new BlobHttpHeaders
{
ContentType = contentType,
CacheControl = properties.CacheControl,
ContentDisposition = properties.ContentDisposition,
ContentEncoding = properties.ContentEncoding,
ContentHash = properties.ContentHash,
ContentLanguage = properties.ContentLanguage
};
// Set the blob's properties.
await blobClient.SetHttpHeadersAsync(headers);
}
catch (RequestFailedException e)
{
Console.WriteLine($"HTTP error code {e.Status}: {e.ErrorCode}");
Console.WriteLine(e.Message);
Console.ReadLine();
}
}

using existing SqlCe database in windows phone

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";

Resources