I'm working on MVC project and I'm looping some values, and sometimes ome of those values is null:

enter image description here

What can I write and how can I write ?? operator or whatever in case @Item.User_class.User1.Nickname is null to set some default values.

Code:

@foreach (var item in ViewBag.nextClassesList)
{ 
    <tr class="@item.Status">
        <td>@item.ClassDate</td>
        <td>@item.User_Class.User1.NickName ? @item.User_Class.User.NickName   </td>
        <td>@item.User_Class.ClassType.ClassTypeName.Name (@item.User_Class.ClassType.ClassTypeName.Time min)</td>
    </tr>
}

So this line is problem:

<td>@item.User_Class.User1.NickName ? @item.User_Class.User.NickName   </td>


<td>@item.User_Class.User1.NickName </td> Is null sometimes...

I´m using VS 2013 sql server 2014, I´m trying to do this tutorial https://www.c-sharpcorner.com/article/simple-login-application-using-Asp-Net-mvc/

And I´m getting an error here

ar obj = db.UserProfiles.Where(a => a.UserName.Equals(objUser.UserName) && a.Password.Equals(objUser.Password)).FirstOrDefault();

Error: The specified schema is not valid. Errors: \ r \ nThe assignment of the CLR type to the EDM type is ambiguous because several CLR types match the EDM type 'UserProfile'. Type CLR previously found 'MvcLoginAppDemo.Models.UserProfile', type CLR just found 'MvcLoginAppDemo.UserProfile'. "}

And I don´t understand this

I have a dto something like:

public class simpleDto
{
    public string categoryOne;
    public string categoryTwo;
}

I am posting it like this:

public async Task<IHttpActionResult> PostIt( [FromBody] simpleDto model)

It is returning 400 bad request error when categoryTwo is null.

How can I post values even categoryTwo is null ?

In my Default.aspx I have a dropdown list that pulls indextypes from an Object Data source. Code Below

<h4>Index to search</h4>
<asp:DropDownList ID="dlSearchIndex" runat="server" CssClass="input-group " 
DataTextField="INDEX" DataValueField="INDEX" Width="150px" 
DataSourceID="ObjectDataSource1">
</asp:DropDownList>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
SelectMethod="GetIndexType" TypeName="the.dll"> 
</asp:ObjectDataSource>

I am trying to use cookies to set selectedvalue of this dropdown list like this:

If IsPostBack = False Then
        If Request.Cookies("IndexToSearch") IsNot Nothing Then
            dlSearchIndex.SelectedValue = 
            Request.Cookies("IndexToSearch").Value.ToString()
            Response.Cookies("IndexToSearch").Value = 
             dlSearchIndex.SelectedValue
            Response.Cookies("IndexToSearch").Expires = 
            DateTime.Now.AddSeconds(10)
        Else
            Response.Write("<p> No Cookie Found.</p>")
        End If
    End If

And I am creating the cookie like this:

If Request.Cookies("IndexToSearch") Is Nothing Then
            Dim cookie As New HttpCookie("IndexToSearch")
            cookie.Value = Trim(dlSearchIndex.SelectedValue)
            cookie.Expires = DateTime.Now.AddSeconds(350)
            Response.SetCookie(cookie)
            Response.Write("<p>" & cookie.Name & ":" & cookie.Value & ":")
        End If

The first time I run this code it works but after that I get this error:

"dlSearchIndex" has a SelectedValue which is invalid because it does not 
exist in the list of items.
Parameter name: value 

Please, what am I doing wrong? Thank you in advance!

I am getting this error

System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)'

