Please check below the list of things I've tried before closing as duplicate.


The problem:

  • I create a brand new ASP.NET MVC application, I build the application and I run it --> The page takes between 20-30 seconds to load.
  • Every time I rebuild the application and then try to load the page, it takes 20-30 seconds even if I do so immediately after the previous build (i.e., not an idle-timeout issue, I guess?).

I've been struggling with this problem since yesterday, I read every post/article I could found about this with no luck. Though, I have to admit that I'm new to ASP.NET and web development in general and not familiar with the IIS configuration so I might've missed something.

The things I've tried:

  • Disabled antivirus and firewall.

  • Disabled IPv6 by commenting the ::1 localhost line in the hosts file. My hosts file looks like this:

    127.0.0.1       localhost
    # ::1             localhost
    
  • Tried different browsers.

  • Changed the port of the application URL.

  • Changed the application URL from localhost:port to 127.0.0.1:port but when I do so, I get:

    Bad Request - Invalid Hostname

  • Uninstalled and reinstalled IIS Express (tried multiple versions: 7.5, 8.0, and 10.0).

  • Tried installing the "Application Development Features" under Internet Information Services\World Wide Web Services.

  • Launched the VS installer and run a repair.

Environment information:

  • Windows 7 x64.
  • Visual Studio 2015.
  • .NET 4.5.2.
  • IIS currently enabled features: I'm using IIS Express so I'm not sure if this is related.

IIS enabled features

Any idea what could be causing this problem?


Update:

I just tried using Jexus Manager. Loaded the configuration from the .sln file as shown here, started the website and tried the following scenarios:

  • Browsing the website after restarting it (both actions in Jexus Manager) -> 15-20 seconds.
  • Browsing the website (using Jexus) after rebuilding the solution in VS --> 30+ seconds.

I am creating a site that will be using many referral links for many different sites on the internet. When someone uses a referral link I need to track the information on the pages that person goes to so that I can be sure that the person has indeed signed up for the site or made a purchase on the site.

I really have 2 questions:

  1. Can you make a cookie that could do this and how would you do it?

  2. Is there a huge possibility for the website you are going to be tracking the information from to make is so that type of cookie will not be able to function properly.

This is very essential for the site I am creating and I would like a bit more insight.

My MVC C# Web Site app is installed on an internal Azure App Service with a URL like app.domain.internal and resolved by client's DNS and certificates with another URL "app.externaldomain.com", so final users can access the site through "app.externaldomain.com" and the internal URL keeps unknown by users.

Almost everything works fine, the problem is that when code runs an Url.Action to generate URLs, it gets the app.domain.internal root and I need to change or overrite that root URL for "app.externaldomain.com", so the site can generate URLs like app.externaldomain.com/controller/action instead of app.domain.internal/controller/action (that is not accesible for final users).

There is a way to change the root URL used by MVC to generate fully qualified URLs with a custom root instead the URL of the App Service.

It is not factible to do an "url.replace('badroot', 'rigthroot')" or something similar in all the site.

I apologize in advance, I am familiar with programming in ASP/C#. However, my new job has some older applications using VB. I cannot for the life of me get the selected text to pass as a variable to my stored proc. The SQL command was created on the ASP page to pull back the Dropdown options. The VB script executes the stored proc.

ASP

<asp:DropDownList ID="ddlFacultyAssign" runat="server" 
DataSourceID="FacultyAssign" Visible="false" 
DataTextField="FULLNAME" DataValueField="FULLNAME" AutoPostBack="true" 
AppendDataBoundItems="true">                                                
</asp:DropDownList>

VB

MyCommand.Parameters.Add(New SqlParameter("@FACASSIGN", SqlDbType.VarChar, 255))

MyCommand.Parameters("@FACASSIGN").Value = Me.ddlFacultyAssign.SelectedItem.Text

We are seeing connection issues between our ASP.net web application and one of our web services. The issue only happens for a specific call between two specific servers. If we change the from or the to server we don't face the issue. We are trying to track the problem down by enabling tracing in the web config file. I am using the following web config setting that appears to work locally but once I deploy to the server, I am not getting any output except for a single line right after the app is deployed.

Line from the log file: System.Net Information: 0 : [21880] Current OS installation type is 'Client'.

This is actually interesting because if we run a console app on that server that has the same app.config setting for tracing, we get "Current OS installation type is 'Server'.

Here is the web config section for logging

<system.diagnostics>
    <trace autoflush="true" />
    <sources>
      <source name="System.Net">
        <listeners>
          <add name="MyTraceFile"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add name="MyTraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="logfile.log" />
    </sharedListeners>
    <switches>
      <add name="System.Net" value="Verbose" />
    </switches>
  </system.diagnostics>

