I've been following this tutorial http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application but customising it for a project I'm working on.
I'm having problems when I run it though - it fails to initialize the DB and gives me this error when I access a controller which needs to use the DB:
Failed to set database initializer of type 'JustSpecIt.DAL.JustSpecItInitializer, JustSpecIt' for DbContext type 'JustSpecIt.DAL.JustSpecItAppContext, JustSpecIt' specified in the application
My initializer and context files are in a DAL folder. In my webconfig file I have:
<entityFramework>
<contexts>
<context type="JustSpecIt.DAL.JustSpecItAppContext, JustSpecIt">
<databaseInitializer type="JustSpecIt.DAL.JustSpecItInitializer, JustSpecIt" />
</context>
And for my connection string I have:
<connectionStrings>
<add name="JustSpecItAppContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=JustSpecIt;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
</connectionStrings>
I'm new to this so let me know if more info is required.
As requested, here is my initializer class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using JustSpecIt.Models;
namespace JustSpecIt.DAL
{
public class JustSpecItInitialiser : System.Data.Entity.DropCreateDatabaseIfModelChanges<JustSpecItAppContext>
{
protected override void Seed(JustSpecItAppContext context)
{
var Projects = new List<Project>
{
new Project {ProjectName="Just Spec It", ClientID = "GR Corp", Description="Build Just Spec It Application"}
};
Projects.ForEach(s => context.Projects.Add(s));
context.SaveChanges();
var UseCases = new List<UseCase>
{
new UseCase {ProjectID = 1, ActorID = 1, Title = "Print Specification"}
};
UseCases.ForEach(s => context.UseCases.Add(s));
context.SaveChanges();
var Steps = new List<Step>
{
new Step {UseCaseID = 1, Content = "This is step 1"},
new Step {UseCaseID = 1, Content = "This is step 2"},
new Step {UseCaseID = 1, Content = "This is step 3"},
};
Steps.ForEach(s => context.Steps.Add(s));
context.SaveChanges();
var Queries = new List<Query>
{
new Query {UseCaseID = 1, QueryDescription = "We need to add more details to this Use Case!"}
};
Queries.ForEach(s=> context.Queries.Add(s));
context.SaveChanges();
var Actors = new List<Actor>
{
new Actor {Title = "Business Analyst", Description = "This group will interact with the application to generate the use cases. They will follow Cockburn's writing process to produce the use cases in an effective way!"},
new Actor {Title = "End System User", Description = "These users will use the application for two primary purposes. The first is to submit uses case titles (which in fact will be their goals). After the Business Analyst has entered full details into the application about how these goals will be carried out, the End System Users will use the application again to review and comment on them."}
};
Actors.ForEach(s => context.Actors.Add(s));
context.SaveChanges();
}
}
}
JustSpecItInitialiser or JustSpecItInitializer ?
Check syntax.
Related
I'm trying (I'm in need to) to create small web application to manage some ETL processes giving my users few buttons to view SQL Server data and run few SSIS Packages.
I was able to handle the website creation using a C# ASP.NET MVC CRUD tutorial HERE (really useful) and to show the data I need.
I then created a data model pointing to my tables and stored procedures and now I "only" need to create a basic page with a textbox to insert a parameter and a button for each stored procedure I need to run.
Each stored procedure will run an SSIS package that doesn't need to return any value for now.
EDIT: I was able to gather some more information and to modify the code like this
Controller
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Italist_Admin.Models;
using System.Data.SqlClient;
using System.Data.Entity.Core.Objects;
namespace Project.Controllers
{
public class ToolsController : Controller
{
private ProjectEntities db = new ProjectEntities();
public ActionResult Index()
{
ProjectEntities entities = new ProjectEntities();
//return View(entities.SPU_RUNSSIS(""));
return View();
}
[HttpPost]
public ActionResult ExecExportOnly(string txtPeriod) // to get the Student Details
{
ProjectEntities entities = new ProjectEntities();
entities.SPU_RUNSSIS(parameter);
return View();
}}}
View
#{
ViewBag.Title = "Tools";
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Export Only</title>
</head>
<body>
<div>
#using (Html.BeginForm("ExecExportOnly", "Tools", FormMethod.Post))
{
<span>Period:</span> #Html.TextBox("txtPeriod")
<input type="submit" value="Run Export" />
}
</div>
</body>
</html>
Model
public virtual int SPU_RUNSSIS(string parameter)
{
var periodParameter = period != null ?
new ObjectParameter("parameter", parameter) :
new ObjectParameter("parameter", typeof(string));
((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 300;
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("SPU_RUNSSIS", parameterParameter);
}
I added a timeout in the model because on execution, after 30 seconds it was failing due to timeout.
Running this code, the packaged fails (SqlException: The package failed. Check the SSIS catalog logs for more information) after about 30 seconds anyway and AT THE END of the 30 seconds I see in the SQL Trace the following message
RPC:Completed - exec [dbo].[SPU_RUNSSIS] #parameter='parametervalue'
If I manually run the code above, it works.
I'm almost there but it seems I can't find the correct way to trigger the execution of the stored procedure at some point.
Thanks in advance for any suggestion
I managed to circumvent the problem by firing the SSIS directly from the c# code instead of executing a stored procedure that then triggers the SSIS execution.
Maybe not the best solution, but it seems to work:
public ActionResult Index()
{
project entities = new project();
return View();
}
public ActionResult ExecExportOnly(string txtPeriod)
{
project entities = new project();
string targetServerName = ConfigurationManager.AppSettings["targetServerName"];
string folderName = ConfigurationManager.AppSettings["folderName"];
string projectName = ConfigurationManager.AppSettings["projectName"];
string SSIS_ExportOnly = ConfigurationManager.AppSettings["SSIS_ExportOnly"];
// Create a connection to the server
string sqlConnectionString = ConfigurationManager.ConnectionStrings["Variable1"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(sqlConnectionString);
// Create the Integration Services object
IntegrationServices integrationServices = new IntegrationServices(sqlConnection);
// Get the Integration Services catalog
Catalog catalog = integrationServices.Catalogs["SSISDB"];
// Get the folder
CatalogFolder folder = catalog.Folders[folderName];
// Get the project
ProjectInfo project = folder.Projects[projectName];
// Get the package
PackageInfo package = project.Packages[SSIS_ExportOnly];
//Set Parameters
// Add a parameter collection for 'system' parameters (ObjectType = 50), package parameters (ObjectType = 30) and project parameters (ObjectType = 20)
Collection<PackageInfo.ExecutionValueParameterSet> executionParameter = new Collection<PackageInfo.ExecutionValueParameterSet>();
// Add execution parameter (value) to override the default asynchronized execution. If you leave this out the package is executed asynchronized
//executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "SYNCHRONIZED", ParameterValue = 1 });
// Add execution parameter (value) to override the default logging level (0=None, 1=Basic, 2=Performance, 3=Verbose)
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 50, ParameterName = "LOGGING_LEVEL", ParameterValue = 3 });
// Add a project parameter (value) to fill a project parameter
//executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 20, ParameterName = "MyProjectParameter", ParameterValue = "some value" });
// Add a project package (value) to fill a package parameter
executionParameter.Add(new PackageInfo.ExecutionValueParameterSet { ObjectType = 30, ParameterName = "ParamPeriod", ParameterValue = txtPeriod });
// Get the identifier of the execution to get the log
//long executionIdentifier = package.Execute(false, null, executionParameter);
// Run the package
package.Execute(true, null,executionParameter);
return View("Index");
}
Thanks anyways!
R
I created a ConsoleApplication that gets information from an API and then is supposed to put one of the values in a table from the database. Everything works fine (like getting the values and filling the object data with them) but I can't seem to figure out a way to push it to the database.
class Program
{
static void Main(string[] args)
{
HttpClient cons = new HttpClient();
cons.BaseAddress = new Uri("APPURL");
cons.DefaultRequestHeaders.Accept.Clear();
cons.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
MyAPIGet(cons).Wait();
}
static async Task MyAPIGet(HttpClient cons)
{
using (cons)
{
HttpResponseMessage res = await cons.GetAsync("");
res.EnsureSuccessStatusCode();
if (res.IsSuccessStatusCode)
{
VirtualProduct virtualProduct = await res.Content.ReadAsAsync<VirtualProduct>();
Console.WriteLine("\n");
Console.WriteLine("---------------------Calling Get Operation------------------------");
Console.WriteLine("\n");
Console.WriteLine("Id Name ");
Console.WriteLine("-----------------------------------------------------------");
Console.WriteLine("{0}\t{1}\t", virtualProduct.Id, virtualProduct.Header);
Console.ReadLine();
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString))
{
string insertQuery = #"UPDATE VirtualProduct SET ProductImageId = #Id WHERE Name='#Header';";
var result = db.Execute(insertQuery, virtualProduct);
}
}
}
}
}
After running this, everything works fine but my database does not get updated. Upon debugging, I discovered that using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString)) has the following error:
ServerVersion = '((System.Data.SqlClient.SqlConnection)db).ServerVersion' threw an exception of type 'System.InvalidOperationException'
The connection string is perfectly fine, I double checked the app.config which looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add connectionString="Server= SERVER.database.windows.net;Database=SERVER_dev;User Id=user; Password=asd;" name="DefaultConnectionString" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
As stated in this answer, try this:
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnectionString"].ConnectionString))
{
string insertQuery = #"UPDATE VirtualProduct SET ProductImageId = #Id WHERE Name='#Header';";
if (db.State==ConnectionState.Closed)
{
db.Open();
}
var result = db.Execute(insertQuery, virtualProduct);
}
After using using statement, everything declared inside using block of code gets disposed.
If I send an Akka.NET actor a message which is an object containing an IActorRef, and then persist that message, the JSON written to the journal table looks like this:
{"$id":"1","$type":"LearningAkka.Program+BindReference, LearningAkka","Reference":{"$id":"2","$type":"Akka.Actor.ActorRefBase+Surrogate, Akka","Path":"akka://LearningAkka/user/$b#1222898859"}}
If I'm understanding this right, this is just a reference to an actor instance; the "Props" required to create it are not stored in this message.
Weirdly, I am seeing an object there after restarting the app. However, as expected, it is not as constructed before the restart. Where did this actor come from? Has Akka Persistence found an actor which is "similar enough" and used it instead?
The following C# test application creates an object and sends a message binding it to one of three others. After disposing of the actor system, that object is recreated from persistence (SQL Server) and the reference is checked.
My expected behaviour is any of the following (I'm not sure what's most appropriate):
The actor can't be created because one of its messages contains an unresolvable reference.
The actor reference is null because it cannot be resolved.
The actor reference points to dead letters or similar.
Console output:
[WARNING][27/05/2017 21:02:27][Thread 0001][ActorSystem(LearningAkka)] NewtonSoftJsonSerializer has been detected as a default serializer. It will be obsoleted in Akka.NET starting from version 1.5 in the favor of Hyperion (for more info visit: http://getakka.net/docs/Serialization#how-to-setup-hyperion-as-default-serializer ). If you want to suppress this message set HOCON `akka.suppress-json-serializer-warning` config flag to on.
From the first run B
[WARNING][27/05/2017 21:02:28][Thread 0001][ActorSystem(LearningAkka)] NewtonSoftJsonSerializer has been detected as a default serializer. It will be obsoleted in Akka.NET starting from version 1.5 in the favor of Hyperion (for more info visit: http://getakka.net/docs/Serialization#how-to-setup-hyperion-as-default-serializer ). If you want to suppress this message set HOCON `akka.suppress-json-serializer-warning` config flag to on.
From the second run B
C#:
using Akka.Actor;
using Akka.Event;
using Akka.Persistence;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearningAkka
{
class Program
{
static void Main(string[] args)
{
using (var actorSystem = ActorSystem.Create("LearningAkka"))
{
var referenceA = actorSystem.ActorOf(Props.Create(() => new TestReferencedActor("From the first run A")));
var referenceB = actorSystem.ActorOf(Props.Create(() => new TestReferencedActor("From the first run B")));
var referenceC = actorSystem.ActorOf(Props.Create(() => new TestReferencedActor("From the first run C")));
var actor = actorSystem.ActorOf(Props.Create(() => new TestActor()));
actor.Tell(new BindReference { Reference = referenceB });
actor.Tell(new CheckReference());
Console.ReadLine();
}
using (var actorSystem = ActorSystem.Create("LearningAkka"))
{
var referenceA = actorSystem.ActorOf(Props.Create(() => new TestReferencedActor("From the second run A")));
var referenceB = actorSystem.ActorOf(Props.Create(() => new TestReferencedActor("From the second run B")));
var referenceC = actorSystem.ActorOf(Props.Create(() => new TestReferencedActor("From the second run C")));
var actor = actorSystem.ActorOf(Props.Create(() => new TestActor()));
actor.Tell(new CheckReference());
Console.ReadLine();
}
}
public struct BindReference { public IActorRef Reference; }
public struct CheckReference { }
public sealed class TestActor : ReceivePersistentActor
{
public override string PersistenceId => "test hardcoded";
private IActorRef StoredFromMessage;
public TestActor()
{
Command<CheckReference>(m => StoredFromMessage.Tell(m));
Command<BindReference>(m => Persist(m, m2 => StoredFromMessage = m2.Reference));
Recover<BindReference>(m => StoredFromMessage = m.Reference);
}
}
public sealed class TestReferencedActor : ReceiveActor
{
public TestReferencedActor(string ourLabel)
{
Receive<CheckReference>(m => Console.WriteLine(ourLabel));
}
}
}
}
HOCON:
akka {
persistence {
journal {
plugin = "akka.persistence.journal.sql-server"
sql-server {
class = "Akka.Persistence.SqlServer.Journal.SqlServerJournal, Akka.Persistence.SqlServer"
connection-string = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=LearningAkka;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
schema-name = dbo
table-name = Journal
auto-initialize = on
}
}
snapshot-store {
plugin = "akka.persistence.snapshot-store.sql-server"
sql-server {
class = "Akka.Persistence.SqlServer.Snapshot.SqlServerSnapshotStore, Akka.Persistence.SqlServer"
connection-string = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=LearningAkka;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
schema-name = dbo
table-name = Snapshot
auto-initialize = on
}
}
}
}
Could someone please comment on the behaviour here? Thank you.
As you can see from serialization data - your IActorRef points to this address akka://LearningAkka/user/$b. Where $b is usually placed for unnamed actors. So it will always be the second unnamed actor you create in the actor system root (as far as I know).
So you are right - the system behavior is undefined here.
I'm having trouble publishing my Entity Framework database to azure.
I'm working with .NET framework 4.5 and EF 6.1.3. The way my project is set up is as follows and using a code first approach:
Class library for the domain entities(database entities)
Class library for the DTOs
Class library for a repository where I do all the CRUD operations with Entity
Web api project for just the web services(there's no presentation, just restful controllers).
My web services project has references to the repository library and the DTOs library and I never created the database explicitly because EF created it for me using SQL server express I believe, I set up the web.config as follows:
<connectionStrings>
<add name="Database" connectionString="Server=(localdb)\v11.0;Database=Database;Trusted_Connection=True;" providerName="System.Data.SqlClient" />
</connectionStrings>
In my project the database is created along with all the tables and relationships. I added some initial migrations in the repository library like this
namespace Project.Repository.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Project.Repository.ProjectContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(Project.Repository.ProjectContext context)
{
Guid userId = new Guid();
Guid restaurantId = new Guid();
context.Users.AddOrUpdate(
u => u.Id, new Domain.Security.User { Id = userId, Age = 18, Description = "I like restaurants", Email = "user#gmail.com", Password = "12345", Username = "someuser" }
);
context.Restaurants.AddOrUpdate(
r => r.Id,
new Domain.Restaurants.Restaurant
{
Id = restaurantId,
Name = "mcdonalds",
Description = "best restaurant",
FacebookUrl = "www.facebook.com",
GoogleUrl = "www.google.com",
InstagramUrl = "www.instagram.com",
TwitterUrl = "www.twitter.com",
Votes = 3.5f,
UsersWhoLike = new List<Domain.Security.User>() { context.Users.FirstOrDefault(u => u.Id == userId) }
}
);
context.SaveChanges();
}
}
}
When I set to publish the project to my azure websites the webservices publish allright but the database doesn't or at least whenever I call the restaurants service with website/api/restaurants which is the route for getting a list of restaurants it says.
{"Message":"An error has occurred."}
My azure database connection string is setup like this:
Data Source=tcp:someidentifier.database.windows.net,1433;Initial Catalog=Database;Integrated Security=False;User ID=Database#someidentifier;Password=xxxxxx;Connect Timeout=30;Encrypt=True
I don't know what is happening and I don't know if azure is actually seeding the database, what did I left out or what could be my mistakes?
First of all, go to your asp.net webconfig and set this value to Off:
<system.web><customErrors mode="Off"/></system.web>
You'll get an informative Yellow Screen of Death and have a chance of figuring out what's actually wrong. If the YoD is unclear, post it on your answer.
To can see exceptions in azure portal go to your web app -> Tools -> Troubleshoot -> Live HTTP traffic, select Analyze.
I'm new at Telerik & exploring as an option for ORM. I'm trying to do simple thing like writing a record to database using:
Database db = Database.Get("MyConnectionNameIUsedToGenerateClasses");
IObjectScope scope = db.GetObjectScope();
scope.Transaction.Begin();
LookUpType l = new LookUpType();
l.IsActive = true;
l.Name = "test";
scope.Add(l);
scope.Transaction.Commit();
It throws following error: The connection section with id 'MyConnectionNameIUsedToGenerateClasses' cannot be found in the configuration files traversed from '(OpenAccess internally generated. Is there anything I'm missing from the setup? Telerik did add connectionString to my web.config file with it generated classes. Please help. Thanks.
OpenAccess ORM should know of all the assemblies used by the application. The assemblies should be listed under the reference section within the configuration file:
Open the web.config file in the web application project;
Locate the references node;
Alter the references node so that it gets the following form:
<references>
<reference assemblyname="AssemblyName" configrequired="True" />
</references>
The configuration file format is described here.
As I mentioned in the comments above following code works & does my job:
Telerik.OpenAccess.Data.Common.OAConnection dbConnection = dbContext.Connection;
LookUpType l = new LookUpType();
l.IsActive = true;
l.Name = "test123";
LookUpType lkup = new LookUpType();
lkup.IsActive = true;
lkup.Name = "someTest";
dbContext.Add(new LookUpType[] { l, lkup });
dbContext.SaveChanges();