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

Facing error 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' when input control disabled!

$
0
0

Hi

my problem is that when i disable my input control as follow :

<div class="form-group"><label asp-for="OrderId" class="control-label"></label><input asp-for="OrderId" class="form-control" value="@ViewData["_orderID"]" disabled="disabled" /><span asp-validation-for="OrderId" class="text-danger"></span></div>

I'm facing this error during update :

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

But when i remove disable tag from my input element it works correctly!!!

What's the problem & how to solve it ?

Note : The given input field (OrderId) is primary key for my Orders table.

Thanks in advance


How to implement servicehost in asp.net core

$
0
0

Hi Team,

How to implement serviceshost in .net core I migrated asp.net project to .net core 3.1 but found servicehost is not supported

is any way to implement this or any suggestion would be helpful.

Problem to send ajax request to delete item (Returns not found!).

$
0
0

Hi

in my form, i have a list of orders which user can click on delete button to delete each order of specific person. here is my orders list :

@model IEnumerable<Orders><input type="hidden" id="hdnPersonName" value="@ViewData["_personName"]" /><button type="button" id="btnNew" class="btn btn-success btn-sm" onclick="newOrderItem(@((int)ViewData["_personID"]))">Create new</button><br /><table class="table table-bordered"><tr><th>Order ID</th><th>Order Number</th><th>Order Date</th><th>Commands</th></tr>
    @if (Model != null)
    {
        foreach (var item in Model)
        {<tr><td>@item.OrderId</td><td>@item.OrderNumber</td><td>@item.OrderDate.Value.ToShamsiDate()</td><td><input type="button" id="btnEdit" class="btn btn-warning btn-sm" onclick="editOrderItem(@item.OrderId)" value="Edit" /><input type="button" id="btnDelete" class="btn btn-danger btn-sm" onclick="deleteOrderItem(@item.OrderId)" value="Delete" /></td></tr>
        }
    }</table><div id="divPopup"></div>

As you can see in above code, The btnDelete button call 'deleteOrderItem' javascript to delete order as follow :

function deleteOrderItem(orderID) {
    debugger;
    if (confirm('Are you sure want to delete this item?')) {$.ajax({
            type: "POST",
            url: "@Url.Action('DeleteOrder','Home')",
            contentType: "application/json; charset=utf-8",
            data: "{ 'id': '"+orderID+"' }",
            success: function () {
                setTimeout(function () {
                    debugger;
                    var personID = $('#hdnPersonID').val();
                    var personName = $('#hdnPersonName').val();
                    viewItem(personID, personName);
                }, 500)
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(jqXHR.responseText);
            }
        });
    }
}

And here is my action code method to delete order from database :

/ POST: Orders/Delete/5
        public async Task<IActionResult> DeleteOrder(int id)
        {
            var orders = await _dbContext.Orders.FindAsync(id);
            _dbContext.Orders.Remove(orders);
            await _dbContext.SaveChangesAsync();
            return Content(id.ToString());
        }

But at runTime it does not works. when i run on debugging mode (set breakPoint in DeleteOrder action method) it does not fire & i think it can not find my action (or something else).

Can anybody help me where is my problem & how to solve it?

Thanks in advance

File name when uploading

$
0
0

When uploading an image, and if the image is named rover.jpg, and I want the uploaded image to be rover456.jpg, how do I name it?

This Github example uses a random name:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Configuration;
using SampleApp.Utilities;

namespace SampleApp.Pages
{
    public class BufferedMultipleFileUploadPhysicalModel : PageModel
    {
        private readonly long _fileSizeLimit;
        private readonly string[] _permittedExtensions = { ".txt" };
        private readonly string _targetFilePath;

        public BufferedMultipleFileUploadPhysicalModel(IConfiguration config)
        {
            _fileSizeLimit = config.GetValue<long>("FileSizeLimit");

            // To save physical files to a path provided by configuration:
            _targetFilePath = config.GetValue<string>("StoredFilesPath");

            // To save physical files to the temporary files folder, use:
            //_targetFilePath = Path.GetTempPath();
        }

