keep variable throughout the life of the application in mvc - asp.net-mvc

I need to keep variable throughout the life of the application. It shouldn't be disposed NEVER.
I was thinking of two methods:
Keep it the file
Store in database in separate table
But in the second case, create a separate table for one row isn't very clever.
So how to achieve that?

Depending on where the property is initialised:
It could be stored within the Application Scope -
There are different scopes with ASP.NET and other scopes are Session and Request
ASP.NET Application State Overview
ASP.NET Session State Overview
Alternatively set as a static property within the Global.asax
Set as a app setting in Web.Config if its immutable
<appSettings>
<add name="fixedProperty" value="fixedValue" />
</appSettings>
and reference anywhere within the application using
ConfigurationManager.AppSettings["fixedProperty"]
(although this call to configuration to should moved to a single static Settings file to make call to property reusable with one accessor to the web.config - type can also be converted from string to whatever you may require too)
As you already mentioned, persist to file or database - there is nothing wrong with persisting the single record to a database. That's what the data store is for.

You can make that variable as a static variable in a class like StaticData.java and use it with the class name. If you want to access the variable only at client side you can use localstorage.set().

Related

config.groovy meare with .property file in grails

In my config.groovy i have set ..
emailTo="admin#xzyz.com"
emailForm="notification#oabc.com"
but i want some flexibility in this. Can I change this while my project is running form property file ? Please help
Yes, you can use .property file as well, by default Grails looks for properties at:
in calss path ${appName}-config.properties
and global config ~/.grails/${appName}-config.properties
path passed as a system vaiable named ${appName}.config.location
Just take a look at first few lines of your Config.groovy, you can put there any other path to your own .properties
See also http://grails.org/doc/2.1.0/guide/conf.html#configExternalized
I believe there is a plugin to support dynamic reloading of external config files whenever they change, but conceptually if this is data that is supposed to be modifiable at runtime then maybe it would be better to represent it as a domain object and store it in the database.
I use this method on a number of projects, defining a domain class
class AppConfiguration {
String adminEmail
String appTitle
// etc
}
and ensuring there is always exactly one instance in the database, creating an initial instance in BootStrap if it is not already present. Now anywhere in the app that requires this config data I just do AppConfiguration.list()[0]
I just use dynamic scaffolding for the edit pages, which are restricted to be accessible only to admin users through Spring Security.

Implementing custom session state provider in ASP.NET MVC

I'm working on implementing a custom session state provider for my ASP.NET MVC application. My requirement is I've to store the session data as xml in a custom table in Sql server.
Can I use the existing sql session state provider (overriding some methods) or I've to create from scratch by implementing the abstract class SessionStateStoreProviderBase?
yes you can customize your class provider Session even with sql server or oracle. Just inherit from a class in your model inheriting from SessionStateStoreProviderBase and implementing the required methods that he sends, check the list of required methods here.
If you want to use an example, see here.
This example using odbc but simply replace for access class as OdbcConnection to SqlConnection and vice versa.
Good luck.
Why aren't you just using SQL server as your state provider? You can set it in the config and this happens automatically, then SQL server will store the data as serialized binary data and efficiently retrieve it?
The short answer is yes, you can, but it's re-inventing the wheel. Do you need to use the data for anything else or edit it yourself out of process? I'd be inclined to use a seperate process for this. You're going to create a bit of work for yourself doing this and you would be better to just save the xml property somwhere when you set it in sessiopn if you need to look at it later.
Make your xml document a session object
Session["MyCustomXml"] = mydoc;
var mydoc = Session["MyCustomXml"] as XmlDocument;
then use the following config so it's stored in sql server.
<sessionState
mode="SQLServer"
sqlConnectionString="data source=127.0.0.1;user id=<username>;password=<strongpassword>"
cookieless="false"
timeout="20"
/>
If you need to look at later, just save it to disk somwhere safely with the SessionId as the filename to keep it unique.

ASP.NET MVC -> WCF -> NHibernate, how to efficiently update entity with data from viewmodel?

