vnext (asp .net 5.0) and oracle - c#

I created a vnext solution in visual studio ultimate 2015 CTP version 14.0.22609.0 D14REL and in the package manager I added the oracle managed driver.
Install-Package odp.net.managed
then in my config.json
"Data": {
"DefaultConnection": {
"ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-vnext-237fb18c-c414-44a8-8771-e02d4719d1dc;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"hr": {
"ConnectionString": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))(CONNECT_DATA=(SID=mydatabase))); User Id=hr; Password=xxxxxxx;", "providerName":"oracle.manaagedatacess.client"
}
},
when I attempted to use it in a class
using System;
using Oracle.ManagedDataAccess.Client;
using System.Configuration;
namespace vnext.Models
{
internal class dataHelper
{
OracleConnection cn = new OracleConnection(ConfigurationManager.ConnectionStrings["hr"].ConnectionString);
}
}
lots of compile errors such as the type or namespace Oracle, Configuration, and OracleConnection could not be found are you missing an assembly reference? project vnext asp.net Core 5.0

Christian Shay is right... But there is a tweak. I didn't tested but just try to comment the dnxcore50 in project.json as follows:
"frameworks": {
"dnx451": { }
},
Since the default web template targets both the full .NET and .NET Core, the oracle managed driver framework is currently not available in .NET Core. so you can comment it out. Now you should be able to build and run the solution with out error.
Update :
Removed
/* dnxcore50": { } */

Related

netcoreapp1.0 does not find net461 specific package

I am using VS Code to build a net core app. I need to use a NuGet package that is not supported, and therefore changed my project.json file's framework part to the following:
"frameworks": {
"net461": {
"dependencies": {
"ScrapySharp": "2.6.2"
}
},
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
}
}
}
}
Restoring the project seems to work and the package (ScrapySharp) is installed. However when I use the package, it appears that both netcoreapp and net461 look for it. While net461 finds and references it properly, netcoreapp throws the following error:
The type or namespace name 'ScrapySharp' could not be found
Is there anything I can do to work around this?
If package available only for one framework of two - you should modify your program code and do not use this package when compiled under netcoreapp. Effectively, you will lost some functionality of your app when compiled under netcoreapp.
If this suitable for you, then use preprocessor directives like this:
public void function DoSomething()
{
#if NET461 then
// do something with ScrapySharp
#else
// Say to your user that this feature is not available
throw new Exception("This feature is not available on this platform");
#endif
}

How to connect to an Oracle database Connection from .Net Core