        [BindProperty]
        public BufferedMultipleFileUploadPhysical FileUpload { get; set; }

        public string Result { get; private set; }

        public void OnGet()
        {
        }

        public async Task<IActionResult> OnPostUploadAsync()
        {
            if (!ModelState.IsValid)
            {
                Result = "Please correct the form.";

                return Page();
            }

            foreach (var formFile in FileUpload.FormFiles)
            {
                var formFileContent = 
                    await FileHelpers
                        .ProcessFormFile<BufferedMultipleFileUploadPhysical>(
                            formFile, ModelState, _permittedExtensions, 
                            _fileSizeLimit);

                if (!ModelState.IsValid)
                {
                    Result = "Please correct the form.";

                    return Page();
                }

                // For the file name of the uploaded file stored
                // server-side, use Path.GetRandomFileName to generate a safe
                // random file name.
                var trustedFileNameForFileStorage = Path.GetRandomFileName();
                var filePath = Path.Combine(
                    _targetFilePath, trustedFileNameForFileStorage);

                // **WARNING!**
                // In the following example, the file is saved without
                // scanning the file's contents. In most production
                // scenarios, an anti-virus/anti-malware scanner API
                // is used on the file before making the file available
                // for download or for use by other systems. 
                // For more information, see the topic that accompanies 
                // this sample.

                using (var fileStream = System.IO.File.Create(filePath))
                {
                    await fileStream.WriteAsync(formFileContent);

                    // To work directly with the FormFiles, use the following
                    // instead:
                    //await formFile.CopyToAsync(fileStream);
                }
            }

            return RedirectToPage("./Index");
        }
    }

    public class BufferedMultipleFileUploadPhysical
    {
        [Required]
        [Display(Name="File")]
        public List<IFormFile> FormFiles { get; set; }

        [Display(Name="Note")]
        [StringLength(50, MinimumLength = 0)]
        public string Note { get; set; }
    }
}

There has got to be an easier way to do a simple upload of images, and name them as wanted.

How to access ViewData from external javascript ?

$
0
0

Hi

i've use this external javascript function to access ViewData variable(s) :

function deleteOrderItem(orderID) {
    if (confirm('Are you sure want to delete this item?')) {$.ajax({
            type: "POST",
            url: "DeleteOrder",
            data: { id: orderID },
            success: function () {
                setTimeout(function () {
                    debugger;
                    var personID = "@ViewData['_personID']";
                    viewItem(personID);
                }, 500)
            }
        });
    }
}

But at runTime, when i'm using developer tools, the personID contains @ViewData[_personID] as text and not accessing real viewData which i've set in my action method!

Here is my action method :