On the server we are not getting any output to the log file even though the log file is being created and a single entry is written to it.

As title I have some code about add HyperLink and Highlight keywords in RowDataBound. It works when Page changes except stays in same page(click searchbtn). The condiction is HyperLink will disapper but highlight work normally. I try to write in Rowcreated(),if I do this the not only hyperlink but also content will disapper.How can I fix this problem? thanks.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;


namespace todoassignment1
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Visible = false;  
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string valueUser = txtUsername.Text;

            SqlConnection db = new SqlConnection(SqlDataSource1.ConnectionString);

            SqlCommand cmd = new SqlCommand();

            cmd.CommandType = CommandType.Text;

            //User is the name of the table, UserName is the column 
            cmd.CommandText = "INSERT User (UserName) VALUES ('" + valueUser + "')";

            cmd.Connection = db;

            db.Open();

            try
            {
                cmd.Connection.Open();
                cmd.ExecuteNonQuery();
                Label1.Text = "Success writing into database!";
                Label1.Visible = true;  
            }
            catch (Exception ex)
            {
                Label1.Text = "Error writing into database.";
                Console.WriteLine(ex.Message);
                Label1.Visible = true;
            }
            finally
            {
                db.Close();
            }
        }
    }
}

I added the SqlDataSource1 on the Default.aspx page, which seems to be done successfully as I can see the column names of the User table in the gridview. The table is empty, and all I'm trying to do is take input in a textbox and send it to the UserName column. I'm not very good at debugging as the comp-sci program is the type to entirely rely on slide shows, but I have noticed a few errors which I have spent >4 hours researching. Things I've tried:

  • SQL SMS > tools > options > designers > CHECK prevent saving changes that require table re-creation
  • Added using System.Data;
  • Added cmd.Connection.Open();
  • Added an exception to be caught in the catch statement
  • Recreate entire database
  • Quadruple checked things like txtUsername being the correct textbox ID
  • Reconfigure SqlDataSource1 over and over, delete and recreate
  • Confirm that the connectionString in web.config is correct
  • Create the new SQLConnection with the exact string in web.config

        SqlConnection db = new SqlConnection("Data Source=NAME-PC\\SQLEXPRESS;Initial Catalog=Assignment;Integrated Security=True");
    
  • Changed the insert line from concatenation to just "INSERT User (UserName) VALUES ('asdf')" to simplify code, still doesn't work.

  • Tried other syntax

        cmd.CommandText = "INSERT INTO User (UserName) VALUES (@username)";
    
        cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50);
    
        cmd.Parameters["@username"].Value = txtUsername.Text.ToString();
    

Clues from the debugger:

  • saw several "System.InvalidCastExceptions when digging through cmd in autos
  • errorCS0103: the name 'ExecuteNonQuery' does not exist in the current context

  • Always see System.InvalidOperationException after running

I am completely overloaded with stress, have little time, and am crushed to have so much trouble with something so simple. Please help.

I have a old style .NET Web Service running in IIS correctly on my local machine:

http://localhost/MyService/MyService/Service1.asmx

I added a Web Reference and set it's property to dynamic so that I could simply change the URL in the Web.config file. Prior to deploying to staging server, I configured it thus:

<client>
  <endpoint address="http://staging.myserver.net/WSTest/WSTest/Service1.asmx"
    binding="basicHttpBinding" bindingConfiguration="Service1Soap"
    contract="ServiceReference1.Service1Soap" name="Service1Soap" />
</client>

I can access it on the server like this and it works:

http://staging.myserver.net/MyService/service1.asmx

However, I need it to resolve like the following as this is how external clients are accessing it:

http://staging.myserver.net/MyService/MyService/service1.asmx

I can see nothing wrong with the IIS configuration settings on my staging server. Am I missing something?

This is similar to this question IIS 7.5 web application first request after app-pool recycle very slow but I think not exactly the same.

After an application pool recycle, the first database call my ASP.NET application makes is extremely slow. Subsequent calls are extremely fast. This is to a local instance of SQL Server.

Here is a profile of after the application pool is recycled. The call takes 9.7 seconds. enter image description here

And here it is after the application pools have been up a while. The exact same call takes 12ms. enter image description here It's not a caching thing because if I ask the second call to pull back data for a different account it's still extremely fast.

It's really annoying while developing because every time I make a change and compile it recycles the app pool and then it takes far too long for the site to come up again.

What is going on here and is there any way to speed up the first call?

My code:

<asp:DataList ID="datalist" runat="server" >
    <ItemTemplate>
        <asp:Textbox ID="Values" runat="server" type="text" />
    </ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Text="SEND" OnClick="send" />

How could I get each Values ID elements of the DataList from code behind in C# ?

