How to get isolated file in list wp8 - windows-phone-8

I want to list name here i save in isolated storage my code is :
public async void getfile()
{
string _storageFile = "books.db";
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isolatedStorage.FileExists(_storageFile))
{
}
else
{
using (var isoFileStream = isolatedStorage.OpenFile(_storageFile, FileMode.Open))
{
}
}
}
}
How to get the list of all files?

GetFileNames() method would retun you array of filenames:
public async void getfile()
{
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = isolatedStorage.GetFileNames();
}
}

Use IsolatedStorage.GetFileNames to retrieve the list of all files:
public async void getfile()
{
string _storageFile = "books.db";
using (var isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
var files = isolatedStorage.GetFileNames();
}
}

Related

How to inject services in a controller inside a reusable Razor Class Library

I am using a Razor Class Library for making a reusable complex View (which includes its controller and several View Components) that can be used across several ASP.NET Core MVC projects. The problem is that the controller use dependency injection (a custom service called "GatewayProxy" and string localization). What is the correct way to inject services into a controller inside a RCL?
Here is the structure of my RCL:
Here is the exception:
You mentioned how you fixed this by adding the dependencies to Startup.cs of your main project. But consider that any consumer of this reuseable library may not remember (or know) what dependencies are needed for your library.
Something you can do to solve this is to create an extension off of IServiceCollection in your Rcl that does the dependency registration.
public static void AddMyRclServices(this IServiceCollection serviceCollection, IConfiguration config)
{
serviceCollection.AddTransient<IRclService1, RclService1>();
serviceCollection.AddScoped<IRclService2, RclService2>();
}
Then in Startup.cs for your MVC project call the extension
using Rcl.Extensions
public void ConfigureServices(IServiceCollection services)
{
services.AddMyRclServices(config);
}
You can inject from load assemblies.
my code
ISturtupInitializers.cs
public interface ISturtupInitializers {
void Compose(IServiceCollection serviceCollection);
}
TypeLoader.cs
public static readonly Lazy<HashSet<Assembly>> AllAssemblies = new Lazy<HashSet<Assembly>>(() => {
var bin_folder = Assembly.GetExecutingAssembly().GetFileInfo().Directory.FullName;
var bin_assembly_files = Directory.GetFiles(bin_folder, "*.dll", SearchOption.TopDirectoryOnly).Where(x => !SystemAssemblies.Any(xs => x.IndexOf(xs, StringComparison.CurrentCultureIgnoreCase) >= 0)).ToList();
var assemblies = new HashSet<Assembly>();
foreach (var a in bin_assembly_files)
{
try {
var assName = AssemblyName.GetAssemblyName(a);
var ass = Assembly.Load(assName);
assemblies.Add(ass);
} catch (SecurityException e) {
//ignore
} catch (FileNotFoundException e) {
//ignore
} catch (BadImageFormatException e) {
//ignore
}
catch (Exception e) {
throw;
}
}
return assemblies;
});
public static string[] SystemAssemblies = new[] {
"Microsoft.",
"System.",
"Newtonsoft."
};
public static FileInfo GetFileInfo(this Assembly assembly)
{
var uri = new Uri(assembly.CodeBase);
var path = uri.LocalPath;
return new FileInfo(path);
}
Composer.cs
public class Composer {
private static readonly Lazy<HashSet<Type>> _sturtup_initializers = new Lazy<HashSet<Type>>(() => {
var aseemblies = TypeLoader.AllAssemblies.Value.SelectMany(x=>GetAllTypesInAssembly(x, typeof(ISturtupInitializers)));
var result = new HashSet<Type>();
foreach (var item in aseemblies) {
result.Add(item);
}
return result;
});
public static void Compose(IServiceCollection services) {
var composers = _sturtup_initializers.Value;
foreach (var compose in composers) {
public static void Compose(IServiceCollection services, IConfiguration configuration) {
var composers = _sturtup_initializers.Value;
var provider = services.BuildServiceProvider();
foreach (var compose in composers) {
((IStartupInitializers) ActivatorUtilities.CreateInstance(provider, compose)).Compose(services, configuration);
}
}
}
}
private static IEnumerable<Type> GetAllTypesInAssembly(Assembly assembly, Type implementInterface) {
var types = assembly.GetTypes();
return types.Where(x => x.GetInterfaces().Any(i => i == implementInterface));
}
}
MyStartup.cs
public class ServiceCollectionExtensions : ISturtupInitializers
{
public void Compose(IServiceCollection serviceCollection) {
/** YOUR CODE **/
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services) {
/** YOUR CODE **/
Composer.Compose(services);
}

UWP - writing to JSON without owerwrite data

I want to write data to JSON file, without overwriting them. I am using this code
Item test = new Item("test", 23);
try
{
var Folder = Windows.Storage.ApplicationData.Current.LocalFolder;
//var file = await Folder.CreateFileAsync("data.json", Windows.Storage.CreationCollisionOption.ReplaceExisting);
var file = await Folder.GetFileAsync("data.json");
var data = await file.OpenStreamForWriteAsync();
using (StreamWriter r = new StreamWriter(data))
{
var serelizedfile = JsonConvert.SerializeObject(test);
r.Write(serelizedfile);
}
}
catch (Exception a)
{
throw a;
}
Noticed that you're possibly using the Json.NET for serialization and deserialization the Json file. I think it's better to deserialize the list of Json object and you can operate on this list, then serialize the new list to Json and save into the file, not directly serialize one item and write it into the file.
For example, my Json file is like this:
[
{"color":"red","value":"#f00"},
{"color":"green","value":"#0f0"},
{"color":"blue","value":"#00f"},
{"color":"cyan","value":"#0ff"},
{"color":"magenta","value":"#f0f"},
{"color":"yellow","value":"#ff0"},
{"color":"black","value":"#000"}
]
code for adding one item to this file:
if (file != null)
{
using (var streamIn = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataReader reader = new DataReader(streamIn);
await reader.LoadAsync((uint)streamIn.Size);
var jsonInstring = reader.ReadString((uint)streamIn.Size);
var JobjList = JsonConvert.DeserializeObject<List<JsonColor>>(jsonInstring);
reader.Dispose();
JobjList.Add(new JsonColor() { color = "pink", value = "#c0c" });
JsonOutstring = JsonConvert.SerializeObject(JobjList);
}
using (var streamOut = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataWriter writer = new DataWriter(streamOut);
writer.WriteString(JsonOutstring);
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
}
}
else
{
}
My class object:
public class JsonColor
{
public string color { get; set; }
public string value { get; set; }
}
As you can see, I deserialized the Json file and get the List<JsonColor>, then I added one item new JsonColor() { color = "pink", value = "#c0c" } to this list, and finally serialized this new list and save it. So for your scenario, you can modify the Json file and my JsonColor class to fit your need.
Update:
private string JsonOutstring;
private async void Button_Click(object sender, RoutedEventArgs e)
{
//create a json file, if the file is exit, then open it.
var local = Windows.Storage.ApplicationData.Current.LocalFolder;
var Jsonfile = await local.CreateFileAsync("test.json", Windows.Storage.CreationCollisionOption.OpenIfExists);
if (Jsonfile != null)
{
ReadAndWriteJsonFile(Jsonfile);
}
else
{
}
}
public async void ReadAndWriteJsonFile(StorageFile file)
{
using (var streamIn = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataReader reader = new DataReader(streamIn);
await reader.LoadAsync((uint)streamIn.Size);
var jsonInstring = reader.ReadString((uint)streamIn.Size);
var JobjList = JsonConvert.DeserializeObject<List<JsonColor>>(jsonInstring);
reader.Dispose();
if (JobjList == null)
{
JobjList = new List<JsonColor>();
}
JobjList.Add(new JsonColor() { color = "pink", value = "#c0c" });
JsonOutstring = JsonConvert.SerializeObject(JobjList);
}
using (var streamOut = await file.OpenAsync(FileAccessMode.ReadWrite))
{
DataWriter writer = new DataWriter(streamOut);
writer.WriteString(JsonOutstring);
await writer.StoreAsync();
writer.DetachStream();
writer.Dispose();
}
}
public class JsonColor
{
public string color { get; set; }
public string value { get; set; }
}

How to update data continuously in UI text box control using windows phone application

Im developing a small Tcp Client Socket application in windows phone. Actually i have a text box, in that whatever the data received from a TCP server, should update continuously in UI text box control.
while (val)
{
result = Receive();
Dispatcher.BeginInvoke((Action)(() =>
{
txtOutput.Text += result;
}));
}
Here in above code, method receive() will receive string data and should update in textbox control but it is not happening,no data is updating to it.
Can any one suggest, how can i resolve this.
Just telling you what i have been advised, "avoid Dispatcher, CoreDispatcher, etc. There are always better solutions."
Below is the piece of code worked for me for both wp8 and wp8.1 WinRT app,
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
where UpdateTicker() method contains your instructions, in this case...
public void UpdateTicker()
{
result = Receive();
txtOutput.Text += result;
}
Hope this helps...
Thanks for everyone, who given a valuable response for my post.
Hi Nishchith,
I tried your code, but it dint works for me
Here is my logic used to update textbox continuously with data received from TCP server.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp3.Resources;
using System.Net.Sockets;
using System.Threading;
using System.Text;
using Windows.Phone.Networking;
using System.Threading.Tasks;
namespace PhoneApp3
{
public partial class MainPage : PhoneApplicationPage
{
Socket _socket = null;
static ManualResetEvent _clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 1000;
const int MAX_BUFFER_SIZE = 2048;
const int ECHO_PORT = 9055; // The Echo protocol uses port 7 in this sample
const int QOTD_PORT = 49152; // The Quote of the Day (QOTD) protocol uses port 17 in this sample
string result = string.Empty;
public MainPage()
{
InitializeComponent();
}
private void btnEcho_Click(object sender, RoutedEventArgs e)
{
SocketClient client = new SocketClient();
Connect(txtRemoteHost.Text, ECHO_PORT);
//close();
}
public void Connect(string hostName, int portNumber)
{
DnsEndPoint hostEntry = new DnsEndPoint(hostName, portNumber);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(2000);
_socket.ConnectAsync(socketEventArg);
Thread.Sleep(5000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
bool val;
if (result == "Success")
{
val = true;
}
else
{
val = false;
}
IProgress<object> progress = new Progress<object>(_ => UpdateTicker());
Task.Run(async () =>
{
while (val)
{
progress.Report(null);
}
});
}
public void UpdateTicker()
{
result = Receive();
string[] strsplit = result.Split(' ');
txtOutput.Text = strsplit[1];
}
public string Receive()
{
string response = "Operation Timeout";
if (_socket != null)
{
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = _socket.RemoteEndPoint;
socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
if (e.SocketError == SocketError.Success)
{
// Retrieve the data from the buffer
response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
response = response.Trim('\0');
}
else
{
response = e.SocketError.ToString();
}
_clientDone.Set();
});
_clientDone.Reset();
Thread.Sleep(1000);
_socket.ReceiveAsync(socketEventArg);
Thread.Sleep(1000);
_clientDone.WaitOne(TIMEOUT_MILLISECONDS);
}
else
{
response = "Socket is not initialized";
}
return response;
}
public void Close()
{
if (_socket != null)
{
_socket.Close();
}
}
}
}

