How do I set the FailoverBehavior for RavenDB globally - asp.net

Currently, I have something like this everywhere in my ASP.NET MVC site wherever I need to connect to RavenDB.
using (var ds = new DocumentStore { Url = urlBase }.Initialize())
{
ds.Conventions.FailoverBehavior = FailoverBehavior.ReadFromAllServers;
}
Is there a way that I can set the FailoverBehavior globally, like perhaps in the web.config, so that I don't have to do this every time I create a new instance of the DocumentStore?

There needs to be one DocumentStore instance in your application per database (initialized usually from global.asax), you never create one from an MVC controller, so your question never begins...

Related

Adding a tag to the ASP.NET Request Activity

I would like to add a tag to the System.Diagnostics.Activity object for each incoming ASP.NET Request, as soon as the request-handling starts. Is there a way I can access the ActivitySource for the Request Pipeline, and add a listener to it?
Currently I'm thinking of using a Pipeline middleware, but there has to be a more lightweight way. Especially one where other developers can't add any other middleware handlers before this one. Any ideas?
Looks like you can add it via DI at startup. The Key thing is the name of the ActivitySource. I couldn't find it in any documentation. I had to trawl through the aspnetcore code, and it looks like registers an empty name ActivitySource for the DiagnosticListener.
In any case ...
Add the following to Configure(...):
var requestActivityListener= new ActivityListener();
requestActivityListener.ShouldListenTo = activitySource => activitySource.Name == "";
requestActivityListener.ActivityStarted = activity => LetsShapeThisActivityToOurLiking(activity);
ActivitySource.AddActivityListener(requestActivityListener);
That should be it.

Asp net core identity: how to get default ApplicationDbContext outside controller?

I use Net Core 2.1 and I need to do some preparations on startup which require several direct Identity database queries.
I tried:
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
var identityDb = serviceProvider.GetService<ApplicationDbContext>();
}
these lines produce exception: Cannot resolve scoped service 'Ecoc.Data.ApplicationDbContext' from root provider.
Is there a way to get database context in arbitrary place of code?
Use IServiceScopeFactory instead of IServiceProvider and then create a scope and use its ServiceProvider.
Related to you example:
var identityDb = serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
Found the correct approach here (they access Session from arbitrary class as example)
https://neelbhatt.com/2018/02/10/implement-session-in-net-core2-0/

Passing parameters to new page in asp.net (in Redirecting)

I want to fill Listview in Asp.net with Records which should have link to another page . so when user clicks on one record, they will redirect to new page related to that record.I have many parameters want to keep.
In page Redirecting, is there any other way to passing parameters except with "QueryString"?
You can use Cookies
SET :
HttpCookie cookieName = new HttpCookie("Name");
cookieName.Value = "SarahN";
GET :
string name = Request.Cookies["Name"].Value;
OR you can use
Application Variables
SET :
Application["Name"] = "SarahN";
GET :
string Name = Application["Name"].ToString();
OR you can use the Context object
Passing value through context object is another widely used method.
MyForm1.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
MyForm2.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("MyForm2.aspx", true);
From MSDN
Context
The Context object holds data for a single user, for a single
request, and it is only persisted for the duration of the request. The
Context container can hold large amounts of data, but typically it is
used to hold small pieces of data because it is often implemented for
every request through a handler in the global.asax. The Context
container (accessible from the Page object or using
System.Web.HttpContext.Current) is provided to hold values that need
to be passed between different HttpModules and HttpHandlers. It can
also be used to hold information that is relevant for an entire
request. For example, the IBuySpy portal stuffs some configuration
information into this container during the Application_BeginRequest
event handler in the global.asax. Note that this only applies during
the current request; if you need something that will still be around
for the next request, consider using ViewState. Setting and getting
data from the Context collection uses syntax identical to what you
have already seen with other collection objects, like the Application,
Session, and Cache. Two simple examples are shown here:
// Add item to
Context Context.Items["myKey"] = myValue;
// Read an item from the
Context Response.Write(Context["myKey"]);
You can also refer:
ASP.NET State Management Overview
How to: Pass Values Between ASP.NET Web Forms Pages

