Render Razor View into String using .Net Core Console Application - asp.net-core

I have prepared a .net core console application (Framework version .Net Core 2.2) for sending email as a service. Right now its working completely fine with static html content being hardcoded into service method for generating email body string.
I am in seek of the code which provides me a solution to render a razor view to have a html string with the model data.
Tried to implement the RazorEngine dll in entity framework ver. 4.5. with below code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GenerateEmailUsingRazor.Model;
using RazorEngine.Templating;
namespace GenerateEmailUsingRazor
{
class Program
{
static readonly string TemplateFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "EmailTemplates");
static void Main(string[] args)
{
var model = GetUserDetail();
var emailTemplatePath = Path.Combine(TemplateFolderPath, "InviteEmailTemplate.cshtml");
var templateService = new TemplateService();
var emailHtmlBody = templateService.Parse(File.ReadAllText(emailTemplatePath), model, null, null);
Console.WriteLine(emailHtmlBody);
Console.ReadLine();
}
private static UserDetail GetUserDetail()
{
var model = new UserDetail()
{
Id = 1,
Name = "Test User",
Address = "Dummy Address"
};
for (int i = 1; i <= 10; i++)
{
model.PurchasedItems.Add("Item No " + i);
}
return model;
}
}
}
Expected Result:
Console Application should render the razor view and provide me the resultant html string.

I've written a clean library Razor.Templating.Core that works with .NET Core 3.0, 3.1 on both web and console app.
It's available as NuGet package.
After installing, you can call like
var htmlString = await RazorTemplateEngine
.RenderAsync("/Views/ExampleView.cshtml", model, viewData);
Note: Above snippet won't work straight away. Please refer the below working guidance on how to apply it.
Complete Working Guidance: https://medium.com/#soundaranbu/render-razor-view-cshtml-to-string-in-net-core-7d125f32c79
Sample Projects: https://github.com/soundaranbu/RazorTemplating/tree/master/examples

Related

Create link to server controller's action in BlazorWeb assembly

I'm writing an app using WebAssembly Blazor hosted by ASP.NET Core. Some of pages are implemented in Blazor, but some old pages are still ASP.NET Core Razor views. I need to create a link in Blazor component pointing to action of controller on server.
I can write:
NavigationManager.NavigateTo("SomeContoller/SomeAction/123", true)
But I don't want to hardcode url to action, because changing server routing or contoller/action names will break such links. Is there any way to create proper links via some helper, similar to ASP.Net Core UriHelper? Like:
UriHelper.Action("SomeAction", "SomeController", new {id = 123});
In Blazor server apps you can use LinkGenerator. The usage is not much different that of UriHelper:
#using Microsoft.AspNetCore.Routing
#inject LinkGenerator LinkGenerator
Sign in
ReSharper understands this one too, so you will get auto-completion for controller and action names.
In WebAssembly apps LinkGenerator is not available, so your best bet is to dump all routes from the server and implement your own link generator which uses that data on the client (its complexity depends on complexity of your routes, the one from ASP.NET Core is quite complex).
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
namespace BlazorTest.Server.Controllers
{
[Route("api/routes")]
[ApiController]
public class RouteInformationController : ControllerBase
{
private readonly EndpointDataSource _endpointDataSource;
public RouteInformationController(EndpointDataSource endpointDataSource)
{
_endpointDataSource = endpointDataSource;
}
public IEnumerable<object> Get()
{
foreach (var endpoint in _endpointDataSource.Endpoints.OfType<RouteEndpoint>())
{
var actionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
if (actionDescriptor == null)
continue;
yield return new
{
actionDescriptor.ControllerName,
actionDescriptor.ActionName,
Parameters = actionDescriptor.Parameters.Select(p => p.Name),
RoutePattern = endpoint.RoutePattern.RawText,
};
}
}
}
}
You can create a static class with constant properties in it for all the URLs that you use in the app. After that use the same static class property in both the page route and your navigation route. Below is a very basic version of this:
public static class RouteUrls
{
public static string Home = "/Home";
public static string ProductList = "/Product";
public static string ProductDetail = "/Product/Detail";
public static string SomePage = "/SomeContoller/SomeAction";
}
// to access it use like this:
NavigationManager.NavigateTo($"{RouteUrls.SomePage}/123", true)

SendGrid 'DeliverAsync()' Not Working