When I try to run my ASP.NET MVC project. Opening it for the first time on this PC.(I try to register a user and the database doesn't get created and I get the error above.) The database should get created the first time I hit the database PS: It's a code first project I thought I know how to fix it until now. The project runs on my other PC but on this not. So I thought I'll go and change the connection string to

<connectionStrings>
    <add name="foo"
         providerName="System.Data.EntityClient"
         connectionString="Data Source=localhost"/> 
</connectionStrings>

(just change the Data Source= to localhost) The constructor in my DbContext is

public EventManagerDbContext() : base("foo")
        {

        }

Still I can't run my project. PS: I am able to connect to my database using the SQL Server Management Studio, but not from the project. Why is that?

It works only if I remove the angular directive ng-app:

doesn't work:

<div ng-app="">
  @Html.DropDownListFor...
</div>

it works:

<div>
  @Html.DropDownListFor...
</div>

Any idea on how to maintain the selected value on post back inside an angular ng-app?

I have 2 side-by-side CheckBoxList. My purpose is when I check one item in List1, I add that item to the second list. Below is the code I have written.

The problem is it always adds the first item I selected.

protected void lbxSource_SelectedIndexChanged(object sender, EventArgs e)
{
    ListItem itm = lbxSource.SelectedItem;
    ListItem newItem = new ListItem(itm.Text, itm.Value);
    lbTrg.Items.Add(newItem);
}

Actually in the event, I don't know how to get what item I checked last time.

I have a Textbox on Asp.Net page and it lose the focus after Postback. This page is under the MasterPage and MasterPage is using AjaxControlToolKit. It looks like AjaxControlToolKit update panel asynchronous post back is causing an issue.

waiting for help.

I have been working to get a BASIC EXAMPLE of dynamically updating a Progressbar on an asp.net page by incrementing a counter on a c# page. I would like the Progressbar to "grow" as the variable "Jcount" increases. I have tried a hidden text file, and jquery - but I am missing something. Can someone please help. Here is my BASIC EXAMPLE code:

     <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="J2.aspx.cs" Inherits="BASICEXAMPLE.J2" %>
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
    </head>
    <body>
    <form id="form1" runat="server">
    <div>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"/>
    <link rel="stylesheet" href="/resources/demos/style.css"/>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script>
      $(function ()
      {
        $( "#progressbar" ).progressbar({
        value: 27
        });
      });
    </script>
    <div id="progressbar" style="background-color:green; height:80px"></div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
    </div>        
    </form>
    </body>
    </html>

AND

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BASICEXAMPLE
{
public partial class J2 : System.Web.UI.Page
{
    protected int Jcount;
    protected void Page_Load(object sender, EventArgs e) { }
    protected void Button1_Click(object sender, EventArgs e)
    {
       Prog();
    }
    public void Prog()
    { 
        Jcount = 0;
        do
        {
            Jcount++;
            System.Threading.Thread.Sleep(500);  //sleep 0.5 seconds
 //               progressbar.Attributes.Add("value", Jcount);
        }
        while (Jcount < 100);
    }
   }
   }

I created a web application and a model. Then generated dbcontext class and database instance. After I built project, tried to connect database from server explorer in visual studio but could not connect database. Tried to test connection but got 'This connection cannot be tested because the specified database does not exist or is not visible to the specified user.' error.

Whenever I tried to scaffold view or controller I got 'Unable to retrieve metadata for ... one or more validation errors were detected during model generation ModelsTable is based on type TestModel that has no keys defined.' common error.

When I created database object in controller class and write query got same error no key defined.

Also made updates on packages and tried again. I think my connection string is correct.

Here is my model.

public class StateModel
{
    [Key]
    public string ID { get; } = Guid.NewGuid().ToString();
    public string AreaName { get; set; }
    public bool IsWorking { get; set; }
    public string UserName { get; set; }
    public DateTimeOffset Time { get; set; }
}

So I could not use scaffolding, entity framework and write query.

I searched on internet tried founded solutions but did not understand and could not solve. I hope did not ask unneccessary questions. Thanks for your helping.

I have inherited this code which runs a 1-second-JQuery-Ajax-loop on the client side. It used to heavily exploit cookies and I am trying to change it to plain stateless HTTP at least, but now I have the following problem: every POST from the client is processed, and the first few GETs too, but after a short while the server-side HttpHandler is not even called on GET requests and the client code success callbacks always get passed the same - non-updated - data.

//edit: since people tend to assume otherwise: I have stepped through the code with a debugger, so when I say "handler is not called on get requests" and "client code success callbacks get passed the same data always" I mean that quite literally.

I figure this might be a problem of the Web Server caching responses to HTTP requests, but it's kind of a wild guess.

So I have a bunch of questions which might help me solve such problems in the future:
- Is this a reasonable theory?
- I would like to somehow have an overview over all the HTTP requests the server registers and how he chooses to process them.
- Also, where and how would I go about configuring the server beyond the web.config, if for example I wanted to configure its caching behaviour?

I was trying to display sections from my documents after completing an azure search so in my following code

console.WriteLine("Highlights from Document: " +  documentQuery.Results[x].Highlights); 

but is keeps on returning null because my query does not have hit highlights, how do I do this in the parameters? My documents are all word documents.

var parameters = new SearchParameters
{
  QueryType = QueryType.Full,
  SearchMode = SearchMode.Any,
  IncludeTotalResultCount = true,

  HighlightPreTag = "<b>",
  HighlightPostTag = "</b>"
};

documentQuery = credentials2.IndexClient.Documents.Search(searchText,parameters);

The following line of code is not printing out anything

Console.WriteLine("Highlights from Document: " + documentQuery.Results[x].Highlights);

I am trying to set the Expires header value in my web api response, but its not working even after I set it to expire after 7 days.

respMsg.Content.Headers.Expires = DateTimeOffset.Now.AddDays(7);

I added that line of code to my HttpResponseMessage and return that in the end. I still get a value of -1 for my Expires field in the response header.

Below is my code for the GET method :

public HttpResponseMessage Get()
{
    List<string> vals = new List<string>();
    using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = @"                                       
                                    SELECT [ID]
                                    ,[Name]
                                    ,[Age]
                                    FROM [Customers]
                                    ";
                cmd.Connection = conn;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    foreach(DataRow dr in dt.Rows)
                    {
                        vals.Add(dr["Name"].ToString());
                    }
                }
            }
        }
    }
    var respMsg = Request.CreateResponse(HttpStatusCode.OK, vals);
    respMsg.Content.Headers.Expires = DateTimeOffset.Now.AddDays(7);
    return respMsg;
}