I have a SurveyTextBox like below in my asp.net project:

<sc:SurveyTextBox ID="txtFirstName1" runat="server" SessionKey="txtFirstName" DBColumn="FirstName" MaxLength="50">

What I need to is to get if the DBColumn is nullable or not in the DB on the c# side.

I checked the properties of TextBox.DBColumn but there is nothing I saw like .isnullable() or .allowDBNull() kinda option. I appreciate for your any advices.

I am trying to remove part of string value from var1 and then pasting it into another var2 and then into var2. While doing so I update the values of the original variables. So if string length in var1 exceeds max length of 10 it then carries out this manipulation.

The code shown below works fine however I am not sure if this is the best approach of removing part of string and assigning it to a var, updating the value in original variable etc

if (var1.Length > 10)
{
   var newVar2 = var1.Remove(0, 10); // Grab the string from var1 and assign
   var1 = var1.Remove(10); // Update value and remove the part of string
   var2 = newVar2; // Save the newly removed string into var2
   if (var2.Length > 10)
   {
      var newVar3 = var2.Remove(0, 10);
      var2 = var2.Remove(10);
      var3 = newVar3;
   }    
}

Is there a better approach?

We are trying to ignore the IE's compatibility mode when "display intranet sites in compatibility view" is checked. I have come across various solutions to forcefully set IE's compatibility mode off.

I added the header in the web.config

<httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=edge, chrome=1" />
        <remove name="X-Powered-By" />
      </customHeaders>
</httpProtocol>

I can see the X-UA-Compatible in the response header

