Get/Set HttpContext Session Methods in BaseController vs Mocking HttpContextBase to create Get/Set methods - asp.net-mvc

I created Get/Set HttpContext Session Methods in BaseController class and also Mocked HttpContextBase and created Get/Set methods.
Which is the best way to use it.
HomeController : BaseController
{
var value1 = GetDataFromSession("key1")
SetDataInSession("key2",(object)"key2Value");
Or
var value2 = SessionWrapper.GetFromSession("key3");
GetFromSession.SetDataInSession("key4",(object)"key4Value");
}
public class BaseController : Controller
{
public T GetDataFromSession<T>(string key)
{
return (T) HttpContext.Session[key];
}
public void SetDataInSession(string key, object value)
{
HttpContext.Session[key] = value;
}
}
Or
public class BaseController : Controller
{
public ISessionWrapper SessionWrapper { get; set; }
public BaseController()
{
SessionWrapper = new HttpContextSessionWrapper();
}
}
public interface ISessionWrapper
{
T GetFromSession<T>(string key);
void SetInSession(string key, object value);
}
public class HttpContextSessionWrapper : ISessionWrapper
{
public T GetFromSession<T>(string key)
{
return (T) HttpContext.Current.Session[key];
}
public void SetInSession(string key, object value)
{
HttpContext.Current.Session[key] = value;
}
}

The second one seems the best. Although I would probably write those two as extension methods to the HttpSessionStateBase instead of putting them into a base controller. Like this:
public static class SessionExtensions
{
public static T GetDataFromSession<T>(this HttpSessionStateBase session, string key)
{
return (T)session[key];
}
public static void SetDataInSession<T>(this HttpSessionStateBase session, string key, object value)
{
session[key] = value;
}
}
and then inside the controllers, or helpers, or something that has an instance of HttpSessionStateBase use it:
public ActionResult Index()
{
Session.SetDataInSession("key1", "value1");
string value = Session.GetDataFromSession<string>("key1");
...
}
Writing session wrappers is useless in ASP.NET MVC as the HttpSessionStateBase provided by the framework is already an abstract class which could be easily mocked in unit tests.

Just a little correction for the SetDataInSession method of the latest post. In my opinion, it´s a elegant solution! Thanks Darin Dimitrov.
public static class SessionExtensions
{
public static T GetDataFromSession<T>(this HttpSessionStateBase session, string key) {
return (T)session[key];
}
public static void SetDataInSession(this HttpSessionStateBase session, string key, object value) {
session[key] = value;
}
}
First create this class, and after remember to refer its namespace in the Controller class that will call this methods.
When getting the session value:
string value = Session.GetDataFromSession<string>("key1");
The must be a compatible type with the object persisted in the session.

Related

How to pass Dbset object as a parameter to any user define function in entity framework code first?

I want to pass Dbset Object to my method.
This is my Method:
public static class MyClass
{
public static Floor ReturnObject(this DbSet<Floor> floor, int Id)
{
var context = floor.passContext() as MyDBContext;
var data = context.floors.Where(a =>a.Id == Id).FirstOrDefault();
return ad;
}
}
public class MyDBContext: DbContext
{
public DbSet<Floor> floors { get; set; }
}
public static DbContext passContext<TEntity>(this DbSet<TEntity> dbSet)
where TEntity : class
{
//code....
}
Now i want to use my method of static class MyClass that is ReturnObject.
I want to use ReturnObject method in my Controller.
I know i can declare it as private member like this in my controller:
This is my controller:
public class MyController
{
private DbSet<Floor> floor;//but is this a good way???
public ActionResult Index(int Id)
{
var data=MyClass.ReturnObject(????,Id)//what should come in place of question mark??
}
}
How should i pass my First Parameter to ReturnObject Method???
Change your ReturnObject method. It should only take Id as parameter and filter data than return object of Floor.
public static Floor ReturnObject(int Id)
{
using(MyDBContext context = new MyDBContext())
{
var data = context.floors.Where(a =>a.Id == Id).FirstOrDefault();
return ad;
}
}
And when you call it than only pass id as paramter
var data=MyClass.ReturnObject(Id);
This will return object of floor which will be stored in data.

Autofac and DI for ValidationAttribute

