I have already had a look at some of the answers on here and tried google as well. I am not sure whether the question has been answered and I simply don't understand it or if I am doing something differently to create a similar error.

Where I am at. I have been learning C# and MVC for a few months slowly by working through tutorials, trying things and then going back to find another tutorial to try to understand the intricacies of the system. So beginner is where I sit solidly. So if I seem a bit simple this is why.

I am currently working through the tutorial on ASP.NET CLick Here for MVC Music Store on creating a shopping cart application. I am up to creating the StoreManagerController which is the first controller to be created using EF with views. The tutorial is for an older version of VS than I am using, however, so far everything else I have been able to work through.

To date we have created our models, created a few views and controllers. All fine and dandy.

To eliminate any potential issues I have:

-Built the project - Cleaned the project - Commented out the connection string in the web config file - commented out the entity framework in the web config file

None of the above seem to be working for me...or I am doing them wrong.

The not helpful error is:

Error and Controller

Sorry this forum doesn't allow me to enclose code properly with the two images. Will post follow on with code.

I'm having an issues retrieving a WebControl froma static method y ASP.NET using C#. The problem is that the variable "tex" is returning NULL.

EDIT: the "page" variable returns System.Web.UI.Page

Here's my Markup:

    public static void met() {
        Page page = HttpContext.Current.Handler as Page;
        TextBox tex = page.FindControl("elementID") as TextBox;

NOTE: the meth(){


is called from a javascript function:

        type: "POST",
        url: "/Consultas.aspx/met",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
        failure: function (response) {

I have created a dotnet core web api using Asp.Net Core Web Application (.Net Core) template which gives us api/values controller and on the post i am sending a message to azure storage queue using Windows Azure Storage library v8.0. https://www.nuget.org/packages/WindowsAzure.Storage/8.0.0

Currently when i do a single request, the queue takes about an avg. 140ms to complete the method AddMessageAsync() but when i do a load test for 200 request per second the same method takes an average 800ms to complete. According to azure storage queue it should be able to handle 2000 request per sec but i am not able to get 200 request per second.

I would appreciate if someone to provide an some information as why web application api not performing as expected.

Please see below my code example

Startup.cs - ConfigureServices()

// Add QueueAccessLayer.
services.AddSingleton<IQueueAccessLayer, QueueAccessLayer>();


public class EmailController : Controller
    private IQueueAccessLayer _queue;

    public EmailController(IQueueAccessLayer queue)
        _queue = queue;

    // POST api/values
    public async Task<IActionResult> Post([FromBody]string value)
        var emailMessage = "Message Id - " + Guid.NewGuid();
        await _queue.SendMessage(emailMessage);
        return new EmptyResult();


public class QueueAccessLayer : IQueueAccessLayer
    private CloudQueueClient _queueClient;         
    private CloudStorageAccount _storageAccount;

    private CloudQueue _emailQueue;
    private ILogger<QueueAccessLayer> _logger;

    public QueueAccessLayer(ILogger<QueueAccessLayer> logger)
        _storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=test1;AccountKey=#####;");
        _queueClient = _storageAccount.CreateCloudQueueClient();
        _emailQueue = _queueClient.GetQueueReference("emailqueue");

        _logger = logger;

    public async Task<bool> SendMessage(string msg)
        Stopwatch watch = new Stopwatch();
        CloudQueueMessage message = new CloudQueueMessage(msg);
        await _emailQueue.AddMessageAsync(message);

        _logger.LogInformation(msg + " - " + watch.ElapsedMilliseconds + "ms");
        return true;

public interface IQueueAccessLayer
    Task<bool> SendMessage(string msg);

I am trying to set Windows Mobile Device Time using coredll.dll. I have created the functions which will set the time but I am confused about how should I call the function on button click to set the time. Below is the object and method to set the time but not sure how to call it in button click

//This will be the method you need to set the system time

[DllImport("coredll.dll", SetLastError=true)]
static extern bool SetLocalTime(ref SYSTEMTIME lpSystemTime);

//This is the object you need to fill before you use SetLocalTime

public struct SYSTEMTIME
     public short year;
     public short month;
     public short dayOfWeek;
     public short day;
     public short hour;
     public short minute;
     public short second;
     public short milliseconds;

//And this is the final method to execute

public static void SetSystemDateTime(DateTime dt)
     SYSTEMTIME systime;
     systime.year = (short)dt.Year;
     systime.month = (short)dt.Month;
     systime.day = (short)dt.Day;

     systime.hour = (short)dt.Hour;
     systime.minute = (short)dt.Minute;
     systime.second = (short)dt.Second;
     systime.milliseconds = (short)dt.Millisecond;
     systime.dayOfWeek = (short)dt.DayOfWeek;


How should I call this function in the below button click method?

 private void btnSync_Click(object sender, EventArgs e)
//What Should I write here?

So I've asked a few questions on here and been roasted for using SQL injection vulnurable code, even though the site won't be online I've been advised to fix it anyway which I'm now trying to do.

So I did a testpage to test it out, with this following code.

var date = "2017-01-26";

var testQuery = "SELECT * FROM Test WHERE date = @0";
db.Execute(testQuery, date);

So far, just running this page it gives me no error, but probably around 99% of the time I select something from the database I use a foreach to show my data.

foreach (var c in db.Query(testQuery))

And by adding a foreach like this it gives me an error:

A parameter is missing. [ Parameter ordinal = 1 ]

What am I doing wrong? And is this even SQL injection secure otherwise? PS. This isn't a MVC type project.

I'm currently working on a project using asp.net mvc with angular. The problem I'm having is that I need to use one angular controller on two different razor views, one being rendered as the "main" view and the second one as the partial within the first. Let's say that I have boolean flag set initially to false in angular, then within the partial view I've changed it to true. The issue I'm having is that logic used on the "main" view does not recognize any changes made from the partial, so if I'll try to access this flag from the "main" one it still will be set to false. Do you guys have any idea how to solve it? I'm new to angular, the only thing coming to my mind right now is to merge the views (but I really don't want to mess with the models, so that'll be the final option).

I'll highly appreciate any insights.

Is it possible to modify the property names posted to a controller action from within a @Html.EditorFor?

I have a view that both displays a list of objects and a form that should allow a user to create one. I only want to post back the new object values upon creation rather than the entire viewmodel if possible.

My ViewModel structure for the view looks like this:

public class GenericIndexViewModel
    public IEnumerable<GenericListViewModel> ExistingObjects { get; set; }
    public GenericCreateViewModel NewObject { get; set;

public class GenericCreateViewModel
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }

In the view I'm looping through ExistingObjects to display all existing objects, and underneath I'm creating a form with @Html.BeginForm("Index", "GenericController", FormMethod.Post) and inside I have the appropriate @Html.EditorFor(m => m.PropertyA).

The action method signature is as follows:

public ActionResult Index(GenericCreateViewModel model) { ... }

When I submit the form it successfully hits the action method although model parameter is null.

When I inspect the post data I can see that the properties are being prefixed with NewObject:


How do I either prevent the prefix, or get the action method to recognise the prefixed properties as arguments?

I get a null reference exception at the assignment in the setter by calling action Index():

 public class WizardController:Controller

        public WizardViewModel WizardViewModel

                if (Session["WizardViewModel"] == null)
                    return null;

                return (WizardViewModel)Session["wizardViewModel"];


                if (value == null)
                Session["WizardViewModel"] = value;

        public ActionResult Index()
            WizardViewModel = new WizardViewModel();

            return View("Index", WizardViewModel);



Any breakpoint set in Index() will be reached. The exception seems to be raised before. Setting a breakpoint in the setter shows a default new viewModel though.

What's the issure here?

enter image description here

I google a lot and find many solutions, but none of them is working for me. I try to make a project in visual studio 2015 (asp.net core). In below image I want to include header.html in index.html page. How can I do it? Thanks in advance.

This question already has an answer here:

I searched for this particular problem but i am unable to find any solution.

Its a common practice to return a view with model or redirect to another action with query parameter. like

 return RedirectToAction("ResetPasswordConfirmation", new { id = 14 });

which appear after question mark (?) in the URL.

I have a scenario where i want to return a view from an action and want


to be appended at the end of the url like


Any response will be highly appreciate.

Thank you

Below is the order process which i have implemented thorough signalR in asp.net core web api. Every thing is working fine except one scenario(Problem scenario given below) i need the best possible solution.

Figure-System Overview

System Overview:

1) Customer Place new order (Client wait until order being processed by admin client).

2) The order is saved to the DB with ‘status=unknown ‘.

3) Admin is notified through hub about new order. (on a dashboard)

