How to use stimulsoft in .NET6? - c#

I want to use stimulsoft in a project written in ASP.NET MVC .Net6.
StimulSoft version is 2022.1.1 and I installed NuGet
Stimulsoft.Reports.Web.NetCore
in my project.
Controller:
...
public IActionResult PrintPage()
{
return View();
}
public IActionResult GetReport()
{
StiReport report = new StiReport();
report.Load(StiNetCoreHelper.MapPath(this, "wwwroot/Reports/sample1.mrt"));
var list = _unitOfWork.RefereeTypeRepos.GetAll(); //Get information for print.
report.RegData("DT", list);
return StiNetCoreViewer.GetReportResult(this, report);
}
public IActionResult ViewerEvent()
{
return StiNetCoreViewer.ViewerEventResult(this);
}
PrintPage.cshtml:
#using Stimulsoft.Report.Mvc
#using Stimulsoft.Report.Web
#Html.StiNetCoreViewer(new StiNetCoreViewerOptions()
{
Actions =
{
GetReport = "GetReport",
ViewerEvent = "ViewerEvent"
}
})
When the page loads, I get this Error:
I don't know what I should do, and which version or NuGet is proper for .Net6?
I appreciate somebody answers.

It works for me:
public IActionResult GetReport()
{
var person = new { Name = "samplename", Family = "samplefamily" };
StiReport report = new StiReport();
var path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
report.Load(path + "\\Reports\\Ticket.mrt");
var service = new Stimulsoft.Report.Export.StiPdfExportService();
report.RegData("PersonDetail", person);
report.Render(false);
StiPdfExportSettings st = new StiPdfExportSettings();
st.ImageQuality = 1f;
st.EmbeddedFonts = true;
st.ImageResolution = 300;
st.ImageFormat = StiImageFormat.Color;
st.AllowEditable = StiPdfAllowEditable.No;
var stream = new MemoryStream();
// Export PDF using MemoryStream.
service.ExportTo(report, stream, st);
Response.Headers.Add("Content-Disposition", "attachment;filename=card.pdf");
return File(stream.ToArray(), "application/pdf");
}
It creates a pdf file and I use Nuget: stimulsoft.reports.engine.netcore
and there is no need for ViewerEvent() and PrintPage.cshtml

Related

InvalidOperationException in Memory Streams

