I have implement a unit test on my MVC core project using xUnit. When I try to run the test, it gave me an error as below

"The following constructor parameters did not have matching fixture data: Status status"

Below is my code

IStatusService

public interface IStatusService
{
    Task<StatusIndexViewModel> GetStatusAsync();

}

StatusService

public class StatusService : IStatusService
{
    private readonly DbContext dbContext;
    private readonly IMapper mapper;

    public StatusService(DbContext dbContext, IMapper mapper)
    {
        this.dbContext = dbContext;
        this.mapper = mapper;
    }

    public async Task<StatusIndexViewModel> GetStatusAsync()
    {
        var model = await dbContext
           .Status.AsNoTracking()
           .ProjectTo<StatusViewModel>(mapper.ConfigurationProvider)
           .ToListAsync();

        var vm = new StatusIndexViewModel
        {
            Statuses = model
        };

        return vm;
    }

}

Here is the Controller

public class StatusController : Controller
{
    private readonly IStatusService statusService;

    public StatusController(IStatusService statusService)
    {
        this.statusService = statusService;
    }

    public async Task<IActionResult> Index()
    {
        var model = await statusService.GetStatusAsync();
        return View(model);
    }
}

Below is my unit test class

public class StatusUnitTest
{
    StatusController StatusControllerTest;
    private Mock<IStatusService> statusService;
    private List<Status> statuses;
    private Status status;

    public StatusUnitTest(Status status)
    {
        this.status = status;
        statusService = new Mock<IStatusService>();
        statusService.Setup(p => 
        p.GetStatusAsync()).ReturnsAsync(status);
        StatusControllerTest = new StatusController(statusService.Object);
    }

    [Fact]
    public async Task GetStatusByIdNo()
    {
        var result = await StatusControllerTest.Index();
        var viewResult = Assert.IsType<ViewResult>(result);
        Assert.IsAssignableFrom<IEnumerable<Status>> 
       (viewResult.ViewData.Model);            
    }
}

May I know what the mistake I make? How I can test the controller and the service layer? Please give me a guide. Thank you very much.

I have properties I don't want to expose in swagger UI but still allow them to be deserialized if they are passed to the controller. Json ignore does not work as it still appears in swagger and does not allow the serialize and deserialze of the property.

I have created an exclude attribute, and applied it to the property, created a schema filter and added it the startup. But the property still appears in swagger.

[AttributeUsage(AttributeTargets.Property)]
public class SwaggerExcludeAttribute : Attribute
{
}

Added to property:

 [SwaggerExcludeAttribute]
 public int? ContentType { get; set; }

Filter:

 public class SwaggerExcludeSchemaFilter : ISchemaFilter
 {
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema?.Properties.Count == 0)
        {
            return;
        }
        const BindingFlags bindingFlags = BindingFlags.Public |
                                     BindingFlags.NonPublic |
                                     BindingFlags.Instance;

        var memberList = context.Type
                       .GetFields(bindingFlags).Cast<MemberInfo>()
                       .Concat(context.Type
                       .GetProperties(bindingFlags));
        var excludedList = memberList.Where(m =>
                                       m.GetCustomAttribute<SwaggerExcludeAttribute>()
                                       != null)
                                 .Select(m =>
                                     (m.GetCustomAttribute<JsonPropertyAttribute>()
                                      ?.PropertyName
                                      ?? m.Name.ToCamelCase()));

        foreach (var excludedName in excludedList)
        {
            if (schema.Properties.ContainsKey(excludedName))
                schema.Properties.Remove(excludedName);
        }
    }

}

in Startup:

services.AddSwaggerGen(c => { c.SchemaFilter<SwaggerExcludeSchemaFilter>(); });

The contenttype still appears in the swagger document. Does anyone have another suggestion or way to make this happen?

I have a question regarding the defining of classes and variables in programming. I've recently learned that the recent Cylance 'bypass' was, among other things, made possible by reverse engineering and reading the code. The researcher said that by reading the definitions, it helped him out understanding the code a bit better and understanding which functions made up the algorithm.