4) Admin accepts or decline new order then Order status is updated in database.

5) Customer is notified about the order, if is accepted or declined through SignalR

Problem scenario

The business rule that we have to implement is that the order should be automatically declined after 2 minutes if the Admin does not respond. In this case the server should automatically decline the order and the customer should be notified.

Solution 1: We thought of adding a timer on the Customer and Admin side, but we prefer the Timer to be somewhere on the server so we don't have to implement the timers on the customer and admin side.

I am facing a problem

Error converting data type nvarchar to datetime

during inserting a date as a string literal in the format of 26/01/2017. I am using this code in SQL Server during insert:

CONVERT(DATETIME, @PaymentDate, 104)

Hi i am not sure how to retrieve all values with same id and display them in one label.


id foodname

1 chicken

1 fish

desired output:


how can i do that?

In my asp.net mvc 5 application Idenity authentication is expiring quickly when multiple iis processes used for application pool.

If i change the no of iis application pool processes to 1, authentication works as usual.

Please advice what is the reason for the above issue and what can be done to use multiple processes in iis app pool without losing session. I have good amount of server resource hence want to make most of them.

So I'm learning ASP.NET and I'm having trouble figuring out how to allow a user to save info on a black web form through a textbox then clicking on a button and taking their input and posting it to the second page the code I have now is


    <p>First Name: </p>
    <input type="text" name="FirstName" />


    string fname;
    string lname;
    string uname;
    string password;
    string address;
    string email;
    string phonenumber;
    foreach (string varName in Session)
            fname = Session["fname"].ToString();
            lname = Session["lname"].ToString();
            uname = Session["uname"].ToString();
            password = Session["password"].ToString();
            address = Session["address"].ToString();
            email = Session["email"].ToString();
            phonenumber = Session["phonenumber"].ToString();

        Session["fname"] = Request.QueryString["FirstName"];
        Session["lname"] = Request.QueryString["LastName"];
        Session["uname"] = Request.QueryString["UserName"];
        Session["password"] = Request.QueryString["Password"];
        Session["address"] = Request.QueryString["Address"];
        Session["email"] = Request.QueryString["Email"];
        Session["phonenumber"] = Request.QueryString["PhoneNumber"]; 

