Change default session provider in ASP.NET - asp.net

I want to change my session proviced to statically typed - I just hate typing strings because of many many errors I do.
What technology am I using? ASP.NET MVC via EXT.NET MVC
I was trying to do that using web.config but the problem is that after add session state to it visual is not going to compile my code because of that session should be using strings as keys.
I want to use session by enums such as :
public enum SessionEnum{Model}
public class Bar{
void foo(){
Session[SessionEnum.Model] = "blah";
}
}
I am aware that I can create wrapper converting enums to strings but it's not very satisfying solution for me.
public class StorageWrapper{
public object this[SessionEnum enum]{ get{return Session[enum.toString()]}; //+set
}
What I did was create static object for base class for all of my controllers and then I was able to use it across them but after closing and opening the page again I wasn't able to get values from it. I guess I should serialize them somehow but I have no idea how.
Is there any way to do that?
EDIT
My session now looks like this :
[Serializable]
public abstract class DataWrapper<T> : HttpSessionStateBase
{
Dictionary<T, object> Dictionary { get; set; } = new Dictionary<T, object>();
public object this[T a]
{
get
{
try
{
return Dictionary[a];
}
catch
{
return null;
}
}
set { Dictionary[a] = value; }
}
}
[Serializable]
public class SessionWrapper : DataWrapper<SessionNames>
{}
public enum SessionNames { Model, Login, LastOpenedFile }

It's very simple.
Create a UserSession object which does everything you want (holds your values as enum etc), instantiate it, then put it in the session.
var US = new UserSession();
US.stuff = somestuff;
Session["UserSess"] = US
Then you can just always use Session["UserSess"].stuff;

Mmmm, wouldn't you use static const string instead of an enum?
using System.Web;
public static class SessionEnum
{
public static const string Model = "_Session_Model";
public static const string Login = "_Session_Login";
public static const string LastOpenedFile = "_Session_LastOpenedFile ";
}
class test
{
void test()
{
Session[SessionEnum.Model] = "blah";
}
}

Related

any work around to allow for an action result to accept a Abstract class as parameter

I have different configurations all inheriting from a base configuration that are customized in forms. I want all of these to be handled by a single action result.
[HttpPost]
public IActionResult Register(AbstractBaseConfig config)
{
...do some logic...
return View("../Home/Index");
}
However, this is not possible because you cannot base in abstract classes as a parameter to an action result. Is there any work around for this so I don't need a seperate action result for each configuration? (I still want each configuration to be it's own class, I only need access to the base class methods in the action result logic).
Basically you can't, and the reason is that MVC will try to do new AbstractBaseConfig() as part of the Data Binding process (which parses the URL or the Form Post and puts the results in a concrete object). And by definition, doing new AbstractBaseConfig() is impossible for an abstract class.
It also makes sense for other reasons, I will explain why.
You seem to expect that MVC can determine the class from the parameters that are being passed in. That is not how it works, in fact the opposite is true: the Action Method has to specify the exact class, and then the Binder will instantiate that exact class and try to bind its properties.
Suppose you had this:
public abstract class Thing { public int ID { get;set; } }
public class NamedThing : Thing { public string Name { get;set; } }
public class OtherThing : Thing { public string Name { get;set; } }
and suppose it would be allowed to use:
public IActionResult Register(Thing thing)
then what would you expect to be in thing after Data Binding: a Thing object with only the ID set? Or one of the other object types, with Name set, but how would MVC ever be able to know which class you meant?
So for all these reasons, this is not possible.
You could have a base class inherit the abstract class and all your classes inherit from that base class whilst having that base class as your parameter
Take for example
public abstract class ABase
{
public void stuff()
{
var stuff = string.Empty;
stuff = "hello";
}
public virtual void otherstuff()
{
var stuff = string.Empty;
stuff = "hello";
}
}
public class Base : ABase
{
//empty
}
public class Derived : Base
{
public void mystuff()
{
this.stuff();
}
public override void otherstuff()
{
// Custom code
}
}
public ActionResult Register(Base config)
{
}

Xamarin Forms overriding OnAppearing causes app to crash

