SymmetricAlgorithm' does not contain a definition for 'Create' - asp.net-core

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.

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)

Render Razor View into String using .Net Core Console Application

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

What is the equivalent of the HttpResponseBase.BufferOutput property in ASP.NET Core 2?

I am in the process of converting a large .NET Framework project to a .NET Core project, and I have come across the following code:
public class ContentStreamingResult : ActionResult {
private Action<Stream> _onExecuteAction;
public ContentStreamingResult(Action<Stream> onExecuteAction) {
_onExecuteAction = onExecuteAction;
}
public override void ExecuteResult(ControllerContext context) {
var httpContext = context.HttpContext;
httpContext.Response.BufferOutput = false;
_onExecuteAction(httpContext.Response.OutputStream);
}
}
There is no BufferOutput property on the HttpResponse class in .NET Core.
What is the equivalent of the HttpResponseBase.BufferOutput property in ASP.NET Core 2?
For enabling Buffering in Asp.Net Core, you could use UseResponseBuffering middleware in Startup like below:
app.UseResponseBuffering();
After applying the Buffering Middleware, if you want to disable buffer for specific requests, you could try code below:
var bufferingFeature = httpContext.Features.Get<IHttpBufferingFeature>();
bufferingFeature?.DisableResponseBuffering();
You can use IHttpResponseBodyFeature for response buffer or IHttpRequestBodyFeature for request buffer.
httpContext.Features.Get<IHttpResponseBodyFeature>().DisableBuffering()

.Net Core Image Manipulation (Crop & Resize) / File Handling