A week back, I had an ASP.NET MVC application that called on a logical POCO service layer to perform business logic against entities. One approach I commonly used was to use AutoMapper to map a populated viewmodel to an entity and call update on the entity (pseudo code below).
MyEntity myEntity = myService.GetEntity(param);
Mapper.CreateMap<MyEntityVM, MyEntity>();
Mapper.Map(myEntityVM, myEntity);
this.myService.UpdateEntity(myEntity);
The update call would take an instance of the entity and, through a repository, call NHibernate's Update method on the entity.
Well, I recently changed my logical service layer into WCF Web Services. I've noticed that the link NHibernate makes with an entity is now lost when the entity is sent from the service layer to my application. When I try to operate against the entity in the update method, things are in NHibernate's session that shouldn't be and vice-versa - it fails complaining about nulls on child identifiers and such.
So my question...
What can I do to efficiently take input from my populated viewmodel and ultimately end up modifying the object through NHibernate?
Is there a quick fix that I can apply with NHibernate?
Should I take a different approach in conveying the changes from the application to the service layer?
EDIT:
The best approach I can think of right now, is to create a new entity and map from the view model to the new entity (including the identifier). I would pass that to the service layer where it would retrieve the entity using the repository, map the changes using AutoMapper, and call the repository's update method. I will be mapping twice, but it might work (although I'll have to exclude a bunch of properties/children in the second mapping).
No quick fix. You've run into the change tracking over the wire issue. AFAIK NHibernate has no native way to handle this.
These may help:
https://forum.hibernate.org/viewtopic.php?f=25&t=989106
http://lunaverse.wordpress.com/2007/05/09/remoting-using-wcf-and-nhibernate/
In a nutshell your two options are to adjust your service to send state change information over the Nhibernate can read or load the objects, apply the changes and then save in your service layer.
Don't be afraid of doing a select before an update inside your service. This is good practice anyway to prevent concurrency issues.
I don't know if this is the best approach, but I wanted to pass along information on a quick fix with NHibernate.
From NHibernate.xml...
<member name="M:NHibernate.ISession.SaveOrUpdateCopy(System.Object)">
<summary>
Copy the state of the given object onto the persistent object with the same
identifier. If there is no persistent instance currently associated with
the session, it will be loaded. Return the persistent instance. If the
given instance is unsaved or does not exist in the database, save it and
return it as a newly persistent instance. Otherwise, the given instance
does not become associated with the session.
</summary>
<param name="obj">a transient instance with state to be copied</param>
<returns>an updated persistent instance</returns>
</member>
It's working although I haven't had time to examine the database calls to see if it's doing exactly what I expect it to do.

Using repository pattern in ASP.NET MVC with a SQL Server DB; how to mock repository so its unit testable without breaking OOD

I've been learning the ASP.NET MVC framework using the Apress book "Pro ASP.NET MVC Framework" by Steven Sanderson. To that end I have been trying out a few things on a project that I am not that familar with but are things that I thing I should be doing, namely:
Using repository pattern to access my database and populate my domain/business objects.
Use an interface for the repository so it can be mocked in a test project.
Use inversion of control to create my controllers
I have an MVC web app, domain library, test library.
In my database my domain items have an Id represented as an int identity column. In my domain classes the setter is internal so only the repository can set it.
So my quandries/problems are:
Effectively all classes in the domain library can set the Id property, not good for OOP as they should be read-only.
In my test library I create a fake repository. However since it's a different assembly I can't set the Id properties on classes.
What do others do when using a database data store? I imagine that many use an integer Id as unique identifier in the database and would then need to set it the object but not by anything else.
Can't you set your objects' IDs during construction and make them read-only, rather than setting IDs through a setter method?
Or do you need to set the ID at other times. If that's the case, could you explain why?
EDIT:
Would it be possible to divorce the ID and the domain object? Does anything other than the repository need to know the ID?
Remove the ID field from your domain object, and have your repository implementations track object IDs using a private Dictionary. That way anyone can create instances of your domain objects, but they can't do silly things with the IDs.
That way, the IDs of the domain objects are whatever the repository implementation decides they are - they could be ints from a database, urls, or file names.
If someone creates a new domain object outside of the repository and say, tried to save it to your repository, you can look up the ID of the object and save it as appropriate. If the ID isn't there, you can either throw an exception to say you need to create the object using a repository method, or create a new ID for it.
Is there anything that would stop you from using this pattern?
you can use the InternalsVisibleTo attribute. It will allow the types from an assembly to be visible from the tests (provided they are in different assemblies).
Otherwise you can leave the property read-only for the external objects but in the same time have a constructor which has an ID parameter and sets the ID property. Then you can call that constructor.
Hope this helps.

Protecting images in ASP.NET MVC (w/ custom RouteHandler)

I created a custom RouteHandler for images that I want protected. My RouteHandler simply takes a new route (graphics/{filename}) and does a lookup for the true file path, sets the mime type, and serves it up. That works fine. (http://www.mikesdotnetting.com/Article/126/ASP.NET-MVC-Prevent-Image-Leeching-with-a-Custom-RouteHandler)
What I wanted to do next was to do a check within my custom handler for a session variable that I would set earlier to make sure the person trying to view the image had permission to do so.
Basically, they would pass a login (enter a code), which would set a session variable that I would look for in the custom RouteHandler.
My problem is that I can't seem to get at the session data from within the custom RouteHandler.
Finally, my question is: How can I set data in a controller and have it available to me from within a custom RouteHandler on a subsequent request?
First, from the RequestContext passed in to the GetHttpHandler method, can you not access the Session via requestContext.HttpContext.Session? I am not sure, I could see this not working by default since it is so early in the pipeline.
If not, you can always easily move the Session checking logic into the handler by adding the IRequiresSessionState interface to your handler.

Resources