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

Primary key not available - Error: Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys

$
0
0

Hi.

I am using SQL and trying to use ASP.NET Core and Razor pages.

The sql table does not have a primary key and I will not be able to make changes to the SQL table. I am trying to use a stored procedure to retrieve the data from the table and show the resultant data in UI.

Since there is no primary key available, I am getting error as  - Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateNonNullPrimaryKeys

Below is the code so far used.

//Data - myDbContext

 public class MyDbContext : DbContext
    {
        public DbSet<LOB> lobs { get; set; }

        public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
        {
        }

        }

// Model  
 public class LOB
    {
        public string Desc { get; set; }
    }
//Index.cshtml.cs

 public class IndexModel : PageModel
    {
        private readonly MyDbContext _dbContext;
        public IndexModel(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public List<LOB> lOBs { get; set; } = new List<LOB>();

                [BindProperty]
        public string[] SelectedLOBs { get; set; }

        public SelectList LOBOptions { get; set; }

        
        public async Task OnGetAsync()
        {
            lOBs = await _dbContext.Set<LOB>().FromSql("EXECUTE sp")
                              .AsNoTracking()
                              .ToListAsync();

            LOBOptions = new SelectList(lOBs, "Desc1");
        }
    }

// Index.cshtml

  <select class="form-control" required multiple id="selLOB" asp-for="SelectedLOBs" asp-items="Model.LOBOptions"></select>

How to fix this?

Thanks


How to get fields exist on table by passing table name by using asp.net core 2.1 ?

$
0
0

How to get fields exist on table by passing table name ?

suppose I have table name Employee on SQL server 2012

and this is fields of Employee Table EmployeeCode,EmployeeName,,..etc

How to make function pass to it table name and it will retrieve fields or columns as 

EmployeeCode,

EmployeeName

I work on web API core project with angular 7 

structure of function as below

public List<string> GetColumnNames(string tablename)
{
}



Migrate existing as.net web forms application to asp.net core.

$
0
0

Hi,

I have an asp.net web forms application which I would like to migrate to asp.net core platform.

Since i'm a novice in .Net core, I want to understand the migration strategy recommended by Microsoft and the best practices being followed.

Thanks

AJ

Leveraging ADO.NET in ASP.NET Core 2.0

$
0
0

Hi.

I am trying to use the ADO.NET option to retrieve data in ASP.NET Core 2.0 - https://www.learnentityframeworkcore.com/raw-sql 

The method defined here:

using (var context = new SampleContext())
using (var command = context.Database.GetDbConnection().CreateCommand())
{
    context.Database.ExecuteSqlCommandAsync("EXEC SP");
}

Few doubts:

1) Does context mean the DataContext ?

2) Should the above code be written in index.html.cs ?

3) how should the resultant data be passed to a UI control ( dropdown )

Read data from querystring and validate it for SQL Injection

$
0
0

Hi.

In ASP.NET Core 2.0, how to read the data from query string and then pass it to a stored procedure as a parameter.

Before passing it as parameter, how to validate the query string field for SQL Injection ?

Thanks

Role based authorization for Windows Authentication in ASP.NET Core MVC

$
0
0

This problem has been puzzling me for over a week now. I am trying to build a MVC Core website and the users are supposed to automatically log on to the website using their windows authentication. I can see who has logged in but I also need to restrict their access to certain actions of controllers.  How do I approach this ? I have a SQL Server 2017 with me and I would like that the users be authenticated or authorized from this database.  

I tried looking at few examples online but most of them deal with Individual User Accounts. I saw concepts of Roles and Permissions and Claims being discussed but that breezed over my head. Please help me here. The scenario is like this :-  

1) The user will try to access the website and if he/she is one of the authorized users, he/she will be provided the Index page.

2) The roles of the users of the websites will be Admin, Privileged and Users.

how to persist data between forms without db

$
0
0

Hi, I have a quiz that goes over several pages. I have forms on all of them, but I don't want to store the data in the database untill the very last page. 

I could do this in the frontend using javascript, but I want to find a way to do this on the server. Is it even possible to persist form data from page to page untill the last one in asp.net core?

Data type to store time variable in model

$
0
0

What the datatype of the variable   in a model class to store a value from sqlserver database with time(7) . It is the dattype of the column Clockedin and Clockedout. What would be the model class variable to  hold the value from the data base

[ClockedIN] [time](7) NULL,
[ClockedOut] [time](7) NULL,


return back to exactly where I click

$
0
0

