Storing Variable in When Tombstone Occurs - windows-phone-8

How can i store the variables in savestate() method of TombstoneHelper class to avoid Tombstone in windows phone 8.

I think you can try to use PhoneApplicationService.State Property - it works like Dictionary(string, object). MSDN
To save on Deactivated event:
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
int myObject = 5;
PhoneApplicationService.Current.State.Add("myName", myObject);
}
To restore on Activated event:
private void Application_Activated(object sender, ActivatedEventArgs e)
{
var returnedOnject = PhoneApplicationService.Current.State["myName"];
}

Thanks Man +1 For your comment Romasz .It is now working but there is an error when app went to the tombstone stage because PhoneApplicationService State is null when your app comes from the Tombstone Stage.So i stored that phoneState in the isolated storage in application_Deactivated and retrieve from isolated Storage in application_activated.
I made simple LoginData Class where i can store my data that i have to preserving.
[DataContract]
public class LoginData
{
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public int EstablishmentId { get; set; }
[DataMember]
public bool chainmanager { get; set; }
[DataMember]
public string logoimage { get; set; }
public LoginData(string username, string password, int establishmentId, bool ischainmager,string logoimage)
{
this.Username = username;
this.Password = password;
this.EstablishmentId = establishmentId;
this.chainmanager = ischainmager;
this.logoimage = logoimage;
}
}
Then make method to save the Class object in app.xml
public void save(LoginData ld)
{
PhoneApplicationService phonestate = PhoneApplicationService.Current;
phonestate.State["_lOGINcREDENTIALs_"]= ld;
var settings = IsolatedStorageSettings.ApplicationSettings;
settings["Credatials"] = phonestate.State["_lOGINcREDENTIALs_"];
}
And Method to load the Class object
public void load()
{
PhoneApplicationService phonestate = PhoneApplicationService.Current;
var settings = IsolatedStorageSettings.ApplicationSettings;
object credentials;
if (settings.TryGetValue("Credatials", out credentials))
{
phonestate.State["_lOGINcREDENTIALs_"]= credentials;
}
}
and call these methods in various event like
private void Application_Launching(object sender, LaunchingEventArgs e)
{
load();
}
private void Application_Activated(object sender, ActivatedEventArgs e)
{
load();
}
private void Application_Deactivated(object sender, DeactivatedEventArgs e)
{
save();
}
private void Application_Closing(object sender, ClosingEventArgs e)
{
save();
}

Related

How to configure a connection to MySql with nhibernate in net core

I am programming the connection to the database for a api in net core. I decided to inhibit but I can not connect to the mysql database, it's a local configuration, what I have is the following
that is my CreateSessionFactory
private static ISessionFactory CreateSessionFactory()
{
try
{
string connection = "server='localhost';Database='equalsbd';UserId='root';Password='123456';port=3304";
var db = MySQLConfiguration.Standard.ConnectionString(connection);
return Fluently.Configure().Database(db)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf
<SessionNHibernate>()).BuildSessionFactory();
}
catch
{
}
return null;
}
this is my full class
public class SessionNHibernate
{
private static ISessionFactory sessionFactory = null;
private static ISession session = null;
private static ISessionFactory SessionFactory
{
get
{
if (SessionFactory == null)
sessionFactory = CreateSessionFactory();
return sessionFactory;
}
}
public static ISession Session
{
get { return session; }
}
public static ISession OpenSession() {
try
{
session = SessionFactory.OpenSession();
return session;
}
catch (Exception ex)
{
var p = ex;
return session;
}
}
public static void CloseSession()
{
session.Close();
}
private static ISessionFactory CreateSessionFactory()
{
try
{
string connection = "server='localhost';Database='equalsbd';UserId='root';Password='123456';port=3304";
var db = MySQLConfiguration.Standard.ConnectionString(connection);
return Fluently.Configure().Database(db)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf
<SessionNHibernate>()).BuildSessionFactory();
}
catch
{
}
return null;
}
}
the first change I made was to modify
private static ISessionFactory sessionFactory = null;
by
private static ISessionFactory _sessionFactory = null;
to prevent confusions
the second was to update the usermap by changing its private property to protected, this being private for some reason does not allow the connection to read the attributes
leaving in this way
this
public class Usuarios
{
public virtual long idUsuarios { get; private set; }
public virtual string Usuario { get; private set; }
public virtual string Password { get; private set; }
public virtual string Perfiles_idPerfiles { get; private set; }
public static List<Usuarios> ListaUsuario() {
using (var session = SessionNHibernate.OpenSession() )
{
return session.Query<Usuarios>().ToList();
}
}
}
by the correct way
public class Usuarios
{
public virtual long idUsuarios { get; protected set; }
public virtual string Usuario { get; protected set; }
public virtual string Password { get; protected set; }
public virtual string Perfiles_idPerfiles { get; protected set; }
public static List<Usuarios> ListaUsuario() {
using (var session = SessionNHibernate.OpenSession() )
{
return session.Query<Usuarios>().ToList();
}
}
}
with this your connection to mysql will work or with any other database