how to print rdlc report programatically in asp.net? have an application where I have to print a RDLC report using print button in asp.net

I have a legacy ASP.NET 3.5 (NOT ASP.NET MVC )application using VB.NET. I want to download an excel spreadsheet when a user clicks on a button.I am using OpenXML library. I have used the same feature in ASP.NET MVC where you could return a file using OpenXML like this:-

public FileContentResult GetCollectionsExcel()
{
    var collections = CurrentBroker.Collections;

            var model = new FinancialCollectionsModel(collections);

            var package = new ExcelPackage();
            var sheet = package.Workbook.Worksheets.Add("Collections");

   return File(package.GetAsByteArray(),"application/vnd.openxmlformatsofficedocument.spreadsheet.sheet", "Collections.xlsx");
}

What would be it's equivalent in traditional ASP.NET and VB.NET ? What should be the return type of the method as we don't have a FileContentResult in ASP.NET.

This is my chart code.

<!-- Graphs -->
<script src="../Scripts/Chart.min.js"></script>
<script>
  var ctx = document.getElementById("myChart");
  var myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
      datasets: [{
        data: [1, 6, 2, 5, 9, 5, 6],
        label: "Issues Resolved",
        lineTension: 0,
        backgroundColor: 'transparent',
        borderColor: '#007bff',
        borderWidth: 4,
        pointBackgroundColor: '#007bff'
      }, {
                data: [8, 5, 8, 6, 0, 2, 2],
                label: "Issues Raised",
                lineTension: 0,
                backgroundColor: 'transparent',
                borderColor: '#ff8400',
                borderWidth: 4,
                pointBackgroundColor: '#ff8400'
          }]
    },
    options: {
      scales: {
        yAxes: [{
          ticks: {
            beginAtZero: false
          }
        }]
      },
        legend: {
            display: true
        },
        title: {
                  display: true,
                  text: 'Issues Raised VS Issues Resolved'
                }
    }
    });
</script>