I own this site: http://www.sohjel.ir ; I've implemented an option called: "Watch Bag", using ASP.NET Core 2.1 MVC Session.
And my problem is: I want to return back to exactly where I click "Add To Watch Bag" in that page after I click this button and adding that lesson to "Watch Bag" instead of returning back to "Begin of Page".
How do I do that?!
Note that I've used this code in my Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(int id)
{
List<int> lstViewBag = HttpContext.Session.Get<List<int>>("sjViewBag");
if (lstViewBag == null)
{
lstViewBag = new List<int>();
}
lstViewBag.Add(id);
HttpContext.Session.Set("sjViewBag", lstViewBag);
return RedirectToAction("Index", "Home", new { area = "Customer" });
}

string wasnot recognised as valid datetime. Please can you help urgent

$
0
0

I am trying to store time part into the string from datetime variable in the format hh:mm, but the error is coming'string wasnot recognised as valid datetime'.  Also there is a chance for null value coming for the column DateClockedIn , DateClockedOut . How can I manage if there is null coming to the column DateClockedIn and DateClockedOut.

Please help

My model class

public AttendanceLogModel()
public string ClockedIn { get; set; } // To store time part hh:mm
public string  ClockedOut { get; set; }   // to store time part hh:mm    
public DateTime DateClockedIn { get; set; }
public DateTime DateClockedOut { get; set; }

My Program

DataTable dt = new DataTable();
            dt = ReportBLL.GetEmployeeAttendanceReport(depot, department, employee, fromDate, toDate, connectionSettings);
            List<AttendanceLogModel> log = dt.AsEnumerable().Select(row =>
            {
                var p = new AttendanceLogModel
                {
                    ClockedIn = Convert.ToDateTime(row["DateClockedIn"].ToString()).ToShortTimeString(), // Here is the error is coming
                    ClockedOut = Convert.ToDateTime(row["DateClockedOut"].ToString()).ToShortTimeString() // Here is the error is coming 
                };

                return p;
            }).ToList<AttendanceLogModel>();

            return log;

Error: InvalidOperationException: Invalid attempt to call FieldCount when reader is closed

$
0
0

Hi,

I am getting the error - InvalidOperationException: Invalid attempt to call FieldCount when reader is closed, when trying to populate a dropdown using below code:

 public class IndexModel : PageModel
    {
        private readonly MyDbContext _dbContext;
        public IndexModel(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }
        public List<LOB> lOBs { get; set; } = new List<LOB>();
        [BindProperty]
        public string[] SelectedLOBs { get; set; }

        public SelectList LOBOptions { get; set; }
        
        public async Task OnGetAsync()
        {                  
            using (var command = _dbContext.Database.GetDbConnection().CreateCommand())
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.CommandText = "sp";
                _dbContext.Database.OpenConnection();
                 using (var result = command.ExecuteReader())
                {
                    if (result.Read())
                    {
                        LOBOptions = new SelectList(result, "Desc");
                    }
                }
            }

        }
    }

//Index.cshtml
 <select class="form-control" required multiple id="selLOB" asp-for="SelectedLOBs" asp-items="Model.LOBOptions"></select>

How to fix this ?

Thanks

Please advise with suggested code to check null value for datetime

$
0
0

Please anyone can advise me with a suggested code to check null value for DateClockedIn  and DateClockedOut 

DataTable dt = new DataTable();
            dt = ReportBLL.GetEmployeeAttendanceReport(depot, department, employee, fromDate, toDate, connectionSettings);
            List<AttendanceLogModel> log = dt.AsEnumerable().Select(row =>
            {
                var p = new AttendanceLogModel
                {
                    DateClockedIn = Convert.ToDateTime(row["DateClockedIn"].ToString()),
                    DateClockedOut = Convert.ToDateTime(row["DateClockedOut"].ToString()),
                };

                return p;
            }).ToList<AttendanceLogModel>();

With Thanks

Pol

Introducing FOREIGN KEY constraint 'FK_Move_Center_CenterToId' on table 'Move' may cause cycles or multiple cascade paths

$
0
0

Hi All

I'm trying to reference tow foreign keys in the same model:

    public class Move
    {
        public int Id { get; set; }

        public int CenterFromId { get; set; }
        public int CenterToId { get; set; }
        public virtual Center CenterFrom { get; set; }
        public virtual Center CenterTo { get; set; }
    }

which will takes value from Center model:

    public class Center
    {
        public int Id { get; set; }
        [MaxLength(100)]
        String CenterName { get; set; }

        public virtual ICollection<Move> MoveFrom { get; set; }
        public virtual ICollection<Move> MoveTo { get; set; }
    }

and deining the relatios in Context:

        public virtual DbSet<Center> Center { get; set; }
        public virtual DbSet<Move> Move { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Move>()
                        .HasOne(m => m.CenterFrom)
                        .WithMany(t => t.MoveFrom)
                        .HasForeignKey(m => m.CenterFromId)
                        .OnDelete(DeleteBehavior.Restrict);


            modelBuilder.Entity<Move>()
                        .HasOne(m => m.CenterTo)
                        .WithMany(t => t.MoveTo)
                        .HasForeignKey(m => m.CenterToId)
                        .OnDelete(DeleteBehavior.Restrict);
        }