I've learned that it's a best practice to make definition and variable names very descriptive so others can figure out what it does or stands for. But is this really a best practice? Are there examples of for instance companies that internally decide to keep a list of their way to obfuscate their code to prevent this from happening?

And then of course I mean obfuscating the names before obfuscating the whole code itself.

Article about Cylance: https://skylightcyber.com/2019/07/18/cylance-i-kill-you/

I'm curious if someone has a good take on this, as it sparked my interest.

i need help with my homework

This is my question:

Write ASP code in the space below so that the heading displayed on the page will say "Good morning!" if the request parameter "when" is equal to "m" or "M", "Good afternoon!" if it is equal to "a" or "A", and "Hello!" in all other cases.

and this is my code:

 <html>
    <head>
      <title>Greetings</title>
    </head>
    <body>
      <h1>
        <%

string when = Request["m,M"];
        if (when != null && when.Contains("m")|| when != null && when.Contains("M"))

            Response.Write("Good morning!");

else

if(when != null && when.Contains("a") || when != null &&  when.Contains("A"))
            Response.Write("Good afternoon!");
else

 Response.Write("Hello!");

        %>
      </h1>
      Welcome to my ASP page.
    </body>
  </html>

What is not OK here?

I would like to set the background color of the bar based on condition in Chartjs.

I am referencing ChartJs documentation and this earlier question posted(Change bar color depending on value).

Some additional details: I haved used chartjs - plugins- annotation....which draws line as a target line in my histogram. I would like to change the color of the bars falling on the left and right of the target line.

I am not getting any error...but the chart is not getting updated as per desired output.

I have created bins usind d3. My consoleoutput is :

Array(15) => Count [ 10,8,45,20...]
Array(15) = > Bins [ 0,20,40,60....]

Refer(https://jsfiddle.net/s5482nou/1/). The only addition I have done is looping in the code :

for ( i = 0; i <bins.length; i ++)
if (bins[i].value > 40 {

fillcolor = "red"
}

else
{

fillcolor = "blue"
}

I also tried using:

var chartColors = {
  red: 'rgb(255, 99, 132)',
  blue: 'rgb(54, 162, 235)'
};

var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ['value 1', 'value 2', 'value 3', 'value 4'],
    datasets: [{
      label: 'Dataset 1',
      backgroundColor: [
        chartColors.blue,
        chartColors.blue,
        chartColors.blue,
        chartColors.blue
      ],
      data: [33, 57, 65, 42]
    }],
  }
});
var dataset = myChart.data.datasets[0];
for (var i = 0; i < dataset.data.length; i++) {
  if (dataset.data[i] > colorChangeValue) {
    dataset.backgroundColor[i] = chartColors.red;
  }
}
myChart.update();

No error but no result. Kindly help !

I have one problem: I'm using a ValidationExpression in fileupload control, the user muse not upload files like executables or zips, or rars, etc. So I use a RegularExpressionValidator and it works, users can't upload this kind of files, but if users try to upload a forbidden file, the ValidationExpression works, shows the message on the control, but If the user try again to upload new files that are correct, the fileupload control don't work because the first time the RegularExpressionValidator is activated forbidden the upload:

this is my fileupload control:

<asp:FileUpload runat="server" ID="UploadImages" AllowMultiple="true"  />
                    <asp:RegularExpressionValidator ID="expValUpImg_Ext" runat="server"
                        ControlToValidate="UploadImages" ErrorMessage="Formato invalido"
                        ValidationExpression="/^[^.]+$|\.(?!(js|exe|zip|rar|7z|tar|msi)$)([^.]+$)/" >
                    </asp:RegularExpressionValidator>

How can reactivate the upload control, or refresh it for a new validation?

I hope anyone please help me.

best regards

I have a webservice (asmx) running under 1 app pool with maxWorkerThreads set to 1.

