โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Retrieve a value from a request with content type application/json

I have the following script that is sending data to a controller in MVC:

$.ajax({
    url: '/products/create',
    type: 'post',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({
        'name':'widget',
        'foo':'bar'
    })
});

My controller looks like this:

[HttpPost]
public ActionResult Create(Product product)
{
    return Json(new {success = true});
}

public class Product 
{ 
    public string name { get; set; }
}

Is there a way I can get the "foo" variable in my controller action without

  • modifying the model
  • modifying the signature of the action

If it was a regular form submission, I would have access to Request.Form["foo"], but this value is null since it was submitted via application/json.

I want to be able to access this value from an Action Filter and that is why I don't want to modify the signature/model.

Google Analytics API and .Net

Google announced the Analytics Data Export API some days ago, thereby making it much easier to get analytics data for a site. The API debuted with Java and JavaScript clients, but no direct .Net support (other than going straight for the XML). It seems the API is similar to the other Google Data APIs though, and there's a .Net client for those. Has anyone tried using the components in that library to get at the analytics data?

I'm in the process of building an ASP.Net MVC site and thought I'd use Google Analytics to generate "Most viewed" lists and stuff like that (since Google is probably better at weeding out spurious requests, robots, etc.). If you have any thoughts on that idea, I'd much appreciate hearing them too.

I represent many products in view but the return of all them in controller is the first product I use ASP.NET Core 6 MVC

I represent many projects correctly but It's return the same object in controller specifically the first item in database

In controller:

public IActionResult AddToBasket(ProductsModel products)
{
    if (AuthController.user != null)
    {
        using Data data = new Data();

        int id = data.products.Where(x => x.Name == products.Name && x.Price == products.Price && x.Discription == products.Discription).ToList()[0].Id;

        data.basket.Add(new BasketModel { Amount = products.Amount, AccountId = AuthController.user.Id, ProductId = id });
        data.SaveChanges();

        return RedirectToAction("Products");
    }
}

In the view, I have this markup:

<form method="post" asp-action="AddToBasket" asp-controller="Products" style="width:100%;">
    @foreach(ProductsModel pro in ViewBag.prod)
    {
        <div class="col-lg-4 col-sm-12" style="float:right;">
            <div class="beds_section active">
                <input readonly="readonly" class="bed_text" value="@pro.Name" style="border:none;" asp-for="Name">
                <div><img src="../@pro.Img" class="image_2"></div>
                <input type="submit" value="Add to Basket" style="float:right;" name="input"/> 
                <input type="number" placeholder="amount" asp-for="Amount" value="1" min="1" max="@pro.Amount" style="width:80px;float:right; width:80px;" /> 
                <span asp-validation-for="Amount" class="text-danger"></span>
                <input style="border:none; width:150px;" readonly="readonly" value="@pro.Price" asp-for="Price" />
                <br />
                <br />
                <input style="border:none; width:100%; height:100%;"  readonly="readonly" value="@pro.Discription" asp-for="Discription">
            </div> 
        </div>
}
</form>

It's seems all product share same asp-for.

How to solve it this first time I use stack overflow may my question isn't clear ๐Ÿ˜…

Table header shifting the right after clicking button