// POST: Orders/Delete/5
        [HttpPost]
        public async Task<IActionResult> DeleteOrder(int id)
        {
            var orders = await _dbContext.Orders.FindAsync(id);

            ViewData["_personID"] = orders.PersonId;

            _dbContext.Orders.Remove(orders);
            await _dbContext.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

Where is the problem & how to solve it?

Thanks in advance

how to fix JSON Self Referencing Loop Exceptions

$
0
0

My Project in asp.net core 3.0 .Net core framework 

I have the following  model.

When I run the query in postman the following error is coming 'JSON Self Referencing Loop Exceptions'  when I try to include the  Icollection list Gigs . Please help

public class Event
    {
        public int EventId { get; set; }
        public string EventName { get; set; }
        public DateTime EventDate { get; set; }

        [ForeignKey("VenueId")]
        public int VenueId { get; set; }
        public Venue Venue { get; set; }
        public  ICollection<Gig> Gigs { get; set; }
    }

public class Comedian
    {
        public int ComedianId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ContactPhone { get; set; }
    }

 public class Gig
    {
        public int GigId { get; set; }
        public string GigHeadline { get; set; }
        public int GigLengthInMinutes { get; set; }

        [ForeignKey("EventId")]
        public int EventId { get; set; }
        public Event Event { get; set; }

        [ForeignKey("ComedianId")]
        public int ComedianId { get; set; }
        public Comedian Comedian { get; set; }
    }

public class Venue
    {
        public int VenueId { get; set; }
        public string VenueName { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string ZipCode { get; set; }
        public int Seating { get; set; }
        public bool ServesAlcohol { get; set; }
    }

I have the following record

Event
EventId	EventName		EventDate			VenueId
1	Funny Comedy Night	2019-05-19 00:00:00.0000000	1
4	Funny Comedy Night2	2019-05-19 00:00:00.0000000	1


Gig
GigId	GigHeadline		GigLengthInMinutes	EventId		ComedianId
1	Pavols Funny Show	60			1		1
2	Lifetime Of Fun	45	1			2


Venue
VenueId	VenueName	Street			City		State	ZipCode	Seating	 ServesAlcohol
1	Mohegan Sun	123 Main Street		Wilkes Barre	PA	18702	125	   1


Comedian
ComedianId	FirstName	LastName	ContactPhone
1		Pavol		Almasi		111-222-3333
2		Robin		Williams	444-555-6666

My code is given below

[HttpGet("{eventId:int}")]
        public async Task<ActionResult<EventDto>> GetEvent(int eventId, bool includeGigs = true)
        {
            try
            {
                var result = await _eventRepository.GetEvent(eventId, includeGigs);

                if (result == null) return NotFound();

                var mappedEntity = _mapper.Map<EventDto>(result);
                return Ok(mappedEntity);
            }
            catch (Exception)
            {
                return this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure");
            }
        }


Repo Sql  
public async Task<Event> GetEvent(int eventId, bool includeGigs = false) { _logger.LogInformation($"Getting event for event id {eventId}"); IQueryable<Event> query = _db.Events .Include(v => v.Venue); if (includeGigs) { query = query.Include(g => g.Gigs) .ThenInclude(c => c.Comedian); } query = query.Where(e => e.EventId == eventId); return await query.FirstOrDefaultAsync(); }
in Startup.cs
 public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped<IEventRepository, EventRepository>();

          
            services.AddControllers();

        }



Multiple routes and global attributes

$
0
0

hi guys

I am playing around with razor pages and building a new website with it.

  1. How do I add a global configuration to all the files in a folder e.g Pages >> Accounts folder (I know in webforms I could add this in the root web.config file or in MVC I could add the attribute to the root controller e.g the [Authorize] attribute and it would apply to all controller actions
  2. How do I add multiple routes to a page as I have Pages >> Admin  which I want to be either administrator or admin currently I am using @Pages "/Admin"

thanks

Ehi

Upload image .net core 3.1

$
0
0

Before code generated:

@page
@model pcore31.CreateModel

@{
    Layout = null;
}

<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Create</title></head><body><h4>Pet</h4><hr /><div class="row"><div class="col-md-4"><form method="post"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Pet.PetName" class="control-label"></label><input asp-for="Pet.PetName" class="form-control" /><span asp-validation-for="Pet.PetName" class="text-danger"></span></div><div class="form-group"><label asp-for="Pet.Dogpic" class="control-label"></label><input asp-for="Pet.Dogpic" class="form-control" /><span asp-validation-for="Pet.Dogpic" class="text-danger"></span></div><div class="form-group"><label asp-for="Pet.Odate" class="control-label"></label><input asp-for="Pet.Odate" class="form-control" /><span asp-validation-for="Pet.Odate" class="text-danger"></span></div><div class="form-group form-check"><label class="form-check-label"><input class="form-check-input" asp-for="Pet.Ocheck" /> @Html.DisplayNameFor(model => model.Pet.Ocheck)</label></div><div class="form-group"><input type="submit" value="Create" class="btn btn-primary" /></div></form></div></div><div><a asp-page="Index">Back to List</a></div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}</body></html>

After code

AFTER

@page
@model pcore31.CreateModel

@{
    Layout = null;
}

<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width" /><title>Create</title></head><body><h4>Pet</h4><hr /><div class="row"><div class="col-md-4"><form method="post"><div asp-validation-summary="ModelOnly" class="text-danger"></div><div class="form-group"><label asp-for="Pet.PetName" class="control-label"></label><input asp-for="Pet.PetName" class="form-control" /><span asp-validation-for="Pet.PetName" class="text-danger"></span></div><div class="form-group"><div class="form-group"><label asp-for="Pet.Dogpic" class="control-label"></label><div class="custom-file"><input asp-for="Pet.Dogpic" class="custom-file-input" id="customFile" type="file" width="100"><label class="custom-file-label" for="customFile">Choose file</label></div><span asp-validation-for="Pet.Dogpic" class="text-danger"></span></div></div>
<div class="form-group"><label asp-for="Pet.Odate" class="control-label"></label><input asp-for="Pet.Odate" class="form-control" /><span asp-validation-for="Pet.Odate" class="text-danger"></span></div><div class="form-group form-check"><label class="form-check-label"><input class="form-check-input" asp-for="Pet.Ocheck" /> @Html.DisplayNameFor(model => model.Pet.Ocheck)</label></div><div class="form-group"><input type="submit" value="Create" class="btn btn-primary" /></div></form></div></div><div><a asp-page="Index">Back to List</a></div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }</body></html>

I only added in:

<div class="form-group"><div class="form-group"><label asp-for="Pet.Dogpic" class="control-label"></label><div class="custom-file"><input asp-for="Pet.Dogpic" class="custom-file-input" id="customFile" type="file" width="100"><label class="custom-file-label" for="customFile">Choose file</label></div><span asp-validation-for="Pet.Dogpic" class="text-danger"></span></div></div>

For the dialog to upload an image.

All works to that point:

But in the model behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using pcore31.Models;

namespace pcore31
{
    public class CreateModel : PageModel
    {
        private readonly pcore31.Models.DatabaseContext _context;

        public CreateModel(pcore31.Models.DatabaseContext context)
        {
            _context = context;
        }

        public IActionResult OnGet()
        {
            return Page();
        }

        [BindProperty]
        public Pet Pet { get; set; }

        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }
             HOW DO I CALL UploadedFile
             AND HOW TO INCLUDE PICNAME IN THE
             SAVE OPERATION, SINCE INDIVIDUAL
             FIELDS AREN'T USED IN THE GENERATED
             CODE ??????
            _context.Pet.Add(Pet);
            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");
        }

        public string UploadedFile(Pet model)
        {
             What code goes here???
        }
        return picname;
    }
}

