Quantcast
Channel: ASP.NET Core
Viewing all 9386 articles
Browse latest View live

How can I create a new controller dynamically after building the project?

$
0
0

I have made an API controller by asp.net core to communicate with a third-party APP.

When the user authorizes my API in the third-party APP, my API needs to provide a brand new controller and URL to the APP which only works for this user. And then, the server of the APP will transfer data from the user to my API via the URL.

Each controller only differs from some string such as user name and token so that I made a base controller and about to inherit from it.

Whereas, I don't know how to create a controller dynamically after building the project.

In addition, I need the controller which creates dynamically still exists even the server of my API restart.

How can I achieve it? Thank you.


Solution Architecture and Referencing

$
0
0

Evening All,

For the longest I've worked in VB with Visual Studio, recently I migrated to C# which was interesting.  But now I want to learn more about ASP.Net Core.

My question is as follows, normally i would create separate projects for web, infrastructure, implementation, entry etc. And then add project references and imports.

With ASP.net Core I'm seeing that this is

Not Possible? Or i don't understand how to create project to project references

whats the best way to organize a large Asp.net core solution

do i use core for the entry which is web and then net frame work for the rest?

thanks

Madaxe

Returning a mp3 file trough File Action results, stops after being played for 10 minutes

$
0
0

I have an action that returns mp3 file as below : 

                var memory = new MemoryStream();
                using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    await stream.CopyToAsync(memory);
                }
                memory.Position = 0;

                //Response.Headers.Add("Accept-Ranges", "bytes");
                //Response.Headers.Add("Connection", "keep-alive");

                return File(memory, "audio/mpeg", $"music.mp3", true);

So the is partial content. After 10 minutes of playing the mp3 file by calling my action, the player stops. I saw that html default player has logged following error in the browser console :

" net::ERR_CONNECTION_RESET 206 (Partial Content)"

What would be the reason ? 

smtp virtual server question

$
0
0

Hello,

I have an asp.net core web app, It is working on the IIS 8 windows server 2012. I need to send an e-mail to one of the action controllers. I installed the SMTP server. Did some googling and made configuration. I tried to send from one of my Gmail accounts. But I got "Delivery to the following recipients failed." error. Anyone who accomplished sending e-mail can help me, please?

Here is the sending e-mail in the controller:

public void sendMail(string body, string email)
        {
            SmtpClient client = new SmtpClient(server IP here);
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential("myaccount@gmail.com", "my password");

            MailMessage mailMessage = new MailMessage();
            mailMessage.From = new MailAddress("myaccount@gmail.com");
            mailMessage.To.Add(email);
            mailMessage.Body = body;
            mailMessage.Subject = "Serials";
            client.Send(mailMessage);
        }

Best Regards.

How do i improve ttfb for my website

$
0
0
Hello,
I develop the web app on asp.net core mvc and the database is huge on it.
So i checked in inspector of browser so the first touch on website browser is taking so long time.
My website is optimize but its load data before showing to client. Its fetch almost almost 500 rows from table.
So how do i show speed up ttfb.

Or how do i cache query results ?

Please help me I didn't find proper solution for it.

Thank you,
Prathamesh

WebApi using Token

$
0
0

Hi

  I have Visual Studio 2012. I want to develop Restful Api using token. Is there any tutorial or link available.

Can Api be developed in VS 2012 using Asp.net core.

Thanks

how to change a asp.cs file to aspnet core razor

$
0
0

I am changing over to aspnet core razor from asp net web. It is a magazine that will be in the www root as they are JavaScript pages.  How do I change a default aspx file to the razor format . I can't use system web Ui but I able to dowload system IO which has stream reader in it. 

Below is the file any ideas or help would be great

sing System;
using System.IO;
using System.Web.UI;

