MongoDb.GridFS.FindOneById returns null - c#

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)

Related

How to use stimulsoft in .NET6?

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

LinqToExcel file delete IOException after read

I have a class that reads excel worksheet names using LinqToExcel.
public class ExcelREader: IReader
{
public IEnumerable<string> GetWorksheetNames(_fileName)
{
using (var excelQueryFactory = new ExcelQueryFactory(_fileName))
{
return excelQueryFactory.GetWorksheetNames();
}
}
}
And I am using in my asp.net mvc project.
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
var path = Path.Combine(Server.MapPath("~/App_Data"), file.FileName);
file.SaveAs(path);
var reader = new ExcelREader();
var items = reader.GetWorksheetNames(path);
File.Delete(path);
return View();
}
But File.Delete(path) throws an exception. "The process cannot access the file 'XXX' because it is being used by another process."
I used using keyword. And used GC.Collect(); or GC.WaitForPendingFinalizers(); methods but not worked.
Set the UsePersistentConnection property to false:
var excel = new ExcelQueryFactory(fileName)
{
UsePersistentConnection = false
};

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");

send image with other attributes to post method in api

I use the code below to send an image to post method and save it as BLOB in DB and it's working successfully:
angular code:
public postUploadedFile(file:any){
this.formData = new FormData();
this.formData.append('file',file,file.name);
this.Url='http://localhost:38300/api/site/PostUploadFiles';
console.log("url passed from here",this.Url)
return this.http.post(this.Url , this.img).subscribe()
}
API code:
public IHttpActionResult PostUploadFiles()
{
int i = 0;
var uploadedFileNames = new List<string>();
string result = string.Empty;
HttpResponseMessage response = new HttpResponseMessage();
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
while(i < httpRequest.Files.Count && result != "Failed")
{
br = new BinaryReader(httpRequest.Files[i].InputStream);
ImageData = br.ReadBytes(httpRequest.Files[i].ContentLength);
br.Close();
if (DB_Operation_Obj.Upload_Image(ImageData) > 0)
{
result = "success";
}
else
{
result = "Failed";
}
i++;
}
}
else
{
result = "can't find images";
}
return Json(result);
}
but now I need to send more info with image ( type id, name) not just the image, so angular code will be like :
public postUploadedFile(file:any, type_id:number,site_id:number){
this.img = new Image_List();
this.img.images = new Array<PreviewURL>();
this.img.type_id= type_id;
this.img.Reference_id = site_id;
this.img.images.push(file);
this.formData = new FormData();
this.formData.append('file',file,file.name);
this.Url='http://localhost:38300/api/site/PostUploadFiles';
console.log("url passed from here",this.Url)
return this.http.post(this.Url , this.img).subscribe()
}
any help to send and insert in DB.
I think you could just make a single upload file method, and make another method for data insert with the file name,so it will be like:
public postUploadedFile(file:any){ this.formData = new FormData(); this.formData.append('file',file,file.name); this.Url='http://localhost:38300/api/site/PostUploadFiles';
This.newMethod(filename);//and here you upload the other data
console.log("url passed from here",this.Url) return this.http.post(this.Url , this.img).subscribe() }
Use FormData to append additional information to api call.
const formData = new FormData();
formData.append(file.name, file,'some-data');
You can use multiple values with the same name.

Web API Upload Files

I have some data to save into a database.
I have created a web api post method to save data. Following is my post method:
[Route("PostRequirementTypeProcessing")]
public IEnumerable<NPAAddRequirementTypeProcessing> PostRequirementTypeProcessing(mdlAddAddRequirementTypeProcessing requTypeProcess)
{
mdlAddAddRequirementTypeProcessing rTyeProcessing = new mdlAddAddRequirementTypeProcessing();
rTyeProcessing.szDescription = requTypeProcess.szDescription;
rTyeProcessing.iRequirementTypeId = requTypeProcess.iRequirementTypeId;
rTyeProcessing.szRequirementNumber = requTypeProcess.szRequirementNumber;
rTyeProcessing.szRequirementIssuer = requTypeProcess.szRequirementIssuer;
rTyeProcessing.szOrganization = requTypeProcess.szOrganization;
rTyeProcessing.dIssuedate = requTypeProcess.dIssuedate;
rTyeProcessing.dExpirydate = requTypeProcess.dExpirydate;
rTyeProcessing.szSignedBy = requTypeProcess.szSignedBy;
rTyeProcessing.szAttachedDocumentNo = requTypeProcess.szAttachedDocumentNo;
if (String.IsNullOrEmpty(rTyeProcessing.szAttachedDocumentNo))
{
}
else
{
UploadFile();
}
rTyeProcessing.szSubject = requTypeProcess.szSubject;
rTyeProcessing.iApplicationDetailsId = requTypeProcess.iApplicationDetailsId;
rTyeProcessing.iEmpId = requTypeProcess.iEmpId;
NPAEntities context = new NPAEntities();
Log.Debug("PostRequirementTypeProcessing Request traced");
var newRTP = context.NPAAddRequirementTypeProcessing(requTypeProcess.szDescription, requTypeProcess.iRequirementTypeId,
requTypeProcess.szRequirementNumber, requTypeProcess.szRequirementIssuer, requTypeProcess.szOrganization,
requTypeProcess.dIssuedate, requTypeProcess.dExpirydate, requTypeProcess.szSignedBy,
requTypeProcess.szAttachedDocumentNo, requTypeProcess.szSubject, requTypeProcess.iApplicationDetailsId,
requTypeProcess.iEmpId);
return newRTP.ToList();
}
There is a field called 'szAttachedDocumentNo' which is a document that's being saved in the database as well.
After saving all data, I want the physical file of the 'szAttachedDocumentNo' to be saved on the server. So i created a method called "UploadFile" as follows:
[HttpPost]
public void UploadFile()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded file from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
string folderPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
//string folderPath1 = Convert.ToString(ConfigurationManager.AppSettings["DocPath"]);
//Directory not exists then create new directory
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
// Get the complete file path
var fileSavePath = Path.Combine(folderPath, httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
}
Before running the project, i debbugged the post method, so when it comes to "UploadFile" line, it takes me to its method.
From the file line, it skipped the remaining lines and went to the last line; what means it didn't see any file.
I am able to save everything to the database, just that i didn't see the physical file in the specified location.
Any help would be much appreciated.
Regards,
Somad
Makes sure the request "content-type": "multipart/form-data" is set
[HttpPost()]
public async Task<IHttpActionResult> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.Contents != null && provider.Contents.Count == 0)
{
return BadRequest("No files provided.");
}
foreach (HttpContent file in provider.Contents)
{
string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
byte[] buffer = await file.ReadAsByteArrayAsync();
using (MemoryStream stream = new MemoryStream(buffer))
{
// save the file whereever you want
}
}
return Ok("files Uploded");
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}

Categories