IsolatedStorage best practise

I am building my first WP8 application and I ran into a doubt.
I have to save in the IsolatedStorage some data obtained by serializing three different object.
My code for loading this data is this:
public static Statistics GetData()
{
Statistics data = new Statistics();
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("stats.xml", FileMode.OpenOrCreate))
{
XmlSerializer serializer = new XmlSerializer(typeof(Statistics));
data = (Statistics)serializer.Deserialize(stream);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message + "\n" + e.InnerException);
}
return data;
}
And for saving data of course is this
public static void SaveStats(Statistics stats)
{
XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
xmlWriterSettings.Indent = true;
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("stats.xml", FileMode.Create))
{
XmlSerializer serializer = new XmlSerializer(typeof(Statistics));
using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
{
serializer.Serialize(xmlWriter, stats);
}
}
}
}
catch
{
MessageBox.Show("Salvataggio non riuscito");
}
}
This works fine, now the problem is that I have to do the same also for other two classes.
Do I have to write the same exact code again, only changing Statistics with the other class?
Or there is something way more clever to do?
Take a look at Generics.
Your serialize method would look like this:
public static void SaveStats<T>(T obj) where T : class, new()
{
...
XmlSerializer serializer = new XmlSerializer(typeof(T));
...
}
Method invoke:
SaveStats<Statistics>(new Statistics());
SaveStats<OtherObject>(new OtherObject());

