How can I retrieve a value from IsolatedStorage in other class? - class

I have two classes. First is using for store boolean value from ToggleSwitchButton by using IsolatedStorage.
Like this...
private void tglSwitch_Checked(object sender, RoutedEventArgs e)
{
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["EnableLocation"] = true;
}
private void tglSwitch_Unchecked(object sender, RoutedEventArgs e)
{
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["EnableLocation"] = false;
}
The second class will use the boolean value from the first class to do something.
Like this...
if(booleanValFromFirst){
//Do something
}
else{
//Do something
}
Thanks.

Is this, what you want?
if ((bool)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["EnableLocation"] == true)
P.S. I would recommend for you to create a single class for all values, stored in Application Settings and work with it.
Like this:
public static class SettingsManager
{
private static IsolatedStorageSettings appSettings;
public static IsolatedStorageSettings AppSettings
{
get { return SettingsManager.appSettings; }
set { SettingsManager.appSettings = value; }
}
public static void LoadSettings()
{
// Constructor
if (appSettings == null)
appSettings = IsolatedStorageSettings.ApplicationSettings;
// Generate Keys if not created
if (!appSettings.Contains(Constants.SomeKey))
appSettings[Constants.SomeKey] = "Some Default value";
// generate other keys
}
}
Then you can work with that class instance
Initialize it at your startup class as SettingsManager.LoadSettings();
an then in any class just call for it:
if ((bool)SettingsManager.AppSettings[Constants.SomeBoolKey])
doSomething();

Related

interface does not give me initalize method

I am missing method from interface
value of annotiations is null.
Already tried hardcoded, it works, but I need to be customizable.
package com.luv2code.springdemo.mvc.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class CourseCodeConstraintValidator implements ConstraintValidator {
private String coursePrefix;
public void initalize(CourseCode theCourseCode) {
coursePrefix = theCourseCode.value();
}
#Override
public boolean isValid(String theCode, ConstraintValidatorContext theConstraintValidatorContext) {
/*if (coursePrefix==null)
coursePrefix = "LUV";*/
System.out.println(theConstraintValidatorContext.getDefaultConstraintMessageTemplate());
boolean result;
if (theCode!=null) {
System.out.println(coursePrefix);
result = theCode.startsWith(coursePrefix);
} else {
result = true;
}
return result;
}
}
Expecting possible #Override method initialize
initalize => initialize
just one letter missing

set property of new instance

thank you for helping.
First, I created a form with a (user defined) property.
as see below
public partial class nfrmtableitem : Form
{
private DataRow _datarow;
public DataRow U_Table_Row { get { return _datarow; } set { _datarow = value; } }
public nfrmtableitem()
{
InitializeComponent();
}
}
And I create second form with property as type of Form.
as see below
public partial class nftableshow : Form
{
private DataTable _datatable;
public DataTable U_DataTable { get { return _datatable; } set { _datatable = value; } }
private Form _inputform1;
public Form U_DGV_InputForm1 { get { return _inputform1; } set { _inputform1 = value; } }
}
when call it:
any where
nftableshow newfrmtableshow = new nftableshow()
{
Name = "newfrmtableshow",
Text = "Show the table",
MdiParent = this,
U_DGV_InputForm1 = new nfrmtableitem(),
};
newfrmtableshow.Show();
But I can not use the first form property in second form.
and the property is not in instance.
//the button in second form
private void button1_Click_Click(object sender, EventArgs e)
{
Form f1 = _inputform1 as Form;
/*
* {
* U_Table_Row = db.maindataset.Tables["customer"].NewRow(),
* };
*/
f1.Show();
}
Question:
How can I use the First form with specific (user defined) property in second form.
Regards
You should probably use dot notation to access the property of the first form. Try using
//the button in second form
private void button1_Click_Click(object sender, EventArgs e)
{
Form f1 = _inputform1 as Form;
{
f1.U_Table_Row = db.maindataset.Tables["customer"].NewRow(),
};
f1.Show();
}

Creating a hot observable and adding things to it