![enter image description here

This change should have turn off compatibility issue but when we run the test and we can still see some IE 7 browsers.

I further investigated and using the developer tool in IE i am seeing request header has a user agent which is like Mozilla/4.0 (compatible; MSIE 7.0... ) (this is from my office's network) but fiddler shows the request header as Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0). Even whenever I visit the site from my home network then request header is fine Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; rv:11.0)

I am struggling to resolve this and not sure if the request header's user agent MSIE:7.0 is causing the issue. Does anyone has any similar kind of issue before. I can uncheck the "display intranet sites in compatibility view" in my machine to skip this issue but this won't be a solution for the whole office user. Is it something we can avoid using code or is it a network settings issue? .Any help or suggestions would be appreciated.

Thanks in advance

it's possible to call method desktop application from webapi ? I need because I'm developing restful where some dll only run for desktop app.

Thank's

I want to get the folder name from another domain. I can get the folder name using the below code

foreach (var directoryName in new DirectoryInfo(Server.MapPath(@"Folder1/")).GetDirectories())
{
    FolderName = directoryName.Name;
}

This Server.MapPath(@"Folder1/") will go to the folder which is inside the project.

Using this below code, I can access the folder which is inside the domain

foreach (var directoryName in new DirectoryInfo("D:/ProjectDir/Folder1/").GetDirectories())
{
    FolderName = directoryName.Name;
}

But when I try to get the folder Name using the above code, I failed and it throws an IOException and the got the error message is The username and password are incorrect. Because it has a credential from another domain.

My path will be something like this \\192.168.x.x\c$\Folder1\

I'm trying to post a data from a Web Api to another Web Api in different project solution with a controller like this

public class PublishWebController : ApiController
{
    static HttpClient client = new HttpClient();

    static async Task<Uri> CreateArticleAsync(Article article)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/articles", article);
        response.EnsureSuccessStatusCode();

        // return URI of the created resource.
        return response.Headers.Location;
    }

    void Main()
    {
        Post().GetAwaiter().GetResult();
    }

    //POST api/<controller>
    [Mime]
    public async Task<Article> Post()
    {

        client.BaseAddress = new Uri("http://localhost:64395/api/");
        client.DefaultRequestHeaders.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var fileuploadPath = HttpContext.Current.Server.MapPath("~/uploads");
        var multiFormDataStreamProvider = new MultiFileUploadProvider(fileuploadPath);
        await Request.Content.ReadAsMultipartAsync(multiFormDataStreamProvider);
        string uploadingFileName = multiFormDataStreamProvider.FileData.Select(x => x.LocalFileName).FirstOrDefault();

        return new Article
        {
            Title = HttpContext.Current.Request.Form["Title"],
            ArticleContent = HttpContext.Current.Request.Form["ArticleContent"],
            ImagePath = "~/Images/" + Path.GetFileName(uploadingFileName),
        };

    }
}

When I tried sending a data with Postman, it returned a value to its localhost but nothing to the uri that I targeted

sending data

uri target

How do I fix this problem?

Background

I have a web api server (asp.net core v2.1) that serve some basic operation, like managing entities on the server. This is the interface:

[HttpPost]
[Route("create")]
public async Task<ActionResult<NewEntityResponse>> Create(CreateEntityModel model)
{
    // 1) Validate the request.
    // 2) Create a new row on the database
    // 3) Return the new entity in response.
}

The user running this REST method in this way:

POST https://example.com/create

Content-Type: application/json

{
    "firstName": "Michael", 
    "lastName": "Jorden"
}

And getting response like this:

Status 200

{
    "id": "123456" // The newly created entity id
}

The Problem

When sending thousands of requests like this, at some point it will fail because of network connections. When connection fails, it can leads us into two different situations:

  • The network call was ended on the way to the server - In this case, the server don't know about this request. Therefore, the entity wasn't created. The user just have to send the same message again.
  • The network call was sent from the server to back to the client but never rich the destination - In this case the request was fulfill completely, but the client don't aware for this. The expected solution is to send the same request again. In this case, it will create the same entity twice - and this is the problem.

The Requested Solution

I want to create an generic solution for web-api that "remmeber" which commands it already done. if he got same request twice, it's return HTTP status code Conflict.

Where I got so far

I thought to add the client an option to add a unique id to the request, in this way:

POST https://example.com/create?call-id=XXX

Add to my server a new filter that check if the key XXX is already fulfill. If yes, return Conflict. Otherwise - continue.

Add another server filter that checks the response of the method and marking it as "completed" for further checks.

The problem with this solution on concurrency calls. If my method takes 5 seconds to be returned and the client sent the same message again after 1 second - it will create two entities with same data.

The Questions:

  1. Do you think that this is good approach to solve this problem?
  2. Do you familiar with ready to use solutions that doing this?
  3. How to solve my "concurrency" problem?
  4. Any other tips will be great!

thanks.

I am actually deploying my web application in to azure and am trying to use azure database instead of on premises database And am using entity framework (model first approach). can someone please let me know how to replace the connectionstring ? and where to replace it (either in azure app service or VS webconfig )?

Thanks in advance

I am using itextsharp to create pdf. I have one text box named txtDate which contains today's date. Now I want this date to show on pdf header. Pdf OnSTart event showing txtDate not found. How to achieve this.

Thanks in advance

I am created one web service its returning wrong output

<menu> <submenuid>26 menuid 27</submenuid> </menu>  but actual output is  <menu> 
<submenuid>26</submenuid>
<menuid>27</menuid>  </menu>   My Web Service   [WebMethod]
[System.Web.Script.Services.ScriptMethod]
public void addRollMenuMap(int roleId, List<menus> menus)
{
    //
   // RollMenuMapping obj = new RollMenuMapping();
    string retval = "";
    try
    {
        //XElement xml = new XElement("menus", menus.Select(i => new XElement("submenuId", i.submenuId, "menuid", i.menuId)));
        // menusList.Add(obj);
        XElement xml = new XElement("menus", menus.Select(i => new XElement("menuid", i.menuId, "submenuId", i.submenuId)));
        RollMenuMapping ob = new RollMenuMapping();
        ob.roleId = roleId;
        DataTable dt = RollMenuMapping_Manager.AddRoleMenuMap(ob,xml.ToString());
        //retval = JsonConvert.SerializeObject(dt, Formatting.Indented);
        Context.Response.Clear();
        Context.Response.ContentType = "application.json";
        Context.Response.Write((((Newtonsoft.Json.Linq.JContainer)(JsonConvert.DeserializeObject(retval)))).First);
    }
    catch (Exception ex)
    {
        retval = "Data not inserted";
        Context.Response.Clear();
        Context.Response.ContentType = "application.json";
        Context.Response.Write(retval);
    }
    finally
    {
        // Context.Response.End();
        HttpContext.Current.Response.Flush();
        // Prevents any other content from being sent to the browser
        HttpContext.Current.Response.SuppressContent = true;
        //Directs the thread to finish, bypassing additional processing
        HttpContext.Current.ApplicationInstance.CompleteRequest();
        //Suspends the current thread
        Thread.Sleep(1);
    }
    //return items;
}

Claass File public class menus { public int menuId { get; set; } public int submenuId { get; set; } }

public class RollMenuMapping
{
    public int roleId;
    public List<menus> menus { get; set; }
}
public class RollMenuMapping_Manager
{
    public static DataTable AddRoleMenuMap(RollMenuMapping ob, string s)
    {
        SqlParameter[] param = new SqlParameter[3];
        param[0] = new SqlParameter("@roleId", ob.roleId);
        param[1] = new SqlParameter("@menus",s);
        param[2] = new SqlParameter("@type", 1);
        SqlCommand cmd = new SqlCommand();
        cmd.Parameters.AddRange(param);
        return CDatabase.GetDataTable("pro_RolemenuMappinginsert", cmd);
    }
}