WP read user_id from JSON and show it

I want to show user_id from the following JSON:
[{"username":"Kac26","email":"xklemenx#gmail.com","city":"Slovenj Gradec","id":"15"}]
So I save this JSON to class. I get JSON from my webpage.
My class:
public class Class2
{
public string username{ get; set; }
public string email { get; set; }
public string city { get; set; }
public int id { get; set; }
}
Saving JSON to class:
private async void Login_Tapped(object sender, TappedRoutedEventArgs e)
{
string str = user.Text; //get user name from textbox
HttpClient http = new HttpClient();
var response= await http.GetStringAsync("http://mywebpage.com/events/apis/user.php/user=" + str);
}
Then I want to show user id in textbox_id when i press button.
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
textbox_id.Text = Class2.id;
}
But error shows up when I try to reach Class2.id
Anyone know how to do that? And do I save json to class correct?
Thanks!!!
In "Saving JSON to class", I don't see where you are actually doing that. Here's how you would deserialize the string returned by the service:
private async void Login_Tapped(object sender, TappedRoutedEventArgs e)
{
string str = user.Text; //get user name from textbox
HttpClient http = new HttpClient();
var response = await http.GetStringAsync("http://mywebpage.com/events/apis/user.php/user=" + str);
Class2 myClass2 = null;
try
{
var jsonSerializer = new DataContractJsonSerializer(typeof(Class2));
using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(response)))
{
myClass2 = jsonSerializer.ReadObject(stream) as Class2;
}
}
catch
{
// serialization error occurred
}
// do something with myClass2
}
Also, FYI if you don't want the property names on your response class to match the JSON properties (for example, not be lower case), you can use DataContractAttribute and DataMemberAttribute on your class like so:
[DataContract]
public class Class2
{
[DataMember(name = "username")]
public string UserName { get; set; }
[DataMember(name = "email")]
public string EMail { get; set; }
[DataMember(name = "city")]
public string SomeCompletelyDifferentNameForCity { get; set; }
[DataMember(name = "id")]
public int Id { get; set; }
}
Class2.id is a static access to a non-static property of Class2. You have to create an instance of Class2 with new Class2(); at some point and then you can access the property.

Why Do I Get this Strange Serialization Exception?

