I am trying to use petapoco with my .NET core MVC application,
I have installed petapoco compiled as stated in another answer but don't know what to do next,
I searched many places but most of them had been using the previous versions of petapoco and not the latest one,
Can someone please help and provide some resources link as to how am I supposed to connect it with my SQL server using a connection string, and since now their documentation suggested to use PetaPoco.DBEntityGenerator instead of T4 templates, I have no idea how to use it.
Start by reading the Quick start guide
To connect to your db, you can start with the samples given:
// Normal
var db = new PetaPoco.Database("connectionStringName");
// Or the fluent configuration (PostgreSQL as an example)
var db = DatabaseConfiguration.Build()
.UsingConnectionString("Host=127.0.0.1;Username=petapoco;Password=petapoco;Database=petapoco;Port=5001")
.UsingProvider<PostgreSQLDatabaseProvider>()
.UsingDefaultMapper<ConventionMapper>(m =>
{
m.InflectTableName = (inflector, s) => inflector.Pluralise(inflector.Underscore(s));
m.InflectColumnName = (inflector, s) => inflector.Underscore(s);
})
.Create();
V6 only change the package and dropped support for some thing like T4, but you don't need the templates to start. The rest it's the same as V5
Related
I'm trying to connect to my context in my VS solution with EF Core
But when I test the connection I get this error
Because it is trying to connect with my domain user instead the user in the connection string
Any idea, please?
Thanks
i cant post pictures in reply so i am using it as answer
i will doublecheck lower versions (i guess 5) - since i dont know which version are you using (but image of EF connection is different than mine (!))
in linqpad 7 it works
in addition, if you need a context you can write using regular connection
using(TypedDataContext context = new TypedDataContext(Connection.ConnectionString)){
context.TABLE.Where(w=>w.ID == 64463).Dump();
}
I'm using RDLC to create reports with my .NET Core Web API. I spent an entire week creating 3 reports using lots of expressions. Now after publishing the application on IIS every report fails with error
An error occurred during local report processing.;An unexpected error
occurred in Report Processing.Object reference not set to an instance
of an object
The report works fine in development. After lots of research I found the issue is with expressions. I have been struggling to find a solution for almost a day searching the entire web. Many people suggested that this is the limitation of RDLC and we can't use expressions. Without expressions there is no use of this tool for me. I can't afford to spend another week to re-create those reports using another tool. In fact I don't even know what else can I use instead of RDLC to create reports.
Any suggestion to fix these issues or an alternative to RDLC will be life saving for me....
It's been a pain to use this unstable tool, but unfortunately I'm stuck in this.
Thanks
Having .NET Core work with library from .NET framework is painful to say the least.
Thanks for the recompiled WinForms library provided by lkosson.
I managed to make this work but it looks like bandage fix more then anything.
Very Important Note!! This solution make use of WPF, WinForms version of RDLC. This limit the .NET 5 solution to Windows build only. (I can't make Web version to work, maybe someone else can)
1. Update .NET 5 project settings
Unload the .NET 5 project
Right click and Edit .csproj
Update/Add 3 lines in property group as following:
<PropertyGroup>
--><TargetFramework>net5.0-windows</TargetFramework>
<RootNamespace>Net_Core_5._0</RootNamespace>
--><UseWindowsForms>true</UseWindowsForms>
--><EnableUnsafeBinaryFormatterSerialization>true</EnableUnsafeBinaryFormatterSerialization>
</PropertyGroup>
Reload the project
2. Add NuGet Packages
Add and install the following packages:
Microsoft.ReportViewer.Common
Microsoft.ReportViewer.WinForms
ReportViewerCore.WinForms
3. Use .NET version's function to generate Report
This is an example for your reference,
using Microsoft.Reporting.WinForms;
using System;
using System.Collections.Generic;
using System.Data;
namespace NET_4._8_RDLC_Lib
{
public class ReportGenerator
{
/// <summary>
/// .NET Core use this function to render reports
/// </summary>
public static byte[] RenderReport(String reportPath, Dictionary<string, DataTable> data, string format)
{
Microsoft.Reporting.WinForms.ReportViewer v1 = new Microsoft.Reporting.WinForms.ReportViewer();
v1.LocalReport.DataSources.Clear();
//Add all datasource to the Report
foreach (KeyValuePair<string, DataTable> pair in data)
{
Microsoft.Reporting.WinForms.ReportDataSource ds = new ReportDataSource(pair.Key, pair.Value);
v1.LocalReport.DataSources.Add(ds);
}
v1.LocalReport.EnableExternalImages = true;
v1.LocalReport.ReportPath = reportPath;
return v1.LocalReport.Render(format: format, deviceInfo: "");
}
}
}
The file is just inside the bytes array.
I'm trying to do the migration with EF Core but I get an error - how can I fix this error?
PM> add-migration ini
Unable to create an object of type 'ApplicationContext'. Add an
implementation of 'IDesignTimeDbContextFactory' to
the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for
additional patterns supported at design time.
This will also happen if you have multiple start-up projects - when migrating, just select one (in VS right click Solution and Set StartUp Projects...)
I had the same issue with asp.net core 3.1.
For me, it was pretty straight forward, adding an implementation of IDesignTimeDbContextFactory to the main web project fixed the issue.
A basic implementation looks something like this:
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<YourDbContext>
{
public YourDbContext CreateDbContext(string[] args)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var builder = new DbContextOptionsBuilder<YourDbContext >();
var connectionString = configuration.GetConnectionString("DefaultConnection");
builder.UseSqlServer(connectionString);
return new YourDbContext(builder.Options);
}
}
Please refer to this blog post on the subject.
It is highly probably because of your default startup project:
Open Package manager console and write this command:
PM> Add-Migration -StartupProject[YourProjectPath(just press a tab all the.csproj paths will come up, and then choose your DataBaseLayer project to execute a migration for)] migrationName
In this way you don't need to again go to solution and set startup
project with your webProject whenever you finished adding a new migration.
1.Modify your code in ConfigureService with :
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
x => x.MigrationsAssembly("WebApplication")));
In command line which includes WebApplication.csproj:
dotnet ef migrations add Init
I got this error when creating a migration. In my code in the ApplicationContext constructor, I used the Database.EnsureCreated() method. Typically this method is used for small applications where you need to check for the existence of a database and create it once. When creating an application with a database that will change with new versions and using migrations, you should not use this method.
In my case, this error existed because I was applying migrations at runtime. After removing Database.Migrate(); in my code, I was able to add the new migration without errors.
By the way, I used EF Core .NET command-line interface (CLI) tools, not the Package Manager Console (I run into problems I couldn't solve when I was using the Package Manager Console, so I went for the CLI alternative, and it was worth the change).
Also, make sure you use the appropriate options to select your startup project and your target project.
I got this error when the Primary Key for the table was not set manually (with attributes or with FluentAPI) and was not determined automatically (not "Id" kayword and not "TableName" + "Id")
Stack: ASP.NET Core EF + Postgres (Npgsql)
I am working on MVC 6 application(DNX Core 5.0 framework). Unfortunately, I don't find any library for pdf export.
Any help will be appreciated.
I finally figured out a way to generate pdf's from .NET Core (without any .NET framework dependencies) is using Node.js from within my .NET Core application.
The following example shows how to implementing a HTML to PDF converter in a clean ASP.NET Core Web Application project (Web API template).
Install the NuGet package Microsoft.AspNetCore.NodeServices
In Startup.cs add the line services.AddNodeServices() like this
public void ConfigureServices(IServiceCollection services)
{
// ... all your existing configuration is here ...
// Enable Node Services
services.AddNodeServices();
}
Now install the required Node.js packages:
From the command line change working directory to the root of the .NET Core project and run these commands.
npm init
and follow the instructions to create the package.json file
npm install jsreport-core --save
npm install jsreport-jsrender --save
npm install jsreport-phantom-pdf --save
Create a file pdf.js in the root of the project containing
module.exports = function (callback) {
var jsreport = require('jsreport-core')();
jsreport.init().then(function () {
return jsreport.render({
template: {
content: '<h1>Hello {{:foo}}</h1>',
engine: 'jsrender',
recipe: 'phantom-pdf'
},
data: {
foo: "world"
}
}).then(function (resp) {
callback(/* error */ null, resp.content.toJSON().data);
});
}).catch(function (e) {
callback(/* error */ e, null);
})
};
Have a look here for more explanation on jsreport-core.
Now create an action in an Mvc controller that calls this Node.js script
[HttpGet]
public async Task<IActionResult> MyAction([FromServices] INodeServices nodeServices)
{
var result = await nodeServices.InvokeAsync<byte[]>("./pdf");
HttpContext.Response.ContentType = "application/pdf";
string filename = #"report.pdf";
HttpContext.Response.Headers.Add("x-filename", filename);
HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "x-filename");
HttpContext.Response.Body.Write(result, 0, result.Length);
return new ContentResult();
}
Off course you can do whatever you want with the byte[] returned from nodeServices, in this example I'm just outputting it from a controller action so it can be viewed in the browser.
You could also exchange the data between Node.js and .NET Core by a base64 encoded string using resp.content.toString('base64') in pdf.js and use
var result = await nodeServices.InvokeAsync<byte[]>("./pdf"); in the action and then decode the base64 encoded string.
Alternatives
Most pdf generator solutions still depend on .NET 4.5/4.6 framework.
None of the two answers above (JsReport and RazorPDFCore) works for .NET Core yet.
There seems to be some paid alternatives available if you don't like to use Node.js:
NReco.PdfGenerator.LT
EVO HTML to PDF Converter Client for .NET Core
Winnovative HTML to PDF Converter Client for .NET Core
I haven't tried any of these though.
I hope we will soon see some open source progress in this area.
If you must rely on Core you'll have two options:
1 - Wait a bit
Core is still RC1, slowly moving to RC2, and you won't find much libs really soon. Since .NET Core is taking much attention, first libs should come out in a few months, but I'd guess you'll have to wait for at least RC2 release.
2 - Fork (or similar)
You can grab an open-source project that best fits your needs, fork (if on GitHub) or just download and start updating to .NET Core. I've just done that with DapperExtensions and it's working like a charm. You can even add some spicy just for you ;)
On the other hand, if you just need something that works but with no direct need of embedding into .NET Core, I've managed to make JsReport work fine. It will start it's very own server (embedded server) based on Node but integration is really easy (with AspNet Core very own Dependecy Injection system!) and PDF are created with no further issue.
If that interests you, here are some instructions:
1 - References
Add those to your project.json:
"jsreport.Embedded": "0.8.1",
"jsreport.Client": "0.8.1"
2 - AspNet integration
After, follow instructions from jsReport here. You can configure AspNet DI system as here:
public void ConfigureServices(IServiceCollection services)
{
// ...
var _server = new EmbeddedReportingServer();
_server.StartAsync().Wait();
services.AddInstance<IEmbeddedReportingServer>(_server);
services.AddSingleton<IReportingService>((s) => { return s.GetRequiredService<IEmbeddedReportingServer>().ReportingService; });
// ...
}
To use you'll just have to either receive an IReportingService or manually grab it from Resolver on your controller, for instance.
3 - Usage
public IActionResult SomeReport()
{
// This is <my> type of usage. It's a bit manual because I'm currently loading reports from DB. You can use it in a diferent way (check jsReport docs).
var service = Resolver.GetRequiredService<jsreport.Client.IReportingService>();
var phantomOptions = new jsreport.Client.Entities.Phantom()
{
format = "A4",
orientation = "portrait",
margin = "0cm"
};
phantomOptions.footer = "<h2>Some footer</h2>";
phantomOptions.footerHeight = "50px";
phantomOptions.header = "<h2>Some header</h2>";
phantomOptions.headerHeight = "50px";
var request = new jsreport.Client.RenderRequest()
{
template = new jsreport.Client.Entities.Template()
{
content = "<div>Some content for your report</div>",
recipe = "phantom-pdf",
name = "Your report name",
phantom = phantomOptions
}
};
var _report = service.RenderAsync(request).Result;
// Request file download.
return File(_report.Content, "application/pdf", "Some fancy name.pdf");
}
4 - Important: your server won't start (missing a zip file)
Due to changes from NuGet on AspNet projects, you have to manually move some content files which are not moved automatically.
First, find your dnx cache for the embedded server. Should be something like:
C:\Users\<name>\.dnx\packages\jsreport.Embedded\0.8.1.
You'll notice a folder called content there. Simply copy it's contents (two files: node.exe and jsreport-net-embedded.zip) into lib\net45.
So, to be plain simple and fool-proof: copy contents (files only) from
C:\Users\<name>\.dnx\packages\jsreport.Embedded\0.8.1\contents
into
C:\Users\<name>\.dnx\packages\jsreport.Embedded\0.8.1\lib\net45.
That should solve startup issues. Remember: first startup will extract files and should take a few minutes. After that, it will be much much faster.
I know that this question was asked a while ago, and I know that there have been several answers provided already that may well be right for certain projects. But I recently created a GitHub repository that allows for the creation of PDFs directly from your C# code without any requirement for nodejs, javascript, or razor. The feature set is a bit limited at the moment but it generates PDFs with images (.jpg only at this stage), shapes, and formatted text. The library works with .net core 2.0 and has no dependency on any other PDF generation tool.
Please note that this is my own repository: https://github.com/GZidar/CorePDF
I do plan to add functionality over time but at least for now this may provide the basis for others to include simple PDF capability in their own projects without the need for additional tooling.
I have amended the RazorAnt/RazorPDF which was working only for older MVC versions to work with ASP.NET Core. Its RazorPDFCore, available on nuget and github:
Example usage
class YourBaseController : RazorPDF.Controller {
// [...]
public IActionResult Pdf() {
var model = /* any model you wish */
return ViewPdf(model);
}
}
In your Startup.cs
add the following line before services.AddMVc();
services.AddSingleton<PdfResultExecutor>();
PLEASE NOTE:
You need to inhere RazorPDF.Controller from your base controller before using the ViewPdf() method
Necromancing.
Adding a dependency to NodeJS is subideal IMHO, especially considering .NET Core self-contained deployment.
As per 2017, you could use my port of PdfSharpCore to .NET Core 1.1
Resolves fonts, and it can use images. Comes with a nice sample application. You'll have to replace the DB part, however.
Credits go to:
https://github.com/groege/PdfSharpCore
which is a bit outdated, and doesn't contain a sample on how to use it with images.
Note that you need to register the font-resolver and the imageSource-Implementation before using the respective features:
PdfSharpCore.Fonts.GlobalFontSettings.FontResolver = new FontResolver();
MigraDocCore.DocumentObjectModel.MigraDoc.DocumentObjectModel
.Shapes.ImageSource.ImageSourceImpl =
new PdfSharpCore.ImageSharp.ImageSharpImageSource();
I have been working on a real time data project using the Microsoft stack and it seems that node.js is made for this very purpose (of real time data) and is getting a lot of publicity.
Does it makes sense to integrate node.js into my MSFT solution? (what criteria should I be considering)
How does it "hook into" the project?
What components does it replace?
Steve Marx demo'd this for http://chat.smarx.com/
You can see the basic code at http://things.smarx.com/#Run Node.js -
var proc = new Process()
{
StartInfo = new ProcessStartInfo(
RoleEnvironment.GetLocalResource("Executables").RootPath + #"\node.exe",
string.Format("server.js {0}",
RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["HttpIn"].IPEndpoint.Port))
{
UseShellExecute = false,
WorkingDirectory = RoleEnvironment.GetLocalResource("Executables").RootPath
}
};
but I can't currently find a full blog post from him about this
If you like node, look at Nancy for .NET
http://elegantcode.com/2010/11/28/introducing-nancy-a-lightweight-web-framework-inspired-by-sinatra/
As per this episode of Cloud Cover and the Node.js blog it would appear that Node.js is officially coming to Azure (and probably Windows in general).
I wrote a series of blog posts about running node.js on Windows Azure a few months ago (http://bit.ly/gxHawS). However I would offer a similar caveat that while it's theoretically possible, I'm not sure I would recommend it (at this point)...