How can I save a JSON response to a file in unity3D for ios and android

I'm working on a 2D mobile game for ios and android using Unity3D.
The game requires to save a JSON response to a file.
I use NGUI and MiniJSON for that.
I want to know how to implement that starting from www function to get JSOn response and save it to a file(including path) and load it from other script.
if it is too much, just give me a example for that.
Thank you
I haven't tested the code yet, but it might give you an idea :-)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
public class WWWJsonTest : MonoBehaviour
{
private const float SECONDS_BEFORE_TIMEOUT = 10;
private const string URL = "INSERT URL HERE";
private const string FILE_PATH = "INSERT FILE PATH";
public void DownloadAndSave()
{
StartCoroutine(DownloadCoroutine());
}
public Dictionary<object, object> GetSavedData()
{
// Use ReadContents() and do your MiniJSON magic here
return null;
}
private IEnumerator DownloadCoroutine()
{
var requestHeaders = new Hashtable()
{
{ "Connection", "close"},
{ "Accept", "application/json"}
};
using(var request = new WWW(URL, null, requestHeaders))
{
float timeStarted = Time.realtimeSinceStartup;
while(!request.isDone)
{
// Check if the download times out
if(Time.realtimeSinceStartup - timeStarted > SECONDS_BEFORE_TIMEOUT)
{
Debug.Log("Download timed out");
yield break;
}
yield return null;
}
// Check for other errors
if(request.error != null)
{
Debug.Log(request.error);
yield break;
}
SaveContents(request.text);
}
}
private string ReadContents()
{
string ret;
using(FileStream fs = new FileStream(FILE_PATH, FileMode.Open))
{
BinaryReader fileReader = new BinaryReader(fs);
ret = fileReader.ReadString();
fs.Close();
}
return ret;
}
private void SaveContents(string text)
{
using(FileStream fs = new FileStream(FILE_PATH, FileMode.Create))
{
BinaryWriter fileWriter = new BinaryWriter(fs);
fileWriter.Write(text);
fs.Close();
}
}
}