× ABOUT DOWNLOADS PROJECTS WORK
    cyberpunk.sh
Profile photo

PREMCHAND CHAKKUNGAL

SENIOR SOFTWARE ENGINEER

Some applications might require extensive use of storage to save app settings. The following code helps you to directly access the variable “Country” anywhere in the project.

First of all, declare a class with the following code


public class StorageEngine  
 {  
      public string Country  
      {  
           get  
           {  
                string tempdata = string.Empty;  
                if(IsolatedStorageSettings.ApplicationSettings.TryGetValue("country", out tempdata))  
                {  
                }  
                return tempdata;  
           }  
           set  
           {  
                IsolatedStorageSettings.ApplicationSettings["country"]=value;  
                IsolatedStorageSettings.ApplicationSettings.Save();  
           }  
      }  
 }  

To use the above value in code, simple initialize a new instance of the above class:

StorageEngine NEWENGINE = new StorageEngine();

Now, whenever you want to save a value, do

NEWENGINE.Country=”India”;
and whenever you want to get the stored value, simple do

String currentcountry=NEWENGINE.Country;

Most of the app developers require a way to uniquely identify each mobile device. Given below is a simple function which will give you the device id in the string format.


public string GetDeviceId()  
 {  
    byte[] myDeviceID=(byte[])Microsoft.Phone.Info.DeviceExtendedProperties.GetValue("DeviceUniqueId");  
    return Convert.ToBase64String(myDeviceID);  
 }  

Given below is an asynchronous task to load an user image from the Isolated Phone Storage and return it as a BitmapImage object.


public async Task loaduserimage()
        {
            BitmapImage bi = new BitmapImage();

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                if (myIsolatedStorage.FileExists("filename.extension"))
                {
                     using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("filename.extension", FileMode.Open, FileAccess.Read))
                        {
                            bi.SetSource(fileStream);

                        }
                }
                else
                {
                    MessageBox.Show("File not found");

                }

            }
            return bi;
}

Modern mobile apps require us to continuously update the app contents when we are online and read the last downloaded content from phone storage when we are offline. Given below is a code snippet which will download a file from Internet and save it in IsolatedStorage.
Declare


public enum Problem { Ok, Cancelled, Other };

Function


public async Task DownloadFileFromWeb(Uri uriToDownload, string fileName, CancellationToken cToken)
 {
            Problem prob;
            try
            {
                using (Stream mystr = await DownloadFile(uriToDownload))
                using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (ISF.FileExists(fileName))
                    {
                        ISF.DeleteFile(fileName);
                    }
                    using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
                    {
                        const int BUFFER_SIZE = 1024;
                        byte[] buf = new byte[BUFFER_SIZE];

                        int bytesread = 0;
                        while ((bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
                        {
                            cToken.ThrowIfCancellationRequested();
                            file.Write(buf, 0, bytesread);
                        }
                    }
                }
                prob = Problem.Ok;
            }
            catch (Exception exc)
            {
                if (exc is OperationCanceledException)
                    prob= Problem.Cancelled;
                else 
                    prob= Problem.Other;
            }
            return prob;
 }

 public static Task DownloadFile(Uri url)
 {
            var tcs = new TaskCompletionSource();
            var wc = new WebClient();
            wc.OpenReadCompleted += (s, e) =>
            {
                if (e.Error != null) tcs.TrySetException(e.Error);
                else if (e.Cancelled) tcs.TrySetCanceled();
                else tcs.TrySetResult(e.Result);
            };
            wc.OpenReadAsync(url);
            return tcs.Task;
 }

For apps such as facebook, twitter or any other having an user account, we might require then to set or update their profile picture. The code below will help you to perform a POST operation to upload the image into an REST API. Since RestSharp at this point doesn’t contain an asynchronous Execute, I have defined a class to achieve this.


public async Task fileUpload(String FileName, byte[] image)
{
           try
           {

              RestClient client = new RestClient(“http://baseurl.com/);
              RestSharpExtension newextension = new RestSharpEextension();
               client.Authenticator = new HttpBasicAuthenticator("admin", "password");
               var request = new RestRequest("api-service/uploadimage", Method.POST);
               request.AddHeader("Content-Type", "application/octect-stream");
               request.AlwaysMultipartFormData = true;
               request.AddFile(FileName, image, FileName);
               var response = await newextension.ExecuteAwait(client, request);
               if (response.StatusCode == System.Net.HttpStatusCode.OK)
               {

                  String JSONData = response.Content.ToString();
                   return true;
               }
               else
               {
                   return false;
               }

           }
           catch(Exception ex)
           {
               MessageBox.Show(ex.Message);
               return false;
           }

   }

The below code snippet implements the ReshSharpExtension


public class RestSharpExtension
    {
        public Task ExecuteAwait(RestClient client, RestRequest request)
        {
            TaskCompletionSource taskCompletionSource = new TaskCompletionSource();
            client.ExecuteAsync(request, (response, asyncHandle) =>
            {
                if (response.ResponseStatus == ResponseStatus.Error)
                {
                    taskCompletionSource.SetException(response.ErrorException);
                }
                else
                {
                    taskCompletionSource.SetResult(response);
                }
            });
            return taskCompletionSource.Task;
        }
    }