Images are stored at wwwroot\images\upload.

Please, I just want to upload an image, and save the name to db.  I already know how to display them.


Front end for .Net Core 3.1

$
0
0

I want to develop a big enterprise application in .Net core. what pattern should i follow for front & backend?

  1. .Net core with bootstrap+Jquery
  2. .Net core with Razor
  3. .Net core with Blazor
  4. .Net core with react/angular/vuejs
  5. anyother better solution?

I need experts suggestions with pros & cons

how do I update a Custom base controller

$
0
0

hi guys

As I said in my last post, I just moved to razor pages and tyring to get a hang of it.

In MVC I always inherit a base controller in all my controllers e.g. for admin accounts I have my custom configs. Now I am using razor pages, It seems I have to update every single page which is cumbersome. is there an easier way ? here is my code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Virtuals.Models.Department;
using Virtuals.Web.Classes;

namespace Virtuals.Web.Pages.Admin.CRUD
{
    public class DeleteModel : MyCustom_PageModel
    {
        private readonly Virtuals.Web.Classes.MyDbContext _context;

        public DeleteModel(Virtuals.Web.Classes.MyDbContext context)
        {
            _context = context;
        }

I want all admin pages to inherit a custom class e.g.

using Microsoft.AspNetCore.Mvc.RazorPages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace VirtualMarkets.Web.Classes
{
    public class MyCustom_PageModel : PageModel
    {
//add my custom config here

Owing to the fact that razor pages unline MVC has no central "God" object e.g controller, do I manually update all code behind ?

thanks

Ehi

Upload image or multiple using razor page only, no code behind

$
0
0

I know how to use sql server in razor, just quick example:

@page
@using System.Data.SqlClient

@using System.Collections.Generic;
@using System.Data;
@using System.Linq;
@using System.Threading.Tasks;


@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration

@{
    Layout = null;
}

@{

    var name = string.Empty;
    var submitset = string.Empty;
    if (Request.HasFormContentType)
    {
        name = Request.Form["name"];
        @if (string.IsNullOrEmpty(name))
        {
            name = "%";
        }
    }

    if (!string.IsNullOrEmpty(name))
    {
        var thisoffset = 0;
        var connectionString = Configuration.GetConnectionString("DefaultConnection");
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand("SELECT * FROM pets WHERE petname LIKE @lastname ORDER BY petname OFFSET " + thisoffset + " ROWS FETCH NEXT 5 ROWS ONLY", conn);

            cmd.Parameters.AddWithValue("@lastname", name + "%");

            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {

                var vpetid = @reader["petid"];<div>@reader["petname"]</div><div>@String.Format("{0:MM/dd/yyyy }", reader["odate"])</div>
                int vocheck = 0;
                var mybool = (reader.GetBoolean(reader.GetOrdinal("ocheck")));
                if (mybool == true)
                {
                    vocheck = 1;
                }<div>@vocheck</div><br /><div><a href="editpet?id=@vpetid">test</a></div>




            }


        }
    }
    else
    {
        <form method="post"><div>Name: <input name="name" /></div><div><input type="submit" name="submit" /></div></form>
    }
}

But my question, using sql server and razor only, how to do image uploads?

Meaning have one page to add data, and post to another a razor page and perform upload and save operation.  No "model" code behind.

Just razor only.

Restful API and Async API

$
0
0

Hi

Please can you advise me  what is the difference between Restful API and Async API. What is the best choice  for an application. I am confused what should I use in a project  either Restful API or Async API

Please can you advise me

Null Exception Issue When Working with Jwt Token

$
0
0

Hello Microsoft Team,

When i try to login by username and password. 

null exception error occur when controller hit opt.TokenValidationParameters = new TokenValidationParameters() which is available in startup.cs .

 opt.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };

Errors is

Exception has occurred: CLR/System.ArgumentNullException
An exception of type 'System.ArgumentNullException' occurred in System.Private.CoreLib.dll but was not handled in user code: 'String reference not set to an instance of a String.'
   at System.Text.Encoding.GetBytes(String s)
   at CI.API.Startup.<ConfigureServices>b__4_4(JwtBearerOptions opt) in D:\MyProject\CI.API\Startup.cs:line 67
   at Microsoft.Extensions.Options.ConfigureNamedOptions`1.Configure(String name, TOptions options)
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
   at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass11_0.<Get>b__0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)

In startup.cs

 services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(opt =>
            {
                opt.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII
                    .GetBytes(Configuration.GetSection("AppSettings:Token").Value)),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });

In appsettings.json

"AppSettings":{"Token":"hey i am here"
  }

AuthController 

      [HttpPost("login")]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            var user = await _userManager.FindByNameAsync(model.UserName);
            var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
            if (!result.Succeeded)
            {
                return BadRequest(result);
            }

            return Ok(new
            {
                result = result,
                token = await JwtTokenGenerator(user)
            });

        }




        public async Task<string> JwtTokenGenerator(User userInfo)
        {
            var claims = new List<Claim>
            {
            new Claim(ClaimTypes.NameIdentifier,userInfo.Id),
            new Claim(ClaimTypes.Name,userInfo.UserName)
          };

            var roles = await _userManager.GetRolesAsync(userInfo);
            foreach (var role in roles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role));
            }

            var securityKey = new SymmetricSecurityKey(Encoding.ASCII
            .GetBytes(_config.GetSection("AppSettings:Token").Value));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(claims),
                Expires = DateTime.Now.AddDays(1),
                SigningCredentials = credentials
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);


        }

Identity Framework vs. Identity Server

$
0
0

Hello everyone and thanks for your help in advance.  I am new to .Core and in the premilitary stages of migrating an intranet along with some external facing api services.  My first task is reading up on security and trying to make sure I have a grasp on how things work.  First, is it generally best practices to separate any type of MVC web application from any api function?  I have always done this in the past, but don't really see anything explicitly stating this other than the MVC app would work on the Identity framework and the api would be secured by Identity Server 4.  I have read the documents https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-3.1&tabs=visual-studio and https://auth0.com/blog/how-to-build-and-secure-web-apis-with-aspnet-core-3/ as well as the corresponding Microsoft doc, but wanted to make sure I understood basic concepts.  Any insight would be appreciated. 

Problem with Session when getting string data to the action of controller

$
0
0

Hi guys,

As some of you knows, I'm developing a quiz application. I have timer in question view and this time I need to get the time between opening the question view and submitting the answer. Then I substruct that interval from 60 in order to get remained seconds which will be the point of the question if the answer is right.  Here is the details:

View

@model Intellect.Models.ViewModels.AdminViewModel<div class="questioncontainer">        <form asp-action="Question" asp-controller="Home" asp-route-id="@Model.NextQuestion.Id" asp-route-count="@ViewBag.Equestions"><div class="row"><div class="col-lg-3"></div><div class="col-lg-6 col-sm-12"><table><tr><th>Qaliq vaxt</th></tr><tr><td><div id="time"></div> </td></tr></table><div class="question">@Model.CurrentQuestion.Description </div></div><div class="col-lg-3"></div></div><div class="row"><div class="col-lg-3 col-sm-0"></div>
                @{
                    int n = 0;
                }
                @foreach (Answer item in Model.Answers)
                {
                    if (n == 0 || n == 2)
                    {
                        @: <div class="col-lg-3 col-sm-12">
                            @: <div class="firstpart">
                            }<input asp-for="@item.Id" name="@item.Id" hidden /><input type="radio" asp-for="@item.Id" name="myanswer" value="@item.Id" />@item.Description<br>
                            if (n == 1 || n == 3)
                            {
                            @:</div>
                        @:</div>
                    }

                    n++;
                }<div class="col-lg-3"></div></div><div class="row"><div class="col-lg-6 col-sm-4"></div><div class="col-lg-3 col-sm-4"></div><div class="col-lg-3 col-sm-4"><div class="nextbtn">
                        @if (ViewBag.Equestions == 0)
                        {<input type="submit" value="Finish" />
                        }
                        else
                        {<input type="submit" value="Next" />
                        }</div></div></div></form></div>

@section Script{ 
    <script>
        function StartTimer(seconds) {
            var intSeconds = seconds;
            var timer = setInterval(myTimer, 1000);
            function myTimer() {
                if (intSeconds < 0) {
                    Alert("bitdi")
                    clearInterval(timer)
                    return;
                }
                document.getElementById("time").innerText = intSeconds;
                intSeconds--;
            }
        }
        StartTimer(60);</script>
}

Controller

 public class HomeController : Controller
    {
        private readonly IntellectDbContext _intellectDbContext;
        private readonly UserManager<ExamUser> _userManager;
        private readonly SignInManager<ExamUser> _signInManager;
        static int exam_id = 0;
        static int? PreviousId = 0;
        static int result = 0;
        static int correctAnswer = 0;
        static List<Question> RemainedQuestions = new List<Question>();
        static List<int> trueAnswers = new List<int>();

        public HomeController(IntellectDbContext intellectDbContext, UserManager<ExamUser> userManager, SignInManager<ExamUser> signInManager)
        {
            _intellectDbContext = intellectDbContext;
            _userManager = userManager;
            _signInManager = signInManager;
        }
        [HttpGet]
        public async Task<IActionResult> Test(int Id)
        {
            exam_id = Id;
            AdminViewModel admodel = new AdminViewModel();
            admodel.Equestions = await _intellectDbContext.Questions.Include(q => q.Answers).Where(q => q.ExamId == Id).ToListAsync();
            admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(q => q.ExamId == Id).FirstOrDefaultAsync();
            RemainedQuestions = admodel.Equestions;
            PreviousId = admodel.CurrentQuestion.Id;
            return View(admodel);
        }


        [HttpGet]
        public async Task<IActionResult> Question(int Id, int count)
        {
            AdminViewModel admodel = new AdminViewModel();
            admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(x => x.Id == Id).SingleOrDefaultAsync();
            admodel.Answers = await _intellectDbContext.Answers.Where(y => y.QuestionId == Id).ToListAsync();
            admodel.Equestions = await _intellectDbContext.Questions.Where(q => q.ExamId == exam_id).ToListAsync();

            // admodel.CurrentQuestion.Remainedtime = new TimeSpan(0, 0, 60);
            HttpContext.Session.SetString("currentQuestion_" + admodel.CurrentQuestion.Id, DateTime.Now.ToString());


            if (count > 1)
            {
                var question = RemainedQuestions.Single(r => r.Id == admodel.CurrentQuestion.Id);
                PreviousId = question.Id;
                RemainedQuestions.Remove(question);
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }
            else
            {
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }

            if (count == -1)
            {
                return RedirectToAction(nameof(Finish));
            }

            ViewBag.Equestions = count;

            return View(admodel);
        }

        [HttpPost]
        public async Task<IActionResult> Question(int Id, int count, int myanswer)
        {
            AdminViewModel admodel = new AdminViewModel();
            admodel.CurrentQuestion = await _intellectDbContext.Questions.Where(x => x.Id == Id).SingleOrDefaultAsync();
            admodel.Answers = await _intellectDbContext.Answers.Where(y => y.QuestionId == Id).ToListAsync();
            admodel.Equestions = await _intellectDbContext.Questions.Where(q => q.ExamId == exam_id).ToListAsync();

            //  admodel.CurrentQuestion.Remainedtime = new TimeSpan(0, 0, 60);
           // HttpContext.Session.SetString("currentQuestion_" + admodel.CurrentQuestion.Id, DateTime.Now.ToString());
            var interval = DateTime.Now - DateTime.Parse(HttpContext.Session.GetString("currentQuestion_" + Id));

            correctAnswer = _intellectDbContext.Answers.Where(a => a.QuestionId == PreviousId && a.Correct == true).SingleOrDefault().Id;

            if (_signInManager.IsSignedIn(User))
            {
                ExamUser examTaker = await _userManager.GetUserAsync(HttpContext.User);

                examTaker.TestTaker = await _intellectDbContext.TestTakers
                                               .Include(tt => tt.UserQuestions) 
                                               .Where(t => t.Id == examTaker.TestTakerId) 
                                               .FirstOrDefaultAsync();
                admodel.CurrentQuestion = examTaker.TestTaker.UserQuestions.Select(u => u.Question).Where(x => x.Id == Id).SingleOrDefault();
                if (myanswer == correctAnswer)
                {
                    admodel.CurrentQuestion.Score = 60 - (int)interval.TotalMilliseconds / 1000;
                    await _intellectDbContext.SaveChangesAsync();
                    // admodel.CurrentQuestion.Score = result;
                }
            }
                if (count > 1)
            {
                var question = RemainedQuestions.Single(r => r.Id == admodel.CurrentQuestion.Id);
                PreviousId = question.Id;
                RemainedQuestions.Remove(question);
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }
            else
            {
                admodel.NextQuestion = RemainedQuestions[0];
                count -= 1;
            }

            if(count == -1)
            {
                return RedirectToAction(nameof(Finish));
            }

            ViewBag.Equestions = count;

            return RedirectToAction(nameof(Question));
        }
     }

When I run the application, the following errors comes (refer to link) when clicking on Next to get to the next question view:  https://prnt.sc/s6y9vy

As you see, action (Question) in controller cannot get string data from session to parse it. 

The problem lies here:        var interval = DateTime.Now - DateTime.Parse(HttpContext.Session.GetString("currentQuestion_" + Id));

Please, assist in solving this issue. 


Inconsistent accesibility:parameter type; HomeControler(IRepositoryissue) is less accessible then method

$
0
0

HomeController.Homecontroller(Irepository<Issue>issue)

Hi, I don't understand why I am getting this error. Below is part of the home controller that I am using.  I have tried everything. I am using aspnetcore mvc 3.1.

using System;
using System.Collections.Generic;  (is not in dark print)
using System.Linq;
using System.Threading.Tasks; (is not in dark print)
using Bumples15.Models;
using Bumples15.Services;
using Bumples15.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering; (is not in dark print)

namespace Bumples15.Controllers
{
public class HomeController : Controller
{
private readonly IRepository<Issue> _issueRepo;

public HomeController(IRepository<Issue> issue)
{
_issueRepo = issue;
}

Thanks, Jen

Facing error 'Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException' when input control disabled!

$
0
0

Hi

my problem is that when i disable my input control as follow :

<div class="form-group"><label asp-for="OrderId" class="control-label"></label><input asp-for="OrderId" class="form-control" value="@ViewData["_orderID"]" disabled="disabled" /><span asp-validation-for="OrderId" class="text-danger"></span></div>

I'm facing this error during update :

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

But when i remove disable tag from my input element it works correctly!!!

What's the problem & how to solve it ?

Note : The given input field (OrderId) is primary key for my Orders table.

Thanks in advance

What does ASP.NET Core Identity provide that I cannot do with bare IdentityServer4?

$
0
0

Hi folks,

I'm looking into removing Azure B2C from a project of mine, for reasons relating to automation and such (which B2C is not yet very compatible with), but want to keep my auth work flows the same. So, I'm looking at ASP.NET Core Identity. Currently, we use B2C to secure our REST API server. We have a React SPA that redirects to B2C for tokens that we then use to access our REST API. I would be needing to implement a self-hosted replacement for B2C, basically. I see that my options appear to include ASP.NET Core Identity and IdentityServer4.

I'm a bit confused as to what each of these projects provide, though. It seems to me that they have a ton of overlap. For example, the official ASP.NET Core Identity documentation says to use IdentityServer4 if you're trying to secure a REST API. I even see that the official Visual Studio project templates use IdentityServer4 if you choose a Web Api project template and choose to enable single account authentication. But then on the IdentityServer4 documentation I see a section explaining how to then integrate IdentityServer4 back into ASP.NET Core Identity. This circular dependency / integration has me a bit confused.

So I come here for help with clarifying this ...

If I'm using IdentityServer4, why would I maybe want to use ASP.NET Core Identity? What does Identity provide on top of IdentityServer4?

As a beginner, the documentation has me very confused. Thanks!

Does ManualResetEventSlim signaling degrades performance?

$
0
0

I am using ManualResetEventSlim to have signaling mechanism in my application and It works great if requests/sec are 100. As I increase request/sec, it gets worse.

Example:

100 Requests/sec -> 90% transaction done in 250 ms and Throughput (Success request/sec) is 134.

150 Requests/sec -> 90% transaction done in 34067 ms and Throughput (Success request/sec) is 2.2.

I use ConcurrentDictionary as give below:

// <key, (responseString,ManualResetEventSlim) >privatestaticConcurrentDictionary<string,(string,ManualResetEventSlim)>EventsDict=newConcurrentDictionary<string,(string,ManualResetEventSlim)>();

Below given process describes need for ManualResetEventSlim:

  1. Api Solution 1 (REST Api) received a request, it added an element (null, ManualResetEventSlim) in ConcurrentDictionary against a key and called thirdparty service (SOAP) using async/await. Thirdparty soap api returned acknowledgement response but actual response is pending. After getting acknowledgement response, it goes to ManualResetEventSlim.wait

  2. Once thirdparty processed the request, it calls Api Solution 2 (SOAP) using exposed method and sends actual response. Api solution 2 sends response to Api Solution 1 (REST Api) by making http request and then inserts data to database for auditlog.

  3. Api Solution 1 will get key from response string and update response string in ConcurrentDictionary and set signal.

  4. Api Solution 1 disposes ManualResetEventSlim object before returning response to client.

Error de migracion al publicar

$
0
0

I have an error when I publish my project, in the dbcontext not show the the conection string for migration.

error_migration

Viewing all 9386 articles
Browse latest View live


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