Entity Framework to multiple databases (same schema) at runtime?

First of all, let me state I'm very new to EF. With that said, here's my dilemma:
There will be an ASP.NET App migrated to ASP.NET MVC. I would like to utilize EF for this. There is one main database which stores "client information". Apart from that, every "client" has their own database. These are the constraints we have.
Currently, client information in the main DB that enables me to build a connection string per client and make individual SQL calls.
How would I accomplish the same thing in Entity Framework? Each database WILL have the same schema. Is there a way to programmatically switch the Connection String? These DBs are currently on the same server, but that's not a requirement and it may be a completely different server.
Any ideas?
Multiple connection strings in the Web.config would be a last resort. Even then, I'm not sure how exactly to wire this up.
Thank you in advance.
If you work through an EntityConnection in the constructor of your entities object, you can change the database pretty easily.
EntityConnection con = new EntityConnection(connString);
con.ChangeDatabase(dbName);
using (Entities context = new Entities(con))
{
// Some code here
}
When you build a data context, here's how to programmatically change the connection string at runtime by modifying the Context.Connection property:
//Get the connection string from app.config and assign it to sqlconnection string builder
SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(((EntityConnection)context.Connection).StoreConnection.ConnectionString);
sb.IntegratedSecurity = false;
sb.UserID ="User1";
sb.Password = "Password1";
//set the object context connection string back from string builder. This will assign modified connection string.
((EntityConnection)context.Connection).StoreConnection.ConnectionString = sb.ConnectionString;
Taken from: http://sivapinnaka.spaces.live.com/blog/cns!B027EF7E7070AD69!211.entry
If the number of your customers is limited and the connection strings hardly ever change, an elegant way might be to use ConfigurationManager.ConnectionStrings to retreive the connection string needed.
Like
string connectionString = ConfigurationManager.ConnectionStrings["Miller"].ConnectionString;
return new Entities(connectionString);
See also
http://msdn.microsoft.com/en-us/library/ms254494.aspx

ASP.NET Localized web site -- updating on the fly

I think I have a solution to this, but is there a better way, or is this going to break on me?
I am constructing a localized web site using global/local resx files. It is a requirement that non-technical users can edit the strings and add new languages through the web app.
This seems easy enough -- I have a form to display strings and the changes are saved with code like this snippet:
string filename = MapPath("App_GlobalResources/strings.hu.resx");
XmlDocument xDoc = new XmlDocument();
XmlNode xNode;
xDoc.Load(filename);
xNode = xDoc.SelectSingleNode("//root/data[#name='PageTitle']/value");
xNode.InnerText = txtNewTitle.Text;
xDoc.Save(filename);
Is this going to cause problems on a busy site? If it causes a momentary delay for recompilation, that's no big deal. And realistically, this form won't see constant, heavy use. What does the community think?
I've used a similar method before for a very basic "CMS". The site wasn't massively used but it didn't cause me any problems.
I don't think changing a resx will cause a recycle.
We did something similar, but used a database to store the user modified values. We then provided a fallback mechanism to serve the overridden value of a localized key.
That said, I think your method should work fine.
Have you considered creating a Resource object? You would need to wrap your settings into a single object that all the client code would use. Something like:
public class GuiResources
{
public string PageTitle
{
get return _pageTitle;
}
// Fired once when the class is first created.
void LoadConfiguration()
{
// Load settings from config section
_pageTitle = // Value from config
}
}
You could make it a singleton or a provider, that way the object is loaded only one time. Also you could make it smart to look at the current thread to get the culture info so you know what language to return.
Then in your web.config file you can create a custom section and set restartOnExternalChanges="true". That way, your app will get the changed when they are made.

Resources