I have the following classes:
[DataContract]
public class MapServiceInfo
{
private EventHandler _infoRetrievalFinished;
public event EventHandler InfoRetrievalFinished
{
add
{
if (this._infoRetrievalFinished == null ||
!this._infoRetrievalFinished.GetInvocationList().Contains(value))
{
this._infoRetrievalFinished += value;
}
}
remove { this._infoRetrievalFinished -= value; }
}
[DataMember] public string currentVersion { get; set; }
[DataMember] public string serviceDescription { get; set; }
[DataMember] public string mapName { get; set; }
[DataMember] public string description { get; set; }
[DataMember] public string copyrightText { get; set; }
[DataMember] public bool supportsDynamicLayers { get; set; }
[DataMember] public List<LayerInfo> layers { get; set; }
public MapServiceInfo() { }
public void RetrieveServiceInfo(string mapServiceUrl)
{
string url = mapServiceUrl.TrimEnd("/".ToCharArray()) + "?f=json";
WebClient webClient = new WebClient();
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri(url));
}
private void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
MapServiceInfo info = null;
try
{
Stream responseStream = e.Result;
StreamReader reader = new StreamReader(responseStream);
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(MapServiceInfo));
info = (MapServiceInfo)serializer.ReadObject(responseStream);
}
catch (Exception ex) { string message = ex.Message; }
finally { this.SetInfo(info); }
}
else { /**/ }
}
public string GetLayerId(string layerName)
{
Debug.Assert(!(string.IsNullOrEmpty(layerName)));
Debug.Assert(!(string.IsNullOrWhiteSpace(layerName)));
if (layerName == null) { throw new ArgumentNullException("layerName"); }
else if (string.IsNullOrEmpty(layerName)) { return ""; }
else if (string.IsNullOrWhiteSpace(layerName)) { return ""; }
string id = string.Empty;
if (layers != null)
{
foreach (LayerInfo i in layers)
{
if (i.name == layerName)
{
id = i.id.ToString();
break;
}
else { continue; }
}
}
else { /**/ }
return id;
}
private void SetInfo(MapServiceInfo info)
{
Debug.Assert(!(info == null));
if (info != null)
{
this.currentVersion = info.currentVersion;
this.serviceDescription = info.serviceDescription;
this.mapName = info.mapName;
this.description = info.description;
this.copyrightText = info.copyrightText;
this.supportsDynamicLayers = info.supportsDynamicLayers;
this.layers = info.layers;
this.TriggerInfoRetrievalFinished();
}
else { /* Do nothing. */ }
}
private void TriggerInfoRetrievalFinished()
{
if (this._infoRetrievalFinished != null) { this._infoRetrievalFinished(this, null); }
}
}
[DataContract]
public class LayerInfo
{
[DataMember] public int id { get; set; }
[DataMember] public string name { get; set; }
[DataMember] public int parentLayerId { get; set; }
[DataMember] public bool defaultVisibility { get; set; }
[DataMember] public List<int> subLayerIDs { get; set; }
[DataMember] public int minScale { get; set; }
[DataMember] public int maxScale { get; set; }
}
The very first time I run my Silverlight app I get the Visual Studio Just-In-Time Debugger popping up saying, "An unhandled exception ('Unhandled Error in Silverlight Application Code: 4004 Category: ManagedRuntimeError Message: System.Runtime.Serialization.SerializationException: 'html>".
If I say "No" to "Do you want to debug using the selected debugger?" and refresh the web page, the error does not return and my app runs as expected. It only happens the very first time I go into debug.
I have determined that the exception is thrown right after the curly brace that comes after my finally block under webClient_OpenReadCompleted(), just before the else statement. Nothing is caught in my catch statement.
I have never seen this before. Does anyone know what might be going on?
The problem is the data read is not valid serialized JSON.
The indicator in the error message - SerializationException: 'html><head> - is a give-away that the data is an [X]HTML document, not the JSON expected.
Then it's just a matter of finding out (and fixing) why such occurs - perhaps the server responded with a custom 403 or 404 response at such a time?
This issue, however, is separate from serialization - invalid data cannot be reliably deserialized.

InsertOnSubmit method throws NullReferenceException ... Linq to sql C# entity/DataContext class