I'm not sure if it matters but this service exists on another server with same settings and they both sit behind a load balancer.

When I check the number of threads under that w3p process using Process Explorer, among other items, I see atleast 4 w3tp items.

Are these w3tp items extra threads that w3p is leveraging off of CLR to execute the code faster or in a more efficient manner?

The challenge is that the code is not multi-thread friendly, the singleton class and it's functionality doesn't meet the requirements. So if this code is executed under multiple threads, it'll cause issues and that's what I suspect is happening.

In this scenario, if the w3tp processes are running this code in conjunction, is it possible that a seperate w3tp thread picks up the first half of the code while another w3tp picks up and continues execution of the rest of the code?

Many thanks in advance for your help.

I am using a that I am generating columns for, based of the ADO.net entity data model, joining 2 fields into 1 column in the gridview. In the CodeBehind, I am iterating through each row using a foreach statement and comparing the numbers (after parsing to decimal), but the error says that the input string is in an incorrect format. I suspect it is from the parsing of the text in the gridview or something within the foreach. When i run and debug on my machine it works as it should, but when published on a server, then it throws the error.

asp:GridView

<asp:GridView CssClass="text-center table table-striped table-condensed" ID="ContributionGridView" runat="server" AutoGenerateColumns="True">
 <Columns>
    <asp:TemplateField HeaderStyle-CssClass="text-center header" 
    HeaderText="Wage Bands">
      <ItemTemplate>
        <asp:Label ID="WageBandLabelStart" runat="server" Text='<%# 
        String.Format("{0:C}", DataBinder.Eval(Container.DataItem, 
        "earningsfrom")) %>'></asp:Label>
        -
        <asp:Label ID="WageBandLabelEnd" runat="server" Text='<%# 
        String.Format("{0:C}", DataBinder.Eval(Container.DataItem, 
        "earningsto")) %>'></asp:Label>
      </ItemTemplate>
    </asp:TemplateField>
  </Columns>
</asp:GridView>

code that gets the table from a database and assigns the datagrid's source

applicableContributionRates = ContributionData.GetContributions(chosenDate);
ContributionGridView.DataSource = applicableContributionRates;
ContributionGridView.DataBind();

Here is the foreach to check the contents and i should put a different backgorund color for the correct row

foreach (GridViewRow row in ContributionGridView.Rows)
{
  Label startLabel = (Label)row.Cells[0].FindControl("WageBandLabelStart");
  Label endLabel = (Label)row.Cells[0].FindControl("WageBandLabelEnd");
  string startLabelText = startLabel.Text.Trim('$');
  string endLabelText = endLabel.Text.Trim('$');
  decimal earningsFrom = Convert.ToDecimal(startLabelText, culture);
  decimal earningsTo = Convert.ToDecimal(endLabelText, culture);

  if (weeklyEarnings >= earningsFrom && weeklyEarnings <= earningsTo)
  {
    tableIndex = row.RowIndex;
    applicableContributionRate = applicableContributionRates[row.RowIndex];
    row.BackColor = System.Drawing.ColorTranslator.FromHtml("#008265");
    row.ForeColor = Color.Beige;
    break;
  }
}

On my computer, it changes the colors for the correct rows as how it should, but when i publish the application and it is placed on a server, when i try it then it throws the error saying: The input string is not in the correct format.

I need to integrate a power bi reports of my workspace, i have already done it with the embed tool provided by Microsoft but the project is developed in MVC structure and i want it with WEB FORMS integration. I don't now if there is an updated program with the current API of Power Bi for Web forms.

using Microsoft.PowerBI.Api.V2;

I'm trying to install ASP.Net 3.5 in my windows docker container using the below command

DISM /Online /Enable-Feature /FeatureName:NetFx3 /All 

I'm getting the below error

Deployment Image Servicing and Management tool Version: 10.0.17763.1

Image Version: 10.0.17763.615

Enabling feature(s) [==========================100.0%==========================]

Error: 1058

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it.