I am trying to do a simple override and load some data when my page loads, I am using the following code in the code behind page.
namespace XYZ
{
public partial class MainPage : ContentPage
{
private Label results;
private Label groupResults;
public MainPage()
{
InitializeComponent();
results = new Label();
groupResults = new Label();
}
protected override void OnAppearing()
{
base.OnAppearing();
storeIdTxt.Text = Settings.StoreIdSetting;
}
}
}
If I uncomment the override things works just fine, the error I am getting seems to be a generic one attached here
my settings class is fairly simple as follows
using System;
using System.Collections.Generic;
using System.Text;
using Plugin.Settings;
using Plugin.Settings.Abstractions;
namespace NWMPosNG.Helpers
{
/// <summary>
/// This is the Settings static class that can be used in your Core solution or in any
/// of your client applications. All settings are laid out the same exact way with getters
/// and setters.
/// </summary>
public static class Settings
{
private static ISettings AppSettings
{
get
{
return CrossSettings.Current;
}
}
#region Setting Constants
private const string SettingsKey = "settings_key";
private static readonly string SettingsDefault = string.Empty;
private const string StoreId = null;
private static readonly string StoreIdDefault = "0";
#endregion
public static string GeneralSettings
{
get
{
return AppSettings.GetValueOrDefault(SettingsKey, SettingsDefault);
}
set
{
AppSettings.AddOrUpdateValue(SettingsKey, value);
}
}
public static string StoreIdSetting
{
get
{
return AppSettings.GetValueOrDefault(StoreId, StoreIdDefault);
}
set
{
AppSettings.AddOrUpdateValue(StoreId, value);
}
}
}
}
I narrowed down the issue to when I access the saved data using
storeIdTxt.Text = Settings.StoreIdSetting;
But I don't understand why that causes the crash.
You are using the Settings Plugin from James Montemagno. Which is pretty much a KeyValuePair that is stored on the local device across sessions.
In your case:
AppSettings.GetValueOrDefault(StoreId, StoreIdDefault);
Translates to:
AppSettings.GetValueOrDefault(null, "0");
Which crashes because 'null' can't be a key. That's why setting the key (StoreId) prevents the crash from happening.
This line was the culprit
private const string StoreId = null;
I don't really understand why but setting this to a non NULL value makes the crash go away

Better way to cache a Model

My simple repository's getAll method:
public List<ListModel> GetAllLists()
{
using (MySqlConnection connection = new MySqlConnection(this.connectionString))
{
return connection.Query<ListModel>("SELECT * FROM projectx.lists").AsList();
}
}
I'm using this class I've found here in so to handle caching:
public class CacheUtils : ICacheService
{
public TValue Get<TValue>(string cacheKey, Func<TValue> getItemCallback, double durationInMinutes = 120) where TValue : class
{
TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
if (item == null)
{
Debug.WriteLine("Not cached");
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
}
else
Debug.WriteLine("Cached!");
return item;
}
public TValue Get<TValue, TId>(string cacheKeyFormat, TId id, Func<TId, TValue> getItemCallback, double durationInMinutes = 120) where TValue : class
{
string cacheKey = string.Format(cacheKeyFormat, id);
TValue item = MemoryCache.Default.Get(cacheKey) as TValue;
if (item == null)
{
item = getItemCallback(id);
MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));
}
return item;
}
}
Home controller:
public ActionResult Index()
{
ListRepository listRep = new ListRepository();
CacheUtils cache = new CacheUtils();
return View(cache.Get("lists", listRep.GetAllLists));
}
Question, is there a better way of handling cache than calling the helper from the controller? Ideally, it should be inside the repository method. But do I need to repeat the check for existing cache data on every single method of the repository? Ie.:
public List<ListModel> GetAllLists()
{
var lists = Cache["lists"];
if(lists == null)
{
using (MySqlConnection connection = new MySqlConnection(this.connectionString))
{
lists = connection.Query<ListModel>("SELECT * FROM projectx.lists").AsList();
}
Cache["lists"] = lists;
}
return ((List<ListModel>)lists);
}
Use a decorator pattern and don't polute business or ui with caching logic.
Wire it up with something like ninject (or poor bastards if you dont want to add a DI) I'd recommend marking it as single instance.
Benefits include:
Adding a invalidating method like void Save(ListModel) is easy to
invalidate the cache.
Your top layer and bottom layer know nothing
about the fact they have been cached.
You can also decorate again to add in logging, profiling, etc
You can also control the caching life cycle
you don't polute the controller level with caching logic
easy to remove
So something like the below would work. For how too add decorators in ninject see https://stackoverflow.com/a/8910599/1073280
public class MyHomeController
{
private readonly IListCrud _listcrud;
public MyHomeController(IListCrud listcrud)
{
_listcrud = listcrud;
}
public ActionResult Index()
{
return View(_listcrud.GetAllLists());
}
}
public interface IListCrud
{
List<ListModel> GetAllLists();
}
public class ListCrud : IListCrud
{
public List<ListModel> GetAllLists()
{
using (MySqlConnection connection = new MySqlConnection(this.connectionString))
{
return connection.Query<ListModel>("SELECT * FROM projectx.lists").AsList();
}
}
}
public class ListCrudCache : IListCrud
{
private readonly ICacheService _cache;
private readonly IListCrud _inner;
public ListCrudCache(ICacheService cache, IListCrud inner)
{
_cache = cache;
_inner = inner;
}
public List<ListModel> GetAllLists()
{
return _cache.Get("lists", _inner.GetAllLists);
}
}
Opinion: maybe just to keep the code small but be careful using select * with a ORM. if someone renames or removes a column you wont have any easy to unit test/detect failure mechanism.
In my opinion it shouldn't be in the repository, as it (to me) smells like violation or SRP. Caching should be a higher level service above the repository.
You need to think about what actually needs the benefits of the caching. If the caching is for speeding up the WEB API interface, then having it in the controller is the best way by far. If you need caching elsewhere too, consider introducing some middle layer service classes and put caching there, but I would always make it optional in some way.

