I have installed an Linux SQL Server instance in my OS X using a docker container and I hace connected to this localhost instance with VS Code
But I need to connect to it in VS for Mac to develop my EF Core Project and I don't know if is it possible because when I try this in my DbContext
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Data Source=localhost;Initial Catalog=Boletus;Integrated Security=True")
.LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Command.Name }, LogLevel.Information)
.EnableSensitiveDataLogging();
}
I get this exception
Any idea please?
Thanks
Here is the solution
optionsBuilder.UseSqlServer("Server=localhost, 1433; Database=Boletus;User=sa; Password=Windows2021!")
.LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Command.Name }, LogLevel.Information)
.EnableSensitiveDataLogging();
Thanks
Related
When I run locally I run the commands below manually and then package and publish the app onto my IIS server.
Add-Migration Initial
Update-Database
When I want to publish to an azure appservice will these commands run automatically? If so how does it know to use a different ConnectionString when I publish it to azure?
I added the connectionString for azure in appsettings.json but I don't understand how I can tell my controllers etc to use that when I publish to azure AppServices
"ConnectionStrings": {
"AzureTestConnection": "Data Source=tcp:xxxxxx-test.database.windows.net,1433;Initial Catalog=xxxxx;User Id=xxx#yyyy.database.windows.net;Password=xxxxxx",
"NWMposBackendContext": "Server=(localdb)\\mssqllocaldb;Database=NWMposBackendContext-573f6261-6657-4916-b5dc-1ebd06f7401b;Trusted_Connection=True;MultipleActiveResultSets=true"
}
I am trying to have three profiles with different connection strings
Local
Published to AzureApp-Test
Published to AzureApp-Prod
When I want to publish to an azure appservice will these commands run automatically?
EF does not support Automatic migrations, you may need to manually execute Add-Migration or dotnet ef migrations add for adding migration files. You could explicitly execute the command to apply the migrations, also you could apply migrations in your code.
And you could add the following code in the Configure method of Startup.cs file:
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
}
I am trying to have three profiles with different connection strings
You would dynamically choose a connection string based on Environment, so here is main steps, you could refer to it.
Set the ASPNETCORE_ENVIRONMENT value to azure in webapp>property>debug.
2.Follow ASP.NET Core MVC with Entity Framework Core to get started.
3.Set the appsetting.json with your two connection string.
{
"ConnectionStrings": {
"DefaultConnection": "connectiondefault",
"azure": "connectionazure"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
Note:You could also set the connectionstring in database on portal to here, then you could test it in local and could use debug to troubleshooting.
Also, you could try to test with one connectionstring to ensure you have no problem with connecting to database.
4.Enable Developer exception page by using app.UseDeveloperExceptionPage(); and the app.UseExceptionHandler methods in your startup class which would display the errors.
public Startup(IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
HostingEnvironment = env;
}
public IConfigurationRoot Configuration { get; }
public IHostingEnvironment HostingEnvironment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
if (HostingEnvironment.IsDevelopment())
{
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
else
{
services.AddDbContext<SchoolContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("azure")));
}
services.AddMvc();
}
For more details, you could refer to this thread.
I am currently taking care of ALM QC upgrade activity from 11 to 12.20.
During this i need to verify, repair and upgrade each project.
Is there any way to automate this?
I am open on using UFT or selenium.
Let me know if there is any other way to do this.
I'd recommend using SaApi. You can read more about it in
ALM help-> API references -> HP ALM Site Administration API Reference
Basically it's a dll that is a COM object, so you can register it by regsvr32 and use it in your .NET application or vbs application.
To get this dll just login to site admin once - and you'll have it along with other site admin libraries in a path like this ->
C:\Users\YOUR_USERNAME\AppData\Local\HP\ALM-Client\YOUR_ALM_NAME
run cmd.exe as Administrator
register SAClient.dll in cmd
-> C:\Windows\system32>regsvr32 C:\Users\YOUR_USERNAME\AppData\Local\HP\ALM-Client\YOUR_ALM_NAME\SAClient.dll
Now you can add SAClient to your project references.
Create a simple client.
public class ALMSiteAdminClient
{
private SAapi sconnection = new SAapi();
public void connect(string url, string user, string password)
{
sconnection.Login(url, user, password);
}
public void disconnect()
{
sconnection.Logout();
}
public void verifyProject(string domain, string project)
{
sconnection.Verify(domain, project, "basic");
}
public void repairProject(string domain, string project)
{
sconnection.Repair(domain, project, "");
}
public void upgradeProject(string domain, string project)
{
sconnection.Upgrade(domain, project, "");
}}
Use the client ;)
static void Main(string[] args)
{
//get list of a projects from anywhere you want
//this is just a mock example
Dictionary<string, string> projects = new Dictionary<string, string>();
projects.Add("domain1", "project1");
projects.Add("domain1", "project2");
//create site admin client and login
ALMSiteAdminClient SACLIENT = new ALMSiteAdminClient();
SACLIENT.connect("http://myd-vm15059.hpeswlab.net:8081/qcbin", "sa","");
//do whatever you need with each project
foreach (KeyValuePair<string, string> project in projects)
{
SACLIENT.verifyProject(project.Key, project.Value);
SACLIENT.repairProject(project.Key, project.Value);
SACLIENT.upgradeProject(project.Key, project.Value);
}
//logout
SACLIENT.disconnect();
}}
I ended up using HP ALM Robot for auto upgrading QC projects. At the time there wasnt much documentation apart from: https://community.softwaregrp.com/dcvta86296/attachments/dcvta86296/itrc-895/91467/1/Robot_User_Guide_0.pdf
Now there are videos to help out the process too: https://www.youtube.com/watch?v=l-McyxeW0aI
How to migrate DB without nuget? It is not possible to use Visual Studio with nuget in production environment. Currently, many examples only teach us to use Visual Studio with nuget.
How to use the generated DbMigration classes?
The easiest way is:
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<MyDbContext,
MyDbMigrationsConfiguration>());
This will run the migrations when initializing the DbContext.
You can also force the execution manually:
var migrator = new DbMigrator(new MyMigrationsConfiguration());
migrator.Update();
(I believe you also have to set TargetDatabase on the configuration, but you can try)
Here are the options:
Use the migrate.exe command line tool that ships in our NuGet
package.
Use the MigrateDatabaseToLatestVersion initializer as
others have described.
Use the runtime API available from the
DbMigrator class.
You can migrate to the latest version using a Web.config setting - see this blog post by Rowan Miller:
If you are using Code First Migrations, you can configure the database to be migrated automatically using the MigrateDatabaseToLatestVersion initializer.
<contexts>
<context type="Blogging.BlogContext, MyAssembly">
<databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[Blogging.BlogContext,
MyAssembly], [Blogging.Migrations.Configuration, MyAssembly]], EntityFramework" />
</context>
</contexts>
Just swap your context class in here: the System.Data.Entity.MigrateDatabaseToLatestVersion is built-in to EF. This setting updates the old AppSettings version of the same idea.
To my mind this is the best way, because the question of which initializer to use is a configuration one really, and you want to be able to Web.config this, and ideally apply config transforms to work for your different environments.
You can do it using the EF Power Tools, there's the migrate.exe program that you can use to run migrations from the command prompt (post build for example). If you want to run migrations on production database you can also use the Update-Database command to generate SQL scripts from the migration classes, very useful if you need to pass through a DBA.
EF Power Tools are available on the Visual Studio Gallery and optionally here, check out this very useful video that, among other things, talks about the Update-Database command.
there is another solution :
Using DB = New SHAContext()
If DB.Database.Exists() Then
Dim migrator As New DbMigrator(New SHAClassLibrary.Migrations.Configuration())
For Each m In migrator.GetDatabaseMigrations()
Try
migrator.Update(m)
Catch ex As Exception
End Try
Next
End If
'DB.test()
End Using
I was looking for a way to control which migrations run explicitly in code without the need of a DbConfiguration class or automatic migrations enabled.
So i managed to create the following extension:
public static void RunMigration(this DbContext context, DbMigration migration)
{
var prop = migration.GetType().GetProperty("Operations", BindingFlags.NonPublic | BindingFlags.Instance);
if (prop != null)
{
IEnumerable<MigrationOperation> operations = prop.GetValue(migration) as IEnumerable<MigrationOperation>;
var generator = new SqlServerMigrationSqlGenerator();
var statements = generator.Generate(operations, "2008");
foreach (MigrationStatement item in statements)
context.Database.ExecuteSqlCommand(item.Sql);
}
}
As an example, having a migration like the following:
public class CreateIndexOnContactCodeMigration : DbMigration
{
public override void Up()
{
this.CreateIndex("Contacts", "Code");
}
public override void Down()
{
base.Down();
this.DropIndex("Contacts", "Code");
}
}
You could run it using your DbContext:
using (var dbCrm = new CrmDbContext(connectionString))
{
var migration = new CreateIndexOnContactCodeMigration();
migration.Up();
dbCrm.RunMigration(migration);
}
Heroku recently began supporting Java apps. Looking through the docs, it seems to resemble the Java Servlet Standard. Does anyone know of an instance where a GWT app has been successfully deployed on Heroku? If so, are there any limitations?
Yes, I've got a successful deployment using the getting started with Java instructions here:
http://devcenter.heroku.com/articles/java
I use the Maven project with appassembler plugin approach but added gwt-maven-plugin to compile a GWT app during the build.
When you push to heroku you see the GWT compile process running, on one thread only so quite slow but it works fine.
The embedded Jetty instance is configured to serve up static resources at /static from src/main/resources/static and I copy the compiled GWT app to this location during the build and then reference the .nocache.js as normal.
What else do you want to know?
You've got a choice, either build the Javascript representation of your GWT app locally into your Maven project, commit it and the read it from your app, or to generate it inside Heroku via the gwt-maven-plugin as I mentioned.
The code to serve up files from a static location inside your jar via embedded Jetty is something like this inside a Guice ServletModule:
(See my other answer below for a simpler and less Guice-driven way to do this.)
protected void configureServlets() {
bind(DefaultServlet.class).in(Singleton.class);
Map<String, String> initParams = new HashMap<String, String>();
initParams.put("pathInfoOnly", "true");
initParams.put("resourceBase", staticResourceBase());
serve("/static/*").with(DefaultServlet.class, initParams);
}
private String staticResourceBase() {
try {
return WebServletModule.class.getResource("/static").toURI().toString();
}
catch (URISyntaxException e) {
e.printStackTrace();
return "couldn't resolve real path to static/";
}
}
There's a few other tricks to getting embedded Jetty working with guice-servlet, let me know if this isn't enough.
My first answer to this turned out to have problems when GWT tried to read its serialization policy. In the end I went for a simpler approach that was less Guice-based. I had to step through the Jetty code to understand why setBaseResource() was the way to go - it's not immediately obvious from the Javadoc.
Here's my server class - the one with the main() method that you point Heroku at via your app-assembler plugin as per the Heroku docs.
public class MyServer {
public static void main(String[] args) throws Exception {
if (args.length > 0) {
new MyServer().start(Integer.valueOf(args[0]));
}
else {
new MyServer().start(Integer.valueOf(System.getenv("PORT")));
}
}
public void start(int port) throws Exception {
Server server = new Server(port);
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setBaseResource(createResourceForStatics());
context.setContextPath("/");
context.addEventListener(new AppConfig());
context.addFilter(GuiceFilter.class, "/*", null);
context.addServlet(DefaultServlet.class, "/");
server.setHandler(context);
server.start();
server.join();
}
private Resource createResourceForStatics() throws MalformedURLException, IOException {
String staticDir = getClass().getClassLoader().getResource("static/").toExternalForm();
Resource staticResource = Resource.newResource(staticDir);
return staticResource;
}
}
AppConfig.java is a GuiceServletContextListener.
You then put your static resources under src/main/resources/static/.
In theory, one should be able to run GWT using the embedded versions of Jetty or Tomcat, and bootstrap the server in main as described in the Heroku Java docs.
I am having an issue deploying MVC2 app on Window Server 2003 R2 x64. Does anyone have the same issue? I have tried different methods from global.asx, wild card mapping and to no avail. I'm thinking this is window server 2003 R2 x64 specific issue.
http://haacked.com/archive/2008/11/26/asp.net-mvc-on-iis-6-walkthrough.aspx
Deploying Asp.Net MVC 2 /C# 4.0 application on IIS 6
Do you have a Default.aspx on your home dir? If not, try adding one with this code-behind
public partial class _Default : Page
{
public void Page_Load(object sender, System.EventArgs e)
{
// Change the current path so that the Routing handler can correctly interpret
// the request, then restore the original path so that the OutputCache module
// can correctly process the response (if caching is enabled).
string originalPath = Request.Path;
HttpContext.Current.RewritePath(Request.ApplicationPath, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
HttpContext.Current.RewritePath(originalPath, false);
}
}