The DISM log file can be found at C:\Windows\Logs\DISM\dism.log

Also i tried different powershell commands like, but no luck. Getting same error

Enable-WindowsOptionalFeature -Online -FeatureName IIS-ASPNET

Anyone faced this issue, Any workaround or solution?

I am working on poorly commented work that I can't wrap my head around. Basically, there are two models which are not related through foreign keys (nor I want to create one now since I am still learning the design).

 class ModelA:
    borrowedTotalGroup
    code

 class ModelB:
    name
    code
    public virtual ICollection<ModelA> MAs { get; set; }

the code column is the same for both in terms of value. I have a controller now that makes use of ModelB but now I want to fetch values from ModelA as well. But everytime I try, it raises the error that column ModelB_code doesn't exist. From my impression, it is expecting ModelB_code to be column in ModelA.

My controller has first to access ModelA and get an array of items but the following generates the error:

        GroupResults(ModelB mb)
        var ModelAValues = mb.MAs.Select(
            r => new { r.borrowedTotalGroup });

Is there anyway I can get ModelA data for a given code without necessarily creating database relationships at this stage?

I am new to asp.net programming and have come into this unusual error. I have a master page called Master.Master which contains the following code for specifying a CSS file.

<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>

    <asp:ContentPlaceHolder ID="Stylesheets" runat="server">
        <link rel="stylesheet" href="~/Styles/StyleSheet.css" type="text/css" />
    </asp:ContentPlaceHolder>
</head>

note that for the master page the CSS works perfectly with no issues, I have since created a default asp web form which takes all contents from the Master.Master page. This page however is not displaying the CSS at all, here is that pages code.

<%@ Page Title="Home" Language="C#" MasterPageFile="~/Master.Master" AutoEventWireup="true" CodeBehind="Home.aspx.cs" Inherits="GarageManager.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="stylesheets" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>

from researching this issue many users on here even suggested using script language for resolving URL like such, but to no avail.

<a runat="server" href="<%= this.ResolveUrl(~/Styles/StyleSheet.css) %>" onmouseover="document.Home_Img.src='<%= this.ResolveUrl("Images/home_2.png") %>'"
        onmouseout="document.Home_Img.src='<%= this.ResolveUrl("Images/home.png") %>'">
        <img alt="" src="Images/home.png" name="Home_Img" runat="server" />
    </a>

thanks in advance

Here is my situation. When I click on the button to export the Excel file, I call a method on the client side that shows a loader GIF, while in the code behind I search for the information, and then export it to an Excel file. I don’t have any problem until here.

The problem is when the file is downloaded, and I try to stop displaying the GIF with a ScriptManager from the code behind, this doesn’t work because the response has already been sent to download the Excel file.

I’m not finding any way to stop displaying the GIF. Help please!!

The response is cleared, to send the excel file. The response clears, to send the excel file. I use a ScriptManager to call a javascript method on client side that hides the loader GIF. If I comment the descargarExcel() method, the GIF disappears correctly. But that's not the idea... How it should work

How it should work enter image description here

How it works enter image description here

Can someone please explain to me what they are doing in background? I had problems when using HttpContext.SignInAsync with the SecurityStamp.

After using SigninManger.SignInAsync the error never occurred again.

Can you explain to me what the difference between these variants is? I want to understand why HttpContext.SignInAsync is behaving like this.

I have properties I don't want to expose in swagger UI but still allow them to be deserialized if they are passed to the controller. Json ignore does not work as it still appears in swagger and does not allow the serialize and deserialze of the property.

I have created an exclude attribute, and applied it to the property, created a schema filter and added it the startup. But the property still appears in swagger.

[AttributeUsage(AttributeTargets.Property)]
public class SwaggerExcludeAttribute : Attribute
{
}

Added to property:

 [SwaggerExcludeAttribute]
 public int? ContentType { get; set; }