ASP.NET MVC How to avoid static variables?

recently posted about questioning how unsafe static variables are, I've since discovered I need to get rid of them. But I cannot figure out how to? Was thinking a static Get() method for each class, that returns a single instance, but then that instance would have to be declared static.
So the only way to do it, is to have the instance references (for each helper, I.E user helper.cs, imagehelper.cs etc.) is to declare them as instance properties on some sort of globally accessible class? But which class? Is there something I'm missing here?
Code below of a sample class I need to change:
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvc.Mailer;
namespace MVCWebsite.Helpers
{
public class AppSettings
{
public static void OnAppInit()
{
//General
AppName = "MyApp";
DesktopBaseURLs = new Dictionary<string, string>();
DesktopBaseURLs.Add("dev", "localhost:50560");
DesktopBaseURLs.Add("test", "www.test.whatever.com");
DesktopBaseURLs.Add("live", "www.whatever.com");
MobileBaseURLs = new Dictionary<string, string>();
MobileBaseURLs.Add("dev", "m.local.whatever.com");
MobileBaseURLs.Add("test", "m.test.whatever.com");
MobileBaseURLs.Add("live", "m.whatever.com");
//Emails
EmailHostName = AppName + ".com"; //For the moment atleast
NoReplyEmailAddress = "no-reply#" + EmailHostName.ToLower();
SupportEmailAddress = "support#" + EmailHostName.ToLower();
ErrorEmailAddress = "errors#" + EmailHostName.ToLower();
//Resources
TempFileURL = "/content/temp/";
UserDataURL = "/content/user-content/";
ProfilePicturesURL = UserDataURL + "profile-pictures/";
var a = GlobalHelper.GetURLAsServerPath(ProfilePicturesURL);
var b = a;
}
//General
public static string AppName { get; set; }
public static Dictionary<string, string> DesktopBaseURLs;
public static Dictionary<string, string> MobileBaseURLs;
//Emails
public static string EmailHostName { get; set; }
public static string NoReplyEmailAddress { get; set; }
public static string SupportEmailAddress { get; set; }
public static string ErrorEmailAddress { get; set; }
//Resources
public static string UserDataURL { get; set; }
public static string TempFileURL { get; set; }
public static string ProfilePicturesURL { get; set; }
//Methods
public static void SetAppURL()
{
}
}
}
I recommend creating an interface for your AppSettings class, so that you can use it in your controllers now, and implement it in different ways as you see fit:
public interface IAppSettings
{
string AppName { get; set; }
...
}
You can then implement it immediately with your static class via a wrapper class:
public class AppSettingsWrapper : IAppSettings
{
public AppName
{
get
{
return AppSettings.AppName;
}
set
{
AppSettings.AppName = value;
}
}
...
}
Later on, you can create an implementation of IAppSettings that uses session, or cookies, or database values, or whatever. The important thing is to abstract the way you store things so that you can implement in a way that meets your needs.
The answer to you previous question clearly stated that the IDictionary was the only unsafe variable in your static method because it's not thread safe. You just need to store these variables differently. You don't need to get rid of all of your static variables. You just need to change IDictionary to something thread safe.
By the way, someone there makes a good coment about web.config
Right I think I've figured it out, they should be stored as instance variables within Global.asax.cs. This file contains your Application class which inherits from System.Web.HttpApplication. This master class is limited to one instance (of itself) per request. So if you store any references to your helpers here, you can reference them by going, MvcApplication.MyHelper.DoSomething(); Someone please correct me if this is wrong, but seems right to me. "At any single point of time, an HTTPApplication instance handles only one request, so we don't need to think about locking and unlocking of any non static members, but for static members we do require. " -from : http://www.codeproject.com/Articles/87316/A-walkthrough-to-Application-State#c

ASP.NET [ScriptIgnore] doesn't work on related objects

the [ScriptIgnore] attribute works fine for me on the direct object that is getting serialized, but if I put it on a property of a related object (that is referenced from a property on the direct object), it doesn't apply?
i.e Json(user)
I.E
class user {
Badges badges
}
class Badge {
[ScriptIgnore]
SomeObject obj; //Causes circular reference error because scriptignore doesn't apply
}
Is there a way to get around this?
Is there a way to get around this?
I would recommend you using a view model exposing only the properties you need and passing the view model to the Json method.
If you don't want to follow the view model approach I recommend then the [ScriptIgnore] attribute should also work for you.
Example:
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
public class User
{
public IEnumerable<Badge> Badges { get; set; }
}
public class Badge
{
[ScriptIgnore]
public User User { get; set; }
}
public class Program
{
static void Main()
{
var user = new User();
var badge = new Badge { User = user };
user.Badges = new[] { badge };
var serializer = new JavaScriptSerializer();
Console.WriteLine(serializer.Serialize(user));
}
}
If you remove the [ScriptIgnore] attribute from the User property on the Badge class JSON serialization will fail due to circular reference error.

Resources