I have a table that works beautifullly but for some reason when I click on my testing button the table headers shift to the right. I tried using `style="position:fixed" and I tried taking out the thead in my table neither one worked. I can't find any other resources with my exact problem. Any help is appreciated.

LangInfo view:

@model OfficerLangVM

<body>
<div class="full-width">
    <h4>Language Information</h4>
    <table style="background-color:lightgray; width:75%" class="table table-boardered table-striped" cellpadding="5">
        <thead>
            <tr>
                <th>Language</th>
                <th>Fluency</th>
                <th>Read</th>
                <th>Write</th>
                <th>Speak</th>
                <th>Understand</th>
                <th>Date Modified</th>
                <th><!--Edit--></th>
                <th><!--Delete--></th>
            </tr>
        </thead>
        <tbody>
            <input type="hidden" asp-for="OfficerKey" />
            <input type="hidden" asp-for="AgGuid" />
            <input type="hidden" asp-for="LanguageKey"/>
            @{
                if (Model.Languages != null)
                {
                    int rownum = 0;
                    foreach (Language lang in Model.Languages)
                    {
                            <tr id="@rownum">
                                <td>@lang.LanguageName</td>
                                <td>@lang.Fluency</td>
                                @if (lang.CanRead == true)
                                {
                                    <td><input type="checkbox" checked="checked" /></td>
                                }
                                else
                                {
                                    <td><input type="checkbox" /></td>
                                }
                                @if (lang.CanWrite == true)
                                {
                                    <td><input type="checkbox" checked="checked" /></td>
                                }
                                else
                                {
                                    <td><input type="checkbox" /></td>
                                }
                                @if (lang.CanSpeak == true)
                                {
                                    <td><input type="checkbox" checked="checked" /></td>
                                }
                                else
                                {
                                    <td><input type="checkbox" /></td>
                                }
                                @if (lang.CanUnderstand == true)
                                {
                                    <td><input type="checkbox" checked="checked" /></td>
                                }
                                else
                                {
                                    <td><input type="checkbox" /></td>
                                }
                                    <td>@lang.DateUpdated</td>
                                    <td>
                                        <!--Testing to keep user on same view page, doesn't pull an info-->
                                        <input type="button" value="testing" onclick="show(@lang.LanguageKey); hide(@rownum)"/> 
                                    </td>
                                    <td>
                                        <!--This works just takes user to new view page-->
                                        <a asp-action="LanguageUpdate" asp-route-id="@lang.LanguageKey">Edit</a>
                                    </td>
                                    <td>
                                        <a asp-action="DeleteLang" asp-route-id="@lang.LanguageKey">Delete</a>
                                    </td>
                            </tr>
                            <tr style="display:none" id="@lang.LanguageKey">
                                @await Html.PartialAsync("LanguageUpdate", lang)
                            </tr>
                        rownum++;
                    }
                }
        }
        </tbody>
    </table>
</div>

<script type="text/javascript">
    function show(key) {
        document.getElementById(key).style.display = "block";
    }

    function hide(rownum) {
        document.getElementById(rownum).style.display = "none";
    }
</script>

<style>

    .body-container {
        /*remove the container default padding attribute*/
        /*padding-left: 0px !important;
                padding-right: 0px !important;*/
        /*increase width as per your need*/
        max-width: 100%;
    }
</style>

LanguageUpdate view that is called from testing button:

@model Language

<form asp-action="UpdateLang" method="post">
<input type="hidden" asp-for="OfficerKey" />
<input type="hidden" asp-for="AgGuid" />
<input type="hidden" asp-for="LanguageKey" />
@{
    if (Model != null)
    {
        <td>
            <select asp-for="LanguageName">
                <option Value=""> 1) Select a Language . . .</option>
                <option value="American Sign English (ASE)">American Sign English (ASE)</option>
                <option value="American Sign Language (ASL)">American Sign Language (ASL)</option>
                <option value="Arabic: Algerian">Arabic: Algerian</option>
                <option value="Arabic: Egyptian">Arabic: Egyptian</option>
                <option value="Awadhi">Awadhi</option>
                <option value="Azerbaijani">Azerbaijani</option>
                <option value="Bengali">Bengali</option>
                <option value="Bhojpuri">Bhojpuri</option>
                <option value="Chinese: Cantonese">Chinese: Cantonese</option>
                <option value="Chinese: Fukein">Chinese: Fukein</option>
                <option value="Chinese: Jinyu">Chinese: Jinyu</option>
                <option value="Chinese: Mandarin">Chinese: Mandarin</option>
                <option value="Chinese: Min Nan">Chinese: Min Nan</option>
                <option value="Chinese: Wu">Chinese: Wu</option>
                <option value="Creole">Creole</option>
                <option value="Creole-Jamaican">Creole-Jamaican</option>
                <option value="Czech">Czech</option>
                <option value="Dutch">Dutch</option>
                <option value="Esperanza">Esperanza</option>
                <option value="Estonian">Estonian</option>
                <option value="Farsi">Farsi</option>
                <option value="French">French</option>
                <option value="Gaelic">Gaelic</option>
                <option value="German">German</option>
                <option value="Greek">Greek</option>
                <option value="Hausa">Hausa</option>
                <option value="Hebrew">Hebrew</option>
                <option value="Hindi">Hindi</option>
                <option value="Hmong">Hmong</option>
                <option value="Hungarian">Hungarian</option>
                <option value="Icelandic">Icelandic</option>
                <option value="Italian">Italian</option>
                <option value="Japanese">Japanese</option>
                <option value="Kannada">Kannada</option>
                <option value="Korean">Korean</option>
                <option value="Lao">Lao</option>
                <option value="Latin">Latin</option>
                <option value="Maithili">Maithili</option>
                <option value="Marathi">Marathi</option>
                <option value="Malayalam">Malayalam</option>
                <option value="Native American: Blackfoot">Native American: Blackfoot</option>
                <option value="Native American: Cheyenne">Native American: Cheyenne</option>
                <option value="Native American: Chippewa">Native American: Chippewa</option>
                <option value="Native American: Cree">Native American: Cree</option>
                <option value="Native American: Dakota">Native American: Dakota</option>
                <option value="Native American: Lakota">Native American: Lakota</option>
                <option value="Native American: Lenape">Native American: Lenape</option>
                <option value="Native American: Navajo">Native American: Navajo</option>
                <option value="Native American: Ojibwi">Native American: Ojibwii</option>
                <option value="Native American: Oneida">Native American: Oneida</option>
                <option value="Native American: Onodaga">Native American: Onodaga</option>
                <option value="Native American: Paivte">Native American: Paivte</option>
                <option value="Native American: Shoshoni">Native American: Shoshoni</option>
                <option value="Native American: Sioux">Native American: Sioux</option>
                <option value="Niger-Congo: Akan">Niger-Congo: Akan</option>
                <option value="Niger-Congo: Twi">Niger-Congo: Twi</option>
                <option value="Norwegian">Norwegian</option>
                <option value="Oriya">Oriya</option>
                <option value="Panjabi">Panjabi</option>
                <option value="Patois">Patois</option>
                <option value="Polish">Polish</option>
                <option value="Portuguese">Portuguese</option>
                <option value="Romanian">Romanian</option>
                <option value="Russian">Russian</option>
                <option value="Serbian">Serbian</option>
                <option value="Serbo-croatian">Serbo-croatian</option>
                <option value="Sign Language">Sign Language</option>
                <option value="Sindhi">Sindhi</option>
                <option value="Slovaic(Slovak)">Slovaic(Slovak</option>
                <option value="Spanish">Spanish</option>
                <option value="Sunda">Sunda</option>
                <option value="Swedish">Swedish</option>
                <option value="Tagalog">Tagalog</option>
                <option value="Tamil">Tamil</option>
                <option value="Telugu">Telugu</option>
                <option value="Thai">Thai</option>
                <option value="Turkish">Turkish</option>
                <option value="Ukrainian">Ukrainian</option>
                <option value="Urdu">Urdu</option>
                <option value="Vietnamese">Vietnamese</option>
            </select>
        </td>
        <td>
            <select asp-for="Fluency">
                <option value="1) Limited Proficiency">1. Limited Proficiency</option>
                <option value="2) Novice">2. Novice</option>
                <option value="3) Intermediate">3. Intermediate</option>
                <option value="4) Advanced">4. Advanced</option>
                <option value="5) Native Speaker">5. Native Speaker</option>
            </select>
        </td>
        @if (Model.CanRead == true)
        {
            <td>
                @Html.CheckBoxFor((modelItem => Model.CanRead))
            </td>
        }
        else
        {
            <td>
                @Html.CheckBoxFor((modelItem => Model.CanRead))
            </td>
       }
       @if (Model.CanWrite == true)
       {
            <td>
                @Html.CheckBoxFor((modelItem => Model.CanWrite))
            </td>
       }
       else
       {
           <td>
               @Html.CheckBoxFor((modelItem => Model.CanWrite))
           </td>
       }
       @if (Model.CanSpeak == true)
       {
            <td>
                @Html.CheckBoxFor((modelItem => Model.CanSpeak))
            </td>
       }
       else
       {
            <td>@Html.CheckBoxFor((modelItem => Model.CanSpeak))</td>
       }
       @if (Model.CanUnderstand == true)
       {
            <td>
                @Html.CheckBoxFor((modelItem => Model.CanUnderstand))
            </td>
       }
       else
       {
            <td>@Html.CheckBoxFor((modelItem => Model.CanUnderstand))</td>
       }
       <td>@Model.DateUpdated</td>
       <td>
            <input type="submit" value="Update" class="btn btn-primary" style="background-color:lightgray; color:black" />
       </td>
       <td>
            <input type="submit" value="Delete" class="btn btn-primary" style="background-color:lightgray; color:black" asp-action="DeleteLang" asp-route-id="@Model.LanguageKey" />
       </td>
       <td>
            <input type="submit" class="btn btn-primary" asp-action="Editing" asp-route-id="@Model.OfficerKey" value="Cancel" style="background-color:lightgray; color:black" />
       </td>
    }
}    

Controller:

public IActionResult LanguageUpdate (int id)
{
  Language lang = getLanguage(id);

  return View(lang);
}

[HttpPost]
public IActionResult UpdateLang(Language UpdateLang)
{
  MailkitErrors errors = new(ServiceProvider!, Configuration!);

  UserEmail = HttpContext.Session.GetString("UserEmail")!;

  string ConnectionString = connectionStrings.Get("ForeignLanguageConnectString");

  var objLangUpdateConnect = new SqlConnection(ConnectionString);
  var objLangUdDataSet = new DataSet();
  string strLangUpdate = "UpdateLanguage";
  try
  {
    var objCommandlang = new SqlCommand(strLangUpdate, objLangUpdateConnect);
    objCommandlang.CommandType = CommandType.StoredProcedure;

    //Add parameters for input
    objCommandlang.Parameters.AddWithValue("@RowCount", 1);
    objCommandlang.Parameters.AddWithValue("@OfficerKey", UpdateLang.OfficerKey);
    objCommandlang.Parameters.AddWithValue("@LanguageKey", UpdateLang.LanguageKey);
    objCommandlang.Parameters.AddWithValue("@LanguageName", UpdateLang.LanguageName);
    objCommandlang.Parameters.AddWithValue("@Fluency", UpdateLang.Fluency);
    objCommandlang.Parameters.AddWithValue("@CanRead", UpdateLang.CanRead);
    objCommandlang.Parameters.AddWithValue("@CanWrite", UpdateLang.CanWrite);
    objCommandlang.Parameters.AddWithValue("@CanSpeak", UpdateLang.CanSpeak);
    objCommandlang.Parameters.AddWithValue("@CanUnderstand", UpdateLang.CanUnderstand);
    objCommandlang.Parameters.Add("@UserUpdated", SqlDbType.VarChar, 150).Value = "";

    var ObjDataAdapterLang = new SqlDataAdapter(objCommandlang);
    ObjDataAdapterLang.Fill(objLangUdDataSet, "Language"); //FLIPV2 dbo.Language Table
}
catch (Exception)
{
    ViewBag.ErrorMessage = "There has been an error. MAGLOCLEN HelpDesk has been notified.";
    errors.ErrorEmails(UserEmail, "Error occured while updating language for selected officer:\n");
}

UpdateLang.Officer = getOfficer(UpdateLang.OfficerKey);
UpdateLang.syncOfficer();
return RedirectToAction("Editing", new { id = UpdateLang.OfficerKey });

}

Using Jwt and cookies together for authentication

I have managed to create the jwt token, but I am not sure where should I store it. I have seen many online websites talking about storing the jwt token in the cookie, but I not sure if it is the right approach as I thought normally the jwt token should be stored in the header inside the authorization parameter. I have the below code in AccountController to use cookies, but I am not sure how to include the jwt token inside.

if (login.Password.Equals(passwordCheck) && login.Username.Equals(adminCheck))
{
    var claims = new List<Claim>
    {
        new Claim("Role", "Admin")
    };

    var claimsIdentity = new ClaimsIdentity(
        claims, CookieAuthenticationDefaults.AuthenticationScheme);

    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity));

    return RedirectToAction("Index", "User");
}

and I have the below code in Program.cs to add cookie and jwt, and according to some online article about using both jwt and cookie:

builder.Services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
{
    options.LoginPath = "/Account/Login";
    options.AccessDeniedPath = "/Account/AccessDenied";
    options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
})
.AddJwtBearer(x =>
{
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true,
        ValidIssuer = builder.Configuration.GetValue<string>("JwtSettings:Issuer"),
        ValidateAudience = true,
        ValidAudience = builder.Configuration.GetValue<string>("JwtSettings:Audience"),
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(builder.Configuration.GetValue<string>("JwtSettings:SecretKey"))),
        ValidateLifetime = true,
        ClockSkew = TimeSpan.FromSeconds(300),
        RequireExpirationTime = true
    };
});

Using ASP.NET MVC, I have multiple actions in the controller that has Http Request such as (and I am not sure if I should use ValidateAntiForgeryToken instead of jwt token):

[HttpGet]
public async Task<string> GetActivationCode(string id)
{
    var actCode = (await _productService.GetProduct(id)).ActivationCode;
    return actCode;
}

but I am not sure how to use jwt token to authenticate for these ajax calls from the views:

$.ajax({
    url: '/Product/GetActivationCode',
    type: 'GET',
    data: {
        id: id
    },
    success: function (response) {
        $("#actCodeText").text("Activation Code: " + response);
    },
    error: function (xhr, status, error) {
        console.error(error);
    }
});

Your help is greatly appreciated. Thanks :)

I tried referring to multiple online articles such as this: Combining cookie and jwt authentication, but I keep getting this error: SignInAsync when principal.Identity.IsAuthenticated is false is not allowed when AuthenticationOptions.RequireAuthenticatedSignIn is true.

How to handle CrudRepository exceptions with showing error message on page from where the form was submitted?

The function below handles form submission to change a user data in the database (save, delete):

@PostMapping(consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String manageUser(@RequestBody MultiValueMap<String, String> formData, HttpServletRequest request) {
    Long userId = Long.valueOf(formData.getFirst("userId"));
    Long id = Long.valueOf(formData.getFirst("id"));
    String username = formData.getFirst("username");
    String password = formData.getFirst("password");
    User changedUserData = new User(id, username, password);
    List<Role> roles = Arrays.stream(formData.getFirst("roles").split(","))
            .map(roleName -> new Role(0L, changedUserData, roleName))
            .collect(Collectors.toList());
    changedUserData.setRoles(roles);
    String actionName = formData.getFirst(ACTION_SAVE) != null ? ACTION_SAVE : ACTION_DELETE;
    if (ACTION_SAVE.equals(actionName)) {
        userRepository.save(changedUserData);
    } else if (ACTION_DELETE.equals(actionName)) {
        userRepository.deleteById(userId);
    }
    return "redirect:" + request.getHeader("referer");
}

I use userRepository.save(changedUserData). This function doesn't throw any excpetions to find out whether there are any errors or not. I have read something about Spring's "exception translating mechanism" but I don't know how to apply it in my situation.

I want that when an exception was thrown the error message is displayed on the page from where the form was submitted (passing as model attributes to Thymeleaf or redirecting with flash attributes).

Read Asp.Net Core Response body in ActionFilterAttribute

I'm using ASP.NET Core as a REST API Service. I need access to request and response in ActionFilter. Actually, I found the request in OnActionExcecuted but I can't read the response result.

I'm trying to return value as follow:

[HttpGet]
[ProducesResponseType(typeof(ResponseType), (int)HttpStatusCode.OK)]
[Route("[action]")]
public async Task<IActionResult> Get(CancellationToken cancellationToken)
{
    var model = await _responseServices.Get(cancellationToken);
    return Ok(model);
}

And in ActionFilter OnExcecuted method as follow:

_request = context.HttpContext.Request.ReadAsString().Result;
_response = context.HttpContext.Response.ReadAsString().Result; //?

I'm trying to get the response in ReadAsString as an Extension method as follow:

public static async Task<string> ReadAsString(this HttpResponse response)
{
     var initialBody = response.Body;
     var buffer = new byte[Convert.ToInt32(response.ContentLength)];
     await response.Body.ReadAsync(buffer, 0, buffer.Length);
     var body = Encoding.UTF8.GetString(buffer);
     response.Body = initialBody;
     return body;
 }

But, there is no result!

How I can get the response in OnActionExcecuted?

How to get current model in action filter

I have a generic action filter, and I want to get current model in the OnActionExecuting method. My current implementation is like below:

public class CommandFilter<T> : IActionFilter where T : class, new()
{
    public void OnActionExecuting(ActionExecutingContext actionContext)
    {
        var model= (T)actionContext.ActionArguments["model"];
    }
}

It works well if my all model names are same. But i want to use differnet model names.

How to solve this problem?

public class HomeController : Controller
{
    [ServiceFilter(typeof(CommandActionFilter<CreateInput>))]
    public IActionResult Create([FromBody]CreateInput model)
    {
        return new OkResult();
    }
}

Validation failed for query for method public abstract util.List

I am new to Spring Data JPA, so I am having a trouble writing queries. I want to get all actors that had role in a certain movie that I get from movieID.

When trying this, I get error while trying to start :

Validation failed for query for method public abstract java.util.List

@Repository
public interface RoleRepository extends JpaRepository<RoleEntity, Long> {

    @Query(value = "select distinct r.actor from RoleEntity r " +
            "where r.movie.movieID = ?1")
    List<ActorEntity> findByMovieID(Long movieID);

}

Here are my entities:

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Entity(name = "roles")
public class RoleEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long roleID;

    @ManyToOne
    @NotNull
    @JoinColumn(name = "actor_id", referencedColumnName = "id")
    private ActorEntity actor;

    @ManyToOne(fetch = FetchType.LAZY)
    @NotNull
    @JoinColumn(name = "movie_id", referencedColumnName = "id")
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private MovieEntity movie;

    private String roleName;

}
@Entity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Table(name="actor")
public class ActorEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long actorID;

    @NotEmpty
    private String firstName;

    @NotEmpty
    private String lastName;

    @Enumerated(EnumType.STRING)
    private Gender gender;

    @OneToMany(mappedBy = "actor", cascade = CascadeType.ALL)
    @JsonBackReference
    private Set<RoleEntity> roles = new HashSet<>();

}




@Getter
@Setter
@ToString
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "movie")
public class MovieEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private Long movieID;

    @NotEmpty
    private String name;

    @NotEmpty
    private String description;

    @NotEmpty
    private String duration;

    @NotNull
    private LocalDate startTime;

    private LocalDate endTime;

    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
    private Set<RoleEntity> roles = new HashSet<>();

    @OneToMany(mappedBy = "movie", cascade = CascadeType.ALL)
    private Set<ProjectEntity> projects = new HashSet<>();

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "movie_genres",
            joinColumns = @JoinColumn(name = "movie_id"),
            inverseJoinColumns = @JoinColumn(name = "genre_id"))
    private Set<GenreEntity> genres;

}

I tried using native query, but it says it returns Long?!

@Query(value = "select a.id, a.first_name, a.last_name, a.gender " +
        "from actor a " +
        "join roles r on r.actor_id = a.id " +
        "where r.movie_id = ?1", nativeQuery = true)
List<ActorEntity> findByMovieID(Long movieID);

Thank you very much in advance!!! :D

Unexplained automatic data insert into SQL Server database

I have created a form to collect data from students who are registering. However, I am encountering an issue where the data is automatically inserting into the SQL Server database, even though I have disabled the button that sends the data to the controller for processing and insert into the database.

I'm unsure why this automatic insert is happening and would appreciate if someone could take a look at it. Additionally, this error arises unexpectedly. My program was functioning properly, but suddenly, between 100 to 300 entries are being inserted into the database without any apparent reason. While registration continues to work as expected, this issue is frustrating and baffling.

enter image description here

[HttpPost]
public ActionResult SubmitRegistration(Tbl_Registration Registration, HttpPostedFileBase Picture, HttpPostedFileBase B_Form, HttpPostedFileBase B_Certificate, HttpPostedFileBase P_Report)
{
    try
    {
        if (activeAcademicID.HasValue)
        {
            Tbl_Registration newRecord = new Tbl_Registration
                    {
                        Registration_ID = Registration.Registration_ID,
                        Class_ID = Registration.Class_ID,
                        Academic_ID = activeAcademicID.Value,
                
                        Picture = Path.GetFileName(picturePath),
                        Picture_Path = Path.Combine("Applicant_Photo", Path.GetFileName(picturePath)),
                        B_Certificate = Path.GetFileName(bCertificatePath),
                        B_Certificate_Path = Path.Combine("Birth_Certificate", Path.GetFileName(bCertificatePath)),
                        B_Form = Path.GetFileName(bFormPath),
                        B_Form_Path = Path.Combine("Bay_Form", Path.GetFileName(bFormPath)),
                        P_Report = Path.GetFileName(pReportPath),
                        P_Report_Path = Path.Combine("Progress_Report", Path.GetFileName(pReportPath)),

                        Is_Active = true,
                        Created_On = DateTime.Now,
                    };

            int selectedClassID;

            if (int.TryParse(Request.Form["Class_ID"], out selectedClassID))
            {
                newRecord.Class_ID = selectedClassID;
            }

            dbContext.Tbl_Registration.Add(newRecord);
            dbContext.SaveChanges();

            string fatherName = Registration.Father_Name;
            string selectedClassName = dbContext.Tbl_Class
                        .Where(c => c.Class_ID == selectedClassID)
                        .Select(c => c.Class_Name)
                        .FirstOrDefault();

            string childName = Registration.NameOfApplicant;
            string subject = string.Format("Congratulations, {0}! Registration Successful", fatherName);
            string body = GenerateEmailBody(childName, fatherName, selectedClassName);
            string fatherEmail = Registration.Father_Email;

            SendEmail(fatherEmail, subject, body, Registration.NameOfApplicant, selectedClassName, formattedRegistrationNo, newRecord);

            TempData["SuccessMessage"] = "Data saved successfully.";

            return RedirectToAction("Index", "Frontend");
        }
        else
        {
            return RedirectToAction("Index");
        }
    }
    catch (DbUpdateException ex)
    {
        TempData["SaveErrorMessage"] = "Failed to save - please try again later." + ex;
        return View("Index");
    }
    catch (System.Data.Entity.Validation.DbEntityValidationException ex)
    {
        string propertyErrorDetails = "";

        foreach (var validationErrors in ex.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                System.Diagnostics.Debug.WriteLine($"Property: {validationError.PropertyName} Error: {validationError.ErrorMessage}");
                propertyErrorDetails += $"Property: {validationError.PropertyName} Error: {validationError.ErrorMessage}<br/>";
            }
        }

        SendErrorEmail(Registration.NameOfApplicant, propertyErrorDetails);

        TempData["SaveErrorMessage"] = "Failed to save - please try again later.";

        return View("Index");
    }
}

ASP.NET Core 8 MVC web app : scaffolding not working as expected

I'm migrating a project from ASP.NET Core 3.1 to ASP.NET Core 8.0. I created a new project (targeting .NET 8) and copied the folders, classes, model, controller and view files into the new project folder.

When compiling the new project, I get errors on all views. An example of one of the errors is:

The type or namespace name 'Models' does not exist in the namespace 'Samadhi.Pages.Samadhi' (are you missing an assembly reference?).

D:\PROJECTS_VS\MyWebsite_2024\Samadhi\Microsoft.CodeAnalysis.Razor.Compiler.SourceGenerators\Microsoft.NET.Sdk.Razor.SourceGenerators.RazorSourceGenerator\Views_Rbk_VideoFiles_cshtml.g.cs

I tried basic things like Clean, Build, Rebuilds, etc. but that did nothing.

https://www.reddit.com/r/dotnet/comments/14zd7zp/brand_new_default_aspnet_core_mvc_8_project/

I tried the steps shown in the link above - a post that sounded like a similar issue - however, this had no effect.

The steps in the above post were:

  1. Install the Nuget Package Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation
  2. In Program.cs append builder.Services.AddControllersWithViews() with .AddRazorRuntimeCompilation()

Can anyone shed some light on what is causing this problem?

Project file

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="Samadhi\" />
    <Folder Include="Views\Shared\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="DeviceDetector.NET" Version="6.3.3" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="QRCoder" Version="1.4.3" />
    <PackageReference Include="Stripe.net" Version="43.22.0" />
  </ItemGroup>

</Project>

Project explorer

enter image description here

Error list

enter image description here

React Preamble error when trying to serve files through Vite dev server to ASP.NET Project

I'm trying to set up an ASP.NET MVC application with a ClientApp that uses React with Vite as the bundler. This is meant to be an MPA instead of a SPA, so there will be a separate .tsx file for each page of my application (i.e. home.tsx, about.tsx, etc.)

During development, the ClientApp files should be served by the Vite development server to my ASP.NET app for HMR, while in production the app will use the bundled files within wwwroot/dist.

I've attempted to set up my Program.cs to communicate with the Vite development server using the Vite.AspNetCore package.

Program.cs:

using Vite.AspNetCore.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddViteServices(options =>
{
    options.PackageDirectory = "ClientApp"; // Set the root path to the ClientApp folder
});

builder.Services.AddControllersWithViews();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
else
{
    app.UseViteDevelopmentServer();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

In order to read from the Vite development server, I've added the following block to my _Layout.cshtml file that will be shared by all my views:

<environment include="Development">
    <script type="module" src="https://localhost:5173/@@vite/client"></script>
    <link rel="stylesheet" href="https://localhost:5173/src/theme/site.css" />
    @if (ViewData["ViteScript"] != null)
    {
        <script defer type="module" src="@($"https://localhost:5173/src/pages/{ViewData["ViteScript"]}/index.tsx")"></script>
    }
</environment>

In other words, I'm trying to read the site.css file from ClientApp/src/theme/site.css, and the index.tsx file that's associated with the particular page I'm on, like ClientApp/src/pages/home/index.tsx. The name of the page (like "home") is stored in the ViewData["ViteScript"] at the top of the Razer view.

So I run my Vite development server on port 5173 and then I run my ASP.NET app, but I'm met with the generic message:

"Uncaught Error: @vitejs/plugin-react can't detect preamble. Something is wrong."

For reference, here is my vite.config.ts file:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import mkcert from "vite-plugin-mkcert";
import appsettings from "../appsettings.json";
import appsettingsDev from "../appsettings.Development.json";

const cssPattern = /\.css$/;
const imagePattern = /\.(png|jpe?g|gif|svg|webp|avif)$/;

export default defineConfig({
  plugins: [react(), mkcert()],
  build: {
    manifest: appsettings.Vite.Manifest,
    outDir: "../wwwroot/dist",
    emptyOutDir: true,
    rollupOptions: {
      input: {
        home: "./src/pages/home/index.tsx",
        site: "./src/site.ts",
        styles: "./src/theme/site.css",
      },
      output: {
        entryFileNames: "js/[name].js",
        chunkFileNames: "js/[name]-chunk.js",
        assetFileNames: (info) => {
          if (info.name) {
            if (cssPattern.test(info.name)) {
              return "css/[name][extname]";
            }
            if (imagePattern.test(info.name)) {
              return "images/[name][extname]";
            }

            return "assets/[name][extname]";
          } else {
            return "[name][extname]";
          }
        },
      },
    },
  },
  server: {
    port: appsettingsDev.Vite.Server.Port,
    strictPort: true,
    hmr: {
      host: "localhost",
      clientPort: appsettingsDev.Vite.Server.Port,
    },
  },
});

When I check the Sources tab of the Chrome Developer Tools, I see the ASP.NET app running on localhost:44380 and the Vite dev server running on localhost:5173 (and its files like ExampleComponent.tsx and pages/home/index.tsx.

Sources tab

Here's a screenshot of my ClientApp within the Solution Explorer:

ClientApp folder

If anyone has experienced a similar issue when trying to integrate the Vite development server into an MPA, I'd appreciate your help.

Thanks!

QueryString is empty during MVC form post

Note: the answer may be in either VB.NET or C#. I have no preference for this Q&A.

I'm following this example to build a simple ASP.NET 8 MVC application that uses cookie authentication. I'm running into a problem where the query string on the URL isn't being sent to the controller. The value for Request.QueryString is an empty string.

Here's my URL:

https://localhost:55387/Account/SignIn?ReturnUrl=%2FContacts

Here's my controller:

Public Class AccountController
  <HttpPost>
  Public Async Function SignInAsync(Setting As Setting) As Task(Of IActionResult)
    Dim ReturnUrl As String = Me.Request.Query("ReturnUrl")

    ' etc.
  End Function
End Class

...and here's my view:

@model Db.Models.Setting

@{
  ViewData["Title"] = "Sign In";
}

<h1>Sign In</h1>
<h4>Enter the site PIN</h4>
<hr />
<div class="row">
  <div class="col-md-4">
    <form asp-action="SignIn">
      <div asp-validation-summary="ModelOnly" class="text-danger"></div>

      <div class="form-group col-5">
        <label asp-for="AuthPin" class="control-label"></label>
        <input id="authPin" asp-for="AuthPin" class="form-control" />
        <span asp-validation-for="AuthPin" class="text-danger"></span>
      </div>

      <div class="form-group">
        <input id="signInButton" type="submit" class="btn btn-primary" value="Sign In" disabled />
      </div>
    </form>
  </div>
</div>

The trouble is that the example is for a Razor Pages application. Mine is MVC. In the example, this works just fine:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
  this.ReturnUrl = returnUrl;
}

Here, the returnURL variable is populated as expected. But in MVC we don't have an OnPostAsync function. I'm handling everything in the controller action. And the action isn't picking up the query string for some reason.

There's this answer, but in my case there is no Url property on the Request instance. There is a Path property, but its value doesn't contain a query string (/Account/SignIn).

There's also this answer, but adding a ReturnUrl parameter on the SignIn post action didn't help.

How can I get my controller/action to collect the query string on form POST?

Unable to resolve service for dbContext

To obtain an ASP.NET Core MVC web site, after a crash, I follow the indications of this thread again.

I installed the Visual Studio extension, I inserted the four Entity Framework Core references, I typed dotnet ef database update and so on according to this thread, after replacing the name of the DbContext by the correct value.

And I read the answer, with the errors on white background when any.

(is there anything I have to search in the solution, to verify this step is executed correctly ?)

And now, I am taking care of "unable to resolve service on dbContext" error in what follows, and given the number of different tries I made, it seems it could help that somebody can point out that error more precisely, before I am able to write a concise synthesis. After that I shall take care of storing the connection string in a more confidential place, but first getting the data on the web page could be an interesting step.

As you understand, I could create an orders controller, but when I try to display its Index page, I obtain the error

"InvalidOperationException: Unable to resolve service for type 'MVCcumul_01.Models.NorthwindContext' while attempting to activate 'MVCcumul_01.Controllers.OrdersController'. Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ThrowHelperUnableToResolveService(Type type, Type requiredBy)

I verified the connection string (that error appeared in a past try). Data appears properly from the servers explorer in Visual Studio 2022 Community, and/or from SSMS 19.1, on Windows 11 Version 23H2 (OS build 22631.3296)

I first forgot about declaring AddDbContextFactory in ConfigureServices, then declared both it and NorthwindContext as singleton, then both as scoped (that should have both worked), then mixed (that was not supposed to work, or perhaps I mixed up, but not to ... waste the travel).

Here is the code:

Startup.cs:

using Microsoft.EntityFrameworkCore;
using MVCcumul_01.Models;

namespace MVCcumul_01
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString = @"Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Encrypt=True;TrustServerยฒCertificate=True";

            services.AddDbContext<NorthwindContext>(options => options.UseSqlServer(connectionString),
                ServiceLifetime.Singleton);

            services.AddDbContextFactory<NorthwindContext>(
               options => options.UseSqlServer(),
                lifetime: ServiceLifetime.Singleton);
        }

        public void Configure()
        {
        }
    }
}

Program.cs:

using Microsoft.AspNetCore.Hosting;
using MVCcumul_01;

// EF Core uses this method at design time to access the DbContext
static IHostBuilder CreateHostBuilder(string[] args)
    => Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(
            webBuilder => webBuilder.UseStartup<Startup>()); 

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

ApplicationDbContextFactory.cs:

using Microsoft.EntityFrameworkCore.Design;
using Microsoft.EntityFrameworkCore;

namespace MVCcumul_01.Models
{
    internal class ApplicationDbContextFactory : IDesignTimeDbContextFactory<NorthwindContext>
    {
        NorthwindContext IDesignTimeDbContextFactory<NorthwindContext>.CreateDbContext(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            var builder = new DbContextOptionsBuilder<NorthwindContext>();
            var connectionString = configuration.GetConnectionString("DefaultConnection");

            builder.UseSqlServer(connectionString);

            return new NorthwindContext(builder.Options);
        }
    }
}

appsettings.json:

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "MVCcumul_01Context1": "Server=(localdb)\\mssqllocaldb;Database=MVCcumul_01Context-bfca8e78-d989-4ba3-a265-435e16ece2bb;Trusted_Connection=True;MultipleActiveResultSets=true",
        "MVCcumul_01Context": "Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True;Encrypt=True;Trust Server Certificate=True"
    }
}

Why I am getting NullReferenceException

I am getting an exception although everything seems to be fine.

Exception: NullReferenceException: Object reference not set to an instance of an object.

error image

Code breaks at:

    await _userManager.AddToRoleAsync(user, Input.Role);

Code:

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl ??= Url.Content("~/");
        ExternalLogins = (await  _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

        if (ModelState.IsValid)
        {
            var user = CreateUser();
            await _userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None);
            await _emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None);

            var result = await _userManager.CreateAsync(user, Input.Password);

            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");
            
                if (Input.Role != null) 
                {
                    await _userManager.AddToRoleAsync(user, Input.Role);
                }
                else
                {
                    await _userManager.AddToRoleAsync(user, Roles.Role_User_Cust);
                }

                var userId = await _userManager.GetUserIdAsync(user);
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page("/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl },
                    protocol: Request.Scheme);
            }
        }
    }
โŒ
โŒ