I have the following validation attribute class:
public class ZipCodeValidationAttribute : ValidationAttribute
{
private readonly IValidationRepository _repository;
public override bool IsValid(object value)
{
var repository = _repository;
return repository.IsPostalCodeValid((string) value);
}
}
To test I am trying to use Autofac as my IOC and use property injection. I've set up the test as follows:
[TestMethod]
public void When_PostalCodeAttribute_Given_ValidPostalCode_Then_SystemReturnsTrue()
{
// arrange
var value = "53051";
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterType<ValidationRepository>().As<IValidationRepository>().InstancePerDependency();
containerBuilder.RegisterType<ZipCodeValidationAttribute>().PropertiesAutowired();
var container = containerBuilder.Build();
var attrib = container.Resolve<ZipCodeValidationAttribute>();
// act
var result = attrib.IsValid(value);
// assert
Assert.IsTrue(result);
}
During the test my repository isn't being resolved. New to Autofac and hoping someone can point me in the right direction.
I solved the whole problem (triggering DI under the control of Validator.TryValidate etc / ASP.NET MVC etc) in this answer, enabling one to write:
class MyModel
{
...
[Required, StringLength(42)]
[ValidatorService(typeof(MyDiDependentValidator), ErrorMessage = "It's simply unacceptable")]
public string MyProperty { get; set; }
....
}
public class MyDiDependentValidator : Validator<MyModel>
{
readonly IUnitOfWork _iLoveWrappingStuff;
public MyDiDependentValidator(IUnitOfWork iLoveWrappingStuff)
{
_iLoveWrappingStuff = iLoveWrappingStuff;
}
protected override bool IsValid(MyModel instance, object value)
{
var attempted = (string)value;
return _iLoveWrappingStuff.SaysCanHazCheez(instance, attempted);
}
}
With some helper classes (look over there), you wire it up e.g. in ASP.NET MVC like so in the Global.asax :-
DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(
typeof(ValidatorServiceAttribute),
(metadata, context, attribute) =>
new DataAnnotationsModelValidatorEx(metadata, context, attribute, true));
You need to declare the repository as a property to be auto wired by Autofac.
public class ZipCodeValidationAttribute : ValidationAttribute
{
public IValidationRepository Repository { get; set; }
public override bool IsValid(object value)
{
return Repository .IsPostalCodeValid((string) value);
}
}

How to configure ObjectFactory to call parameterized constructor structuremap

PLEASE: If my question isn't clear, please tell me and I'll try to rephrase it
I need [Default Constructor] in LogOnModel, so it can't be removed.
LoadModel+ModelFactory and LogOnModel are physically in different files in different projects AND project2 has reference to project1 and NOT vice versa.
1 - Let say that
type=typeof(LogOnModel). When ObjectFactory.GetInstance(t) is called I want it to call the
parameterized constructor of LogOnModel and pass it the #params
2 - If I'll add to the parameterized constructor of LogOnModel another parameter,for example
public LogOnModel(string param, IPageService pageService)
so ObjectFacytory should call this constructor without any problems
How to configure/initiate ObjectFactory, so this will work?
Thank you
EDITED
//Project1/file1.cs
public void LoadModel(Type type, string param)
{
var factory = new ModelFactory();
var model = factory.Get(type, **param**);
}
public class ModelFactory : IModelFactory
{
public PageModel Get(Type t, **string param**)
{
//NOW I NEED SOMEHOW TO PASS **param** TO EVERY INSTANCE THAT INHERITS FROM **PageModel**
return ObjectFactory.GetInstance(t) as PageModel;
}
}
//Project2/file2.cs
public class LogOnModel : PageModel
{
public LogOnModel()
{
}
public LogOnModel(string param)
{
}
}
public class Model2 : PageModel
{
public LogOnModel()
{
}
public LogOnModel(string param)
{
}
}
public class Model3 : PageModel
{
public LogOnModel()
{
}
public LogOnModel(string param)
{
}
}
StructureMap will use the constructor with the most parameters by default, so that part is easy. Then you just need to configure the value of param like so:
ObjectFactory.Initialize(i => {
i.For<LogOnModel>().Use<LogOnModel>();
});
When you call the container, use the with method to pass in your parameter:
return ObjectFactory.With("param").EqualTo(param).GetInstance(t) as PageModel;

Ninject And Connection Strings