namespace Bumples20.UI
{
public partial class IssuesDefault : BasePage
{

Thanks Jen
private Int32 issue = 0;
private String section = "";

protected void Page_Load(object sender, EventArgs e)
{
//
if (String.IsNullOrEmpty(this.Request.QueryString["Issue"]))
{
this.issue = 1;
//throw new SecurityException("Error loading Issue!");
}
else
{
try
{
this.issue = Int32.Parse(this.Request.QueryString["Issue"]);
}
catch
{
this.issue = 1;
}
}

if (issue < 1 || issue > 25)
{
issue = 1;

}


//
if (String.IsNullOrEmpty(this.Request.QueryString["Section"]))
this.section = "";
else
this.section = this.Request.QueryString["Section"];

if (this.IssueName() == "Issue003" || this.IssueName() == "Issue004" || this.IssueName() == "Issue005" || this.IssueName() == "Issue006")
{
if (this.User.Identity.IsAuthenticated && (
this.User.IsInRole("Administrators") ||
this.User.IsInRole("Issue003") || this.User.IsInRole("Issue004") || this.User.IsInRole("Issue005") || this.User.IsInRole("Issue006") || this.User.IsInRole("Register")))
{
;
}
else
{
//String page = System.Web.HttpContext.Current.Request.Url.AbsoluteUri; // this.GetCurrentPageName();

this.Response.Redirect("~/Account/Login.aspx");
//throw new SecurityException("You are not allowed to edit existent articles!");
}
}

/* Execute */
this.LoadJavaScript();
/* Execute */

}

private void LoadJavaScript()
{
String javaScript = "";

javaScript += LoadFile("~/Issues/JavaScript/Page.js");
javaScript += LoadFile("~/Issues/JavaScript/Movime.js");
javaScript += LoadFile("~/Issues/JavaScript/TalkingBalloon.js");
javaScript += LoadFile("~/Issues/JavaScript/DivClass.js");
javaScript += LoadFile("~/Issues/JavaScript/MoveObjectsTo.js");
javaScript += LoadFile("~/Issues/JavaScript/MemoryClass.js");
javaScript += LoadFile("~/Issues/JavaScript/Magazine.js");
javaScript += LoadFile("~/Issues/JavaScript/TalkingBalloon.js");
javaScript += LoadFile("~/Issues/" + this.IssueName() + "/JavaScript.js");

Page.ClientScript.RegisterStartupScript(this.GetType(), "", javaScript, true);
}

public String LoadCss()
{
return "<style type=\"text/css\"> " + LoadFile("~/Issues/" + this.IssueName() + "/CssStyles.css") + " </style>";
}

private String IssueName()
{
return "Issue" + ((this.issue < 100) ? "0" : "") + ((this.issue < 10) ? "0" : "") + this.issue.ToString().Trim() + this.section;
}

private String LoadFile(String fileName)
{
//Open a file for reading
fileName = Server.MapPath(fileName);

//Get a StreamReader class that can be used to read the file
StreamReader objStreamReader = File.OpenText(fileName);

//Now, read the entire file into a string
String fileContent = objStreamReader.ReadToEnd();

objStreamReader.Close();

return fileContent;
}

}

}

Highlighting table cell depending of value

$
0
0

I have a controller, he takes four values from four dropdowns (vehicle1, vehicle2, etc) and returns selected value to ViewBag.

[HttpGet]publicIActionResultCompare(int vehicle1,int vehicle2,int vehicle3,int vehicle4){PlaneCollection planeCollectionContext =newPlaneCollection(Context);var planeCollection = planeCollectionContext.GetPlaneDataFromDb();ViewBag.Vehicle1Selected= planeCollection.Where(p => p.Id== vehicle1);ViewBag.Vehicle2Selected= planeCollection.Where(p => p.Id== vehicle2);ViewBag.Vehicle3Selected= planeCollection.Where(p => p.Id== vehicle3);ViewBag.Vehicle4Selected= planeCollection.Where(p => p.Id== vehicle4);returnView(planeCollection);}

View shows data from ViewBag like this