I am trying to create a hot observable where I can add stuff to it. Here's an outline of the basic class
public class MyObservable
{
public IObservable<string> Stream;
public MyObservable()
{
Observable.Create...?
}
public void AddString(string eventDescription)
{
//Add to Stream
}
}
Somewhere else in the code I want to be able to do something like
var ob = new MyObservable();
MyObservable.Add("User created");
Then somewhere else something like:
ob.Stream.Subscribe(Console.WriteLine);
I am not really sure how I am supposed to add strings to the observable
edit: I've tried doing something like this, but I'm not sure if maybe I'm not doing things in the way it's supposed to be done
private IObserver<string> _observer;
public void Add(string e)
{
if(Stream == null)
{
Stream = Observable.Create<string>(
(IObserver<string> observer) =>
{
_observer = observer;
observer.OnNext(e);
return Disposable.Empty;
});
}
else
{
_observer.OnNext(e);
}
}
You should do a little more reading on the contracts of observables and observers
Regardless, what you are looking for is a Subject, which implements both the Observable and Observer interfaces.
If you still want to wrap it it would look like so:
public class MyObservable
{
private Subject<string> subject;
public IObservable<string> Stream
{
get { return this.subject.AsObservable();
}
public MyObservable()
{
subject = new Subject<string>();
}
public void AddString(string eventDescription)
{
//Add to Stream
this.subject.OnNext(eventDescription);
}
}

Fluent NHibernate not querying the database correctly

i have just looked into hooking my application into nhibernate (fluent nhibernate) but i am having a few difficulties...
I have tried to follow what people have done and found this:
public class NHibernateSessionPerRequest : IHttpModule
{
private static readonly ISessionFactory _sessionFactory;
static NHibernateSessionPerRequest()
{
_sessionFactory = CreateSessionFactory();
}
public void Init(HttpApplication context)
{
context.BeginRequest += BeginRequest;
context.EndRequest += EndRequest;
}
public static ISession GetCurrentSession()
{
return _sessionFactory.GetCurrentSession();
}
public void Dispose() { }
private static void BeginRequest(object sender, EventArgs e)
{
ISession session = _sessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
private static void EndRequest(object sender, EventArgs e)
{
ISession session = CurrentSessionContext.Unbind(_sessionFactory);
if (session == null) return;
try
{
session.Transaction.Commit();
}
catch (Exception)
{
session.Transaction.Rollback();
}
finally
{
session.Close();
session.Dispose();
}
}
private static ISessionFactory CreateSessionFactory()
{
string connString = "AV8MediaUser";
FluentConfiguration configuration = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(
x => x.FromConnectionStringWithKey(connString)))
.ExposeConfiguration(
c => c.SetProperty("current_session_context_class", "web"))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Category>());
return configuration.BuildSessionFactory();
}
}
But when i run it through it seems to connect to the database correctly but it doesnt run a query:
return Session.CreateCriteria<Category>()
.List<Category>();
Am i doing something stupidly wrong?
CreateCriteria expects you to specify a model object name that you'd like to retrieve instances of. You seem to be missing your model object type name. Try something more like this:
List<YourModelObject> results = session.CreateCriteria<YourModelObject>()
.List<YourModelObject>();
To see what's actually being sent to the database consider using Ayende's NHProfiler - it will come in handy later when seeing what your more complex criteria queries or HQL queries actually result in...
Got it... i didnt realise that my mappings werent included in the project for some unknown reason... but included them again and it is all good!
Weird how it didnt throw an error though.

Refactoring two basic classes

