I haven an event, if I push the Stop button, the Visual Studio sends a word to Arduino. But the Arduino back send to the c#, and with this I want to stop my cycle. With this I want to skip the Ajax but I want to simulate that the data go in live. But my webpage doesn't appear. Has anyone an idea how can I correct it? My code:

        public JsonResult stopButtonOnClick()

            String forthearduino = "1";
            return Json("Ok", JsonRequestBehavior.AllowGet);

In index controller:

 data_rx = myport.ReadLine();
                   data_rx = myport.ReadLine();


And in the Arduino:

int val = Serial.read();
  if (val==1)

In Ruby we have one mechanize gem, that will work as without maintaining a session we can post and get data as Web client (or) HTTP Post is their any chance to use that gem in .net also.

This question already has an answer here:

I am trying to show a popup on radio button selection.

I use MVC razor.

Following is my code

 @Html.RadioButtonFor(model => Model.Container.Type, Model.container.type.1,
                       new { id = "type1", @class = "validate[required]", data-toggle = "modal", data-target = "#Modal" })

I get following error

CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member acce

Seems that the attributes data-toggle and data-target dont work with @Html.RadioButtonFor()

I am trying to handle the event in which a button in my button field is pressed and subsequently removes the row from the website and from the database. and I do that but using the following code in my .aspx.cs file:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        if (e.CommandName == "Delete")
            System.Diagnostics.Debug.WriteLine("testing buttons");

However, whenever I go to click a button in the button field, it throws the error saying that the event is not handled. The following code is the aspx for the entire data table.

<asp:GridView ID="gridViewStudent" runat="server" CellPadding="4" ForeColor="#333333"
      emptydatatext="There are no data to display">
      <AlternatingRowStyle BackColor="White" />
          <asp:ButtonField ButtonType="Button" CommandName="Delete" HeaderText="Edit" ShowHeader="True" Text="Remove" />
      <EditRowStyle BackColor="#2461BF" />
      <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
      <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
      <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
      <RowStyle BackColor="#EFF3FB" />
      <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
      <SortedAscendingCellStyle BackColor="#F5F7FB" />
      <SortedAscendingHeaderStyle BackColor="#6D95E1" />
      <SortedDescendingCellStyle BackColor="#E9EBEF" />
      <SortedDescendingHeaderStyle BackColor="#4870BE" />


I'm trying to mix Windows and Anonymous authentication in a .Net Core 2.0 empty web app. I would like to avoid the [Authorize] attribute as I do not want to use Mvc or controllers.

My setup is as follows:

  1. I created an empty .Net Core 2.0 web application

  2. I went to project properties -> Debug -> Checked "Enable Windows Authentication" and disabled "Enable Anonymous Authentication". Now "windowsAuthentication": true and "anonymousAuthentication": false appeared in my launchSettings.json under "IIS".

  3. Inside Startup.cs, in ConfigureServices I added services.AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration.IISDefaults.AuthenticationScheme); as mentioned in https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#windows-authentication-httpsys--iisintegration

  4. I added a simple Console.WriteLine(context.User.Identity.Name); to see that it works inside app.Run and... It all works!

However... as soon as I set "anonymousAuthentication" to true in launchSettings.json it stops working and I cannot figure out what can I do to make the Windows authentication work alongside with it. Context.User.Identity.IsAuthenticated is always false. As you can see my configuration is very simple and I need it to stay this way. I want to enable/disable windows authentication on certain dynamic routes, so using controllers with the [Authorize] attribute is not an option.

What I'm trying to achieve is a simple app where the url "/authenticated" would reply with the value of context.User.Identity.Name and the url "/public" would reply with something like say "This is a public page!". Something similar to NTLM authentication on specific route in ASP.NET Core but without the [Authorize] attribute and controllers. The resources are very scarce... Anyone have any idea what I could be missing? Thanks!

I have placed a LinkButton in an UpdatePanel. The UpdatePanel is in a ListView. I am also using MasterPages, so the ListView also resides in a ContentPlaceHolder. I can only click on any of the LinkButtons one time and get the partial postback. The second time I click on any of the LinkButtons, it is doing a full postback. This is undesired.

If I place the LinkButton and UpdatePanel outside the ListView, it works correctly giving only the partial postback on every click.