<tr><tdstyle="width:20%">Max speed</td><tdstyle="width:15%">@((ViewBag.Vehicle1Selected as IEnumerable<Plane>).FirstOrDefault().MaxSpeed)</td><tdstyle="width:15%">@((ViewBag.Vehicle2Selected as IEnumerable<Plane>).FirstOrDefault().MaxSpeed)</td><tdstyle="width:15%">@((ViewBag.Vehicle3Selected as IEnumerable<Plane>).FirstOrDefault().MaxSpeed)</td><tdstyle="width:15%">@((ViewBag.Vehicle4Selected as IEnumerable<Plane>).FirstOrDefault().MaxSpeed)</td></tr>

This is a table in the browser

I want to make green bg highlighting cells with max value (for example 600), red highlighting with min value and no highlighting to cells between max and min. How to make it, with taghelper or view component? (without AJAX if it possible)


When using SaveChangesAsync() my other code stop execute

$
0
0

I have problem and i think its a deadlock and i cant resolve the problem. I know there simular problem discuse but i need help. When i try to saveChange on productReposotory it stuck and dont execute the other code.

Here is my controller:

public IActionResult All(string type)
{
var viewModel = new AllFireplaceViewModel
{
Fireplaces =
this.fireplaceService.GetAllFireplaceAsync<IndexFireplaceViewModel>(type).Where(x => x.TypeOfChamber == type),
};
return this.View(viewModel);
}

My IFireplaceService:

using System.Collections.Generic;
using System.Threading.Tasks;

using KaminiCenter.Web.ViewModels.Fireplace;

public interface IFireplaceService
{
Task AddFireplaceAsync(FireplaceInputModel fireplaceInputModel);

IEnumerable<T> GetAllFireplaceAsync<T>(string type);

T GetByName<T>(string name);
}

And this is my implementation of the interface:

public async Task AddFireplaceAsync(FireplaceInputModel model)
{
var typeOfChamber = Enum.Parse<TypeOfChamber>(model.TypeOfChamber);

if (model.Power == null ||
model.Size == null ||
model.Chimney == null)
{
throw new ArgumentNullException("Cannot safe null or whitespace values!");
}

await this.productService.AddProductAsync(model.Name, model.Group);
var productId = this.productService.GetIdByNameAndGroup(model.Name, model.Group);
var groupId = this.groupService.FindByGroupName(model.Group).Id;

var fireplace = new Fireplace_chamber
{
Id = Guid.NewGuid().ToString(),
Power = model.Power,
Size = model.Size,
Chimney = model.Chimney,
Price = model.Price,
Description = model.Description,
ImagePath = model.ImagePath.ToString(),
TypeOfChamber = typeOfChamber,
ProductId = productId,
GroupId = groupId,
CreatedOn = DateTime.UtcNow,
ModifiedOn = DateTime.UtcNow,
};

await this.fireplaceRepository.AddAsync(fireplace);
await this.fireplaceRepository.SaveChangesAsync();
}
This is the productService.AddProductAsync:

public async Task AddProductAsync(string name, string groupName)
{
var group = this.groupService.FindByGroupName(groupName);

if (group == null)
{
await this.groupService.CreateAsync(groupName);
}

var product = new Product
{
// TO Check for Id Initializesion
Id = Guid.NewGuid().ToString(),
Name = name,
GroupId = group.Id,
CreatedOn = DateTime.UtcNow,
ModifiedOn = DateTime.UtcNow,
};

await this.productRepository.AddAsync(product);
await this.productRepository.SaveChangesAsync();
}

And my Add Action

public IActionResult Add()
{
var createFireplaceInputModel = new FireplaceInputModel();

return this.View(createFireplaceInputModel);
}

How to override HandleUnauthorizedRequest in ASP.NET Core?

$
0
0

I'm migrating my project to asp.net core and I'm stuck in migrating my CustomAuthorization attribute for my controllers. Here is my code.

public class CustomAuthorization : AuthorizeAttribute
{
    public string Url { get; set; }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery);
        }
        else if (!Roles.Split(',').Any(filterContext.HttpContext.User.IsInRole))
        {
            filterContext.Result = new ViewResult
            {
                ViewName = "AcessDenied"
            };
        }
        else
        {
            base.HandleUnauthorizedRequest(filterContext);
        }
    }
}

then i used it to my controllers

