I have five check boxes when user click's any check box it fetch records and shows it in a textbox1, I have another textbox where user input code and fetch records which also show in textbox1. Problem is when user click's checks checkbox it brings records but 1 more than the original records and it shows no records when user input code and fetch records in another textbox for the first time.

Here is my page load method where i declared count method.

 int contacts = txt_contacts.Text.Split(',').Length-1;
 codecount.Text = contacts.ToString();

I need some guidance on how to solve a problem here.

Currently i have a c# console application (running in the background), that writes log entries into a sql svr database. I have a IIS based web application that i use to query these log entries periodically.

My task is to replace the database-solution with an "in-memory" solution.

As a web developer, i was thinking "Session" and "Application" State Objects, where i can store and retrieve data. Are there any predefined "memory objects" i can use to write / read to, to make this work? Maybe include a library so i can write to the current Application Object of the WebServer, and then query it from there?

(I do realize we are going to run out of memory with this approach, but that's beside the point) :)

Just a nudge in the right direction would be appreciated.

can someone help me, I got some issues here, I need to do a system where the user need to input data called Lot Id in textfield in order to search the information needed, the result is in the form of gridview. when the user enter the lot id, they will choose & tick checkbox for the category they needed, and then they need to click enter button for the next process which is searching, the result will display at the new page.

my issues here is, the result won't display information according to the particular Lot ID given, it will display the whole data in the database. I don't know where's the mistake is. please help me.

behind coding for enter button in webform1

   Protected Sub getdata(ByVal sender As Object, e As EventArgs) Handles 
   ButtonEnt.Click


    If idText.Text <> "" Then
        Response.Redirect("WebForm2.aspx?= " & "&getdata=" +idText.Text + 
    "&getcater1= " + Locchk.Checked)


        'Else
        'Response.Write("Input One Lot ID")

    End If
    End Sub

   'checkbox
     Protected Friend Sub getcater1(ByVal sender As Object, ByVal e As 
     System.EventArgs)

    idText.Text = Locchk.Checked

     End Sub

this the new page ,webform2:

    Protected Sub BindGrid()

    Dim cLoc As String = Request.QueryString("getcater1")

    Try
        Dim as As String = ConfigurationManager.ConnectionStrings("IMS_LocationConnectionString").ToString
  ()

        Using con As New SqlConnection(as)
        Using cmd As New SqlCommand()

      Dim abc As String
      abc = Request.QueryString("getdata")


    cmd.CommandText = (" USE IMS_LOCATION select  
    coalesce(a.LOT_ID, b.LOT_ID,c.LOT_ID,d.LOT_ID) as LotId, 
    coalesce(a.CheckIn, 
    b.CheckIn,c.CheckIn,d.CheckIn) as CheckIn,coalesce(a.CheckOut, 
    b.CheckOut,c.CheckOut,d.CheckOut) as CheckOut,coalesce(a.StatusDesc, 
    b.StatusDesc,c.StatusDesc,d.StatusDesc) as StatusDesc from LOT_LOC_BOND 
    a LEFT 
    JOIN LOT_LOC_IEBT b ON  a.LOT_ID= b.LOT_ID, LOT_LOC_MBT c LEFT JOIN 
    LOT_LOC_SEAL 
   d ON c.LOT_ID = d.LOT_ID  where a.LOT_ID ='@LOT_ID'")

                cmd.Connection = con
                cmd.Parameters.AddWithValue("@LOT_ID", 
    SqlDbType.VarChar).value= abc
                con.Open()

                Dim dt As New DataTable()
                Dim sda As New SqlDataAdapter(cmd)

                sda.Fill(dt)
                lotlocsum.DataSource = dt

                If dt.Rows.Count <> 0 Then
                    lotlocsum.DataBind()

                Else
                    errorResult1.Visible = True
                End If

            End Using
        End Using

    Catch ex As Exception
    End Try

End Sub

this is the page loader for webform 2 where the BindGrid() will be call

    Protected Friend Sub Page_Load(ByVal sender As Object, ByVal e As 
    System.EventArgs) Handles Me.Load

    'Dim cLoc As String = Request.QueryString("getcater1")



    If Request("getdata") IsNot Nothing Then 
        Me.BindGrid()
    End If

this is the sqlDatasource

   USE IMS_Location

   SELECT  COALESCE(a.LOT_ID, b.LOT_ID, c.LOT_ID, d.LOT_ID)                 
   AS LotId,
   COALESCE(a.CheckIn, b.CheckIn, c.CheckIn, d.CheckIn)             AS 
    CheckIn,
   COALESCE(a.CheckOut, b.CheckOut, c.CheckOut, d.CheckOut)         AS 
    CheckOut,
   COALESCE(a.StatusDesc, b.StatusDesc, c.StatusDesc, d.StatusDesc) AS 
   StatusDesc --missing alias name d  
   FROM   LOT_LOC_BOND a
   LEFT JOIN LOT_LOC_IEBT b
           ON  a.LOT_ID = b.LOT_ID
   LEFT JOIN LOT_LOC_MBT c
           ON  a.LOT_ID = c.LOT_ID
   LEFT JOIN LOT_LOC_SEAL d
           ON  c.LOT_ID = d.LOT_ID 

I am trying to convert numeric numbers to words in vb.net. But somewhere I am getting Type Expected error. Below is my entire code. I am also putting code separately where this error is coming.

Public Shared Function ConvertNumbertoWords(number As Integer) As String
    If number = 0 Then
        Return "ZERO"
    End If
    If number < 0 Then
        Return Convert.ToString("minus ") & ConvertNumbertoWords(Math.Abs(number))
    End If
    Dim words As String = ""
    If (number / 1000000) > 0 Then
        words += ConvertNumbertoWords(number / 1000000) & Convert.ToString(" MILLION ")
        number = number Mod 1000000
    End If
    If (number / 1000) > 0 Then
        words += ConvertNumbertoWords(number / 1000) & Convert.ToString(" THOUSAND ")
        number = number Mod 1000
    End If
    If (number / 100) > 0 Then
        words += ConvertNumbertoWords(number / 100) & Convert.ToString(" HUNDRED ")
        number = number Mod 100
    End If
    If number > 0 Then
        If words <> "" Then
            words += "AND "
        End If
        Dim unitsMap = New () {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE",
            "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN",
            "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
            "EIGHTEEN", "NINETEEN"}
        Dim tensMap = New () {"ZERO", "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY",
            "SIXTY", "SEVENTY", "EIGHTY", "NINETY"}

        If number < 20 Then
            words += unitsMap(number)
        Else
            words += tensMap(number / 10)
            If (number Mod 10) > 0 Then
                words += " " + unitsMap(number Mod 10)
            End If
        End If
    End If
    Return words
End Function

In below line I am getting Type Expected error

Dim unitsMap = New () {"ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE",
                "SIX", "SEVEN", "EIGHT", "NINE", "TEN", "ELEVEN",
                "TWELVE", "THIRTEEN", "FOURTEEN", "FIFTEEN", "SIXTEEN", "SEVENTEEN",
                "EIGHTEEN", "NINETEEN"}
            Dim tensMap = New () {"ZERO", "TEN", "TWENTY", "THIRTY", "FORTY", "FIFTY",
                "SIXTY", "SEVENTY", "EIGHTY", "NINETY"}

I've created a JSon Object with Newtonsoft. When I want to pass it to restful webservice and want to response from it, I get "request timed out" error, although I set Timeout for request is -1 or any. Where can be the problem?

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://app.myservice.com/sendJSon");
    request.ContentType = "text/json";
    request.Method = "POST";
    request.Timeout = 200000;

    JObject asnInfo = CreateAsnInfo();

    JsonSerializer serializer = new JsonSerializer();
    using (var streamWriter = new StreamWriter(request.GetRequestStream()))
    {
        using (var writer = new JsonTextWriter(streamWriter))
        {
            serializer.Serialize(writer, asnInfo);
        }
    }
    var response = (HttpWebResponse)request.GetResponse();
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
    }

I need to catch Ispostback event using javascript for some purpose. I found many example in google but none of them has worked for me. Like one example i used which is below:

$(document).ready(function () {
   var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';
        if (chkPostBack == 'true') {
            alert("Ispostback alert");
        }
        
});

But this is not working.

I am having experience in SAPUI5/OPENUI5. I am trying to create responsive web application to be hosted on IIS server. but I want to use OpenUI5.

Till now to achieve my desire I have come to the following solution.

  1. Follow MVC architecture by SAPUI5/Fiori principles.
  2. Use PageMethods/WebMethods to call C# code from JavaScript
  3. C# to get the data from SQL Server and expose it to JSON model and bind the view.

Kindly let me know if someone has tried it or have any better solution.

I am trying the above approach but not able to call the C# method.

Every bit of information is appreciated.

Thanks, Nooru

Here's my html

  <table class="table table-responsive table-bordered" style="width:100%" id="HeightConfig">
    <tbody id="HeightConfigBody">
@if (Model != null)
{
@foreach (var data in Model.Reverse())
{
     <tr>
                         <td style="width:40%">
  <label><b>Recorded Time:</b> <input type="text" id="recordDate"  class="recordDate"   
  value="@data.recordDate.ToString("yyyy-MM-dd")" disabled></label>
                      </td>



                       <td style="width:40%">
                         <label><b>Height (CM):</b> <input type="text" id="ColumnTypeData" class="ColumnTypeData" 
                          value="@data.ColumnTypeData" ></label>
                      </td>

                      <td style="width:40%">
                           <a class="btn btn-primary btn-default" title="delete"
                            data-target="#modal-container" data-toggle="modal" data-align="center">
                            <div id="minusHeight"><i class="fa fa-minus" aria-hidden="true"></i></div>
                            </a>


     <a class="btn btn-primary btn-default" title="add"  >
                              <div id="addHeight" ><i class="fa fa-plus" aria-hidden="true"></i></div>
     </a>
                       </td>

</tr>

}
}

     </tbody>
  </table>

I need to hide the "plus button" in the third column, and display only in the last row.

this is what I got

<script>
 debugger;
        var x = document.getElementById("HeightConfig").rows.length;
        var ctr = 1
        $("#HeightConfig tbody tr").each(function (key, value) {
            debugger;

            if (ctr != x)
            {
                $(this).find('.addHeight').hide();

            }
            ctr++;
        });
</script>

i get first the length of the table, then loop on each row, then when the counter match the last row of the table it will not hide the button

I'm using Visual Studio 2017 Community Edition

This project is being developed on ASP.NET Core and EntityFramework Core.

I'm very new in ASP.NET

My Domain Model

public class Books
{
    public int Id { get; set; }

    [Required]
    [StringLength(256)]
    public string Name { get; set; }

    public Publisher Publisher { get; set; }

    [Display(Name = "Publisher")]
    public int PublisherId { get; set; }

    public Category Category { get; set; }

    [Display(Name = "Category")]
    public int CategoryId { get; set; }

    [Range(0,99999999999999)]
    public long? Barcode { get; set; }

    [Range(0, 100000)]
    [DisplayFormat(DataFormatString = "{0:n3}", ApplyFormatInEditMode = true)]
    public Int? Pages { get; set; }

    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
    [Range(0, 1000000000000)]
    [Display(Name = "Cost (₹)")]
    public decimal CostPrice { get; set; }

    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
    [Range(0, 1000000000000)]
    [Display(Name = "MRP (₹)")]
    public decimal Mrp { get; set; }

    [DataType(DataType.Currency)]
    [DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
    [Range(0, 1000000000000)]
    [Display(Name = "Price (₹)")]
    public decimal SellingPrice { get; set; }

    [Display(Name = "Tax %")]
    public Tax Tax { get; set; }

    [Display(Name = "Tax %")]
    public int TaxId { get; set; }

    public int Stock { get; set; }

    public int Capacity { get; set; }

    [Display(Name = "Last Updated")]
    public DateTime LastUpdated { get; set; }

    public string Description { get; set; }
}

If I Bind few of the properties to the model will it work?

My Controller Class

// GET: Books/Add/5
    public async Task<IActionResult> Add(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var book = await _context.Book.SingleOrDefaultAsync(m => m.Id == id);
        if (book == null)
        {
            return NotFound();
        }
        return View(book);
    }

    // POST: Books/Add/5        
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Add(int id, [Bind("Id,Stock,LastUpdated")] Book book)
    {
        if (id != book.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                if (book.Stock > book.Capacity)
                {
                    book.Capacity = book.Stock;
                }
                _context.Update(book);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BookExists(book.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction("Index");
        }

        return View(book);
    }

My View Page

<form asp-action="Add">
<div class="form-horizontal">
    <h4>Product</h4>
    <hr />
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
    <input type="hidden" asp-for="Id" />

    <div class="form-group">
        <label asp-for="Stock" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Stock" class="form-control" />
            <span asp-validation-for="Stock" class="text-danger"></span>
        </div>
    </div>

    <input type="hidden" asp-for="LastUpdated" class="form-control" value="@DateTime.Now" />

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div></form>

As you can see I've created only one input field from which the user inserted value will be will be added (arithmatic addition) with the value of stock (model property) already present in the database and then the sum will be updated in the database.

I set attributes into a dropdownlist

the problem is that when I try to read them in a button click I get null !!

Why is that and how to fix it?

This is my Code

    protected void ddlReps_DataBound(object sender, EventArgs e)
    {
        foreach (System.Data.DataRow row in dt.Rows)
        {
            ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportPath", row["ReportPath"].ToString());
            ddlReps.Items.FindByValue(row["ReportID"].ToString()).Attributes.Add("ReportServer", row["ReportServer"].ToString());
        }
        string AttribValue1 = ddlReps.SelectedItem.Attributes["ReportPath"];
     //When I check here I can see the valu
    }

    protected void btnViewReport_Click(object sender, EventArgs e)
    {
        string AttribValue2 = ddlReps.SelectedItem.Attributes["ReportPath"];
     //Here is null :(
    }

I created a method that traverses the data returned from the primary key in a repeat structure but the following error occurs, Can not implicitly convert type "System.Attribute" to "bool"

  using System;
  using System.Collections.Generic;
  using System.ComponentModel;
  using System.Data.SqlClient;
  using System.Linq;
  using System.Reflection;
   using System.Web;





 private void SetSelf(Cliente Entity)
    {
        //percorre os dados retornados da primaryKey
        foreach (PropertyInfo pro in Entity.GetType().GetProperties())
        {

            if (this.GetType().GetProperty(pro.Name).GetCustomAttribute(typeof(DataObjectFieldAttribute)) //Can not implicitly convert type "System.Attribute" to "bool"
                this.GetType().GetProperty(pro.Name).SetValue(this, pro.GetValue(Entity));

        }

    }

My JavaScript is working perfectly, though my radio buttons will not display as checked when clicked. When I alt+tab away from my web page and alt+tab back, it shows a shaded circle around the radio button, but still no proper check fill. Why is this?

I'm hoping this is an easy fix. I updated my asp radio button to call a JavaScript function as my ASP codebehind was issuing a postback and clearing some controls on my page. Needless to say, with the asp c# code behind functionality, the radio buttons were properly checking when clicked. I simply need to see the checks on the radio buttons when clicked with the JavaScript functionality in place. Here is my radio control HTML:

<div class="col s12 form-section" id="crimeInsurance">
            <h4 class="section-heading">CRIME INSURANCE</h4>
            <p>
                <asp:RadioButton ID="radLLCrimeIns" runat="server" GroupName="CrimeInsurance" ClientIDMode="Static" CssClass="with-gap" OnClick="return CrimeInsuranceToggle();" AutoPostBack="true" text="ACCEPT Crime Insurance (fee of $250.00)" />
            </p>
            <p>
                <asp:RadioButton ID="radLLNOCrimeIns" runat="server" GroupName="CrimeInsurance" ClientIDMode="Static" CssClass="with-gap" OnClick="return CrimeInsuranceToggle();" AutoPostBack="true" text="DO NOT ACCEPT Crime Insurance" />
            </p>
        </div>

and here is my JavaScript method:

function CrimeInsuranceToggle() {
        //controls the crime insurance radio yes/no buttons to update crime insurance fees
        var oCrimeRte = document.getElementById("lblCrimeCovFlatRate");
        var oCrimeTtl = document.getElementById("lblCrimeCovAmtDue");
        var oCrimeY = document.getElementById("radLLCrimeIns");
        var oCrimeN = document.getElementById("radLLNoCrimeIns");

        var radios = document.getElementsByTagName('input');
        var value;
        for (var i = 0; i < radios.length; i++) {
            if (radios[i].type === 'radio' && radios[i].checked) {
                //find each radio that is checked, and act on the ID
                value = radios[i].value;
                if (value == 'radLLCrimeIns') {
                    oCrimeTtl.innerHTML = oCrimeRte.innerHTML;
                    radios[i].checked = true;
                }
                else if (value == 'radLLNOCrimeIns') {
                    oCrimeTtl.innerHTML = "0.00";
                    radios[i].checked = true;
                }
            }
        }

        return false;
    }

Help is very much appreciated.

I'm trying to pass a map to a view. Before that I populate it with data from some entities(Session, Movie, Theater). I start doing a selection in my sessions:

var sessions = from s in db.Sessions where s.TheaterID == id orderby s.MovieID, s.Time select s;

This is the method. Inside it I iterate over each session and verify if in my map I have a list with the movie name as a key. When execution reaches thie very point I'm receiving the infamous "There is already an open DataReader associated with this Command which must be closed first." exception. I can't cast to a list because of types:

public ActionResult MyAction(int id)
        {
            Theather theater = db.Theater.Find(id);
            ViewBag.TheaterName = theater.NomeCinema;
            var sessions = from s in db.Sessions where s.TheaterID == id orderby s.MovieID, s.Time select s;

            var mapMovies = new Dictionary<string, List<DateTime>>();

            foreach (Session s in sessions)
            {
                if ( !mapMovies.ContainsKey( s.Movie.MovieName ) )
                {
                    mapMovies.Add( s.Movie.MovieName, new List<DateTime>() );
                }
                mapMovies[s.Movie.MovieName].Add(s.Time);
            }
            ViewBag.MapMovies = mapMovies;
            return View();
        }

What do Ineed to do to pass this error?

So unfortunately I'm dealing with a C# Razor Web-forms (NOT MVC) web application.

I was given a C# program with a class consisting of async functions that I need to make work on a cshtml page and I cannot figure out how...

The two functions below are from a C# class that worked well with a C# Forms application. (Notice that "TextBox1" is assigned the text).

My problem is that I need the string variable "xml" to be displayed on a cshtml page (preferably in a "textarea" element) and I cannot seem to call the showData() function to retrieve the value

Can anyone help?

 public static async void showData(string gID)
{
    string xml = "";
    try
    {
       xml = await WaitAsynchronouslyAsync(gID);
       //The original code set a TEXTBOX to the string value
       //I need to revise this code so that I can display it on a cshtml page
       TextBox1.Text = xml;

    }
    catch (HttpRequestException)
    {
        throw new ApplicationException("Could not connect to the server");
    }       
}


public static async Task<string> WaitAsynchronouslyAsync(string gID)
{
    await Task.Delay(10);
    urlLink = "*** A custom Intranet URL ***";
    ....
    ....
    ** preparing a Token/Client response url **
    ....
    ....
    string result = await serviceClient.GetStringAsync(urlLink);
    return result;
}

I've tried to bypass the void function and access the Task<string> function, but I cannot convert a Task<string> to a string value.

I'm trying to add a navigation sidebar in a simple web app that has two primary models, and I'm running into a peculiar error when I try to use a nested loop to render data in the sidebar.

My app has two models like Category and Thing in the example below:

public class Category
{
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Things> Thing { get; set; }
}

public class Thing
{
    public int ID { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public int CategoryID { get; set; }
    public virtual Category Category { get; set; }
}

I want to add a sidebar that contains a list of all my Categories. I created a ViewComponent that I'm referencing in _Layout.cshtml like so:

// SidebarViewComponent.cs
public class SidebarViewComponent : ViewComponent
{
    private readonly MyContext db;

    public SidebarViewComponent(MyContext context)
    {
        db = context;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        var categories = await GetCategoriesAsync();
        return View(categories);
    }

    private Task<List<Category>> GetCategoriesAsync()
    {
        return db.Category.ToListAsync();
    }
}

// View file for SidebarViewComponent
@model IEnumerable<MyApp.Models.Category>
<div id="sidebar">
    @foreach (var category in Model)
    {
        <div class="header">@category.Name</div>
            @foreach (var thing in @category.Things)
            {
                <div>@thing.Title</div>
            }
        </div>
    }
</div>

// _Layout.cshtml
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewData["Title"]</title>

    <!-- Stylesheets -->
    <link rel="stylesheet" href="~/css/site.css">
</head>
<body>
    @await Component.InvokeAsync("Sidebar")
    @RenderBody()
</body>
</html>

When I access a page that's rendered by my ThingController, this works perfectly. But on my home page or any page handled by CategoryController, I get the error "NullReferenceException: Object reference not set to an instance of an object." at the line @foreach (var thing in @category.Things).

How can I get this sidebar to work on every page?

I made a method called update that updates the data in the database,Which calls the method named GetUpdateCommand that has the method with the database update command,I created a variable cn that receives the connection string with bank,But when trying to open the connection and surround it with a try catch, it does not find the variable cn with the connection, Because you can not find the variable

public SqlCommand GetUpdateCommand()
    {

        //faz o for em que vai percorrer, traga somente os campos com o atributo customizado do tipo DataObjectFieldAttribute
        SqlCommand retorno = new SqlCommand();
        retorno.CommandText = "Update  {0}  set {1} where {2}";

        String tabela = typeof(T).Name;
        String campos = "";
        String chave = "";
        foreach (PropertyInfo pro in typeof(T).GetProperties().ToList().Where(p => p.GetCustomAttribute(typeof(DataObjectFieldAttribute)) != null))
        {
            DataObjectFieldAttribute att = (DataObjectFieldAttribute)pro.GetCustomAttribute(typeof(DataObjectFieldAttribute));

            if (att.PrimaryKey==true)//defini a chave primaria no DataObjectField na classe cliente colocando true
            {
                chave= pro.Name + "=@" + pro.Name;//pega a chava a chave primaria e adc no parametro
                retorno.Parameters.AddWithValue("@" + pro.Name, pro.GetValue(this));//adicona os parametros
            }
            else
            {
                campos += pro.Name + "=@" + pro.Name + ",";
                retorno.Parameters.AddWithValue("@" + pro.Name, pro.GetValue(this));
            }


        }
        //retorna com os parametros de acordo com o comando sql do uopdate.
        retorno.CommandText = String.Format(retorno.CommandText, tabela, campos,chave);

        return retorno;


    }

 public void atualizar()
    {

        using (SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|C:\Users\Antonio Viana\documents\visual studio 2017\Projects\Loja\Eccomerce\App_Data\dados.mdf;Integrated Security=True")) ;
        {

            SqlCommand cm = this.GetUpdateCommand();

            try
            {
                cn.Open();
            }
            catch (Exception)
            {

                throw;
            }

            cm.Connection = cn;
            cm.ExecuteNonQuery();
        }

    }

I have some existing functionality in unmanaged C++ which I wanted to use in a Web App. This code was already wrapped in C++/CLI and used via desktop C# apps. So there is already an existing mixed mode .NET assembly containing the functionality I want to use in a Web App. I also already have Azure hosted web apps that are composed of assemblies containing only C# and I can publish them from Visual Studio 2017 to an Azure App service with no problem.

So I tried to add the mixed mode assembly and started getting errors from the publish about the dependencies of the mixed mode assembly. The only dependency of the mixed mode assembly is on the VC++ runtime so I assumed that was the problem. To prove this I created an Azure VM started IIS on it and published to that and got exactly the same error. I then installed the VS 2017 C++ runtimes on the VM and published again. The error went away and the Web site works fine.

I them logged onto the machine hosting the Web service using Kudu and it appears to have the VS 2017 C++ run time already installed. So I am baffled why I get the error when I publish to it. I have tried adding the runtime DLL's like vcruntime140.dll to my publish but this didn't fix things. I also tried re-installing the runtimes with no luck.

So does anyone have any insights as to why I am getting DLL dependency errors and what I can do to fix it. Ideally I was hoping for a Hello World example of using C++/CLI in a Web App from Microsoft but have not been able to find one.

Note there is a similar question here multi-file c++/cli .net assembly in ASP.NET web site without an answer.

I am getting the following issue on my identy pages. I am very new to the way the new identy core works so please excuse me. Yes my tables have been created in sql server fine. If anyone has an idea please let me no.

enter image description here

InvalidOperationException: Unable to resolve service for type 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext' while attempting to activate 'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4[Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUser,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext,System.String]'. Microsoft.Extensions.DependencyInjection.ServiceLookup.Service.PopulateCallSites(ServiceProvider provider, ISet callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)

My database context is as follows

public class solitudeDContext : IdentityDbContext<IdentityUser>

{ 
 public solitudeDContext(DbContextOptions<solitudeDContext> options) : base(options)
    {
    }
    public DbSet<basketheader> BasketHeader { get; set; }
    public DbSet<basketlines> BasketLines { get; set; }
    public DbSet<customer> Customer { get; set; }

}

This is my account controller which I do not see why is casuing this

public class AccountController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly IMessageService _messageService;

        public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, IMessageService messageService)
        {
            this._userManager = userManager;
            this._signInManager = signInManager;
            this._messageService = messageService;
        }

        public IActionResult Register()
        {
            return View();
        }
        [HttpPost]

        public async Task<IActionResult> Register(string email, string password, string repassword)
        {
            if (password != repassword)
            {
                ModelState.AddModelError(string.Empty, "Password don't match");
                return View();
            }

            var newUser = new IdentityUser
            {
                UserName = email,
                Email = email
            };

            var userCreationResult = await _userManager.CreateAsync(newUser, password);
            if (!userCreationResult.Succeeded)
            {
                foreach (var error in userCreationResult.Errors)
                    ModelState.AddModelError(string.Empty, error.Description);
                return View();
            }

            await _userManager.AddClaimAsync(newUser, new Claim(ClaimTypes.Role, "Administrator"));


            var emailConfirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);
            var tokenVerificationUrl = Url.Action("VerifyEmail", "Account", new { id = newUser.Id, token = emailConfirmationToken }, Request.Scheme);

            await _messageService.Send(email, "Verify your email", $"Click <a href=\"{tokenVerificationUrl}\">here</a> to verify your email");

            return Content("Check your email for a verification link");
        }

        public IActionResult ForgotPassword()
        {
            return View();
        }
        public IActionResult ResetPassword(string id, string token)
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> ResetPassword(string id, string token, string password, string repassword)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
                throw new InvalidOperationException();

            if (password != repassword)
            {
                ModelState.AddModelError(string.Empty, "Passwords do not match");
                return View();
            }

            var resetPasswordResult = await _userManager.ResetPasswordAsync(user, token, password);
            if (!resetPasswordResult.Succeeded)
            {
                foreach (var error in resetPasswordResult.Errors)
                    ModelState.AddModelError(string.Empty, error.Description);
                return View();
            }

            return Content("Password updated");
        }
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return Redirect("~/");
        }
        [HttpPost]
        public async Task<IActionResult> ForgotPassword(string email)
        {
            var user = await _userManager.FindByEmailAsync(email);
            if (user == null)
                return Content("Check your email for a password reset link");

            var passwordResetToken = await _userManager.GeneratePasswordResetTokenAsync(user);
            var passwordResetUrl = Url.Action("ResetPassword", "Account", new { id = user.Id, token = passwordResetToken }, Request.Scheme);

            await _messageService.Send(email, "Password reset", $"Click <a href=\"" + passwordResetUrl + "\">here</a> to reset your password");

            return Content("Check your email for a password reset link");
        }

        [HttpPost]
        public async Task<IActionResult> Login(string email, string password, bool rememberMe)
        {
            var user = await _userManager.FindByEmailAsync(email);
            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "Invalid login");
                return View();
            }
            if (!user.EmailConfirmed)
            {
                ModelState.AddModelError(string.Empty, "Confirm your email first");
                return View();
            }

            var passwordSignInResult = await _signInManager.PasswordSignInAsync(user, password, isPersistent: rememberMe, lockoutOnFailure: false);
            if (!passwordSignInResult.Succeeded)
            {
                ModelState.AddModelError(string.Empty, "Invalid login");
                return View();
            }

            return Redirect("~/");
        }
    }