I have tried placing ClientIDMode="Auto" in the page directive, but this does not help. I have also tried putting the ListView within the UpdatePanel, which also did not help. That actually resulted in all the buttons doing a full post back everytime.

I am assuming this has something to do with creating these LinkButtons at runtime.

Not that this will help, but here is some code...

     <asp:ListView ID="ListView1" runat="server"  GroupPlaceholderID="groupPlaceHolder1" ItemPlaceholderID="itemPlaceHolder1">
            <asp:PlaceHolder runat="server" ID="groupPlaceHolder1"> </asp:PlaceHolder>
                <asp:PlaceHolder runat="server" ID="itemPlaceHolder1"> </asp:PlaceHolder>
                <asp:UpdatePanel ID="UpdatePanel1" runat="server" ChildrenAsTriggers="true">
                <asp:LinkButton ID="LinkButton1" runat="server" onclick="AddItem_Click" CommandArgument='<%# Eval("txtCustomerItem") %>'>Add to Cart</asp:LinkButton>

How can I set this up to where it is doing a partial postback everytime? These LinkButtons need to be in a ListView, because there is an undetermined amount depending on the products being displayed. Any and all help is greatly appreciated.

Greetings fellow coders!

I've done tons of research on this topic and can't manage to find any resources that truly depict how this process can be done (or if it can be done). So, I'm turning to you all for some advice!

The Issue:

So right now, I have a form that sends the filled out data back to the controller via HttpPost. At this point, I pass that form data to the model function to create the PDF. Now at this point, I have it returning the PDF file if the model function was successful.

        PDFMemStream memstream = new PDFMemStream();
        CreatePDFinfo formdata = new CreatePDFinfo();

        if (ModelState.IsValid)
            memstream = CreatePDF.Populate_PDFcontent(formdata);
            if (memstream.retval.success)
                // if creating pdf is successful, return file
                return File(memstream.mstream, "application/pdf");
        ViewBag.PageTitle = "Cool PDF Project";
        ViewBag.TabTitle = "Really Cool PDF Project";
        return View(formdata);
  • I can display this created PDF in a separate tab if I use the code below in the view. This assumes that the current view is called "createPDF". So this part works all fine and dandy.

    $('#form').submit(function () {
            if ($('#form').valid())
                window.open('', 'createPDF');
                this.target = 'createPDF';
  • If I don't use the above code, after the button click, it will remain on the current page and reload the page with only the pdf content in the native browser PDF viewer.

The Needed Solution:

As I stated, everything works perfectly if I wanted the PDF to be populated in at new tab or the existing one. HOWEVER, what I need, is a way to view the PDF on the same page either in a partial view or embedded on the existing page. I could even deal with the PDF being embedded in a new view as long as I could pass the model data to the new view for other sections of that page.

Resources & Articles:

Here's all of the articles and resources I've already looked into and read (so please do not post the same ones):

using ITextSharp to extract and update links in an existing PDF

Displaying a pdf to webpage using iTextSharp?


MVC Application to Display embedded PDF documents



C# ASP.NET MVC Create PDF from view Rotativa or iTextSharp?

Convert PartialView Html to String for ITextSharp HtmlParser

How to open a PDF file in an <iframe>?

How to render an ASP.NET MVC View in PDF format

Now some of the articles aren't completely relevant but I included them just in case they may be helpful.

Any suggestions, tips or advice?...

i have a ViewModel that included RoleList and InsertData, such as:

public class AdminViewModel
    List<InsertAdminDataModel> InsertAdminData{ get; set; }
    List<RoleListModel> RoleList { get; set; }

Controller GET:

 public IActionResult AddAdmin(){
            AdminViewModel avm = new AdminViewModel{
                RoleList = ia.getRoleList()
            return View(avm);

this is my Razor:

@model AdminPanel.Models.AdminViewModel
<form asp-action="AddAdmin" asp-controller="Admin" role="form" method="POST" id="submitform">
      <div id="box_clone" class="box_clone">
           <div class="col l12 s12 m12 header-title">
                <div class="col l4 s10 m5">
                     <span>New Admin</span>
                        <a href="#/"><i class="material-icons right">delete</i></a>
      <div class="col l12 s12 m12 main-content">
           <div class="col l8 s12 m8 box-name">
                <input id="name" asp-for="InsertAdminData.First().name" type="text" class="validate" placeholder="Name" />
          <div class="col l8 s12 m8 content-box">
               <div class="col s12 m12 l12 content-box-top content-category-top">
                  <div class="col l12 s12 m12 left-align">
                    <span class="left">Role</span>
               <div class="col l12 s12 m12 content-box-bottom content-category-bottom">
                  for (int i = 0; i < Model.RoleList.Count(); i++)
                         <li class="parent_cat">
                         <input type="hidden" asp-for="InsertAdminData.First().idroles" />
                         <input type="checkbox" id="category' + @Model.RoleList[i].idroles + '" asp-for="InsertAdminData.First().idroles" class="check_parent" />
                         <label for="category' + @Model.RoleList[i].idroles + '">@Model.RoleList[i].roles</label>
         <div class="fixed-action-btn">
              <a class="btn-floating btn-large">
                 <i class="large material-icons">add</i>
 <div class="outputclone"></div>

i need to POST that <List>insertAdminDataModel from Razor to Controller, however there are error occurred on load:

ArgumentNullException: Value cannot be null.
Parameter name: source
System.Linq.Enumerable.TryGetFirst<TSource>(IEnumerable<TSource> source, out bool found)

is there are any way to solve this problem? was using for loop but same result occurred. By the way, for new card, i'm using jquery, and it's works perfectly.

I am trying to apply what I have been studying and I have been involved in a part of contexts.

What I'm trying to apply is a Microsoft.Identity structure along with the application entities.

Structure of the solution:


I have created an interface to keep the same new properties and so do not have problem of migration of two classes to the same 'table'

public interface IUsuario
    string Fullname { get; set; }

I applied to my User entity and ApplicationUser:

namespace BaseFull.Web.Models
    // Add profile data for application users by adding properties to the ApplicationUser class
    public class ApplicationUser : IdentityUser,  IUsuario
        public string Fullname { get; set; }

namespace BaseFull.Entities.Models
    public class Usuario : IUsuario
        public string Fullname { get; set; }
        public Usuario()
            Id = Guid.NewGuid().ToString();
        #region Propriedades da AspnetUsers(Identity)
        public string Id { get; set; }
        public virtual string Email { get; set; }
        public virtual string UserName { get; set; }


I've separated the entities in a project. I am also trying to separate the context in a project and it is at this moment that I am in difficulties.

 namespace BaseFull.Infra.Data.Context
    public class BaseFullContext: DbContext
        public DbSet<Usuario> Usuarios { get; set; }

namespace BaseFull.Web.Data
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)

    protected override void OnModelCreating(ModelBuilder builder)


In the Startup class of the Web project I made the call of the contexts:

public void ConfigureServices(IServiceCollection services)
        services.AddDbContext<ApplicationDbContext>(options =>
        services.AddDbContext<BaseFullContext>(options =>

I had an assembly error, which I resolved by changing the service to the same assembly as the main project

services.AddDbContext<BaseFullAppContext>(options =>
                                , b => b.MigrationsAssembly("BaseFull.Web"))

However, running the second context update generated the error 'table already exists'.

There is already an object named 'Usuarios' in the database.

My biggest question is how to solve this problem, which is the most correct and efficient way to use both contexts for this.

The User configuration class to remain the same as ApplicationUser did not show here because I do not think it's necessary, but if I need to, I'll show it as well.

I'm having an issue with using error message in ASP.net mvc. When the user clicks save even nothing wasn't entered it still redirects them to another page but I would like to give them an error if no information was entered. I want it to be done on the client side. This what I have thus far

    public ActionResult Finish(Student model, string finish)
        if (!ModelState.IsValid)
            ViewBag.error("No item was entered");
           return View(getStudent);

        else (string.IsNullOrEmpty(finish))
            //redirects to student record page when finish is clicked
            return RedirectToAction("StudentRecord");


I have been tasked to migrate a legacy application to ASP.Net web forms. This is a rather broad question, but I will have a try anyway.

What is the best (fastest) way to apply business logic in this scenario?

For example I have two controls on a web form: Net price and Gross price. Currently when the user enters the net price, I perform a callback and grab a data object from session. The data object calculates the gross price and in the OnCallback event I recreate the controls with both values.

This process takes about 2 seconds. Way too slow, when there are dozens of controls. What are my options here?

Is JQuery a possibility? Should I scrap web forms in favor of MVC?

Pointers in any direction are highly appreciated.

I have a jQuery function, which can be seen below. It displays the result in a span but when the page is reloaded this span hides and shows for some time.

I do not want it to hide. Is there a way to do this?

<span id="timer"></span>


       var counter = 61;
       var x = setInterval(function () {

           counter = counter-1;



We are building an MVC application, we need to render some SSRS reports, so we are trying to use Reporting Services Web Service for this purpose, looking for some documentation of SOAP API I found this, so I tried to replicate that code and write my own controller, but as you can see I don't return any ActionResult, I don't know what should I return.

So my questions are, which is the best way to use Reporting Service Web Service in an MVC application? What should I return in case rs.Render is success?

    public ActionResult soapReport(string path)
        soapSSRS.ReportExecutionService rs = new soapSSRS.ReportExecutionService();
        rs.Url = "http://xxx.xxx.xxx.xx:xxxx/reportserver/ReportExecution2005.asmx";
        rs.Credentials = new System.Net.NetworkCredential(

        // Render arguments
        byte[] result = null;
        string reportPath = "/MyReportFolder/MyReport";
        string format = "MHTML";
        string historyID = null;
        string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";

        // Prepare report parameter.
        soapSSRS.ParameterValue[] parameters = new soapSSRS.ParameterValue[3];
        parameters[0] = new soapSSRS.ParameterValue();
        parameters[0].Name = "token";
        parameters[0].Value = "XxXxXxXxXxXxXx";

        DataSourceCredentials[] credentials = null;
        string showHideToggle = null;
        string encoding;
        string mimeType;
        string extension;
        soapSSRS.Warning[] warnings = null;
        ParameterValue[] reportHistoryParameters = null;
        string[] streamIDs = null;

        soapSSRS.ExecutionInfo execInfo = new soapSSRS.ExecutionInfo();
        soapSSRS.ExecutionHeader execHeader = new soapSSRS.ExecutionHeader();

        rs.ExecutionHeaderValue = execHeader;

        execInfo = rs.LoadReport(reportPath, historyID);

        rs.SetExecutionParameters(parameters, "en-us");
        String SessionId = rs.ExecutionHeaderValue.ExecutionID;

            result = rs.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
            execInfo = rs.GetExecutionInfo();
        catch (SoapException e)

In View have the following foreach loop to display links:

@model List<IGrouping<string, FileInfo>>

    ViewData["Title"] = "Index";
    int i = 0;

<div class="container-fluid main-container">
  <div class="col-md-3 sidebar">
      <ul class="nav nav-pills nav-stacked">

        @foreach (var link in @Model)
            <li><a href="#">@link.Key</a> <span>(***)</span></li> 

            foreach(var item in Model[i])


The nested foreach displays the correct info but on a different line - I would like it positioned where the *** is in code listing.

Also I would like a comma ',' placed between each culture.

Any help appreciated.

Current output showing as:

enter image description here

EDIT: updated code to following and still getting same issue

 @foreach (var link in @Model)
                <a href="#">@link.Key</a> 
                    @foreach(var item in link)

What is best way to get?

I have a field where user will upload video.

When you click the upload button, Video get uploaded. This work perfectly.

I needed the duration of the video from physical path, i tried

using WMPLib;
WindowsMediaPlayer wmp = new WindowsMediaPlayerClass();
IWMPMedia mediaInfo = wmp.newMedia(Server.MapPath("~/Uploads/test.mp4"));
double duration = mediaInfo.duration;

but its not working, i get error The type 'WMPLib.WindowsMediaPlayerClass' has no constructors defined Interop type 'WMPLib.WindowsMediaPlayerClass' cannot be embedded.

How to catch the duration?

I have a C#/.NET project that I want to scan using SonarQube (C# language).

I am getting the scan to pass but with many errors (Over 200 repeated errors)

Provide an 'AssemblyVersion' attribute for this assembly.

This above message is repeated many times and accounts for a majority of SonarQube bugs I see in my report.

SonarQube properties file

# Comma-separated paths to directories with sources (required)
# Language



I even ran this msbuild (using MSBuild.exe Version 14 which I downloaded from https://www.microsoft.com/en-us/download/details.aspx?id=48159) batch file in my project

C:\Users\pwrdbyadmin\Desktop\sonar-scanner-msbuild-\SonarQube.Scanner.MSBuild.exe begin /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"ProjectName" /v:"1.0"
"C:\Program Files (x86)\MSBuild\14.0\Bin\amd64\MSBuild.exe"  /t:Rebuild
C:\Users\pwrdbyadmin\Desktop\sonar-scanner-msbuild-\SonarQube.Scanner.MSBuild.exe end

Downloaded SonarQube 6.5 and ran following command to start server


Command I run from within project


I still cannot resolve many of the .NET errors in my project.

How can I resolve these obvious C# errors that come about after I run SonarQube on my project, do I need Visual Studio installed, do I need to build my project in Visual Studio? What are the proper steps I need to follow to scan my project?


The new three liner allowed analysis to work without any Insufficient Privilege error showing up at the end. I used VS 2017's latest MSBuild.exe in my 3 line command

C:\Users\<UserName>\Desktop\sonar-scanner-msbuild-\SonarQube.Scanner.MSBuild.exe begin /d:"sonar.host.url=http://localhost:9000" /d:"sonar.login=<login>" /d:"sonar.password=<password>" /k:"org.sonarqube:sonarqube-scanner-msbuild" /n:"<ProjectName>" /v:"1.0"
"C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe"  /t:Rebuild
C:\Users\<UserName>\Desktop\sonar-scanner-msbuild-\SonarQube.Scanner.MSBuild.exe end /d:"sonar.login=<login>" /d:"sonar.password=<password>"

In spite of using the updated command sequence, I still get the Assembly Version errors in my report.

Do I need to delete the project and re-analyze. Also, even thought my 3 liner shows MSBuild 15 used the yellow notice comes up saying I am using MSBuild 12. I am not sure why.

I have created OnModelCreating method in ApplicationDbContext class but i can't set the MigrateDatabaseToLatestVersion class because Configuration type couldn't be found. What would be the reason for this?

enter image description here

I'm trying to create an array of strings in javascript by calling a function in my MVC controller and passing back an array of strings. This pretty simply just isn't working and I'm not sure what i need to do to amend this. below you can see both my javascript and controller code. Any help is greatly appreciated


var optionString = @Html.Action("PopulateDashboardDropdown", "Embed", new { Dashboards = Model[0][0].Dashboards });


public string[] PopulateDashboardDropdown(ODataResponseListDashboard[] dashboards)
        string email = "";
        //loop that finds the groupID assigned to the currently logged in user
        foreach (Claim claim in ClaimsPrincipal.Current.Claims)
            if (claim.Type == "emails")
                email = claim.Value;
                email = email.ToLower();
        string[] orgs = GetOrgs(email);
        string[] retVal = new string[orgs.Length];
        bool[] admin = new bool[orgs.Length];
        for (int i = 0; i < orgs.Length; i++)
            admin[i] = isAdmin(orgs[i], email);
            retVal[i] = "";

        //loop that creates a string to emulate the innerHtml of a dropdown selector based on the names of all dashboards in the workspace
        for (int i = 0; i < orgs.Length; i++)
            for (int j = 0; j < dashboards[i].Value.Count; j++)
                if (dashboards[i].Value.ElementAtOrDefault(j).DisplayName.Contains("Admin"))
                    if (admin[i])
                        retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
                    retVal[i] += "<option>" + dashboards[i].Value.ElementAtOrDefault(j).DisplayName + "</option>";
        return retVal;

I have this select element that is being populated by options with a foreach loop.

@foreach (var item in selection)
   <option value="@item.Id" >

For my form I am using the Request.Form[] property to save input values.

value="@(Request.Form["navn"] != null ? Request.Form["navn"].ToString() : "")"

But I am unsure how I can save these values in my request. How I can save the @item.Id in my request form name/value collection? The value is of type string.

Breakpoint hit to ActionResult after some time while changing value combobox or datepicker or from some other controls (Filtering purpose). In that mean time the controls get freezed. If I increase the list items (loaded into partial views) then it get more time to get hit. My filtering code has no problems. It works well after reaching ActionResult method I am not able to find why actually it happens. I've tested across all browsers but it still exists in all.

So I have a database field called Content that saves html-content view as a string like this :

"<table> <tr> <td colspan="3"> header </td> </tr> <tr> <td> left </td> <td>body</td> <td>right</td> </tr> <tr> <td colspan="3"> footer </td> </tr> </table>"

How can i create a view from that string , i mean to render a view that translates this html content (Html.Raw()) and show a ViewResult on screen containing head , body , footer and so on.