Now when I try to run the command 'update-database' it gives me this error:

Introducing FOREIGN KEY constraint 'FK_Move_Center_CenterToId' on table 'Move' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.

How to solve please?

AllowAnonymous and Identity

$
0
0

I have to allow anonymous users to access the HomeController of my application, but many users will be authenticated, and I want to route them depending on their Active Directory groups. I added an ActionFilter via a ServiceFilter attribute (so I could leverage dependency injection) that grabs the logged-in user's Active Directory info, along with all the emails their account is associated with. That last part was important, so that users logged in with any of their Active Directory emails would resolve correctly. My ActionFilter runs at the start of every action. 

All of that works, with one glaring exception... HttpContext.User.Identity.Name is null when accessed from a method with the AllowAnonymous attribute added. I've read up on it, and apparently this attribute, whose name suggests anonymous login is anoption, bypasses the authentication handler altogether, making is an "AnonymousRequired" attribute, in effect. The controller is decorated with an Authorize attribute, and the Index method with AllowAnonymous. I tried redirecting to another method in the HomeController that does NOT have the anonymous attribute, but the Identity is still null. If I remove the AllowAnonymous attribute entirely, authentication works as expected, but I can't allow access for anonymous users. 

I need the HomeController's Index method to keep the AllowAnonymous attribute, but also get the Identity from HttpContext. Any suggestions? 

dotnet core (2.2) razor page tag helpers add custom HTML targets

$
0
0

 use helper tags for label and select tags like so:

<select asp-for="Article.Countries.Id"></select>

I now want to use a custom tag multiselect into which a JS library hooks into.

I now want to use the tag helper expansion from select in this new tag:

<multiselect asp-for="Article.Countries.Id"></multiselect >

What is the safest way to extend the select-helper tag to also kick in for this new tag?


How to mock dbset methods Add() , Remove() ,SaveChanges()? How to configure positive and negative return values?

$
0
0

I am trying to write unit tests for my controller action. I am using NUnit 3 and Moq.

I have Db methods such as Add() and Remove() in the action.

I understand that I need to mock the Db and setup return values to the methods accordingly.

However when it comes to methods such as db.Add(), db.Remove() , db.SaveChanges(); I don't understand how to setup true and false return values for the same.

My action to be tested:

[HttpPost][Route("Add")]publicList<string>Add([FromBody]model addModel){List<string> errors =newList<string>();try{
        model Model=new model(){
          propertyA = addModel.propertyA};
        db.Add(Model);
        db.SaveChanges();}catch(Exception e){
        errors.Add(e.Message);return errors;}

    errors.Add("Success");return errors;}

To write positive and negative tests for the above methods, I need to be able to set positive and negative return values for db.Add() and db.SaveChanges() methods.

I have tried the following:

[TestCase]publicvoidAdd_Succesfull_True(){Mock<DbContext> mockdb =newMock<DbContext>();var model= db.model.Select(x => x).FirstOrDefault();
            model addModel =new model(){
               propertyA= model.propertyA};AuthController authController =newAuthController(userManager, configuration, mockdb.Object);var apiEndPoint = authController.Add(addModel);
            mockdb.Setup(x => x.Add(addModel)).Returns(??);Assert.IsTrue(apiEndPoint.Contains("Success"));}

Through intellisense I can see that db.Add() expects a return type of

Microsoft.EntityFrameworkCore.ChangeTracking.

My understand of mocking the DbContext is as follows:

  • Mock the DbContext interface.
  • Add,Remove, Save etc are all just methods which have no implementation when mocked.
  • we setup the function and specify a return value as need for the test case which substitutes as an implementation.

I believe I have mocked the above in a wrong way. Need direction thank you:)

Help, trying to create an /api/controller in a simple web project

$
0
0

Hi

Please help, I created this simple controller within my asp.net core web app.

But I cannot seem to call this method?

    [AuthenticateActionFilter]
    [Route("api/Security")]
    [ApiController]
    public class SecurityController : ControllerBase
    {
        [HttpPost]
        public async Task<ActionResult<SecurityResultModel>> PostSecurityManager(SecurityRouteModel routeModel)
        {
            SecurityResultModel result = new SecurityResultModel();

            List<Task> tasks = new List<Task>();
            tasks.Add(Task.Run(()=> {result.message = "Completed!";}));

            await Task.WhenAll(tasks);

            return CreatedAtAction(nameof(PostSecurityManager), result);
        }
    } 

I tried calling it like this but i get 404 page not found?? it does not seem to enter the method or my breakpoint either.