I have spent the last 5 hours trying to find a feasible way to accomplish what seems to me quite an easy task if it was a previous version of the .NET family that I was working with:
Uploading a picture
Resizing & Cropping the picture
Saving the new picture into a directory
I have come accross to couple of libraries that are either in pre-release stage or in a not-complete stage.
Has anyone at all accomplished the above tasks without specifically including the System.Drawing namespace and/or adding a dependency for an earlier version of the .NET framework?
UPDATE on 08 / 08 / 2016
I ended up using System.Drawing something which is very annoying and disappointing. If you are developing a software used by thousands of developers, and if all these developers are relying on the components of this software, I believe, one cannot just come up with a new version, "sweet talk" about it during the conferences to show off your public speaking skills rather than giving a shit about your work and on one hand proudly hold in high esteem of it, and on the other, strip away the mostly used and demanded portions of it.
I do understand and appreciate with great excitement myself - of the new era of .net with the core framework - being a loyal asp dev since the first days of classic asp - however, to me, it is just an uncomplete product causing more frustrations and dissappointment than pleasure. When there are millions of websites in today's content-driven world, completely relying on content management, you can't just come up and say, "Hey, I have this brilliant, techonology, leaner, faster blah blah" but errr, you will have some problems with "managing" your content..
It should not be forgotten that, although, MS (and us) is very excited about this new core framework, with now being open source etc, there are other languages and frameworks out there that are doing what MS is promising to do, for a very very long time now.
ImageSharp
ImageSharp is a new, fully featured, fully managed, cross-platform, 2D graphics API.
Designed to democratize image processing, ImageSharp brings you an incredibly powerful yet beautifully simple API.
Compared to System.Drawing we have been able to develop something much more flexible, easier to code against, and much, much less prone to memory leaks. Gone are system-wide process-locks; ImageSharp images are thread-safe and fully supported in web environments.
Built against .Net Standard 1.1 ImageSharp can be used in device, cloud, and embedded/IoT scenarios.
You can use the Microsoft ASP.NET Core JavaScript Services to invoke arbitrary NPM packages at runtime from .NET code which means you can choose any npm package that provide image scaling and invoke it.
The following example shows how to use JavaScriptServices to resize image
https://github.com/aspnet/JavaScriptServices/tree/dev/samples/misc/NodeServicesExamples
Hope that Helps
.NET Core Image Processing blog post (January 19, 2017) compares 6 libraries:
CoreCompat.System.Drawing
ImageSharp
Magick.NET (Win only)
SkiaSharp
FreeImage-dotnet-core
MagicScaler
Feb 26 update: post was updated, two new packages added
To complete the #Hossam Barakat answer, you can use the Microsoft ASP.NET Core JavaScript Services to invoke arbitrary NPM packages at runtime from .NET code which means you can choose any npm package that provide image scaling and invoke it.
The sample use the sharp module, which has a lot of dependecies. If you prefere, like me, to use jimp which is pure javascript:
Startup.cs
public class Startup
{
...
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Enable Node Services
services.AddNodeServices();
...
}
...
}
ImageController.cs
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.AspNetCore.StaticFiles;
using System.Security.Cryptography;
using System.Text;
namespace NodeServicesExamples.Controllers
{
public class ResizeImageController : Controller
{
private const int MaxDimension = 1000;
private static string[] AllowedMimeTypes = new[] { "image/jpeg", "image/png", "image/gif" };
private IHostingEnvironment _environment;
private INodeServices _nodeServices;
public ResizeImageController(IHostingEnvironment environment, INodeServices nodeServices)
{
_environment = environment;
_nodeServices = nodeServices;
}
[Route("resize/{*imagePath}")]
[ResponseCache(Duration = 3600)]
public async Task<IActionResult> Index(string imagePath, double maxWidth, double maxHeight)
{
// Validate incoming params
if (maxWidth < 0 || maxHeight < 0 || maxWidth > MaxDimension || maxHeight > MaxDimension
|| (maxWidth + maxHeight) == 0)
{
return BadRequest("Invalid dimensions");
}
var mimeType = GetContentType(imagePath);
if (Array.IndexOf(AllowedMimeTypes, mimeType) < 0)
{
return BadRequest("Disallowed image format");
}
// Locate source image on disk
var fileInfo = _environment.WebRootFileProvider.GetFileInfo(imagePath);
if (!fileInfo.Exists)
{
return NotFound();
}
var eTag = GenerateETag(Encoding.UTF8.GetBytes($"{fileInfo.LastModified.ToString("s")}-{fileInfo.Length}"));
HttpContext.Response.Headers["ETag"] = eTag;
var match = HttpContext.Request.Headers["If-None-Match"].FirstOrDefault();
if (eTag == match)
{
return StatusCode(304);
}
// Invoke Node and pipe the result to the response
var imageStream = await _nodeServices.InvokeAsync<Stream>(
"./Node/resizeImage",
fileInfo.PhysicalPath,
mimeType,
maxWidth,
maxHeight);
return File(imageStream, mimeType, fileInfo.Name);
}
private string GetContentType(string path)
{
string result;
return new FileExtensionContentTypeProvider().TryGetContentType(path, out result) ? result : null;
}
private string GenerateETag(byte[] data)
{
string ret = string.Empty;
using (var md5 = MD5.Create())
{
var hash = md5.ComputeHash(data);
string hex = BitConverter.ToString(hash);
ret = hex.Replace("-", "");
}
return ret;
}
}
}
Node\resizeImage.js
var jimp = require("jimp");
module.exports = function (result, physicalPath, mimeType, maxWidth, maxHeight) {
// Invoke the 'jimp' NPM module, and have it pipe the resulting image data back to .NET
jimp.read(physicalPath).then(function (file) {
var width = maxWidth || jimp.AUTO;
var height = maxHeight || jimp.AUTO;
file.resize(maxWidth, height)
.getBuffer(mimeType, function (err, buffer) {
var stream = result.stream;
stream.write(buffer);
stream.end();
});
}).catch(function (err) {
console.error(err);
});
};
install jimp: npm install jimp --save
Short answer is no, not yet. Most if not all current libraries rely on System.Drawing. If you need this now, I would go that route and add System.Drawing.
The .NET team is currently working through the features that are missing on the Core 1.0 stack, but this one isn't high enough on their priority list: Link
This is a library to watch as they're getting very close to a releasable API without System.Drawing. : ImageSharp
use SkiSharp, it is on the official microsoft documentation also:
https://learn.microsoft.com/en-us/dotnet/api/skiasharp?view=skiasharp-1.68.0