I am trying to upload an image to cloudinary cloud. The file converts fine to memory stream but when I try to call upload method of cloudinary to upload the image, I get InvlalidOperationException. What I think is, there is something wrong with converting file to stream.See the image showing error
[HttpPost]
public async Task<IActionResult> AddPhotoForUser(int userId, [FromForm] AddPhotoDto addPhotoDto)
{
try
{
if (userId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
{
return Unauthorized();
}
var userFromRepo = await _datingRepository.GetUser(userId);
var file = addPhotoDto.File;
var uploadResult = new ImageUploadResult();
if (file.Length > 0)
{
using (var stream = file.OpenReadStream())
{
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file.Name, stream),
Transformation = new Transformation()
.Width(500).Height(500).Crop("fill").Gravity("face")
};
uploadResult = _cloudinary.Upload(uploadParams);
}
}
addPhotoDto.Url = uploadResult.Url.ToString();
addPhotoDto.PublicId = uploadResult.PublicId;
var photo = _mapper.Map<Photo>(addPhotoDto);
if (!userFromRepo.Photos.Any(p => p.IsMain))
{
photo.IsMain = true;
}
userFromRepo.Photos.Add(photo);
if (await _datingRepository.SaveAll())
{
var photoToReturn = _mapper.Map<ReturnPhotoDto>(photo);
return CreatedAtRoute("GetPhoto", new { id = photo.Id }, photoToReturn);
}
return BadRequest("Could not add photo");
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
Can you please share why do you use open stream? You can try:
var imageuploadParams = new ImageUploadParams () {
File = new FileDescription (#"https://res.cloudinary.com/demo/image/upload/v1561532539/sample.jpg"),
PublicId = "myimage",
Transformation = new Transformation().Width(500).Height(500).Crop("fill").Gravity("face")
};
var ImageuploadResult = cloudinary.Upload (imageuploadParams);

How to Upload a file in Dotnet core 3.1 Web app

Actually I'm try to upload a file from user. But I'm getting error. I tried various way even the Microsoft doc also. I can't help myself. So please help me
Link: Microsoft Doc dotnet core 3.1
My action :
[HttpPost]
public async Task<IActionResult> Updateperson(UpdatePersonViewModel updatePerson)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if(updatePerson.Photo != null)
{
string[] words = updatePerson.Photo.FileName.Split('.');
int a = words.Rank;
uniqueFileName = words[a];
uniqueFileName = Guid.NewGuid().ToString() + "_." + uniqueFileName;
string filePath = Path.Combine("Images",uniqueFileName);
//string filePath = Path.Combine(config["Images"], uniqueFileName);
// using (var stream = System.IO.File.Create(filePath))
// {
// await formFile.CopyToAsync(stream);
// }
await updatePerson.Photo.CopyToAsync(new FileStream(filePath,FileMode.Create));
}
_context.Persons.Update(updatePerson);
_context.SaveChanges();
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
else
{
return RedirectToAction("Profile", new RouteValueDictionary(new { action = "Profile", id = updatePerson.Id }));
}
}
>>> config is a object of IConfiguration
Here is Error:
It means no such directory named Image exists!
You can simply check if it exists, or create one if it doesn't exist.
if(!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
To test:
Use a directoryPath variable like this:
var directoryPath=Path.Combine(Directory.GetCurrentDirectory(), "Images");

ASP.NET Rotativa Generate PDF from view from another controller

I have two controllers, 1 is an api controller, the other is a view controller, what I am trying to do is generate the PDF from the api controller from a view in the view controller...is this possible and how would I do it?
API Controller - This is where I want to generate the PDF
public byte[] getReportsPDF(string community, string procedure)
{
byte[] pdfBytes = new byte[] { };
System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext();
if(procedure == "GetProductionTasks")
{
var actionPDF = new Rotativa.ActionAsPdf("RedBluePDF", new { community = community, procedure = procedure })
{
PageSize = Size.A4,
PageOrientation = Rotativa.Options.Orientation.Landscape,
PageMargins = { Left = 1, Right = 1 }
};
pdfBytes = actionPDF.BuildFile(context);
}
return pdfBytes;
}
View Controller - This is the view I want to generate.
public ActionResult RedBluePDF(string community, string procedure)
{
return View();
}
After trying for a very long time, finally I managed to solve by this:
var controller = DependencyResolver.Current.GetService<ViewController>();
RouteData route = new RouteData();
route.Values.Add("action", "RedBluePDF");
route.Values.Add("controller", "ApiController");
ControllerContext newContext = new ControllerContext(new HttpContextWrapper(System.Web.HttpContext.Current), route, controller);
controller.ControllerContext = newContext;
controller.RedBluePDF(community, procedure);
I have been trying:
var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);
But this will give me the wrong pdf, because it will use your current controller (API Controller in this case) to make the call for ActionAsPdf()
Credit to this answer

MongoDb.GridFS.FindOneById returns null

I'm uploading image to server with following code:
public ActionResult AttachImage(HttpPostedFileBase file)
{
var options = new MongoGridFSCreateOptions
{
Id = ObjectId.GenerateNewId().ToString(),
ContentType = file.ContentType
};
Context.Database.GridFS.Upload(file.InputStream, file.FileName, options);
return RedirectToAction("Index");
}
and trying to get file like:
public ActionResult GetImage(string id)
{
var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
if(image == null)
{
return HttpNotFound();
}
return File(image.OpenRead(), image.ContentType);
}
After upload I can see file in database, but when I'm trying to load it as
Context.Database.GridFS.FindOneById(new ObjectId(id));
I'm always geting null. Could you please suggest what I'm doing wrong?
public class DbContext
{
public MongoDatabase Database;
public DbContext()
{
var client = new MongoClient(Properties.Settings.Default.ConnectionString);
var server = client.GetServer();
Database = server.GetDatabase(Properties.Settings.Default.DatabaseName);
}
}
mongocsharpdriver 2.5.0
mongo server 3.6
It turned out I incorrectly searched for file by Id.
Instead of
var image = Context.Database.GridFS.FindOneById(new ObjectId(id));
I should use
var image = Context.Database.GridFS.FindOneById(id);
I used code from examples for previous version of driver but in 2.5 we don't need to use
new ObjectId(id)

IActionResult return both file and view from Controller

Is it possible to return both file for download and update a view from IActionResult?
If not, is there a workaround? (JavaScript or AJAX)
I am hoping to refresh a view after the file download.
Code:
[HttpPost]
public IActionResult ProcessFile(ViewModel model, List<IFormFile> files)
{
var uploadedfileName = UploadFile(files);
try
{
if (uploadedfileName != null)
{
// Generate a report for download
var fileInfo = GenerateReports(model.Host, uploadedfileName);
// Prompt Download File
var webClient = new System.Net.WebClient();
var downloadData = webClient.DownloadData(fileInfo.ToString());
var content = new System.IO.MemoryStream(downloadData);
var contentType = "APPLICATION/octet-stream";
var fileName = Path.GetFileName(fileInfo.ToString());
return File(content, contentType, fileName);
}
else
{
ViewBag.Message = "Please select the file";
}
}
catch (Exception e)
{
// Log Error
}
finally
{
// Delete the file after the report is generated
System.IO.File.Delete(uploadedfileName);
}
return View("Index");
}

Categories