Within a .netCore library I want to connect to an Oracle database. Is there any way I can do that yet?
I have tried the suggestions on another SO post, but it doesn't work, perhaps removed since? As you can see in my project.json, I'm trying to use "net461".
I'm currently trying using Oracle.ManagedDataAccess.Client via old fashioned ADO.Net. I also know that Oracle haven't bought out a .netCore connector yet. But even there I can't get it to work, it struggles to get the System.Data included, it errors whenever I try to add it.
My project.json looks like this:
{
"version": "1.0.0-*",
"dependencies": {
"NETStandard.Library": "1.6.0",
"Oracle.ManagedDataAccess": "12.1.24160719",
},
"frameworks": {
"netstandard1.6": {
"imports": [
"dnxcore50",
"net461"
]
}
}
}
This is how I was trying to do it at the moment.
using Oracle.ManagedDataAccess.Client;
public class MyRepository
{
public string GetServerVersion()
{
var _db = new OracleConnection("User Id=myUser;Password=myPassword;Data Source=MyOracleConnection");
var serverVersion = _db.ServerVersion;
return serverVersion;
}
}
However the above doesn't compile as it doesn't have System.Data, which I'm struggling to import.
I'm not entrenched on any particular way of doing it, I just want the best reasonable option at this point in time.
Beta release .Net Core Managed driver released by Oracle at the end of January 2018 http://www.oracle.com/technetwork/topics/dotnet/downloads/net-downloads-160392.html.
Supported platfom mentionet in doc is now Win and Linux.
Nuget: https://www.nuget.org/packages/Oracle.ManagedDataAccess.Core
Other old alternatives with standart/instant Oracle clients :
for .Net Core 2.0 I recomend to use ericmend oracleClientCore-2.0 : https://github.com/ericmend/oracleClientCore-2.0. Nuget: dotNetCore.Data.OracleClient I used it succesfully in Win and Linux platform. There is my small sample
alternativelly System.Data.OracleClient works for 2.0 too - see #Owen post. But I test it only in Win platform
for .Net Core >= 1.0 you can use unofficial LinqDan Oracle client for .NET Core based on Mono's Oracle client https://github.com/LinqDan/oracleclientcore
Nuget: Mono.Data.OracleClientCore.
my TestCore.csproj for last alternative :
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp1.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Mono.Data.OracleClientCore" Version="1.0.0" />
</ItemGroup>
</Project>
My program.cs:
using System;
using System.Data.OracleClient;
namespace TestCore
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting.\r\n");
using (var _db = new OracleConnection("User Id=myUser;Password=myPassword;Data Source=MyOracleConnection"))
{
Console.WriteLine("Open connection...");
_db.Open();
Console.WriteLine( "Connected to:" +_db.ServerVersion);
Console.WriteLine("\r\nDone. Press key for exit");
Console.ReadKey();
}
}
}
}
Oracle published the official Data Provider for .NET Core on nuget.
Here is a basic example to show how to use it:
using Oracle.ManagedDataAccess.Client;
public void Execute(string queryString, string connectionString)
{
using (OracleConnection connection = new OracleConnection(connectionString))
{
OracleCommand command = new OracleCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
Basically you can use it exactly like the official .NET System.Data.SqlClient (easy to find online tutorials for this) and just replace everywhere in the code SqlConnection with OracleConnection and SqlCommand with OracleCommand.
Oracle plans to certify ODP.NET, Managed Driver on Microsoft .NET Core around the end of calendar year 2017.
Oracle intends to support managed ODP.NET on .NET Core on Windows operating systems and Oracle Linux.
Managed ODP.NET may support additional operating systems. Oracle will continue to evaluate support for
other Linux distributions and will announce additions to the certification list at a future time.
Oracle does not plan to certify on earlier versions than Microsoft .NET Core 2.0. .NET Core 2.0 contains
numerous features that make managed ODP.NET certification possible on the framework
From this article :http://www.oracle.com/technetwork/topics/dotnet/tech-info/odpnet-dotnet-core-sod-3628981.pdf
Updated: Beta released ODP.NET Core
If you are using oracle database with .NET core then need to install few nuget packages.
Microsoft.EntityFrameworkCore
Oracle.EntityFrameworkCore
Oracle.ManagedADataAccess.Core
After this need to write some code in the configureServices method of startup class.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<OracleDbContext>(options=>options.UseOracle(Configuration.GetConnectionString("OracleConnection")));
}
OracleDbContext class is inherting from the DbContext class and OracleConection connection string is set up in the appSettings.json file.
OracleDbContext.cs
public class OracleDbContext : DbContext
{
public OracleDbContext(DbContextOptions options):base(options){}
}
appSettings.json
{
"ConnectionStrings":{
"OracleConnection":"Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=
(PROTOCOL=TCP)(HOST={url of your database})(PORT={port})))(CONNECT_DATA=
{name of your database for ex: SID})));User Id={user id};password=
{password}:"
}
}
Values in bracket {} needs to be replaced. This connection string is used when the database is on the server, not locally.
As mentioned in other answers, Oracle has not yet released a package for their Managed Client, but is planned for later this year.
However, as of the release of .NET Standard 2.0, the System.Data.OracleClient library has been updated (available via NuGet). Obviously this is not an ideal solution since that library is obsolete, but it does give you something to work with - and you can just write a wrapper and swap it out for the official Oracle library when it is released.
Add appsettings.json to project (output dir: copy always). fill connection strings:
{
"ConnectionStrings": {
"connection-db": "Data Source=192.168.1.3:1521/ORACLEVM;User
Id=userId;Password=123;Validate Connection=true;"
}
}
Open Manage Nuget Packages in project, add these packages:
Microsoft.Extensions.Configuration.Json (to use configuration manager in .net core)
Oracle.ManagedDataAccess.Core (.net core version of oracle data access client)
static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
var configuration = builder.Build();
var connectionString = configuration.GetConnectionString("connection-db");
using (OracleConnection connection = new OracleConnection(connectionString))
{
var command = new OracleCommand("INSERT INTO ..", connection);
connection.Open();
command.ExecuteNonQuery();
}
}
You should delete "dnxcore50" (This means your project is not a pure .net core application any more) from project.json under frameworks node and try again. As far as I know you can not connect to oracle via .net core FOR NOW, maybe checking this link can helpful
Based on Oracle .NET team They have released a new beta ODP.​NET Core;
You can also find it here
finally devart's dotConnect for Oracle support .net core since version "9.4.280".
We have done this by setting up an oracle linked server and using stored procedures that make calls to the Oracle linked server from SQL server. You might try that. You can use Openquery or Exec .. At [likedserver] to make the querys execute on the Oracle side.