The Contents of my startup.cs

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    public IConfigurationRoot Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc();
        services.AddDbContext<solitudeDContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),b=>b.MigrationsAssembly("solitudeeccore")));
        services.AddIdentity<IdentityUser, IdentityRole>()
   .AddEntityFrameworkStores<IdentityDbContext>()
   .AddDefaultTokenProviders();

    }

I need to check the span`s text and based on the text replace it with the span class. It uses asp Repeater and creates a table.

<span class="label label-default" id="status">

<%# Eval("ProjectStatus")%>

and my not working javascript:

var status = document.getElementById('status').innerHTML;

          for (var i = 0; i < status.length; i++) {
              if (status === "Completed") {
                  status[i].innerHTML = "<span class='label label-success'> + status + </span>";
              }
          }

So the compiled code looks like this:

<span class="label label-default" id="status">Completed</span>
<span class="label label-default" id="status">Hopper</span>

So my goal here is to check which text has that span and replace its class depending on that text. If its Completed set class='label label-success' and so on. thanks.

I am trying to solve this issue from last 6 hours, but couldn't complete it.

here I have one template script in my Razor view.

<script type="text/template" id="Blog_Post_Template">   

    {{if DescType == "FULL"}}
            ${FDesc}
    {{/if}}

    {{if DescType == "SORT"}}
            ${SDesc}
    {{/if}}

</script>

Now, what I want is to use Razor function inside this template.

Let's take @Html.Raw(), I want to use @Html.Raw() in ${FDesc}, and ${SDesc}.

I tried many escape sequences like,

@Html.Raw("'${FDesc}'")
@Html.Raw("\'${FDesc}\'")

And mane more solutions, but I came up at the point where I started.

Input is like, A simple text with html parameters

<p> Test this </p>

Output will be a html

Appreciate, if anyone can resolve it..