I following a post from ADO.NET team Code First Migrations: Alpha 3 ‘No-Magic’ Walkthrough
I'm trying to read a file with sql for a migration in a asp.net mvc web application. I'm using sql method. The problem is that no matter what I do I can not get a root path to my project. I always get 'c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\'
Could someone point me a way to open my file?
Thanks.
Edited
public partial class AddMembership : DbMigration
{
public override void Up()
{
//var file = File.OpenText(System.IO.Path.GetDirectoryName() + "Model/Schema/membership-up.sql");
//var file = File.OpenText(AppDomain.CurrentDomain.BaseDirectory + "Model/Schema/membership-up.sql");
//var path = HttpContext.Current.Request.MapPath("/Models/Schema/membership-up.sql");
var path = HttpContext.Current.Server.MapPath("/Models/Schema/membership-up.sql");
Sql(file.ReadToEnd());
}
public override void Down()
{
// ....
}
}
What about using Server.MapPath
http://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
To run the migration directly from the site you could add this code
var dbMigrator = new DbMigrator(new Settings());
dbMigrator.Update();
To run migrations from either process (IIS vs Package Manager Console) you could check first if Server object is created before using Server.MapPath, this way you'd recognize if you're under IIS or under Package Manager Console.
If Server object is null you're under Package Manager Console so you could use something more appropriate to get your current path from like
Directory.GetCurrentDirectory();
So I would replace this code
var path = HttpContext.Current.Server.MapPath("/Models/Schema/membership-up.sql");
with something like this
String path;
if (HttpContext.Current.Server != null) {
path = HttpContext.Current.Server.MapPath("/Models/Schema/membership-up.sql");
} else {
path = Path.Combine(Directory.GetCurrentDirectory(), "Models/Schema/membership-up.sql");
}
Related
I have multiple projects that are written on the top of ASP.NET MVC framework. Each of these projects use common views and editor-templates. Thus, I have to duplicate the common views like editor-templates and master-layout into every project on my local machine.
Instead of duplicating views, is there a way to include an absolute path instead of using ~ to determine the views' path when the app is running locally?
In another words, instead on using something like ~/CustomViews/Shared/{0}.cshtml is there a way to use c:\\MyProjects\\CommonViews\\Views\\Shared\\EditorTemplates\\{0}.cshtml to tell razor-engine where to search?
I would only include the absolute path if my running environment is dev or running on a localhost.
I tried to create a my own engine which extends the RazorViewEngine class
public class CustomViewEngine : RazorViewEngine
{
public CustomViewEngine()
: base()
{
ViewLocationFormats = GetGlobalViews();
}
public string[] GetGlobalViews()
{
var views = new List<string>();
if (Running on localhost...)
{
var baseDirectory = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~"));
var root = baseDirectory.Parent.Parent.Parent;
var viewsPath = Path.Combine(root.FullName, "CommonViews", "Views");
if (Directory.Exists(viewsPath))
{
// include the Views directory
views.Add(viewsPath.ToString() + "/{1}/{0}.cshtml");
// include the Views/Shared directory
var sharedViewsPath = Path.Combine(viewsPath, "Shared");
views.Add(sharedViewsPath.ToString() + "/{1}/{0}.cshtml");
// include the Views/Shared/EditorTemplates directory
var editorTemplatesViewsPath = Path.Combine(sharedViewsPath, "EditorTemplates");
views.Add(editorTemplatesViewsPath.ToString() + "/{1}/{0}.cshtml");
}
}
return views;
}
}
Then in the Application_Start method of my app I added the following code to use the CustomViewEngine.
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new CustomViewEngine());
But when the system error because the view does not exists, none of my absolute bath is listed as it was searched
Note: I am not worrying about deployment issues or production environment issues I just want this to work locally.
I can initialise the Consul services at startup using the /consul/config directory. I would like to be able to initialise my application settings into the Consul kv store when I start the Consul container. Is this possible?
There are several projects which might be interesting for this scenario:
https://github.com/zerotens/consul-kv-bootstrap
https://github.com/cimpress-mcp/git2consul
https://github.com/cimpress-mcp/fsconsul
I wanted a simple approach to set application settings in Consul for a microservice project. I'm sure there are a number of existing tools but I wanted something that was lightweight and suits my development process. So rather than try to work with some of #mgyongyosi's suggestions I wrote a quick dotnet console application to do the (not so) heavy lifting. Under the project root directory I've created a directory structure Consul/kv. The child directories under that path represent keys in the Consul KV store and a json file at a leaf represents the application settings. Note there is only expected to be a single json file per leaf directory. The application uses the Consul.NET nuget package for communicating with Consul.
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Consul;
namespace ConfigureConsulKv
{
class Program
{
private static readonly string _basePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"Projects", "MyProject", "Consul", "kv");
static void Main(string[] args)
{
RecurseDirectory(_basePath);
}
static void RecurseDirectory(string path)
{
foreach (var dir in Directory.EnumerateDirectories(path)) RecurseDirectory(dir);
var file = Directory.EnumerateFiles(path, "*.json").FirstOrDefault();
if (!string.IsNullOrWhiteSpace(file))
{
var key = path.Substring(_basePath.Length + 1);
var json = File.ReadAllBytes(file);
Console.WriteLine($"key {key} file {file}");
using (var client = new ConsulClient())
{
var attempt = client.KV.Put(new KVPair(key) { Value = json }).Result;
Console.WriteLine($"status {attempt.StatusCode}");
}
}
}
}
}
I'm using EF6 Code First Migrations for Multiple Models means working with a single database via multiple dbContext and Migrations, In MVC5!
Why?
Because i want to add new Entities to database from my Areas!..So each Area have their own dbContext and Migrations Files. i use Update-Database command in console package manager and my database will update without any problem.
As every body knows: You can update your database from each projects of your solution but if you set it as StartUpProject of solution.
and my challenge is about what i said in above Blockquote ! because in another step i want to update my database programmatically by this code:
//ActionResult of my Area:
public ActionResult Create()
{
var configuration = new Configuration();
var migrator = new DbMigrator(configuration);
migrator.Update(); //got Error in this line
return View();
}
i get
network-related or instance-specific error
in specified line and i know why!..because my Area Project is not set as StartUpProject of my solution and it shouldn't be.
So how can i handle this situation in your view?
I knew. i should give ConnectionString to my configuration instance, straightly like this:
public ActionResult Create()
{
var configuration = new Configuration();
configuration.TargetDatabase = new DbConnectionInfo(
"Server=.;Database=SegalFrameWork;Trusted_Connection=True;",
"System.Data.SqlClient");
configuration.ContextKey = "BlogDbContext";
var migrator = new DbMigrator(configuration);
migrator.Update();
return View();
}
now there is no need to read connection string from web.config so it doesn't need any startup project to find it.
I am using EF Code First Migration with ASP.NET MVC5 project. I want to seed the database with about 5000 records. The examples on the asp.net web site and blogs all have the seed function within the configuration method.
internal sealed class Configuration : DbMigrationsConfiguration<foo.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
MigrationsDirectory = #"Migrations\ApplicationDbContext";
}
protected override void Seed(foo.ApplicationDbContext context)
{
SeedProducts(context);
SeedFoods(context);
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
What are some options to seed large data sets when using EF Migration?
Currently The configuration file is over 5000 lines long and is different to manage.
I would prefer to store them in another database or excel spreadsheet and then import them in using the seed function. I am not sure how to go about importing data from external sources within the Seed method.
I also tried to break up the data set into several files but when I try to call the function
SeedProducts(context);
SeedFoods(context);
outside of the Configuration Class I get a build error: "The name does not exists in the current context". (I am not sure what this means?
You can store the sql file in the base directory and use it. You can create multiple sql files. I used following code to execute all sql files stored on base directory.
protected override void Seed(CRM.Data.DbContexts.CRMContext context)
{
var sqlfiles = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory+"\\initialdata", "*.sql");
sqlfiles.ToList().ForEach(x=> context.Database.ExecuteSqlCommand(File.ReadAllText(x)));
}
Why we need to have a seed data for 5000 records. If you prefer this way it will take lot of manual work also. where as, its not required here.
Instantly you can Create Scripts and execute that into you db. via Code as well as Manually.
Db Scripts can be taken for entire db as well as each table, Store Procedure wise also. So, that you will get records particularly.
Follow the steps from this link OR MSDN
Note: After Creating the Database Script. You can read the file from Seed Function and Execute the query from function itself. Or Manually you can go and execute when ever you need it.
I ended up using a CSV (comma delimited file) and storing it as a domain resource. Then reading the CSV file and adding database records:
I am able to Seed the database using EF Migration Seed method and a CSV file as defined as follows in the Migration.cs file. Note: the CSV file in the project in Visual Studio are set to the Build Action to Embedded Resource.
public void SeedData(WebApp.Models.ApplicationDbContext Context)
{
Assembly assembly = Assembly.GetExecutingAssembly();
string resourceName = "WebApp.SeedData.Name.csv";
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
{
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
CsvReader csvReader = new CsvReader(reader);
csvReader.Configuration.WillThrowOnMissingField = false;
var records = csvReader.GetRecords<Products>().ToArray();
foreach (Product record in records)
{
Context.Products.AddOrUpdate(record);
}
}
}
Context.SaveChanges();
}
Am using visual studio 2010 and trying to load a rpt file.
I have used the following code.
ReportDocument rpt = new ReportDocument();
rpt.Load("E:\\Crystal reports docs\\Crystal Reports samples\\Crosstab report");
Then I used isLoaded() function to check whether it is loaded.
When I compile the program, it keeps on running.
Any suggestions???
Thanks in advance!!!!
Here is the sample code how to load a crystal report (.rpt) file that is saved on a local drive instead of embedded. The advantage to this is the program does not need to be re-compiled each time a report is modified. Also, the .rpt can be upload from the application and stored in a database and then written to file. Do not embed the .rpt file when using this method.
using System;using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Shared;
namespace Report
{
public partial class Report : Document
{
public void ReportLoad()
{
ReportDocument reportDocument = new ReportDocument();
string filePath = "C:\Projects\Application\Report\CrystalReport.rpt";
reportDocument.Load(filePath);
crystalReportViewer.ReportSource = reportDocument;
}
}
}
Refer More about
http://scn.sap.com/thread/3312329
How do I load external Crystal Reports (2008) files in c#?
ReportDocument reportDocument = new ReportDocument();
//ADD
string filePath = openFileDialog1.FileName;
reportDocument.Load(filePath);
crystalReportViewer1.ReportSource = reportDocument;