How-tos

Getting Started on Bluemix ADO .Net Core Application to access IBM Data Servers

Share this post:

Introduction

The purpose of this blog is to help you get started using ADO .Net Core Applications hosted on IBM Bluemix to connect and Perform DML operations against IBM Data Servers

Prerequisites

  1. Sign up for a Bluemix account, visit SignUp in your web browser and click “Sign-up” in the top right corner.You’ll receive an email in a couple of minutes. If you already have a login, please continue starting at step 3.
  2. There should be a link in the email that says “Click here to complete your registration.” Click that. Sign in with the username and password you created from step 1.
  3. Follow the steps given in this link Using the starter applications and after step 5, click on the Asp .net Core app created. From there, you’ll be taken to a new page. In the new page, click on Getting Started and follow the steps given to set up the Bluemix command line environment on your local machine, download .Net Core Starter App and push the app back to Bluemix

We’ll modify this Starter App into a ADO .Net Core Application, which will be hosted on Bluemix and can connect to IBM database servers.

Setup Database Objects

  • Creating a dashDB instance on Bluemix

If you already have a existing database, you can skip this section and navigate to the Database Table section.

IBM Bluemix dashDB for Analytics is used as the database for working with this blog.

  1. Log in to Bluemix, if you haven’t already.
  2. From the BluemixCatalog navigate to theServices-> Data & Analytics section, then click on dashDB for Analytics.
  3. Type a service name — for example “dashDBDemo” and click on Create.
  4. Now the dashDBDemo instance is created. Next, click on that service. You’ll be navigated to a new page.
  5. Click on the Service Credentials tab, then click on the New Credential button. Here you’ll get a new window. Click on Add and a new set of credentials will be created.
  6. You can view the credentials details by clicking on View Credentials and take a note of the following: database, username, password, hostname, port. These details will be used in the application to connect to this database
  7. Now click on “Manage” tab and then click on Open. You’ll be navigated to a new window.
  8. In the new window, click on Run, and then clear the existing SQL commands. Copy and paste the SQL commands from the below Database Table section and click on RunAll.
  9. The necessary table required for this blog has been created and the value for the columns of the table have been inserted successfully.
  • Database Table

If you already have an existing database, use any DB2 Database client and execute the following commands:

  • CREATE TABLE Blog ( BlogId int NOT NULL , url nvarchar(500) NOT NULL, CONSTRAINT PK_Blog PRIMARY KEY (BlogId)) ORGANIZE BY ROW ;
  • INSERT INTO Blog VALUES (1,’https://console.ng.bluemix.net/docs/cfapps/starter_app_usage.html’), (2,’https://www.ibm.com/developerworks/community/forums/html/forum?id=11111111-0000-0000-0000-000000000467′), (3,’http://blogs.msdn.com/dotnet’) ;

Steps to be followed to modify the Bluemix .Net Core Starter App into a ADO .Net Core application

  1. Unzip the downloaded starter app and open the solution in Visual Studio 2015. Make sure you are using Visual Studio 2015 Update 3, .Net Core 1.0.1 – SDK 1.0.0 Preview2 and .NET Core 1.0.1 tools Preview2.
  2. Open project.json and add the following packages under dependency section:
      
         "Microsoft.AspNetCore.Mvc": "1.1.1",
         "IBM.EntityFrameworkCore-lnx": "1.1.1.101"
    

    and Add “Views” folder in buildOptions and publishOptions.

         "buildOptions": {
              "copyToOutput": {
              "include": [ "wwwroot","Views" ]
          },
          "debugType": "portable",
          "emitEntryPoint": true,
          "preserveCompilationContext": true
          },
    
          "publishOptions": {
              "include": [ "wwwroot","Views" ],
              "exclude": [ "**.user", "**.vspscc" ]
          },
    
  3. Add three folders to the project namely “Controllers” “Models” “Views”.
  4. Create two class(.cs) files under Models folder and name them “Blogs.cs” and “BloggingContext.cs” accordingly.
  5. Add a MVC Controller class under Controllers folder and name it as “BlogsController.cs”
  6. Create a folder called “Blogs” under “Views” folder.
  7. Add the following class to Models/Blogs.cs file
           public partial class Blog
    {
    public Blog()
    {
    }

    public int BlogId { get; set; }

    public string Url { get; set; }
    }

  8. Copy and paste the following namespace into Models/BloggingContext.cs file:
        
          using Microsoft.EntityFrameworkCore;
    

    and replace the existing BloggingContext class with the below code and update the connection string:

            public partial class BloggingContext : DbContext
    {
    public BloggingContext(DbContextOptions options)
    : base(options)
    { }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    modelBuilder.Entity<Blog>(entity =>
    {
    entity.Property(e => e.Url).IsRequired();
    });
    }
    public virtual DbSet<Blog> Blog { get; set; }
    }

  9. Open the BlogsController.cs file under Controllers folder and add the following namespace:
      
          using Microsoft.AspNetCore.Mvc;
          using <YOURPROJECTNAMESPACE>.Models; 
          using System.Linq;
    

    Copy and paste the source code below to overwrite the existing BlogsController class:

            public class BlogsController : Controller
    {
    private BloggingContext _context;

    public BlogsController(BloggingContext context)
    {
    _context = context;
    }

    public IActionResult Index()
    {
    return View(_context.Blog.ToList());
    }
    }

  10. Right click on Views/Blogs folder and select Add New and select “MVC View Page.” Name it as Index.cshtml. Copy and paste the below content:
          @model IEnumerable<<YOURPROJECTNAMESPACE>.Models.Blog>
          @{
             ViewBag.Title = "Blogs";
           }
          <h2>Blogs</h2>
          <table class="table">
             <tr>
                <th>Id</th>
                <th>Url</th>
             </tr>
          @foreach (var item in Model)
          {
             <tr>
             <td>
                @Html.DisplayFor(modelItem => item.BlogId)
             </td>
             <td>
                @Html.DisplayFor(modelItem => item.Url)
             </td>
             </tr>
          }
          </table>
    
  11. Open the Startup.cs file, then copy and paste with the following code:
           using .Models;
           using Microsoft.AspNetCore.Builder;
           using Microsoft.AspNetCore.Hosting;
           using Microsoft.Extensions.Configuration;
           using Microsoft.Extensions.DependencyInjection;
           using IBM.EntityFrameworkCore;
           using IBM.EntityFrameworkCore.Storage.Internal;
    

    public class Startup
    {
    public void Configure(IApplicationBuilder app)
    {
    app.UseDefaultFiles();
    app.UseStaticFiles();
    app.UseMvc(routes =>
    {
    routes.MapRoute(
    name: "default",
    template: "{controller=Blogs}/{action=Index}/{id?}");
    });
    }
    public void ConfigureServices(IServiceCollection services)
    {
    var connection = "DATABASE=dbname;SERVER=hostname:sslport;UID=username;PWD=password;Security=SSL;";
    services.AddDbContext<BloggingContext>(options => options.UseDb2(connection,p=>p.SetServerInfo(IBMDBServerType.<servertype>, IBMDBServerVersion.<serverversion>)));
    services.AddMvc();
    }
    public static void Main(string[] args)
    {
    var config = new ConfigurationBuilder()
    .AddCommandLine(args)
    .Build();

    var host = new WebHostBuilder()
    .UseKestrel()
    .UseConfiguration(config)
    .UseStartup()
    .Build();
    host.Run();
    }
    }

  12. Navigate to the Project root folder and open the manifest.yml file.
    Add the following env variable to set the LD_LIBRARY_PATH to clidriver/lib present in the packages folder.
    LD_LIBRARY_PATH: $HOME/.nuget/packages/IBM.Data.DB2.Core-lnx/1.1.1.101/build/clidriver/lib

    Sample manifest.yml file :
    applications:
    – path: .
    memory: 512M
    instances: 1
    domain: mybluemix.net
    name: dotnetStarterApp
    host: dotnetStarterApp
    disk_quota: 1535M
    env:
    LD_LIBRARY_PATH: $HOME/.nuget/packages/IBM.Data.DB2.Core-lnx/1.1.1.101/build/clidriver/lib