Filter:

 public class SwaggerExcludeSchemaFilter : ISchemaFilter
 {
    public void Apply(OpenApiSchema schema, SchemaFilterContext context)
    {
        if (schema?.Properties.Count == 0)
        {
            return;
        }
        const BindingFlags bindingFlags = BindingFlags.Public |
                                     BindingFlags.NonPublic |
                                     BindingFlags.Instance;

        var memberList = context.Type
                       .GetFields(bindingFlags).Cast<MemberInfo>()
                       .Concat(context.Type
                       .GetProperties(bindingFlags));
        var excludedList = memberList.Where(m =>
                                       m.GetCustomAttribute<SwaggerExcludeAttribute>()
                                       != null)
                                 .Select(m =>
                                     (m.GetCustomAttribute<JsonPropertyAttribute>()
                                      ?.PropertyName
                                      ?? m.Name.ToCamelCase()));

        foreach (var excludedName in excludedList)
        {
            if (schema.Properties.ContainsKey(excludedName))
                schema.Properties.Remove(excludedName);
        }
    }

}

in Startup:

services.AddSwaggerGen(c => { c.SchemaFilter<SwaggerExcludeSchemaFilter>(); });

The contenttype still appears in the swagger document. Does anyone have another suggestion or way to make this happen?

This question already has an answer here:

I'm new to web dev, I have two Layouts: _Lay1.cshtml and _Lay1.cshtml and I want to add both to my main page like:

@{
    Layout = "~/Views/Shared/_Lay1.cshtml";
    Layout = "~/Views/Shared/_Lay2.cshtml";
}

but when I do this it ignores the first layout and take the second layout, my question is how to add both?

I am trying to set up a WPF application that is supposed to parse razor pages. Essentially I want to create templates in Razor Pages, and add the UI of WPF. I have developed some templates in razor formats. How can I parse them in my WPF project? Is it even possible?

I am trying to loop through a list of objects in a View. This loop should render multiple tables and a button to add a record to given table.

Whenever the users clicks on this button, a modal should open, containing a (different) table with rows and within these rows, a button can be found as well to add given record to the previous mentioned table.

How could I (or how am I supposed to) change the onClick attribute of the buttons found within the modal, based on what button I clicked in the prior table (based on parameter)?

This is what I tried:

<div class="modal" id="add-forms" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Add a record</h4>
            </div>
            <div class="modal-body">
                <table class="table table-hover" id="add-form">
                    <thead>
                        <tr>
                            <th>
                                Form name
                            </th>
                            <th>
                                Select
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (KeyValuePair<int, string> kvp in ViewBag.dictCollection)
                        {
                            <tr>
                                <td>
                                    @kvp.Value
                                </td>
                                <td>
                                    @*<button type="button" class="btn btn-success" onclick="link = '@Url.Action("Index", "Controller", new { id = kvp.Key.ToString(), id= Url.RequestContext.RouteData.Values["id"], para = "para" })'; link = link.replace('para', para);">*@
                                    <button type="button" class="btn btn-success" onclick="window.location.href='/Controller/' + '@kvp.Key' + '@Url.RequestContext.RouteData.Values["id"]' + para">
                                        <span class="glyphicon glyphicon-plus"></span>&nbsp;Add
                                    </button>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

@* First table rendered,  used to open the modal and  *@
@foreach (MyClass myClass in ViewBag.myClasses)
{
    <table class="table table-hover">
        <thead>
            <tr>
                <th class="text-center" colspan="3">
                    Property: #@myClass.Property
                </th>
            </tr>
            <tr>
                <th class="text-center">
                    Status
                </th>
                <th>
                    Activity
                </th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>
                    <div class="" style="width: 15px; height: 15px; margin: 0 auto; background-color: red; border: 1px solid #000;"></div>
                </td>
                <td>
                    ~
                </td>
                <td>
                    ~
                </td>
            </tr>
            <!-- I would like to add records here through the modal but only for desired "entity" table, by using some sort of key -->
        </tbody>
    </table>
    <button type="button" class="btn btn-success pull-right"
            onclick="$('#add-forms').modal('show');para = '@myClass.Propety';">
        <span class="glyphicon glyphicon-plus"></span>&nbsp;Add
    </button>
}

(If it would be better to use @Url.Action() please elaborate how I could apply it here)

What could I do to make interaction between tables and modal work in this example?

I have an enum that looks like this:

public enum SMSTaskStatus
{
    New = 0,
    Awaiting = 1,
    InProgress = 2,
    OnHold = 3,
    Done = 4,
    Error = 5
}

and I am trying to return the value in a razor view using

<td>@{ (SMSTaskStatus) item.Status.Value;}</td>

but i get an error that

'Only assignment, call, increment, decrement, await and new
 object expressions can be used as a statement'

How can I cast it to the enum value in the view? It's a nullable int in my class

public int? Status { get; set; }

My view does not repopulate new list items that are added dynamically with the client-side script. I can see them in ModelState but they do not end up in the reloaded form.

P.S. Changes to properties of existing items do get persisted.

Is such functionality supported by the engine? If so, what is wrong with my solution? If not what is the best way to do this?

Razor File:

 @for (int i = 0; i < Model.Items; i++)
 {
     <div>
         @Html.Hidden("Items.Index", i)
         <input asp-for="Items[i].Property1" />
         <input asp-for="Items[i].Property2" />
     </div>
  }
  <--!  Javascript adds new divs here on demand by mimicking HTML above and incrementing i -->

Model:

public class MyModel
{
    public List<SubModel> Items { get; set; }
}


public class SubModel 
{
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}

Going through some old code and it appears the e.preventdefault() isn't behaving correctly on a button click. I am not sure how I didn't notice this before, but for some reason it just Simpy isn't doing its job. Page still refreshed even if If statement is executed. Am I missing something, am I blind? Can anyone tell what's going on here?

Also, I would like to add, it definetly gets into the IF statement, because the DIV that needs to be un-hidden does show, however page gets refreshed anyway and it submits which it should not.

Below is my code:

Thank you.

Form:

    <form class="form-group" method="get" action="#">
    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped table-hover table-bordered">
                <thead>
                    <tr>
                        <th>Terminal</th>
                        <th>Command</th>
                        <th>Command Value</th>
                        <th> </th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>@Html.DropDownListFor(o => o.TerminalsDDL, Model.TerminalsDDL, new { id = "ddlTerminalID", @class = "form-control align-middle" })</td>
                        <td onchange="UpdateHelpDescript();">@Html.DropDownListFor(o => o.TerminalCommandLookupsDDL, Model.TerminalCommandLookupsDDL, new { id = "ddlCommandValue", @class = "form-control align-middle" })</td>
                        <td>@Html.TextBoxFor(o => o.UserEnteredTerminalCommands, new { Class = "form-control align-middle", Id = "cmdValueValue" })</td>
                        <td> <input id="btnSaveTerminalCommand" type="button" value="Insert" class="btn btn-primary align-middle" /> </td>
                </tbody>
            </table>
        </div>
    </div>
</form>

JS:

   $(function () {
    $("#btnSaveTerminalCommand").click((e) => {

        if ($("#ddlCommandValue").val() == " " || $("#ddlCommandValue").val() == null || $("#ddlCommandValue").val() == 0 || $("#cmdValueValue").val() == " " || $("#cmdValueValue").val() == null) {

             //window.alert("Please select a valid command.");
             $("#alertPopUp").removeClass("hidden");
             e.preventDefault();
            e.stopImmediatePropagation();
        };

        var data = {
            TerminalID: $("#ddlTerminalID").val(),
            CommandID: $("#ddlCommandValue").val(),
            CommandValue: $("#cmdValueValue").val()
        };

        $.ajax({
            url: '@Url.Action("AddTerminalCommand", "TerminalCommand")',
            type: "POST",
            data: data,
            success: function (response) {
                console.log("Success");
                window.location.href = response.Url;
            }
        });
    });
});