How do you unit test ASP.NET Core Web Application (.Net Framework)?

I'm building an ASP.NET Core Web Application (.Net Framework) and am having a hard time figuring out how to hook unit tests up to it. I am targeting the .net framework version 4.6.1
If I create a regular "Class Library" project targeting 4.6.1, as I would for previous version of MVC, it lets me add references to my MVC project (which is part of the same solution) but any namespaces I add through a using statement report an error that I might be missing a reference or using statement. If I double click on the reference under the "References" section in the solution explorer it tells me that the project can't be found or hasn't been build yet.
I tried creating a "Class Library (.NET Core)" but that complains since I'm targeting .Net Framework and not .NET Core. I edited the class libaries Project.json to have it target the .net framework and that lets me add my references and doesn't complain when I the namespaces in a using statement but none of my tests are discovered by the test runner. I've tried both XUnit and NUnit and they both behave the same.
Is it possible to unit test an ASP.Net Core Web Application targeting the .Net Framework 4.6.1 or do I need to commit to the .NET Core?
Edit to add my test class
Here is my test class stripped down to the bare minimum. TestBank.Services is the class I want to test.
using System;
using TestBank.Services;
using Xunit;
namespace TestBankUnitTests
{
public class Class1
{
[Fact]
public void TestA()
{
Assert.True(false);
}
}
}
and here is my project.json
{
"version": "1.0.0-*",
"dependencies": {
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-build10025",
"TestBank": "1.0.0-*"
},
"frameworks": {
"net461": {
}
}
}
Your project.json needs a testRunner setting. Per the project.json documentation, the testRunner setting not only specifies which test framework to use, but also marks the project as a test project.
Try adding it and see if it finds your tests (verified locally that it will not find tests without this setting in the file)
{
"version": "1.0.0-*",
"dependencies": {
"xunit": "2.1.0",
"dotnet-test-xunit": "1.0.0-rc2-build10025",
"TestBank": "1.0.0-*"
},
"frameworks": {
"net461": {
}
},
"testRunner": "xunit"
}
I was having a similar issue and found a solution. I am posting it here in case it helps someone. What I have learned is that using an xproj library targeting net461 to test an Asp.Net Core Project (.Net Framework) project targeting net461 and a Windows class library targeting framework 4.61 works but the setup seems to be very finicky and fragile. The key insight for me came from this thread https://github.com/aspnet/Tooling/issues/245 where #BradRem indicated that the folder structure of the projects seemed to the source of issues.
Initially I tried unsuccessfully to use this folder structure:
src
____Asp.Net Core Project (.Net Framework) project targeting Net461
____Windows class library targeting framework 4.61
test
____Core Library used to run xUnit Tests
But when I tried to run the tests using this folder structure it produced the exception that starts off like this:
Unable to start C:\Program Files\dotnet\dotnet.exe
dotnet-test Error: 0 : [ReportingChannel]: Waiting for message failed System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.Stream.ReadByte()
at System.IO.BinaryReader.ReadByte()
at System.IO.BinaryReader.Read7BitEncodedInt()
at System.IO.BinaryReader.ReadString()
at Microsoft.DotNet.Tools.Test.ReportingChannel.ReadMessages()
But when I changed to the following folder structure I was able to get it to work:
src
____Asp.Net Core Project (.Net Framework) project targeting Net461
____Windows class library targeting framework 4.61
____Core Library used to run xUnit Tests
So the key was putting the folder that housed the testing class library in the src folder where the other projects folders were.
That said, the other thing that seemed to make a big difference was to add the references to the other two projects to the Core Library test project at the same time rather than one at a time.
I have found something that works for me.
Inside my test project, my project.json file looks like this:
{
"version": "1.0.0-*",
"testRunner": "xunit",
"dependencies": {
"xunit": "2.2.0-beta2-build3300",
"dotnet-test-xunit": "2.2.0-preview2-build1029",
"Ng2a.WebApi": "1.0.0-*"
},
"frameworks": {
"net452": {
}
}
}
'Ng2a.WebApi' is my web api core project. It targets only net452.
The Ng2a.WebApi project.json file looks like this:
"frameworks": {
"net452": {}
},

How do I use System.Data in a .NET Core RC2 console app (Linux, Debian 8)?