After setting ValidateRequest to false on my ASP.NET web page, and input a JavaScript in my asp.net text box, the JavaScript will not run. Since there is no input validation, it should run. The input is:


I want to take a screenshot of an URL given.

I have found several other examples, but, theses takes screenshots of the current page (Same page the JQuery lies).

  1. Feedback JS (http://experiments.hertzen.com/jsfeedback/)
  2. html2canvas (http://html2canvas.hertzen.com/)
  3. Another example (http://www.xpertdeveloper.com/2012/10/webpage-screenshot-with-html5-js/)

There are many SO Posts related to getting screenshot of a site from the backend but, I want to take the screenshot from the client side (This is because the user may be logged in to his/her profile and the screenshot will contain those information if the client side generated the screenshot. If the server takes the screenshot then the information contained in the website cann't be taken)

However, none of these example helps me to sort the issue I have.

What I want to be done :

When a user provides a URL . I want to take generate a screen shot of that particular URL.

Note: My backend is on C#

I am trying to send an alert message to other users that currently on the same URL as the updater.

Let say I am on page .../Customers/Detail/597

What I am trying to do is this:

As soon as the page reloads, I want to send a signal to the users that are currently on the same page (.../Customers/Detail/597)

I tried to read the URL and extract the id number and pass that to the Hub Function, but that did not work.

Currently, if the other users are on the different page like .../Customers/Detail/687 they still see the alert message.

so yeah... I have searched and looked at many Q/A regarding this subject and answer seems to be NO mvc CANNOT Display a list of information in a list view. I have a form in create view and All I want to do is when the user selects a value from a drop down and it populates a space on the screen with a grid or list of information in the space I have on the screen since mvc seems to waste so much screen space. I am okay with it displaying it at the bottom of the screen I don't care I just want easy way to do this simple task that seem to choke and kill mvc as there has been no good answer listed for this:

I have looked at the following http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-webgrid-in-mvc-4-using-simple-model-and-data/



WHen I try to build a list the only example I see are the ones that I used to build my drop down list but they only return two values. Text or value..

I need a list..

Anyone with ANY ideas that are easy to do? I currently use viewbags since I can use linq to filter the data and populate my drop down list... I was hoping I could use view bags to populate some sort of data or web grid view.

Any ideas would be appreciated thanks

this code will in the end result in all the data that I want from the database. This being sumKG, dt(date), completeAvg and peak (All these are integers and one is date). I want to use this data inside a Google chart with dt(date) on the horizontal axis and the other three on the vertical axis.

Since I'm using two foreach loops I guess I have to store the values in some kind of list or any other sort of thing that can hold my data and loop it out inside the javascrip to the chart.

    var sumKG = 0;
    DateTime nextDay;
    var inputDate = "2016-12-01";
    var totReps = 0;
    var avg = (decimal)0;
    var completeAvg = (decimal)0;
    DateTime dt = Convert.ToDateTime(inputDate);

    var peak = (decimal)0;

    for (int i = 1; i < 30; i++)
        var getData = "SELECT (kg*rep*sett) as weight, (kg/max) as avg, (rep*sett) as reps, date FROM Test WHERE date = '" + dt + "'";
        var getPeak = "SELECT MAX(kg/max) as peak FROM Test WHERE date = '" + dt + "'";

        //Resets the value to 0 for next foreach loop.
        sumKG = 0;
        totReps = 0;
        avg = 0;

        nextDay = dt.AddDays(1);
        dt = nextDay;

        foreach (var c in db.Query(getData))
            var total = c.weight;
            var reps = c.reps;
            var calcAvg = c.avg * c.reps;
            avg += calcAvg;
            totReps += reps;
            sumKG += total;

        foreach (var d in db.Query(getPeak))
            if (d.peak != null)
                peak = d.peak;

        if (sumKG > 0) {
            var sumKGs = sumKG + "kg";
            completeAvg = avg / totReps;
            <a>@sumKGs,  @dt.AddDays(-1).ToString("dd MMM, yyyy"), @completeAvg.ToString("0.#%"), @totReps, @peak.ToString("0.#%")</a> <br />

The following is the code for my chart, its a column chart with two lines as well and both a right and left vertical axis.

<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>

    google.charts.load('current', {
        'packages': ['corechart']

    function drawVisualization() {

    var data = google.visualization.arrayToDataTable([
        ['Day', 'Kilogram', 'Average', 'Peak'],

        //Use foreach here instead of the static data below.
        ['1', 700, 50, 60],
        ['2', 780, 80, 90],

    var options = {
        title: 'Volume statistics',
        vAxes: {

            0: { logScale: false, viewWindow: {min: 0}},
            1: { logScale: false, maxValue: 2 }

        hAxis: { title: 'Day' },
        seriesType: 'bars',
        curveType: 'function',
        series: {
            0: { targetAxisIndex: 0, color: '#20f400'},
            1: { targetAxisIndex: 1 },
            1: { targetAxisIndex: 1, type: "line"},
            2: { targetAxisIndex: 1, type: "line"}

    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
        chart.draw(data, options);

I don't think a list is the right choise here since I can't choose specifically what to get out of the list like you can when using a foreach together with a db query?

Any ideas how to go about this? Also, I'm aware of the SQL injection situation, working on it. This is not a MVC project.

If you'd like to know more information, please let me know.

I have what I think is a fully up-to-date installation of Visual Studio 2015 Update 3.

If I create a new solution using the "ASP.NET Core Web Application (.NET Core)" template, then select the "Web Application" ASP.NET Core Template with "No Authentication" and wait for it to finish restoring packages, then viewing Razor source files with Tag Helpers shows them in bold purple. A good example is Views\Shared_Layout.cshtml:

screenshot of _Layout.cshtml showing bold purple tags

However, if I attempt to upgrade it to .NET Core 1.1 following the instructions at the .NET Web Development and Tools Blog then the design-time TagHelper support is lost:

screenshot of _Layout.cshtml showing un-decorated tags

Also missing is all TagHelper Intellisense.

I have SDK version 1.0.0-preview2-1-003177 installed and referenced in the global.json:

    "projects": [ "src", "test" ],
    "sdk": {
        "version": "1.0.0-preview2-1-003177"

And the project.json looks like this:

    "dependencies": {
        "Microsoft.NETCore.App": {
            "version": "1.1.0",
            "type": "platform"
        "Microsoft.AspNetCore.Diagnostics": "1.1.0",
        "Microsoft.AspNetCore.Mvc": "1.1.0",
        "Microsoft.AspNetCore.Razor.Tools": {
            "version": "1.1.0-preview4-final",
            "type": "build"
        "Microsoft.AspNetCore.Routing": "1.1.0",
        "Microsoft.AspNetCore.Server.IISIntegration": "1.1.0",
        "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
        "Microsoft.AspNetCore.StaticFiles": "1.1.0",
        "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.1.0",
        "Microsoft.Extensions.Configuration.Json": "1.1.0",
        "Microsoft.Extensions.Logging": "1.1.0",
        "Microsoft.Extensions.Logging.Console": "1.1.0",
        "Microsoft.Extensions.Logging.Debug": "1.1.0",
        "Microsoft.Extensions.Options.ConfigurationExtensions": "1.1.0",
        "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.1.0"

    "tools": {
        "BundlerMinifier.Core": "2.0.238",
        "Microsoft.AspNetCore.Razor.Tools": "1.1.0-preview4-final",
        "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.1.0-preview4-final"

    "frameworks": {
        "netcoreapp1.1": {
            "imports": [

    "buildOptions": {
        "emitEntryPoint": true,
        "preserveCompilationContext": true

    "runtimeOptions": {
        "configProperties": {
            "System.GC.Server": true

    "publishOptions": {
        "include": [

    "scripts": {
        "prepublish": [ "bower install", "dotnet bundle" ],
        "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]

So, what am I missing?

I see there is a similar Issue against the Razor tooling at Github

Razor Tag Intellisense disappears

I do hope there is a resolution...