Load variables to AppSettings on web service start-up - c#

I have the following situation (.NET, C#):
My web service needs authentication data, which is stored in a database. The authentication is used for large volume POSTs done to the web service with transactional data. However, it is too heavy for to query the database every time there is a POST, because we are talking many transactions per second. I therefore want to keep the variables for authentication in Cache - which I can do via AppSettings. How do I load these variables into AppSettings when the web services is first started, without some manual process I need to remember to do?
Thanks,
Anders

It's not so easy to save information to web.config or app.config into AppSettings. Truly speaking, for me it's look dangerous when service tries to modify web.config, because a tiny error could cause all service to go down.
Anyway, when you need it, here is link for MSDN article, use ConfigurationManager class. And this article has a full example how to do it:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx
But I suggest you another approach. Use caching either simple System.Runtime.Caching.MemoryCache (or System.Web.Caching.Cache as in one of comments said) or more advanced and scalable scenario using AppFabric caching (for exampe have found link on stackoverflow for you)

Related

Caching application data in memory: MVC Web API

I am writing an MVC webAPI that will be used to return values that will be bound to dropdown boxes or used as type-ahead textbox results on a website, and I want to cache values in memory so that I do not need to perform database requests every time the API is hit.
I am going to use the MemoryCache class and I know I can populate the cache when the first request comes in but I don't want the first request to the API to be slower than others. My question is: Is there a way for me to automatically populate the cache when the WebAPI first starts? I see there is an "App_Start" folder, maybe I just throw something in here?
After the initial population, I will probably run an hourly/daily request to update the cache as required.
MemoryCache:
http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.aspx
UDPATE
Ela's answer below did the trick, basically I just needed to look at the abilities of Global.asax.
Thanks for the quick help here, this has spun up a separate question for me about the pros/cons of different caching types.
Pros/Cons of different ASP.NET Caching Options
You can use the global.asax appplication start method to initialize resources.
Resources which will be used application wide basically.
The following link should help you to find more information:
http://www.asp.net/web-forms/tutorials/data-access/caching-data/caching-data-at-application-startup-cs
Hint:
If you use in process caching (which is usually the case if you cache something within the web context / thread), keep in mind that your web application is controlled by IIS.
The standard IIS configuration will shut down your web application after 20 minutes if no user requests have to be served.
This means, that any resources you have in memory, will be freed.
After this happens, the next time a user accesses your web application, the global asax, application start will be excecuted again, because IIS reinitializes your web application.
If you want to prevent this behaviour, you either configure the application pool idle timeout to not time out after 20minutes. Or you use a different cache strategy (persistent cache, distributed cache...).
To configure IIS for this, here you can find more information:
http://brad.kingsleyblog.com/IIS7-Application-Pool-Idle-Time-out-Settings/

URL to specific Instance of WebRole in Windows Azure

i have a WebRole in my Windows Azure Deployment with a few instances. In this Roles i do a lot of caching. So my client asks everytime another instance for a specific information, which is maybe not stored on the requested instance. All my cached informations got a "instance"-property, so i can route my request in the cloud to the specific instance (via internal endpoints).
Is there a way to get a URL for my instance and not my deployment?
Something like:
instance1.mydeployment.cloudapp.net?
I think something would be really helpful.
Thank you.
Yes, there is. I'm not sure what SDK it came in, but in your csdef file you can alter your normal endpoints section to look like this
<Endpoints>
<InputEndpoint name="Endpoint1" protocol="http" port="80" localPort="80" />
<InstanceInputEndpoint name="Endpoint2" localPort="80" protocol="tcp"><!--localPort must be 80 for this to work-->
<AllocatePublicPortFrom>
<FixedPortRange min="10016" max="10020"/> <!--make a range that covers the # instances you might need or scale too - bear in mind azure port limits ~25 -->
</AllocatePublicPortFrom>
</InstanceInputEndpoint>
</Endpoints>
Now you should be able to access both
http://myapp.cloudapp.net:10016
http://myapp.cloudapp.net:10017
Your approach is very similar to the sticky session issue with Tomcat servers. Since you live in a .NET world I highly suggest that you change your architecture to not relay on this sticky routing.
If you really want to achieve that specific goal (which I don't imagine why one would want), it is possible through Application Request Routing. It is not easy, but it is feasible. you can read here about how to install ARR on Azure Web Role. But you have to maintain automatic configuration and reconfiguration of ARR, especially when you add or remove instances.
Frankly, the whole idea of sticky sessions is broken. Even if you manage to handle automatic installation and configuration of ARR, tell me what will happen when the Azure Fabric controller takes 1 instance down for Guest OS Update. What will happen to your users that were served by that instance?
I'd suggest you to use distributed Windows Azure Caching as a ready robust solution for sharing cached data between instances.
As far as I know, you can not get separate URLs for individual instances.
EDIT: the following answers might help:
Azure Web Role Internal Endpoint - Not Load Balanced
Take a look at this example: http://blog.maartenballiauw.be/post/2011/10/21/Running-Memcached-on-Windows-Azure-for-PHP.aspx
I know, it is a tutorial for PHP and memcache but it uses InternalEndpoint for Role Communication via TCP. Maybe it helps you to understand, how to fix your problem.

How do I implement shared state in an ASP.NET MVC 3 application?

I'm writing a basic RESTful service, and decided I'd use ASP.NET MVC 3 for the task. My application is going to be responsible for maintaining a persistent connection to a server per user (for now). I had assumed that Application_Start is the place to register static/shared state (like persistent connections), but after reading the documentation for Unity.MVC3, it appears that each request/response cycle will trigger the creation of services (by calling Application_Start).
The documentation I refer to says:
On every request, one UpperCaseService, one LowerCaseService and one ExampleContext are instantiated by DependencyResolver via Unity. At the end of the request, the ExampleContext is automatically disposed
After reading other documentation, and from what I already assumed, Application_Start would be called per AppDomain spawned (again assumed that this would be in the vicinity of how many cores there are on the server).
So, what would be an effective way of maintaining a set of persistent connections to a server, that survive the request/response phase, and if possible, are shared between all AppDomains that the IIS server has created?
It might help to mention that this web service is only going to be consumed by another web site. It is essentially an Authentication Proxy server, however, in the future, it is going to do a lot more. Therefore, I can't just cache the response, as future requests will be required, and reauthenticating is not an option.
If you want to survive AppDomain restarts and share state between multiple ASP.NET applications you will have to go out of the IIS process and store this in a central location that is accessible from all applications. A database is a good candidate.

Is it safe to use session in cloud application

We are planning to move one of our applications on cloud, but somewhere I read that using session in cloud can be dangerous. but this blog dosen't explain any danger as such.
I wanted to know that is there really any threat in using session for cloud applications?
I am new to the forum so excuse if I have commited any mistake and please guide me to correct the same.
If you plan to run your application across several nodes, you will need to take load balancing and out-of-proc sessions into account, but there's nothing inherently insecure about using sessions while your servers are hosted somewhere else.
That just doesn't make any sense.
If 'dangerous' means that in certain situations the use of Session won't work, then you're right if you would be using Azure to host your cloud application. Then it depends on the number of instances you are running.
If you're only running 1 instance then you can use Session (that lives in memory on the instance) without changing anything. But if you're using more than 1 instance (the requests are being load balanced and each request can be handled at a different instance) in memory Session won't work out of the box. To resolve this you're able to use 3 different ways to store session.
See this question for more information:
ASP.NET session state provider in Azure

How to share sessions between PHP and ASP.net application?

My company took some old php application over. Due to our preference to ASP.net and to the lack of any documentation from the previous developer, we do not want to spend much resources on developing in PHP.
For implementing new features, we will create an Asp.net application that has the same look to the user. We want to develop a kind of 'coexisting' web application. Therefore we must share sessions between an PHP and an Asp.net webapplication project, because there is a usermanagement involved with an existing MySQL database.
(e.g. link 'A' directs to the PHP website, and link 'B' directs to the asp.net application)
How can we share the session between and PHP and an asp.net application?
And does anyone have a hint for this 'coexisting' thing, that might be useful in development?
Edit: IIS 6 would be our targeted server, altough IIS 7.5 would also be an option
I want to tell you, how I ended up doing it.
Both applications access a MySQL database and access a "session" table, which consists of a Guid, the ID of the user, and a confirmationString (I guess I encoded the IDUser in it, somehow) and a date.
Sessions are only started by the PHP application (due to the fact, that the PHP application is still the main application). A new session will result in a new entry in the log table. Every link in the PHP application, that links to the ASP.Net application contains GET-Parameters, containing the Guid etc.
The ASP.net application checks for the GET-Parameters and sets the IDUser in the ASP.Net Session, if the GET-Parameters point to an existing session.
The links pointing back to the PHP application use the same technique.
(There are also other things to consider, like timeouts or logouts, but that can be handled as well)
All in all, I'd say that my approach is useful and none of the customers complained since the deployment (over 1 year ago)
I don't think it's natively possible to share sessions between PHP and ASP.NET.
However, it might be possible by using a PHP page that reads the contents of the session, stores them in hidden fields and then call an ASP.NET page that would read these fields and load them into ASP.NET session.
Theoretically it's possible.
This is an old question, but I didn't think any of the current answers were complete.
First, I think it is a bad idea to store session data in a database server like mysql or SQL Server. The DB is a precious resource, and there's really no reason to thrash it just for session data.
If you are going to store session in a database like that, there are "better" ways of doing it, like making sure that the session data is on it's own independent disk, etc... but honestly, I still feel like it's a mistake and will limit your scalability.
For storing session, you want to go with a simple key/value store, and in my opinion you can't beat memcached (though I've also had good luck with redis + nodejs).
memcached has clients available for pretty much every language on earth: http://code.google.com/p/memcached/wiki/Clients
So, basically all you need to do when using memcached is generate a pseudo-random token for the key, and do a memcached.set. Then store that key in a cookie called session-id or something.
The session-id cookie can be read from any server language, .net, php, python, whatever - and the session value retrieved with a simple memcached.get.
Check out the memcached docs: http://code.google.com/p/memcached/wiki/NewStart
This is a very simple and scalable way to do sessions, and will work with almost any language/server.
http://cz.php.net/manual/en/function.session-set-save-handler.php
http://support.microsoft.com/kb/317604
You can write PHP's sessions into MsSQL, and configure .NET to use MsSQL as backend for sessions.
Not a big deal.
Your asp app should do a three simple things:
Recieve a sessionid cookie from the client
look for the sess_<id> file in the PHP session save path
implement a PHP serialize/unserialize functions to read/write session data.
A nicer way than just hacking into session storage mechanisms on both sides would be setting up OpenId provider and plugging OpenId consumers to both asp.net and php applications.
There's lot of existing code to do it. It would be both more elegant and error prone than the low level solutions. As a bonus you could use integrated OpenId login in the rest of your company applications and become a company hero.
See: Using OpenID for both .NET/Windows and PHP/Linux/Apache web sites
Oh dear, maybe one day you'll see the error of your ways, in the meantime.....
By default, PHP writes its session data as a serialized array into a file named according to the session. The session is identified usually by a cookie with name PHPSESSID.
So in PHP to manually read the session:
$imported_session=unserialize(file_get_contents(session_save_path() . '/' . $_COOKIE[session_name()]));
The format of the file is very straightforward and simple to parse.
However its quite easy to implement your own PHP session handler to write the files in any format/to any storage you like (have a look at auto-prepend for how to associate the revosed code with every page without having to rewrite each one). Or change the name the cookie used to store the session.
C.

Categories

Resources