I just created a cron job like job using Quartz.net. For the test, it execute a simple request to the database. It simply adds a field.
I have a dbcontext:
private TotoContext db = new TotoContext();
In my job I have:
var totos = from u in db.totos where u.name == name select u;
Toto[] totoArray = totos.ToArray();
In my web.config, I have a special field with my specific connectionstring and so on ("TotoContext").
But when I create a new dbContext it seems that it uses doesn't use the good connectionString. In the watch the connectionString is not linked with "TotoContext".
I initialize my job in:
public override bool OnStart()
And I have a specific Web.toto.config file with the connectionString for the build.
Why it doesn't use the good connectionString ?!
Thanks a lot !
Edit: if I set manually the connectionString in my db.Database.Connection.ConnectionString, it works. But why it doesn't use the web.config ConnectionString.
If you use full IIS mode (default configuration for web role), web.config will be ignored in the role entry point. So it is recommended to put all ASP.NET specific initialization tasks in Global.asax's Application_Start method. Role entry point is used to do something before ASP.NET application starts up, for example, modify IIS configuration. Inside Global.asax, web.config (and config transform) is respected.
I just found why it's not using the Web.config: https://stackoverflow.com/a/10153375/1396323
But the next question is how to store different connectionString depending on the build config (Debug, Release etc...) and where ?
Related
I've created a fresh ASP.NET Web Forms model, with authentication pre built. I've then run through the following link
http://msdn.microsoft.com/en-us/data/jj206878
and created an entity framework from my exisiting database.
Ok, so far so good, however, when i fire up the project and click Register, the user created is still being inserted into a local db in the App_Data folder.
Why is this, and how can I ensure that all new users are pooled / created in my own database?
Probably because your DbContext is using built-in connection string. You can specify which connectionstring from your web.config to use when you initialize it in constructor like so.
public class MainDataContext : DbContext
{
public MainDataContext() : base("Name=NameOfConnectionString") { }
// public DbSet ...
}
Change you Default Connection String at Web.config/App.config with credentials of your own database.
Hope following link will help you:
http://hgminerva.wordpress.com/2013/09/21/how-to-create-the-asp-net-membership-tables-in-your-own-database/
I have a mvc 3 project and I need to populate sql database with data from xml file. So I added the console app project to the solution and wrote the code that will display all needed data on the screen. Now I want to write data into the database. Here is the chunk of code: (fom the console app)
public static void Main()
{
IKernel ninjectKernel = new StandardKernel();
ninjectKernel.Bind<IItemsRepository>().To<ItemsRepository>();
ninjectKernel.Bind<IProductRepository>().To<ProductRepository>();
ninjectKernel.Bind<IShippingRepository>().To<ShippingRepository>();
var itemsRepository = ninjectKernel.Get<IItemsRepository>(); // redirection to datacontext file
var productRepository = ninjectKernel.Get<IProductRepository>();
var shippingRepository = ninjectKernel.Get<IShippingRepository>();
var doc = XDocument.Load(#"C:\div_kid.xml");
var offers = doc.Descendants("offer");
foreach (var offer in offers)
{ // here I use Linq to XML to get all needed data from xml file:
// name, description, price, category, shippingCost, shippingDetails
Product product = productRepository.CreateProduct(name, description, price, category, "Not Specified", "Not Specified");
Shipping shipping = shippingRepository.CreateShipping(shippingCost, shippingDetails);
// here I think I will just create "admin" user and assign its "UserId" to "userId"
Guid? userId = null;
Item item = itemsRepository.CreateItem(product.ProductId, shipping.ShippingId, (Guid) userId, DateTime.Now);
// Resharper highlights this line like unreachable. Why?
Console.WriteLine("name: {0}", offer.Element("name").Value);
}
}
First of all when I run the console app the NullReferenceException occures in MvcProjectName.Designer.cs file in the following line:
public WebStoreDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["WebStoreConnectionString"].ConnectionString, mappingSource)
NullReferenceException: The reference to the object is not pointing to the object instance.
So, I have lots of questions:
1) How to integrate console app code with mvc 3 app code in one solution?
2) I've also found this post on stackoverflow.
But can't I just add reference to MvcProject in references of ConsoleProject? And this way get access to the "mvc repositories" code?
3) Should I use ninject container in console app?
4) Is there any better implementation of loading data from xml file into slq database? I've never had two projects in one solution before, so mabby there are other ways to beautifully handle this situation?
Thanks for Your help in advance!
Edits:
I added app.config file with the connection string:
<add
name="WebStoreConnectionString" connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\WebStore.mdf;Integrated Security=True;Connect Timeout=30"
providerName="System.Data.SqlClient"
/>
Now when I run console app I get the following SqlException when the Linq to SQL ".submitChanges()" method is called:
An attempt to attach an auto-named database for file C:\Users\Aleksey\repos\working_copy\WebStore\LoadDataTool\bin\Debug\WebStore.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
Also in the directory LoadDataTool\bin\Debug "WebStore" file with extension "Program Debug Database" appeared.
It's hard to make an accurate assumption on your solution architecture, but from what I'm reading, it doesn't sound like you've separated your Data Access Layer (DAL) from the presentation layer (MVC) - which seems to be why you're trying to referencing it in a console application.
With that assumption, here's how I would answer your questions.
I wouldn't... But if I was going to I was 1) make sure that I have all the required references, 2) validate that the app.config file is setup correctly pointing to the correct database and server.
I would separate your repositories in a different project and use a dependency resolver to inject them into your MVC Application. With that, the console application will only need to reference the DAL assembly - thus not needed all the references in your console app.
If your think that you're going to be pulling out the DAL in the future, then yes. (**See #2 suggestion).
Unless you can't run your solution without the XML file and database created, a better solution is to simply make an administration Controller and Action that allows you to upload your XML file and complete the tasks.
I hope that helps.
Update
For your issue
An attempt to attach an auto-named database for file
Change your connection string so that it looks something like;
Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\WebStore.mdf;
A good source for connection strings is:
http://www.connectionstrings.com/
I guess that you need to define a connection string in the App.config file that is used by your console application (the same way you have it in your web.config):
<connectionStrings>
<add
name="WebStoreConnectionString"
connectionString="YOUR CONNECTION STRING COMES HERE"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
I have a Web Role that is using the ASP.NET SQL Membership provider. Currently the configuration is in the Web.Config file. I would like to configure the connection string as a Web Role setting instead of having it in the Web.Config. The main reason that I wan this is so that I can set up configurations on the azure project to publish to different hosted services (dev, qa, etc.) Right now, I have to manually edit the web.config each time I want to publish to a different service.
I have a couple ideas on how I might be able to accomplish this.
Write a custom membership provider that wraps the SQL provider and provides custom configuration to it.
Put something in the Web Role OnStart method to change the connection string in the Web.config file.
Has anyone done something like this before, or have recommendations on which option might be best, or have another idea on how to accomplish this?
The Windows Azure SDK allows you to have multiple service configurations per environment. But web.config modifications are a bit harder. In your case I would suggest you write some code (or a startup task) that reads the connection string from the service configuration and writes it to the web.config.
Andy's blog post 'Programmatically modify web.config on WebRole Startup' explains exactly how you can do this:
public override bool OnStart()
{
using (var server = new ServerManager())
{
// get the site's web configuration
var siteNameFromServiceModel = "Web"; // TODO: update this site name for your site.
var siteName =
string.Format("{0}_{1}", RoleEnvironment.CurrentRoleInstance.Id, siteNameFromServiceModel);
var siteConfig = server.Sites[siteName].GetWebConfiguration();
// get the appSettings section
var appSettings = siteConfig.GetSection("appSettings").GetCollection();
AddElement(appSettings, "deploymentId", RoleEnvironment.DeploymentId);
AddElement(appSettings, "internalEndpointPort", RoleEnvironment.CurrentRoleInstance.InstanceEndpoints
.First(t=>t.Key=="InternalEndpoint1").Value
.IPEndpoint.Port.ToString());
server.CommitChanges();
}
return base.OnStart();
}
Is it possible to read the IIS re-write rules from the Azure ServiceConfiguration file instead of the web.config?
The problem that is arising is that we have friendly urls to certain weekly updated pages that are content managed, so a new url is created every week. The old ones are stored in a newslist archive so overwriting is not an option.
We would like to try and avoid having to upload the Azure site files every week, and want to be able to respond quickly (immediately) to possible link changes by altering values in the serviceconfig.
Anyone have any idea if this is possible or wether there is another solution?
Thanks
Yes, you can change your role to modify the web.config at runtime using the Configuration editor classes in the IIS Admin api. I haven't tried this, but it should enable you to load the settings from Azure config during startup then apply to the runtime instance of your role. So you would set this likely in your Application_start section of the web role's global.asax.
Alternatively, you could programitically build up the web.config at role start time using a Startup Task.
For the 1st approach:
Do some research at iis.net and then read this IIS forum post:
http://forums.iis.net/t/1150481.aspx
Take a sample from user ruslany (give credit where due, but pasting so you see it):
using(ServerManager serverManager = new ServerManager()) {
Configuration config = serverManager.GetWebConfiguration("Default Web Site");
ConfigurationSection rulesSection = config.GetSection("system.webServer/rewrite/rules");
ConfigurationElementCollection rulesCollection = rulesSection.GetCollection();
ConfigurationElement ruleElement = rulesCollection.CreateElement("rule");
ruleElement["name"] = #"MyTestRule";
ruleElement["stopProcessing"] = true;
ConfigurationElement matchElement = ruleElement.GetChildElement("match");
matchElement["url"] = #"foo\.asp";
ConfigurationElement conditionsElement = ruleElement.GetChildElement("conditions");
ConfigurationElementCollection conditionsCollection = conditionsElement.GetCollection();
ConfigurationElement addElement = conditionsCollection.CreateElement("add");
addElement["input"] = #"{HTTP_HOST}";
addElement["pattern"] = #"www\.foo\.com";
conditionsCollection.Add(addElement);
ConfigurationElement actionElement = ruleElement.GetChildElement("action");
actionElement["type"] = #"Rewrite";
actionElement["url"] = #"bar.asp";
rulesCollection.Add(ruleElement);
serverManager.CommitChanges();
}
We would like to have the FormsCookieName of FormsCookiePath change per instance of our application. We have an application which has multiple instances on 1 server/domainname. Because of this we can only work in 1 application at the same time, since the cookies will overwrite eachother. Same for the Sessions btw.
Is there a way to dynamicly, for example in the Global.asax Application_Start, change this name? This would be usefull as we keep a license name in each application which could be used as the basis for the CookieName.
We already work with Web.config and extra files to overwrite Web.config values in external files using: <appSettings file="Web.AppSettings.Config">
But this requires manual actions which can be forgotten and are redundant since the settings can be retrieved from the database.
Thanks.
I had similar situation, I did the following. In the Application_Start, I checked to see if my cookie name needed change. This would occur after a new deployment for all applications where I have the same web.config for all.
protected void Application_Start(object sender, EventArgs e)
{
// determine unique cookie name per application
string cookieName = ...
// Get the web.config forms settings
Configuration c = WebConfigurationManager.OpenWebConfiguration("~");
AuthenticationSection auth = c.GetSection("system.web/authentication")
as AuthenticationSection;
// See if we have mismatch in web.config or in Forms cookiename
if (auth != null && auth.Forms != null &&
(auth.Forms.Name != cookieName
|| FormsAuthentication.FormsCookieName != cookieName
)
)
{
// Assign value in web.config for future restarts
auth.Forms.Name = cookieName;
// would be nice if this restarted the app, but it doesn't appear to
c.Save();
// This seems to restart the app
System.Web.HttpRuntime.UnloadAppDomain();
}
...
}
The web.config is modified on the application start and then the web app is restarted. Next time the web app comes up, cookie names are in sync and the reset code is skipped.
I have been struggling with Cookies with quite a few days. It has been an awesome learning experience.
So wanted to share the possible ways I found & discovered: There are several HACKs to modify Forms Authentication Cookie name:
You can automate the modification of cookie name under Authenticaiton secion of Web.Config file in Application_Start event in Global.asax. Thanks to Ron for sharing this. But I could not guarantee that the user whose identity would be used to run application domain have enough privileges to modify the file on disk or not. Hence I needed an improvised solution, so I devised following.
Thanks to ILSpy for letting me see inside the FormsAuthentication class, and many thanks to Reflection to let me modify the private field of a class. I used following code to modify the cookie name on run-time with following small piece of code and this worked like a charm !!!
protected void Application_Start(Object sender, EventArgs e)
{
// This will enforce that FormsAuthentication class is loaded from configuration settings for the application.
FormsAuthentication.Initialize();
// The new cookie name whatever you need can go here, I needed some value from my application setting to be prefixed so I used it.
string newCookieName = string.Format("{0}.ASPXAUTH", ConfigurationManager.AppSettings["SomeSettingThatIsUniquetoSite"]);
// Modifying underlying baking field that points to FormsAuthentication.FormsCookieName
Type type = typeof(FormsAuthentication);
System.Reflection.FieldInfo field = type.GetField("_FormsName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
field.SetValue(null, newCookieName);
}
Suggestions, loopholes are requested as this is my first answer on this forum.
According to MSDN, the FormsAuthentication.FormsCookieName property that stores the cookie name is a read-only property. This property must be read from the web.config.
Each instance will need a separate name in the web.config. I suggest including the name of the authentication cookie in your existing change management system.