I am very new to Ninject and am trying Ninject 2 with MVC and Linq. I have a SqlProductRepository class and all I want to know is what's the best way of passing the connectionstring in the constructor if I am injecting the Repository object in the controller.
public class SqlProductRepository:IProductRepository
{
private Table<Product> productsTable;
public SqlProductRepository(string connectionString)
{
productsTable = (new DataContext(connectionString)).GetTable<Product>();
}
public IQueryable<Product> Products
{
get { return productsTable; }
}
}
This is my ProductController class where I am injecting the Repository:
public class ProductsController : Controller
{
private int pageSize = 4;
public int PageSize { get { return pageSize; } set { pageSize = value; } }
IProductRepository _productsRepository;
[Inject]
public ProductsController(IProductRepository productRepository)
{
_productsRepository = productRepository;
}
public ViewResult List(int page)
{
return View(_productsRepository.Products
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList()
);
}
}
Can somebody please guide me regarding this?
You can set it up in your binding
_kernel.Bind<IProductRepository>()
.To<SqlProductRepository>()
.WithConstructorArgument("connectionString",yourConnectionString );
You're doing:
new DataContext(connectionString)
in your code - this is the very newing and binding to classes you're trying to push out of your code by using a DI container. At the very least, consider adding an IConnectionStringSelector interface or something like that. You dont want to have 20 Bind calls for 20 repositories - you want a higher level abstraction than that.
I'd suggest the best solution is that you should be demanding either an IDataContext or an IDataContextFactory in the constructor instead and letting that worry about it.
You could supply the connection string as a constructor argument when binding the SqlProductRepository to the IProductRepository interface.
public class LinqToSqlModule : NinjectModule
{
public override void Load()
{
Bind<IProductRepository>().To<SqlProductRepository>()
.WithConstructorArgument(connectionString, "connectionstring");
}
}
I would suggest a slightly different approach. First of all, you might want to create a binding for the DataContext class in the kernel. You could do so by using a provider class to create your DataContext passing the connection string as an argument to its constructor. Then you bind the DataContext to the DataContextProvider.
public class DataContextProvider : Provider<DataContext>
{
protected override DataContext CreateInstance(IContext context)
{
string connectionString = "connectionstring";
return new DataContext(connectionString);
}
}
public class LinqToSqlModule : NinjectModule
{
public override void Load()
{
Bind<DataContext>().ToProvider<DataContextProvider>();
Bind<IProductRepository>().To<SqlProductRepository>();
}
}
Next modify the constructor of SqlProductRepository class to accept a DataContext object instead.
public class SqlProductRepository : IProductRepository
{
private readonly DataContext context;
public ProductRepository(DataContext context)
{
this.context = context;
}
public IQueryable<Product> Products
{
get { return context.GetTable<Product>(); }
}
}
By the way you don't have to decorate your constructor with the Inject attribute. Ninject will select the constructor with the most parameters by default.
Please refer below code snap:
//Bind the default connection string
public void BindDataContext()
{
ConstructorArgument parameter = new ConstructorArgument("connectionString", "[Config Value]");
Bind<DataContext>().ToSelf().InRequestScope().WithParameter(parameter);
}
//Re-Bind the connection string (in case of multi-tenant architecture)
public void ReBindDataContext(string cn)
{
ConstructorArgument parameter = new ConstructorArgument("connectionString", cn);
Rebind<DataContext>().ToSelf().InRequestScope().WithParameter(parameter);
}
For more information, please visit below link
MVC3, Ninject and Ninject.MVC3 problem

ASP.NET MVC - How to access Session data in places other than Controller and Views

We can access session data in controllers and views like this:
Session["SessionKey1"]
How do you access Session values from a class other than a controller or view?
I'd use dependency injection and pass the instance of the HttpContext (or just the session) to the class that needs access to the Session. The other alternative is to reference HttpContext.Current, but that will make it harder to test since it's a static object.
public ActionResult MyAction()
{
var foo = new Foo( this.HttpContext );
...
}
public class Foo
{
private HttpContextBase Context { get; set; }
public Foo( HttpContextBase context )
{
this.Context = context;
}
public void Bar()
{
var value = this.Context.Session["barKey"];
...
}
}
You just need to call it through the HttpContext like so:
HttpContext.Current.Session["MyValue"] = "Something";
Here is my version of a solution for this problem. Notice that I also use a dependency injection as well, the only major difference is that the "session" object is accessed through a Singleton
private iSession _Session;
private iSession InternalSession
{
get
{
if (_Session == null)
{
_Session = new SessionDecorator(this.Session);
}
return _Session;
}
}
Here is the SessionDecorator class, which uses a Decorator pattern to wrap the session around an interface :
public class SessionDecorator : iSession
{
private HttpSessionStateBase _Session;
private const string SESSIONKEY1= "SESSIONKEY1";
private const string SESSIONKEY2= "SESSIONKEY2";
public SessionDecorator(HttpSessionStateBase session)
{
_Session = session;
}
int iSession.AValue
{
get
{
return _Session[SESSIONKEY1] == null ? 1 : Convert.ToInt32(_Session[SESSIONKEY1]);
}
set
{
_Session[SESSIONKEY1] = value;
}
}
int iSession.AnotherValue
{
get
{
return _Session[SESSIONKEY2] == null ? 0 : Convert.ToInt32(_Session[SESSIONKEY2]);
}
set
{
_Session[SESSIONKEY2] = value;
}
}
}`
Hope this helps :)
Haven't done it myself, but this sample from Chad Meyer's blog might help (from this post: http://www.chadmyers.com/Blog/archive/2007/11/30/asp.net-webforms-and-mvc-in-the-same-project.aspx)
[ControllerAction]
public void Edit(int id)
{
IHttpSessionState session = HttpContext.Session;
if (session["LoggedIn"] == null || ((bool)session["LoggedIn"] != true))
RenderView("NotLoggedIn");
Product p = SomeFancyDataAccess.GetProductByID(id);
RenderView("Edit", p);
}
I would also wrap all session variables into a single class file. That way you can use intelliSense to select them. This cuts down on the number of paces in code where you need to specify the "strings" for the session.

Resources