I've installed .NET Core RC2 on a Debian 8 amd64 system and would like to test if it's possible to query an instance of Microsoft SQL Server.
So I'd like to add to my project a dependency on the System.Data.SqlClient assembly.
Presently my project file created by running the dotnet new CLI tool looks like this:
{
"version": "1.0.0-*",
"buildOptions": {
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0-rc2-3002702"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}
Using this answer to a similar query, I was able to add a reference to System.Data.Common changing the
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
fragment to
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50",
"dependencies": {
"System.Data.Common": "*"
}
}
}
which made dotnet restore use NuGet to download a bunch of stuff.
I then tried to change that fragment to read
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50",
"dependencies": {
"System.Data.SqlClient": "*"
}
}
}
but NuGet says it's
Unable to resolve 'System.Data.SqlClient' for '.NETCoreApp,Version=v1.0'.
If I change the version string to read "4.1.0-rc3-*" the error message just gets more specific:
Unable to resolve 'System.Data.SqlClient (>= 4.1.0-rc3)' for '.NETCoreApp,Version=v1.0'.
What I'm puzzled about is that the NuGet package gallery dedicated to .NET Core explicitly lists System.Data.SqlClient as available.
So what could I do to add a reference to System.Data.SqlClient assembly to my project and have NuGet download it?
On a side note, I'm currently playing around in a plain console with only the dotnet CLI tool. Is there any way to manage project dependencies for a .NET Core project without resorting to installing IDEs?
Like poke already annotated in the comment is correct. Specify a version to System.Data.SqlClient makes your restore happy ;)
Why is that? System.Data.SqlClient exists in the http://nuget.org gallery. Not specifying a version ("") is not allowed outside of the boundaries of a project (like a nuget feed package) and specifying solely an star "*" (you should never do that, it allows breaking changes) restore the highest available version. Since there is no stable, star will not find anything (there is some magic with the dashes behind). The RC2 version of that library is the mentioned 4.1.0-rc2-24027 and when you ask with 4.1.0-rc2-* it will take the highest of the RC2 builds (but there is only one). In comparison System.Data.Common has a public release on nuget.org for the Universal Windows Platform and is found for that reason.
The RC3 is the next release and only available on developer feeds from the .NET Core and ASP.NET Core team and not the public nuget feed. You should not play with them.
if you are in project.json file, the intellisense guide you now if you have updated the Visual studio with the latest tooling avaiable..
I added the following in the dependencies element and it works perfectly..
"System.Data.SqlClient": "4.1.0-rc2-24027",
On my MINT 19 Tara I do not use System.Data.SqlClient but the newer version Microsoft.Data.SqlClient.
Check nuget
After typing the .NET-cli command, the package was downloaded and the reference was added to the project csproj file.
In the code, use the newer namespace:
using Microsoft.Data.SqlClient;
The "regular" code works fine:
public static void CreateCommand(string queryString, string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
SqlDataReader reader = command.ExecuteReader() ;
while( reader.Read() ) {
for (int i = 0; i < reader.FieldCount; i++)
{
Console.WriteLine( "Column name={0}, Value={1}",
reader.GetName(i),
reader.GetValue(i) );
}
}
}
}

Using Web Api 2 as Self Console Host in C#

I want to build a self Host of a Web Api 2 Webservice.
I am using the .Net Core 1.0 Framework for my Console App and also for the Web Api 2 Project.
Since there was a name change for the packages and Owin is deprecated, I am not able to rebuild the given samples in the official GitHub repository of ASPnet:
https://github.com/aspnet/Hosting/blob/dev/samples/SampleStartups/StartupHelloWorld.cs
(I tried with this one)
I looked in the project.json file which packages they are using but since I can´t find the AspNetCore.Hosting package only a package named AspNet.Hosting but i isn´t working with both packages.
{
"version": "1.0.0-*",
"dependencies": {
"Microsoft.AspNetCore.Hosting": "1.0.0-*",
"Microsoft.NETCore.Platforms": "1.0.1-*"
},
Resharper says something like :
Severity Code Description Project File Line Suppression State
Error CS0246 The type or namespace name 'WebHostBuilder' could not be found (are you missing a using directive or an assembly reference?) WebApiConsoleHost.DNX 4.5.1, WebApiConsoleHost.DNX Core 5.0
Just to be complete, I used the whole Main Function Body of the given sample in the Link:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseDefaultConfiguration(args)
.UseStartup<StartupHelloWorld>()
.Build();
host.Run();
}
Do someone know where the WebHostBuilder class is defined ? Resharper suggests that it is in AspNet.Hosting, but after adding the using it is still not found!
Try to read the latest docs. It is working for me.

Categories

Resources