Tag Archives: ASP.NET

ASP.NET C# Send email in background thread

System.Threading.Thread thread = new System.Threading.Thread(delegate()
{
    SMTPSend(message);
});

thread.IsBackground = true;
thread.Start();

private static void SMTPSend(MailMessage message)
{
    try
        {
            SmtpClient smtp = new SmtpClient();
            ...

On the presentation layer you do not need any AJAX or JavaScript calling code from the backend
Just plain ASP.NET button

<asp:Button ID="btnSend" runat="server" Text="Send Email" onclick="btnSend_Click" />

Code behind

protected void btnSend_Click(object sender, EventArgs e)
{
    try
    {
        Notifications.Send(email);
    }
    catch (Exception ex)
    {
        litResult.Text = ex.ToString();
    }
}

ASP.NET (cookieless) web method returns 401 Authentication failed

I had application with cookieless session. This was the reason why I was getting ‘401 Authentication failed’ error.

Something like this would not work

function LoadDealersData() {
        var url = "/Default.aspx/GetDealers";
	$.ajax({
		type: "GET",
		url: url,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: '{ pid:' + currentProvince + '}',
		error: function (data, exception) {

		},
		success: function (response) {
			// do stuff with reponse.d
		},
		complete: function () {

		}
	});
}

Code behind:

[Webmethod]
public static List<Dealer> GetDealers(int pid)
{
	...
	return dealers;
}

Solution was to use generic handler (.ashx)

public List<Dealer> GetDealers()
{
	try
	{
		int pid = Convert.ToInt32(Request["pid"]);
		List<Dealers> dealers = new List<Dealers>();
		//...
		Response.ReturnJSON(new
		{
			dealers = dealers
		});
	}
	catch()
	return null;
}

public static void ReturnJSON(this HttpResponse response, object data)
{
	response.Clear();
	response.ContentType = "application/json";;
	response.Expires = 0;
	response.Write(new JavaScriptSerializer().Serialize(data));
	response.End();
}

Modified JavaScript

function LoadDealersData() {
	var url = "/SomeLocationWhereHandlerIs/MyHandler.ashx";
	$.ajax({
		type: "GET",
		url: url,
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: data: 'whattodo=getDealers&pid=' + currentProvince,
		error: function (data, exception) {

		},
		success: function (response) {
			// do stuff with response.dealers; 
			// response.dealers becuase we are returning dealers variable in code behind
		},
		complete: function () {

		}
	});
}

ASP.NET The length of the query string for this request exceeds the configured maxQueryStringLength value.

Similar problem happens described by error:

The request filtering module is configured to deny a request where the query string is too long.

Solution, step 1 in web.config:

<configuration>
   <system.web>
		<httpRuntime maxQueryStringLength="4096" />
	</system.web>
</configuration>

<!-- OR -->

<configuration>
   <system.webServer>
		<httpRuntime maxQueryStringLength="4096" />
	</system.webServer>
</configuration>

Solution, step 2 IIS:
In the Connections pane, go to the connection, site, application, or directory for which you want to modify your request filtering settings.
In the Home pane, double-click Request Filtering.

iis01

Click Edit Feature Settings… in the Actions pane.

iis02

Specify your options, and then click OK.

iis03

Source: Request Limits

IIS 7.5 first request very slow

This is somewhat hard to tell whats going on on your other server, however here’s a simple checklist you might want to reconsider:

  1. Always pre-compiling your site, as opposed to copying it! you might gain a significant performance boost compiling your website before deployment: ASP.NET Precompilation Overview
  2. Do not run the production application with debug=”true” enabled, when debug flag is true in your web.config, Much more memory is used within the application at runtime, and since some additional debug paths are enabled, codes can execute much slower
  3. Check your Web.config file to ensure trace is disabled in the section
  4. IIS 7.5 comes with the Auto-Start Feature. WAS (Windows Process Activation Service) starts all the application pools that are configured to start automatically, ensure that your application pool is configured to AlwaysRunning in the IIS 7.5 applicationHost.config, check out here for more detail
  5. Check out the ASPNET.CONFIG file to see if the configuration on both servers are still the same. Every asp.net server can be well configured by aspnet.config file located in the root of the framework folder
  6. Ensure that Publisher Evidence for Code Access Security (CAS) is set to false in your aspnet.config file, This might increase the initial page load when you restart the ASP.NET app pool. you can read more about it here.Here’s how to disable checking for CAS publisher policy for an application:
    <configuration>
        <runtime>
            <generatePublisherEvidence enabled="false"/>
        </runtime>
    </configuration>
    
  7. also you might want to try Application Initialization Module for IIS 7.5, this module also available on IIS 8.0 can decrease the response time for first requests by pre-loading worker processes

Source: Stack Overflow

ASP.NET Executing code in the header

Something like this will not work

<meta property="og:url" content="<%= Utilities.GetFacebookURL() %>" />

Replaced ‘<%=' with '<%#' [code language="html"] <meta property="og:url" content="<%# Utilities.GetFacebookURL() %>" /> [/code] and added in Master Page code behind [code language="csharp"] protected override void OnLoad(EventArgs e) { base.OnLoad(e); Page.Header.DataBind(); } [/code] Thanks to ASP.NET Resources

ASP.NET DropDownList bind to XML and insert first item


XDocument doc = XDocument.Load(filePath);
var ds = (from model in doc.Descendants("model")     
		  select new     
			  {      
				  ID = model.Attribute("id").Value,      
				  Name = model.Attribute("name").Value     
			  }
		  ).OrderBy(m => m.Name).ToList();    

ddlExample.DataSource = ds; 
ddlExample.DataValueField = "ID"; 
ddlExample.DataTextField = "Name"; 
ddlExample.DataBind(); 
ddlExample.Items.Insert(0, new ListItem("Search by model", string.Empty));


ASP.NET set master page programatically

The problem is, of course, that this only works on a page by page basis, so you’d have to add the PreInit event to every page. A better solution is to hook into a global event in Global.asax, allowing the master to be set dynamically for every page.

    void Application_PreRequestHandlerExecute(object src, EventArgs e)
    {
        // hook up the PreInit page handler
        Page p = this.Context.Handler as Page;
        if (p != null)
        {
            p.PreInit += new EventHandler(page_PreInit);
        }
    }
    void page_PreInit(object sender, EventArgs e)
    {
        Page p = this.Context.Handler as Page;
        if (p != null)
        {
            // set the theme and master page
            p.Theme = "MyTheme";
            p.MasterPageFile = "~/MasterPages/MyMaster.master";
        }
    }

PreRequestHandlerExecute happens early enough in the lifecycle to set the master.
via ASP.NET Forum

ASP.NET (MVC) AspNetSqlMembershipProvider and aspnetdb.mdf – use SQL instead

After creating a project, running it I was not able to access to¬†aspnetdb.mdf data. Simply couldn’t open it because of it had incorrect server name set in its connection string setting (web.config was set properly).

Initial connection string:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>

So, instead I set up database and updated Web.config. Database requires all tables and stored procedures to run membership. How to do that without having access to MDF file?

Use aspnet_regsql.exe as
If you are confused with paramters, just run exe without any and you will get access to wizard.

My command:

C:> cd C:WindowsMicrosoft.NETFramework64v4.0.30319
C:> WindowsMicrosoft.NETFramework64v4.0.30319> aspnet_regsql.exe