[CustomAuthorization(Url = "/Admin/Account/Login", Roles = "Admin")]
public abstract class AdminController : Controller { }

so, basically i can use it to redirect to different login page when roles is not met. I have few areas and each of them have different login page.

bulk import into sql using ASp.net

Is it possible to use the tag helper to generate a hyperlink to a Razor Component which has a @page directive?

$
0
0

Is it possible to use the <a> tag helper to generate a hyperlink to a Razor Component which has a @page directive?

This is in a mostly Razor-Pages project which uses Server-Side Blazor and has routing for both Razor pages and Razor 'Component-Pages'.

The /pages folder has a mix of `.cshtml` files and `.razor` files.

Routing is currently working properly for both Razor Pages and Razor Components with @page directives.

Thanks!

Value of html Text column is not get updated from javascript , Please help

$
0
0

I have the following HTML

@model ModernTyres.GO.Common.Models.EmpDocumentModel<input type="text" name="Claim" class="form-control" id="TxtClaim" asp-for="Claim" data-role="text" disabled /><script>$(document).ready(function () {
    SetLicense();

}
  function SetLicense()
    {
    var url = '@Url.Action("GetLicense", "EmpDoc")';$.post(url, $('form').serialize(), function (view) {$("#TxtClaim").val(view.Claim);// The value TxtClaim should be updated from GetLicense. But not working 
        });


}
</script


public IActionResult GetLicense(EmpDocumentModel data)
        {
          EmpDocumentModel doc = new EmpDocumentModel();
          data.Claim = "TestClaim";  // This value should be updated in my html view
          return Json(data);

        }

checking of correct datetime format is not working

$
0
0

Hi

I want to check the given string value is correct  format for converting into  datetime  variable before to convert into date time variable.  But the value '05/03/2020 8:15:00' is showed as incorrect format . Please can you advise me where is the problem

eg: datetimestring  ='05/03/2020 8:15:00'

                string clockeddate = log.AttendanceDate;
                string timeclock = log.Hrs + ':' + log.Mins;
                string datetimestring = clockeddate + " " + timeclock+":00";

                DateTime dDate;
                bool isCorrectDateFormat =   DateTime.TryParseExact(datetimestring, "dd/MM/yyyy HH:mm:ss",
                    CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);
                if(isCorrectDateFormat)
                {
                     dDate = Convert.ToDateTime(clockeddate + " " + timeclock);
                }

IdentityResult IdentityError

$
0
0

Hi - when creating a user by calling "UserManager.CreateAsync(user, password)", one can receive an error (or several) in the returned IdentityResult.

I want to map these errors to specific input fields on the View (so I can display specific error messages next to the field). It seems though, that at this point, the CreateAsync method doesn't actually know anything about my View's fields, so is this a manual process where I can loop through the Errors, and check the Code value which I can try to map to a specific field?

(Also, of course, it appears some errors may not be related to specific fields - so these general errors can be presented at the top of the form).


Razor table add/remove data

$
0
0

Hi,

I have a cshtml page as follows:

<form class="needs-validation" novalidate><div class="container-fluid"><div class="row"><div class="col-md-6"><div class="row"><div class="col-md-4"></div><div class="form-group col-md-5 input-group"><select class="custom-select" id="validationCustom04" required><option selected disabled value="">Choose...</option><option value="ZULA">ZULA - 5TL</option><option value="STEAM">STEAM - 10TL</option><option value="GameForge">Gameforge - 6TL</option><option value="PUBG">PUBG Mobile - 10TL</option><option value="LOL">League of Legends - 12TL</option></select><div class="invalid-feedback">
                            Please select a game.</div></div></div><div class="row"><div class="col-md-4"></div><div class="form-group col-md-5 input-group"><div class="input-group-prepend"><span class="input-group-text" id="basic-addon1">Quantity</span></div><input type="number" class="form-control " id="quantity" name="Quantity" value="1" aria-describedby="basic-addon1" /></div></div><div class="row"><div class="col-md-4"></div><div class="form-group col-md-5 input-group"><div class="input-group-prepend"><span class="input-group-text" id="basic-addon2">E-mail&nbsp;&nbsp;&nbsp;&nbsp;</span></div><input type="email" class="form-control" aria-describedby="basic-addon2" required id="email"/><div class="invalid-feedback">
                            Please provide a valid email.</div></div></div><div class="row"><div class="col-md-4"></div><div class="form-group col-md-5"><input id="btn_purchase" type="submit" value="Purchase" class="btn btn-success" /><input id="btn_clear" type="button" value="Clear" class="btn btn-warning" /></div></div></div><div class="col-md-5"><div class="form-group col-md-5"><h3>Serials</h3><textarea class="form-control" id="result" rows="5" readonly=""></textarea></div></div></div></div></form>

I would like to add a table and a button (add). If the user clicks the add button, I would like to add data from inputs above to the table. In the table in each row, there should be a remove button in order to remove the selected row. Is there any tutorial that I can follow.

Best Regards.

Save Form Array Data at Once into Database

$
0
0

I have a form with multiple data, that i want to save to the Database at Once. I am new to C# but i have been able to do this with PHP in the past. See the form  in the table below:

<tbody>
@{int c = 0;
foreach (var item in Model)
{
c++;

<tr>
<td>@c</td>
<td>@item.FltNo<input type="hidden" name="fleetId[]" value="@item.FltNo" /></td>
<td>@item.FleetModelName<input type="hidden" name="FleetModelId[]" value="@item.FleetModelName" /></td>
<td>@item.EngineName<input type="hidden" name="EngineName[]" value="@item.EngineName" /></td>
<td>@item.LocationName<input type="hidden" name="LocationName[]" value="@item.LocationName" /></td>
<td>@item.ServiceType<input type="hidden" name="ServiceType[]" value="@item.ServiceType" /></td>
<td>@item.ServiceSequence<input type="hidden" name="ServiceSeq[]" value="@item.ServiceSequence" /></td>
<td>@item.EstimatehrPerDay<input type="hidden" name="hrperDay[]" value="@item.EstimatehrPerDay" /></td>
<td>@item.PartNo<input type="hidden" name="PartNo[]" value="@item.PartNo" /></td>
<td>@item.PartName<input type="hidden" name="PartName[]" value="@item.PartName" /></td>
<td>@item.CostperUnit.ToString("C")<input type="hidden" name="Cost[]" value="@item.CostperUnit" /></td>
<td>@item.QtyPerService<input type="hidden" name="Qty[]" value="@item.QtyPerService" /></td>
<td>@item.TotalCost.ToString("C")<input type="hidden" name="Total[]" value="@item.TotalCost" /></td>
</tr>
}
}

</tbody>

Now in the Controller, i want to be able to get all the data and save it into the Database

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Mrptran mrptran)
{

ArrayList myArrayList = new ArrayList();

string[] fltno = Request.Form["FleetId[]"];
string[] Fltmodel = Request.Form["FleetModelId[]"];
string[] Engine = Request.Form["EngineName[]"];
string[] Location = Request.Form["LocationName[]"];
string[] Servtype = Request.Form["ServiceType[]"];
string[] ServiceSeq = Request.Form["ServiceSeq[]"];
string[] hrperDay = Request.Form["hrperDay[]"];
string[] PNo = Request.Form["PartNo[]"];
string[] PName = Request.Form["PartName[]"];
string[] Cost = Request.Form["Cost[]"];
string[] Qty = Request.Form["Qty[]"];
string[] Total = Request.Form["Total[]"];

myArrayList.Add(fltno);
myArrayList.Add(Fltmodel);
myArrayList.Add(Engine);
myArrayList.Add(Location);
myArrayList.Add(Servtype);
myArrayList.Add(ServiceSeq);
myArrayList.Add(hrperDay);
myArrayList.Add(PNo);
myArrayList.Add(PName);
myArrayList.Add(Cost);
myArrayList.Add(Qty);
myArrayList.Add(Total);

var mrp = new Mrptran
{
 //Map all the inputs to the Fields in the DB - This is where the issue of "How  to"
};

_context.Mrptrans.Add(mrp);

Question: Is the way of getting the Data from the form alright? and how do i map the inputs to the fields in the Database, so I can Save it to the Database?If there is a better way, kindly suggest.thanks

how to set select option value as "Y ' from controller to view Select dropdown

$
0
0

I am trying to set the value 'Y' into a select list item from controller. Please can I ask your help to get sorted ? with Many Thanks

I have the following model

EmpDocumentModel
{
[NotMapped]
public string IsClaim { get; set; }
public string Claim { get; set; }
}

I have the controller as given below

public IActionResult GetLicense(EmpDocumentModel data)
        {
            EmpDocumentModel doc = new EmpDocumentModel();
            data.Claim="Test Calim"
            if (data.Claim != null)
            {                data.IsClaim = "Y";  // I am trying to set the value in view only if data.claim is not null
            }
            return Json(data);

        }

My view

 

@model MyModel.Models.EmpDocumentModel<div class="col-md-6"><div class="form-group"><label asp-for="IsClaim" class="control-label control-label-left col-sm-3 text-danger">Any Claim?<br />[If Yes Give Details]</label><div class="controls col-sm-9"><div class="input-group"><div class="input-group-addon"><select id="IsClaim" name="IsClaim" asp-for="IsClaim" data-role="select" >  // I want to set the value as "Y' from controller, if  it is not form-control<option value="N">No</option><option value="Y">Yes</option></select></div><input type="text" name="Claim" class="form-control" id="TxtClaim"  asp-for="Claim" data-role="text" disabled /></div></div></div></div><script>
  function SetLicense() {
    var url = '@Url.Action("GetLicense", "EmpDoc")';$.post(url, $('form').serialize(), function (view) {$("#TxtClaim").val(view.claim);$("#IsClaim").val(view.isclaim);  //is not working 

    });
    }
</script>

Instrumentation Profiler in CoreCLR(.Net Core) - Ways to get HttpContext in .NetStandard assembly

$
0
0

I am trying to Instrument .NET Core web applications that runs on .NET Core 3.1 using CoreCLR Profiler.
When I allow injecting the code into the Web application's method the helper assembly(.NET standard 2.0) is got attached to dotnet.exe process and it is getting callbacks to the helper assembly.
I have created helper assembly(.NET standard 2.0) with the injected functions body.

Now I need to get the HttpContext.Current of the each HTTP request of .NET core web application in helper assembly(.NET standard 2.0). In .Net framework we have System.Web.HttpContext.Current and System.Web.HttpRequest to get the Header,cookie,session id and site name of each request. How can I achieve same in .Net standard? 

1. Can I use Microsoft.AspNetCore.Http.HttpRequest in .NET standard 2.0 assembly? If so how can I add reference to .Net standard assembly?
2. How can I get Header,cookie,session id and site name of .net core web application in .NET standard 2.0 assembly?
3. What is the alternative/equivalent of following .Net Framework namespaces in .Net Core/.Net 
     A. System.Web.HttpContext.Current
     B. System.Web.HttpRequest
     C. System.Web.HttpCookie
     D. System.Web.Hosting.HostingEnvironment.SiteName

It would be much helpful if i get some correct direction to get or use HttpContext.Current in .NetStandard assembly.

Thanks in advance. 

WebAPI: why does it use MVC namespace and classes?

$
0
0

Hello,

I'm pretty new to the WebAPI world.

So far I've read some great articles on how to create and call WebAPI; however, I'm still a bit puzzled about one thing: even if we create "just" a WebAPI, not a MVC application, we are almost "stuck" with theMicrosoft.AspNetCore.Mvc namespace.

For instance:

  • ControllerBase is part of the namespace;
  • HttpMethodAttribute (HttpGet, HttpPost, etc.) is part of the namespace;
  • even return methods like Ok(), CreatedAtRoute(), etc. are part of the namespace.

Why is this like that? Can't we have a "proper" separation between "pure WebAPI" and MVC application? Is that the correct way of doing thing? If no, what is the correct way of creating a "pure WebAPI"?

Thanks and have a nice day :).

Viewing all 9386 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>