How can I make RestSharp use BSON?

I'm using RestSharp, and using Json.NET for serialization (see here).
Json.NET supports BSON, and since some of my requests have huge blocks of binary data, I think this would speed up my application dramatically. However, as far as I can tell, RestSharp does not seem to have any in-built support for BSON.
The use of Json.NET is implemented as a custom serializer for RestSharp, and so at first glance it looks like it would be possible to modify that custom serializer to use BSON. But, the Serialize method of the RestSharp.Serializers.ISerializer interface returns a string - which is (I assume) unsuitable for BSON. So, I assume that it would take some more significant changes to RestSharp to implement this change.
Has anyone figured out a way to do this?
Update: I looked at the RestSharp source, and discovered that the RestRequest.AddBody method that takes my object and serializes it into the request body eventually calls Request.AddParameter (with the serialized object data, and the parameter type RequestBody).
I figured that I might be able to serialize my object to BSON and then call Request.AddParameter directly - and indeed I can. However, when RestSharp then executes the RestRequest, it fails to put the binary content into the request, because there are other embedded assumptions about the request content being UTF-8 encoded.
Thus it looks like this hack would not work - there would need to be some changes made to RestSharp itself, and I'm not the man for the job...
Update 2: I decided to have a go at using the debugger to figure out how much of RestSharp I'd have to change to overcome the body-encoding issue, so I swapped out my NuGet version of RestSharp and included the RestSharp project in my solution. And... it worked.
It turns out that there has been a change to RestSharp in the last few months that isn't yet in the NuGet version.
So, you can now use AddParameter and pass in an already-BSON-encoded object, and RestSharp will send it off to the server without complaint.
Per the updates in my question, it turns out that if you have the latest RestSharp source, then instead of this:
request.AddBody(myObject);
... you can do this instead whenever you have a payload that would benefit from using BSON:
using (var memoryStream = new System.IO.MemoryStream())
{
using (var bsonWriter = new Newtonsoft.Json.Bson.BsonWriter(memoryStream))
{
var serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Serialize(bsonWriter, myObject);
var bytes = memoryStream.ToArray();
request.AddParameter("application/bson", bytes, RestSharp.ParameterType.RequestBody);
}
}
Note that the first parameter to AddParameter is supposedly the parameter name, but in the case of ParameterType.RequestBody it's actually used as the content type. (Yuk).
Note that this relies on a change made to RestSharp on April 11 2013 by ewanmellor/ayoung, and this change is not in the current version on NuGet (104.1). Hence this will only work if you include the current RestSharp source in your project.
Gary's answer to his own question was incredibly useful for serializing restful calls. I wanted to answer how to deserialize restful calls using JSON.NET. I am using RestSharp version 104.4 for Silverlight. My server is using Web API 2.1 with BSON support turned on.
To accept a BSON response, create a BSON Deserializer for RestSharp like so
public class BsonDeserializer : IDeserializer
{
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public T Deserialize<T>(IRestResponse response)
{
using (var memoryStream = new MemoryStream(response.RawBytes))
{
using (var bsonReader = new BsonReader(memoryStream))
{
var serializer = new JsonSerializer();
return serializer.Deserialize<T>(bsonReader);
}
}
}
}
Then, ensure your request accepts "application/bson"
var request = new RestRequest(apiUrl, verb);
request.AddHeader("Accept", "application/bson");
And add a handler for that media type
var client = new RestClient(url);
client.AddHandler("application/bson", new BsonDeserializer());