Folder not getting created in Local Disk C using Custom Action of a Wix Installer.
namespace MyCustomAction
{
public class CustomActions
{
[CustomAction]
public static ActionResult MySimpleAction(Session session)
{
string country = session["COUNTRIES"];
string root = #"C:\Temp";
try
{
if (!Directory.Exists(root))
{
System.IO.Directory.CreateDirectory(root);
File.AppendAllText(#"C:\Temp\country.txt", country);
}
}
catch (Exception)
{
return ActionResult.Failure;
}
return ActionResult.Success;
}
}
}
Related
I am trying to upload a file using webapi (.NET6 ). There is no errors in the code . But warnings are there.I have getting below messge in terminal when I run the .csproj file.
warning CS8618: Non-nullable property 'files' must contain a non-null value
when exiting constructor. Consider declaring the property as nullable.
While I runs, Getting this message and running stops. Warning shows in fileModel.cs at files
I have tried putting IFormFile?. still showing warnings and not runs.
I'm Using VS Code. wwwroot folder is created.
My file model:
fileModel.cs
{
public class fileModel
{
public IFormFile files {get; set;}
}
}
Controller file
FilesController.cs
public class FilesController : ControllerBase
{
[HttpPost]
public string UploadFile(fileModel objFile)
{
try
{
if (objFile.files.Length > 0)
{
UploadFile(objFile);
return "Upload" + objFile.files.FileName;
}
else
{
return "Failed";
}
}
catch (System.Exception ex)
{
return ex.Message.ToString();
}
}
}
Interface & Implementation:
IFileUpload.cs:
public interface IFileUpload
{
public void UploadFile(fileModel formFile);
}
FileUpload.cs
public class FileUpload : IFileUpload
{
private IWebHostEnvironment environment;
public FileUpload(IWebHostEnvironment _enviornment)
{
environment = _enviornment;
}
//
public void UploadFile(fileModel formFile){
if (!Directory.Exists(environment.WebRootPath + "\\Uploads"))
{
Directory.CreateDirectory(environment.WebRootPath + "\\Uploads");
}
using(FileStream fileStream = System.IO.File.Create(environment.WebRootPath + "\\Uploads"+formFile.files.FileName)){
formFile.files.CopyTo(fileStream);
fileStream.Flush();
}
}
}
While I runs, Getting this message and running stops. Warning shows in
fileModel.cs at files.
Well, its pretty obvious that it will stop suddenly because you haven't initialize your IFileUpload interface into your controller class therefore, it will certainly break the execution. You ought to write that in following manners:
Controller With Constructor:
public class FilesController : Controller
{
private readonly IFileUpload _fileUplaod;
public FilesController(IFileUpload fileUplaod)
{
_fileUplaod = fileUplaod;
}
[HttpPost]
public IActionResult UploadFile(fileModel objFile)
{
try
{
if (objFile.files.Length > 0)
{
_fileUplaod.UploadFile(objFile);
return Ok("Upload" + objFile.files.FileName);
}
else
{
return Ok("Failed");
}
}
catch (System.Exception ex)
{
return Ok(ex.Message.ToString());
}
}
}
Program.cs
You must register above interface on your program.cs file as following
builder.Services.AddScoped<IFileUpload, FileUpload>();
Output
Execution Debugging Result:
This is my code:
[HttpPost]
[Route("api/bulkUpload")]
[IgnoreAntiforgeryToken]
public JsonResult bulkUpload(IFormFile file)
{
List<Input> inputs = new List<Input>();
try
{
var extension = Path.GetExtension(file.FileName);
if (extension == ".csv")
{
.
.
.
}
}
catch(exception ex)
{
return json(new { errormessage ="invalid file extension"});
}
return jsonresult(inputs)
}
In swagger api if I give a different file(diff extensions) like .txt or .xls it is giving error code:500.
But I want to return a error message as invalid file extension. PLease help on this code.
This may depend a bit on what version of ASP.NET you are using, but you should be able to do something like:
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[Microsoft.AspNetCore.Mvc.HttpPost]
[Microsoft.AspNetCore.Mvc.Route("api/bulkUpload")]
[IgnoreAntiforgeryToken]
public IActionResult bulkUpload(IFormFile file)
{
List<Input> inputs = new List<Input>();
try
{
var extension = Path.GetExtension(file.FileName);
if (extension == ".csv")
{
// do the thing!
}
}
catch (Exception ex)
{
return BadRequest("invalid file extension");
// or try this:
// return BadRequest(new JsonResult("invalid file extension"));
}
return new JsonResult("ok");
}
}
public class Input
{
}
Here is the docs on it and some examples.
I currently have the below code which I thought would work however I am receiving a "HttpControllerContext.Configuration must not be null" error when I create the Ok result. The goal is to be able to call any function in a controller in one line to keep my controllers clean. Such as "return ApiUtilities.TryCatch(() => _someService.Get(id));"
I only have access to 'Ok()', "NotFound()" and "InternalServerError()" because the ApiUtilities Class inherits from ApiController
public IHttpActionResult TryCatch<T>(Func<T> operation)
{
try
{
if (ModelState.IsValid)
{
var result = operation();
return Ok(result);
}
}
else
{
return BadRequest();
}
}
catch (Exception error)
{
return InternalServerError();
}
Edit:
My controller looks like this
public class PageController : ApiController
{
private ISomeService _someService;
private ApiUtilities _apiUtilities;
public PageController(ISomeService someService)
{
_someService= someService;
_apiUtilities = new ApiUtilities();
}
[Route("api/page")]
public IHttpActionResult Get([FromBody]string url)
{
return _apiUtilities.TryCatch(() => _someService.Get(url));
}
}
Below is the update I've made based on a Friend's suggestion. I've removed the inheritance on the ApiController. I've also returned the same models the Ok, BadRequest and NotFound functions generate using the context of the current api.
public static class ApiUtilities
{
public static IHttpActionResult TryCatch(Action action, ApiController apiController)
{
try
{
if (apiController.ModelState.IsValid)
{
action();
return new OkResult(apiController);
}
else
{
return new BadRequestResult(apiController);
}
}
catch (Exception error)
{
return new NotFoundResult(apiController);
}
}
public static IHttpActionResult TryCatch<T>(Func<T> operation, ApiController apiController)
{
try
{
if (apiController.ModelState.IsValid)
{
var result = operation();
return new OkNegotiatedContentResult<T>(result, apiController);
}
else
{
return new BadRequestResult(apiController);
}
}
catch (Exception error)
{
return new NotFoundResult(apiController);
}
}
}
I have a web API 2 project that implements Ninject. It works fine if my controllers do not use Route attributes but, if I use them, the application returns the following exception: "An error occurred when trying to create a controller of type 'AccountsController'. Make sure that the controller has a parameterless public constructor."
Works fine
public IHttpActionResult get()
{
var entities = EntityService.getAll();
return Ok(entities);
}
Do not work
[Route("user")]
public IHttpActionResult get()
{
var entities = EntityService.getAll();
return Ok(entities);
}
I have the following packages installed
Ninject version="3.2.0.0"
Ninject.Extensions.ContextPreservation version="3.2.0.0"
Ninject.Extensions.NamedScope version="3.2.0.0"
Ninject.Web.Common version="3.2.0.0"
Ninject.Web.Common.OwinHost version="3.2.3.0"
Ninject.Web.Common.WebHost version="3.2.3.0"
Ninject.Web.WebApi version="3.2.4.0"
Ninject.Web.WebApi.OwinHost version="3.2.4.0"
Ninject.Web.WebApi.WebHost
My NintextWebCommon class is
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(ProperdiAPI.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(ProperdiAPI.App_Start.NinjectWebCommon), "Stop")]
namespace ProperdiAPI.App_Start
{
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using System;
using System.Web;
using System.Web.Http;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IEntityService>().To<EntityService>().InRequestScope();
}
}
}
BaseApiController
public class BaseApiController : ApiController
{
private IEntityService entitysService;
public BaseApiController(IEntityService entityService)
{
this.entityService = entityService;
}
protected IEntityService EntitysService
{
get
{
return this.entityService;
}
}
protected IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (!result.Succeeded)
{
if (result.Errors != null)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
return BadRequest();
}
return BadRequest(ModelState);
}
return null;
}
}
}
Controller
[RoutePrefix("api/accounts")]
public class AccountsController : BaseApiController
{
public AccountsController(IEntityService entityService)
:base(entityService)
{
}
[HttpGet]
//[Route("user")]
public IHttpActionResult get()
{
var entities = EntityService .getAll();
return Ok(entities);
}
}
I've tried a lot of things, like building a custom resolver and scope, installing an old ninject version and so on, but nothing works.
Thanks a lot in advance!
Install plugin Ninject.WebApi.DependencyResolver and add this code after call to RegisterServices(kernel);:
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);
I have a customer's DNN site with a custom module that's having issues with module error logging. The site was upgraded to version 7.4 from 6.2 and now to version 9.0. Module exceptions no longer appear in Admin / Host Events since the upgrade to 7.4. It appears module exception logging was changed in DNN 7.4 as explained here. This is the code that worked before but now nothing gets logged;
Test object:
public class foo
{
public int id { get; set; }
public string bar { get; set; }
}
Test webapi Controller:
[DnnAuthorize]
public class MyCustomModuleController : DnnApiController
{
private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(MyCustomModuleController));
[HttpGet]
public HttpResponseMessage GetFoo(int id)
{
try
{
foo test = null;
var bar = test.bar; //will throw null exception
...
}
catch (Exception ex)
{
Logger.Error(ex); //no log entries in db since ver. 7.4
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Server error");
}
}
Is there a setting that I should enable or is there a new way of logging events?
It is my understanding that DotNetNuke.Instrumentation.GetLogger() returns the logging object for doing the Log4Net logging to file appender logs stored in: /Portals/_default/Logs. You can also view them from Host > Host Settings > Logs.
Normally, you would add to your class by setting it up in a constructor and calling the .Error()/.ErrorFormat(), .Warn()/.WarnFormat(), etc functions to append an error or information message to the logging file.
public class MyCustomModuleController : DnnApiController
{
private DotNetNuke.Instrumentation.ILog Logger { get; set; }
public MyCustomModuleController()
{
Logger = DotNetNuke.Instrumentation.LoggerSource.Instance.GetLogger(this.GetType());
}
public HttpResponseMessage GetFoo(int id)
{
try
{
...
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
The other logging technique available is using the DotNetNuke.Services.Exceptions to log the exception to the database. These errors get added to the EventLog and Exceptions tables.
public class MyCustomModuleController : DnnApiController
{
public HttpResponseMessage GetFoo(int id)
{
try
{
...
}
catch (Exception ex)
{
DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
}
}
}
It is possible that DNN disconnected the Log4Net process with the EventLog. I can't remember how it worked back in version 6.