I'm trying to send an email with Azure and SendGrid. I have it all set up (I think) and my code is as per below, but the 'DeliverAsync()' method is not working and there is no 'Deliver()' option available.
Here are my using statements:
using System;
using System.Web;
using System.Web.UI;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using SendGrid;
Here is my code: 'transportWeb.DeliverAsync(myMessage)' is showing as plain black text.
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
myMessage.AddTo("d#gmail.com");
myMessage.From = new MailAddress("d#gmail.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// create a Web transport, using API Key
var transportWeb = new Web(apiKey);
// Send the email, which returns an awaitable task.
transportWeb.DeliverAsync(myMessage);
I'm hoping someone has seen this before and knows the solution. There are a lot of similar problems online, but none I've found with a fix to this. I am using SendGrid v6.3.4. I have tried reverting to v6.3.3 but it didnt help. My stats in SendGrid show zero for everything, no emails sent, no requests, no bounces etc.
UPDATE:
I have tried creating a new Email class to remove any clutter and make this clearer, the 'DeliverAsync' method is still not being recognized after transportWeb.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Net.Mail;
using SendGrid;
using System.Threading.Tasks;
namespace CPWebsite
{
public class Email
{
static async void Main()
{
try
{
// Create the email object first, then add the properties.
var myMessage = new SendGridMessage();
myMessage.AddTo("d#gmail.com");
myMessage.From = new MailAddress("d#gmail.com", "John Smith");
myMessage.Subject = "Testing the SendGrid Library";
myMessage.Text = "Hello World!";
var apiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
// create a Web transport, using API Key
var transportWeb = new Web(apiKey);
// Send the email, which returns an awaitable task.
await transportWeb.DeliverAsync(myMessage);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
I have also tried changing var myMessage = new SendGridMessage(); to SendGridMessage myMessage = new SendGridMessage(); but no luck. Only the following using statements are showing as necessary.
using System;
using System.Net.Mail;
using SendGrid;
Im trying anything at this point!
Is this a console app currently? You'll need to await the method otherwise the console apps main thread will complete execution and cause the worker threads to be killed before they successfully deliver the message.
Try:
await transportWeb.DeliverAsync(myMessage);
Also add the following to your using statements:
using System.Threading.Tasks;
My project (Windows Service) was essentially synchronous with respect to specific thread where SendGrid was called, and hence what I had to do to make it work is to add .Wait() after the .DeliverAsync().
And so, try:
static void Main()
and later:
transportWeb.DeliverAsync(myMessage).Wait();
There is actually a little foot-note in SendGrid documentation eluding to this technique.
Cheers.
I don't know if this has been resolved but try using myMessage.Html for the body instead of myMessage.Text. Especially if you are using html in the body. I have pretty much the same setup and my code works fine.

SymmetricAlgorithm' does not contain a definition for 'Create'

I'm trying to work on ASP.NET 5 application. Here is a class and it looks good (no red curly underlines). But when I try to build, it gives error - SymmetricAlgorithm' does not contain a definition for 'Create'
using System;
using System.IO;
using System.Security.Cryptography;
namespace SalesBook
{
public static class Encryptor
{
private static byte[] EncryptString(string data)
{
byte[] byteData = Common.GetByte(data);
SymmetricAlgorithm algo = SymmetricAlgorithm.Create();
}
}
}
I'm using .net 4.6.1.
Any help?
This method has not been ported to .NET Core. The recommended alternative is to use the specific Create method associated with the algorithm you need:
var algorithm = Aes.Create();
On CoreCLR, it will automatically determine and return the best implementation, depending on your OS environement.
If you don't need .NET Core support, you can remove the dnxcore50/dotnet5.4 from your project.json.

C# Executable project (console app) for a test project

I have a test project which is a library. I want to write a console application to be able to reference the DLL of the test project and call the methods and classes from my test project.
Also while writing the console app, I want to how to execute the exe from command prompt with parameters. My console app code should take in the input I give and execute the tests.
I just need some example code, so that I can pick it up from there.
You have to follow these steps:
Add your DLL file as reference to your console project.
Project>>Add Reference>>Browse and select your dll file.
add usign myNamespaceOfMyDll;
Then in your code you can use the methods from your dll file.
Sample (Using the GMmap's dll):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GMap.NET;
usign myNamespace;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
//GPoint is a user data type declared in GMap.NET
//method is a method definied in myNamespace (your dll)
GPoint s=method(param1,param2);
}
}
}
Suppose that you have the next code, you have to add an array of strings as param in your main method.
using System;
class Program
{
static void Main(string[] args)
{
if (args == null)
{
Console.WriteLine("args is null"); // Check for null array
}
else
{
//Here you can to use then content of your args array.
}
Console.ReadLine();
}
}
Thus if you type:
c:\> myApp param1 param2
args[0]="param1", args[1]="param2", and the length of the array is 2.

code C# use the Google OAuth to sign Google Acount

My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Google.Apis.Blogger.v3;
using Google.Apis.Blogger.v3.Data;
using Google.Apis.Services;
using System.Diagnostics;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Util;
namespace BloggerTest
{
class Program
{
static void Main(string[] args)
{
string apiKey= "{API-KEY}";
string blogUrl= "{BLOG-URL}";
string clientID = "{CLIENT_ID}";
string clientSec = "{CLIENT_SECRET}";
NativeApplicationClient provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = clientID,
ClientSecret = clientSec
};
OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, getAuth);
BloggerService blogService = new BloggerService(new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "BloggerTest"
});
BlogsResource.GetByUrlRequest getReq = blogService.Blogs.GetByUrl(blogUrl);
getReq.Key = apiKey;
Blog blog = getReq.Execute();
Console.WriteLine(blog.Id);
Console.ReadKey();
}
private static IAuthorizationState getAuth(NativeApplicationClient arg)
{
IAuthorizationState state = new AuthorizationState(new[] { BloggerService.Scopes.Blogger.GetStringValue() })
{
Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl)
};
Uri authUri = arg.RequestUserAuthorization(state);
Process.Start(authUri.ToString());
Console.WriteLine("Please enter auth code:");
string authCode = Console.ReadLine();
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
And it have 2 error:
'Google.Apis.Services.BaseClientService.Initializer' does not contain a definition for 'Authenticator'
'Google.Apis.Blogger.v3.BloggerService' does not contain a definition for 'Scopes'
Can you help me fix. Thank you very much!
I get code from: http://garyngzhongbo.blogspot.com/2013/10/bloggerc-blogger-api-v3-6oauth-20.html
There are two common problems faced by beginners when the implement Google APIs. These are both due to the API libraries being unstable, and changing from one release to the next.
When the API changes, the sample apps don't. So developers try to use out of date code with the latest API.
Links to old versions of the API libraries are not purged. So developers can find themselves downloading old libraries.
So 1 and 2 are kinda the opposite, but both occur. Problem 1 is the more common.
So in this case, check that you have downloaded the very latest versions of the API library, and check if the missing definitions have in fact been withdrawn, in which case you'll need to find a more up to date example.