This graph, though working fine, is static. What I want to ask is whether I can dynamically change the data (of which I'll always have 7 values, for each day of the week) in my datasets (of which I'll always have 2 values, for issues raised and issues resolved) from my .aspx.cs (which will get this data from my SQL Database) at runtime. And if so, how?

Thank you for your help.

I have a method defined as follows

[Route("public/sites/GetAllForWeb")]
    [HttpGet]
    public IEnumerable<Domain.Site.Site> GetAllForWeb(DateTime date, int hour, string parameterCode = null)

That is then being called as follows (angular)

return this.http.get<Site[]>("public/sites/GetAllForWeb?date=" + date + "&hour=" + hour + ((parameterCode === undefined) ? "" : "&parameterCode=" + parameterCode)

Unfortunately the call doesn't match any controller methods, I am assuming because of the lack of parameters in the Route attribute.

How should the Route attribute be modified to correctly reflect the method signature?

I am trying to connect to local FTPS (FileZilla Server) with a certificate and no password with a local Certificate (crt)

When I test the connection with FileZilla Client, it works.

But when I am trying to connect through a webapp in ASP.NET like this.

System.Net.Security.SslStream stream = new System.Net.Security.SslStream(this.tcpClient.GetStream());
System.Security.Cryptography.X509Certificates.X509Certificate serverCertificate = new System.Security.Cryptography.X509Certificates.X509Certificate("C:\\MyLocal\\Certificate\\mycert.crt");
stream.AuthenticateAsServer(serverCertificate, false, System.Security.Authentication.SslProtocols.Tls12, true);

I always get the exception Cannot find the requested object.\r\n on the second line.

Any thoughts?

I'm currently using geolocation to get the clients browser location. Right now, I store the values in local storage and then send them when the user submits the form. I would like to send them before the page even loads however, so that I can run the required calculations when the page is first opened on the client side.

Here is the javascript I am using to get the location (which works well). It runs before the page is loaded.

 navigator.geolocation.getCurrentPosition(foundLocation, noLocation);

 function foundLocation(position) {
    if (isPostBack == true) {
            return;
    }

    var lat = position.coords.latitude;
    var long = position.coords.longitude;

    this.localStorage.setItem("lat", Math.round(lat * 1000000) / 1000000);
    this.localStorage.setItem("long", Math.round(long * 1000000) / 1000000);         
 }

I then use window.onload and call the values in storage to load them on the form automatically. The user then clicks a button and the form submits with the values.

How can I just send those values directly to the server? This would allow me to run the required location calculations without the user even having to click. I know I could just automate the submit button click after after the window.onload fires, but I don't want it to look like the form loads, submits then posts back if that makes sense.

I'm new to asp.net so I'm not even sure what question to ask here so my apologies if this is something simple I'm just looking over.

EDIT: The "possible duplicate" is regarding executing js before page load which I am already doing. My question is more on how to send the values back to the server before loads complete.

My ASP.NET application runs on a Windows Server 2008 R2 server. Oracle 11g is installed.

I deployed this application to a Windows Server 2016 server. Oracle 12c is installed in this server (11g is not supported).

When I run the application, I get this error:

Could not load file or assembly Oracle.DataAccess

If I copy Oracle 12c dll (Oracle.DataAccess.dll) to application's bin folder, I see this message:

The provide is not compatible with the version of Oracle client

Is there any way to make this application run without installing Oracle 11g or changing application code?

enter image description here

I have this problem: I am trying to figure out why all my requests for image uploading are pending for more than minute when I try to upload more than 1 image. I relatively fast find out that problem is https. When I visit my web site without http then everything is working fine. I want to point out that problem is not in code meaning that problem is not that request comes in my ASP.NET Web Api controller then there is some database or file system delay.No, problem is that there is huge delay, almost two minutes then when request comes to controller it executes in 2 or 3 seconds. enter image description here

Server configuration: IIS 10

EDIT: Here is update and bounty also. I figured out something. When on IIS I go to site settings and go to SSL settings and check Client cerficates to "Accept" it seems that upload is working. But problem is that users are promted to install some certificate before visisting website. Obvoiusly it is something with SSL but it is hard to figure out what.