Here's my DataContext class:
public class Dealer : DataContext
{
public Table<Vehicle> Vehicles;
public Table<Customer> Customers => GetTable<Customer>();
public Table<Account> Accounts;
public Table<Transaction> Transactions;
public Dealer(string connection) : base(connection) { }
}
Here's the Customer Class:
[Table(Name="Customers")]
public class Customer
{
[Column(IsPrimaryKey = true, DbType = "int NOT NULL IDENTITY", IsDbGenerated = true, CanBeNull = false)]
public int CustomerID { get; set; }
[Column(CanBeNull = false)]
public string FirstName { get; set; }
[Column(CanBeNull = false)]
public string LastName { get; set; }
[Column(CanBeNull = false)]
public string SSN { get; set; }
public override string ToString()
{
return string.Concat(this.FirstName, " ", this.LastName, " ", this.SSN);
}
private EntitySet<Vehicle> vehicles = null;
[Association(Storage = "vehicles", OtherKey = "CustomerID", ThisKey = "CustomerID")]
public EntitySet<Vehicle> Vehicles { get; set; }
//implement INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Here's the code that throws the NullReferenceException:
private void Button_Click(object sender, RoutedEventArgs e)
{
Customer c = new Customer() { FirstName="John", LastName="Smith", SSN = "123456" };
Dealer d = new Dealer(App.connectionString);
d.Customers.InsertOnSubmit(c); //d.Customers is null and throws null reference exception.!!!
try
{
d.SubmitChanges();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
I have googled for many hours now and I can't figure out why it's throwing NullReferenceException... (found a lot of other posts but non of the solutions seem to work for me )
Please help ...
Thanks in advance.
I had the same problem yesterday. Removing getters and setters from DataContext class helped. By the way I'd change CustomerId column property by addingAutoSync=Autosync.OnInsert

Get images from wordpress post with json in windows phone

I would like to get Images from a wordpress Blog. I would start only with one post not with all the posts images.
I am using this code. It works to get the title, excerpt, url... But I cant get images :
namespace WpWordpressJson
{
public class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>();
}
/// <summary>
/// A collection for ItemViewModel objects.
/// </summary>
public ObservableCollection<ItemViewModel> Items { get; private set; }
private string _sampleProperty = "Sample Runtime Property Value";
/// <summary>
/// Sample ViewModel property; this property is used in the view to display its value using a Binding
/// </summary>
/// <returns></returns>
public string SampleProperty
{
get
{
return _sampleProperty;
}
set
{
if (value != _sampleProperty)
{
_sampleProperty = value;
NotifyPropertyChanged("SampleProperty");
}
}
}
public bool IsDataLoaded
{
get;
private set;
}
/// <summary>
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// </summary>
public void LoadData()
{
WebRequest.RegisterPrefix("http://automaticband.es/bio/", WebRequestCreator.ClientHttp);
Uri serviceUri = new Uri("http://automaticband.es/bio/?json=get_recent_posts");
WebClient downloader = new WebClient();
downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
downloader.OpenReadAsync(serviceUri);
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
Stream responseStream = e.Result;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Posts));
Posts response = (Posts)ser.ReadObject(responseStream);
if (response.posts != null && response.posts.Count > 0)
{
foreach (Post post in response.posts)
{
this.Items.Add(new ItemViewModel() { LineOne = post.title, LineTwo = post.excerpt });
}
}
}
catch (Exception x)
{
return;
}
this.IsDataLoaded = true;
}
}
}
[DataContract]
public class Post
{
[DataMember]
public int id;
[DataMember]
public string type;
[DataMember]
public string slug;
[DataMember]
public string title;
[DataMember]
public string content;
[DataMember]
public string excerpt;
}
[DataContract]
public class Posts
{
[DataMember]
public int count;
[DataMember]
public int count_total;
[DataMember]
public List<Post> posts;
}
I got it from this site:
http://kevinashley.com/connect-windows-phone-7-apps-to-wordpress-using-json/
Thank you for all
You are missing the DataMember for thumbnails in Post. Here you can find a full class for WordPress JSON API: http://msicc.net/?p=2929
Hope this helps :-)