http://localhost:50136/api/security

http://localhost:50136/api/securityManager

making a Dictionary available to another project within the same solution - no success

$
0
0

Project TcpServer populates a List<IClient> clients

In project CommandHandler there is:

private List<IClient> clients;

public void Setup(List<IClient> clients)
        {
            this.clients = clients;
        }

The clients list is available throughout CommandHandler.

Want to do the same thing with a Dictionary created in TcpServer:

private readonly Dictionary<string, IClient> connectedClients = new Dictionary<string, IClient>();

In CommandHandler:

private Dictionary<string, IClient> connectedClients;

public void Setup(Dictionary<string, IClient> connectedClients)
        {
            this.connectedClients = connectedClients;
        }

connectedClients is alway null

What am I doing wrong here?

Migrate existing as.net web forms application to asp.net core.

$
0
0

Hi,

I have an asp.net web forms application which I would like to migrate to asp.net core platform.

Since i'm a novice in .Net core, I want to understand the migration strategy recommended by Microsoft and the best practices being followed.

Thanks

AJ

Retrieve Azure AD USer's Manager via .net Core project with Authetication Windows Authetication

$
0
0

Hi All,

I'm trying to retrieve User's manager email address via code below:-

[Authorize]
    public class HomeController : Controller
    {
        IConfiguration _config;
        public string[] Scopes = { "User.Read", "Mail.Send", "Files.ReadWrite" };        
        public string TokenForUser = null;
        public DateTimeOffset Expiration;
        public HomeController(IConfiguration config) {
            _config = config;
        }       


        public IActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                var clientId = _config.GetSection("AzureAd").GetSection("ClientId").Value;
                var tenantId = _config.GetSection("AzureAd").GetSection("TenantId").Value;
                var clientSecret = _config.GetSection("AzureAd").GetSection("ClientSecret").Value;
                var AADInstance = _config.GetSection("AzureAd").GetSection("Instance").Value;

                // Get user's id for token cache.
                var identifier = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                var userName = User.FindFirst(ClaimTypes.Name).Value; // will give the user's userName
                
                var Email = User.FindFirst(ClaimTypes.Upn).Value;
                var FirstName = User.FindFirst(ClaimTypes.GivenName).Value;
                var LastName = User.FindFirst(ClaimTypes.Surname).Value;
                var claimsIdentity = (ClaimsIdentity)User.Identity;
                var tenantid = User.Claims.ToList().Find(r => r.Type == "http://schemas.microsoft.com/identity/claims/tenantid").Value;
                var objectidentifier = User.Claims.ToList().Find(r => r.Type == "http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
                PublicClientApplication clientApp = new PublicClientApplication(clientId);


                GraphServiceClient graphClient = new GraphServiceClient("https://graph.microsoft.com/v1.0", new DelegateAuthenticationProvider(async (requestMessage) =>
                {
                    var token = await GetTokenForUserAsync();
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
                }));
                var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
                var users = graphClient.Users.Request().Select("Department,Mail,Display,Id,GivenName,Surname,UserPrincipleName").Expand(m=>m.Manager).GetAsync().ToAsyncEnumerable();
                var manager = (Microsoft.Graph.User)graphClient.Users[userId].Manager.Request().GetAsync().Result;

                //var users = graphClient.Users.Request()
                //.Where(user => user.UserPrincipalName.Equals(searchString)).Expand(m => m.Manager)
                //.ExecuteAsync().Result.CurrentPage.ToList();

            }
            return View();
        }

        public async Task<string> GetTokenForUserAsync()
        {
            var clientId = _config.GetSection("AzureAd").GetSection("ClientId").Value;
            var tenantId = _config.GetSection("AzureAd").GetSection("TenantId").Value;
            PublicClientApplication IdentityClientApp = new PublicClientApplication(clientId);
            IEnumerable<IAccount> accounts = IdentityClientApp.GetAccountsAsync().Result.ToArray();
            IAccount firstAccount = accounts.FirstOrDefault();
            AuthenticationResult authResult;
            try
            {
                authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, firstAccount);
                TokenForUser = authResult.AccessToken;
            }

            catch (Exception)
            {
                if (TokenForUser == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
                {
                    authResult = await IdentityClientApp.AcquireTokenSilentAsync(Scopes, firstAccount);

                    TokenForUser = authResult.AccessToken;
                    Expiration = authResult.ExpiresOn;
                }
            }

            return TokenForUser;
        }

However, I got error :

"One or more errors occurred. (Null account was passed in AcquiretokenSilent API. Pass in an account object or call acquireToken to authenticate.)"

Please assist.

Thanks.

Regards,

Micheale

Viewing all 9386 articles
Browse latest View live


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