How would you refactor these two classes to abstract out the similarities? An abstract class? Simple inheritance? What would the refactored class(es) look like?
public class LanguageCode
{
/// <summary>
/// Get the lowercase two-character ISO 639-1 language code.
/// </summary>
public readonly string Value;
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language)
{
if (language == null)
{
return null;
}
if (language.Length > 2)
{
language = language.Substring(0, 2);
}
try
{
return new LanguageCode(language);
}
catch (ArgumentException)
{
return null;
}
}
}
public class RegionCode
{
/// <summary>
/// Get the uppercase two-character ISO 3166 region/country code.
/// </summary>
public readonly string Value;
public RegionCode(string region)
{
this.Value = new RegionInfo(region).TwoLetterISORegionName;
}
public static RegionCode TryParse(string region)
{
if (region == null)
{
return null;
}
if (region.Length > 2)
{
region = region.Substring(0, 2);
}
try
{
return new RegionCode(region);
}
catch (ArgumentException)
{
return null;
}
}
}
It depends, if they are not going to do much more, then I would probably leave them as is - IMHO factoring out stuff is likely to be more complex, in this case.
Unless you have a strong reason for refactoring (because you are going to add more classes like those in near future) the penalty of changing the design for such a small and contrived example would overcome the gain in maintenance or overhead in this scenario. Anyhow here is a possible design based on generic and lambda expressions.
public class TwoLetterCode<T>
{
private readonly string value;
public TwoLetterCode(string value, Func<string, string> predicate)
{
this.value = predicate(value);
}
public static T TryParse(string value, Func<string, T> predicate)
{
if (value == null)
{
return default(T);
}
if (value.Length > 2)
{
value = value.Substring(0, 2);
}
try
{
return predicate(value);
}
catch (ArgumentException)
{
return default(T);
}
}
public string Value { get { return this.value; } }
}
public class LanguageCode : TwoLetterCode<LanguageCode> {
public LanguageCode(string language)
: base(language, v => new CultureInfo(v).TwoLetterISOLanguageName)
{
}
public static LanguageCode TryParse(string language)
{
return TwoLetterCode<LanguageCode>.TryParse(language, v => new LanguageCode(v));
}
}
public class RegionCode : TwoLetterCode<RegionCode>
{
public RegionCode(string language)
: base(language, v => new CultureInfo(v).TwoLetterISORegionName)
{
}
public static RegionCode TryParse(string language)
{
return TwoLetterCode<RegionCode>.TryParse(language, v => new RegionCode(v));
}
}
This is a rather simple question and to me smells awefully like a homework assignment.
You can obviously see the common bits in the code and I'm pretty sure you can make an attempt at it yourself by putting such things into a super-class.
You could maybe combine them into a Locale class, which stores both Language code and Region code, has accessors for Region and Language plus one parse function which also allows for strings like "en_gb"...
That's how I've seen locales be handled in various frameworks.
These two, as they stand, aren't going to refactor well because of the static methods.
You'd either end up with some kind of factory method on a base class that returns an a type of that base class (which would subsequently need casting) or you'd need some kind of additional helper class.
Given the amount of extra code and subsequent casting to the appropriate type, it's not worth it.
Create a generic base class (eg AbstractCode<T>)
add abstract methods like
protected T GetConstructor(string code);
override in base classes like
protected override RegionCode GetConstructor(string code)
{
return new RegionCode(code);
}
Finally, do the same with string GetIsoName(string code), eg
protected override GetIsoName(string code)
{
return new RegionCode(code).TowLetterISORegionName;
}
That will refactor the both. Chris Kimpton does raise the important question as to whether the effort is worth it.
I'm sure there is a better generics based solution. But still gave it a shot.
EDIT: As the comment says, static methods can't be overridden so one option would be to retain it and use TwoLetterCode objects around and cast them, but, as some other person has already pointed out, that is rather useless.
How about this?
public class TwoLetterCode {
public readonly string Value;
public static TwoLetterCode TryParseSt(string tlc) {
if (tlc == null)
{
return null;
}
if (tlc.Length > 2)
{
tlc = tlc.Substring(0, 2);
}
try
{
return new TwoLetterCode(tlc);
}
catch (ArgumentException)
{
return null;
}
}
}
//Likewise for Region
public class LanguageCode : TwoLetterCode {
public LanguageCode(string language)
{
this.Value = new CultureInfo(language).TwoLetterISOLanguageName;
}
public static LanguageCode TryParse(string language) {
return (LanguageCode)TwoLetterCode.TryParseSt(language);
}
}