Push the app to Bluemix and launch the application in browser

  1. Open any command prompt
  2. Run: bluemix api https://api.ng.bluemix.net
  3. then run: bluemix login -u BluemixUserId@abcd.com -o “BluemixUserId@abcd.com” -s “app”, you’ll be asked to enter your Bluemix login password, then press enter.
  4. Change the directory to the project root folder, where you have the manifest.yml file located.
  5. Now run: bluemix cf push <bluemixAppName> -b dotnet-core
    sample: bluemix cf push dotnetStarterApp -b dotnet-coreAfter the command has been run successfully, you should see the output something like this:requested state: started
    instances: 1/1
    usage: 512M x 1 instances
    urls: dotnetStarterApp.mybluemix.net
    last uploaded: Tue Jan 17 11:14:48 UTC 2017
    stack: cflinuxfs2
    buildpack: dotnet-core
    state since cpu memory disk
    details
    #0 running 2017-01-17 06:18:50 AM 113.9% 283.8M of 512M 983.3M of 1.5G
  6. Open any browser and copy paste the url https://dotnetStarterApp.mybluemix.net/Blogs and you’ll be able to see the inserted data from the Blogs table as shown below:

    Blogs

    Id Url
    1 https://console.ng.bluemix.net/docs/cfapps/starter_app_usage.html
    2 https://www.ibm.com/developerworks/community/forums/html/forum?id=11111111-0000-0000-0000-000000000467
    3 http://blogs.msdn.com/dotnet

<Edited the blog to update the mandatory server type changes from IBM Data Server Provider for EFCore 1.1.1 release.>
For more information about server type setting, please go through this link

More How-tos stories
April 30, 2019

Introducing IBM Analytics Engine v1.2 and Announcing the Deprecation of IBM Analytics Engine v1.0

We are excited to inform you about the new version of IBM Analytics Engine v1.2 that will be available starting May 15, 2019. Along with this release, Analytics Engine v1.0 will be retired.

Continue reading

April 23, 2019

Announcing the Deprecation of the Watson Machine Learning JSON Token Authentication Service

We’d like to inform you about the deprecation of the Watson Machine Learning JSON Token Authentication service. This method of authentication will be retired on May 30, 2019.

Continue reading

April 16, 2019

Announcing the Deprecation of the Decision Optimization Beta Service

The End of Beta date for the Decision Optimization service is May 17, 2019. The End of Beta Support date is June 20, 2019.

Continue reading