FileUpload : Page Cannot be displayed and maximum request length exceeded error

By default, ASP.NET permits only files that are 4,096 kilobytes (KB) or less to be uploaded to the Web server.  To upload larger files, we must change the maxRequestLength parameter of the <httpRuntime> section in the Web.config file. By default, the <httpRuntime> element is set to the following parameters in the Machine.config file:

<httpRuntime

executionTimeout=90

maxRequestLength=4096

useFullyQualifiedRedirectUrl=false

minFreeThreads=8

minLocalRequestFreeThreads=4

appRequestQueueLimit=100

/>

We can change the value of maxRequestLength to a desired value in our web.config of the application. For 10 mb we can set it to 10240 KB. Even in this case if user tries to upload a file with size more than 10 mb we than get the above “Page cannot be displayed error ” or the page simply hang up. In this case we can catch the error in the Application_Error event handler of the Global.asax file.

void Application_Error(object sender, EventArgs e)

{

if (System.IO.Path.GetFileName(Request.Path) == “Default.aspx”)

{

System.Exception appException = Server.GetLastError();

if (appException.InnerException.Message == “Maximum request length exceeded.”)

{

Server.ClearError();

Response.Write(“The form submission cannot be processed because it exceeded the maximum length allowed by the Web administrator. Please resubmit the form with less data.”);

Response.Write(“<BR><a href=’Default.aspx’>Click Here to go back to page</a> </BR>”);

Response.End();  } } }

I tried with the above code, but it isn’t consistent.

The best solution for this could be to set the value of maxRequestLength to a very high value.

and checking in the code for the size.

Say changing the value to say 700mb ( not sure what the maximum length of request could be)

<httpRuntime useFullyQualifiedRedirectUrl=true

maxRequestLength=716800

/>

And checking for the length in your code

// Putting the constraint of 1 mb

if (FileUpload1.FileContent.Length < 1024){

FileUpload1.SaveAs(@”C:/MyFolder/” + FileUpload1.FileName);}

else{

return;}

At least the above solution would save us from the page not displayed error.

And the last solution which i found was creating an httpmodule to intercept the web request.

using System;

using System.Collections.Generic;

using System.Text;

using System.Web;

namespace HAMModule{

public class MyModule : IHttpModule{

public void Init(HttpApplication app){

app.BeginRequest += new EventHandler(app_BeginRequest);

}

void app_BeginRequest(object sender, EventArgs e){

HttpContext context = ((HttpApplication)sender).Context;

// check for size if more than 4 mb

if (context.Request.ContentLength > 4096000){

IServiceProvider provider = (IServiceProvider)context;

HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

// Check if body contains data

if (wr.HasEntityBody()){

// get the total body length

int requestLength = wr.GetTotalEntityBodyLength();

// Get the initial bytes loaded

int initialBytes = wr.GetPreloadedEntityBody().Length;

if (!wr.IsEntireEntityBodyIsPreloaded()){

byte[] buffer = new byte[512000];

// Set the received bytes to initial bytes before start reading

int receivedBytes = initialBytes;

while (requestLength – receivedBytes >= initialBytes){

// Read another set of bytes

initialBytes = wr.ReadEntityBody(buffer, buffer.Length);

// Update the received bytes

receivedBytes += initialBytes;

}

initialBytes = wr.ReadEntityBody(buffer, requestLength – receivedBytes);}}

// Redirect the user to an error page.

context.Response.Redirect(“Error.aspx”);}}

public void Dispose(){}

}}

and add the following information to web.config

<httpModules>

<add type=HAMModule.MyModule name=MyModule/>

</httpModules>

inside

<system.web>

The last solution worked properly!!!!

BeginRequest event –The BeginRequest event signals the creation of any given new request. This event is always raised and is always the first event to occur during the processing of a request.

Article on creating a custom http module

http://msdn.microsoft.com/en-us/library/ms227673(VS.80).aspx


Bye..

Using Encryption and Decryption in an ASP page

Hi I was looking for implementing cryptography in an ASP page.

I found this following article of great use

http://www.4guysfromrolla.com/webtech/010100-1.shtml

The inc file

<%
Dim sbox(255)
Dim key(255)

Sub RC4Initialize(strPwd)
dim tempSwap
dim a
dim b
intLength = len(strPwd)
For a = 0 To 255
key(a) = asc(mid(strpwd, (a mod intLength)+1, 1))
sbox(a) = a
next

b = 0
For a = 0 To 255

b = (b + sbox(a) + key(a)) Mod 256
tempSwap = sbox(a)
sbox(a) = sbox(b)
sbox(b) = tempSwap
Next
End Sub

Function EnDeCrypt(plaintxt, psw)

dim temp
dim a
dim i
dim j
dim k
dim cipherby
dim cipher

i = 0
j = 0

RC4Initialize psw
For a = 1 To Len(plaintxt)
i = (i + 1) Mod 256
j = (j + sbox(i)) Mod 256
temp = sbox(i)
sbox(i) = sbox(j)
sbox(j) = temp
k = sbox((sbox(i) + sbox(j)) Mod 256)

cipherby = Asc(Mid(plaintxt, a, 1)) Xor k
cipher = cipher & Chr(cipherby)
Next
EnDeCrypt = cipher
End Function

%>

And following is the code for my asp page

<!–#include file=”g.inc”–>

<html>
<head>
<title>TestPage</title>
</head>
<body>
<form action=”G.asp” method=”post”>
<%
dim psw, txt
dim strTemp
txt=”NishantRana”
psw=”myPassword”
strTemp=EnDeCrypt(txt,psw)
response.write “Encrypted Text =” & strTemp & “</Br>”
txt=EnDeCrypt(strTemp,psw)
response.write “Decrypted Text =” & txt
%>
</form>

</body>

</html>

Just copy and paste the code

That’s it …


IIS not serving ASP.NET pages

It mostly happens when IIS is installed after .NET is installed. So in this case we need to make use of aspnet_regiis.exe utility.
1) Go to command prompt
2) Go to the following path
“C:WINDOWSMicrosoft.NETFrameworkv2.0.50727”
depending on the version.
3) Enter “aspnet_regiis.exe -i”
4) It will display the message finished installing
5) Open your IIS
6) Select web service extensions
7) Click on Allow for ASP.NET v2.0.50727

That’s it . Now the IIS has been configured properly

Using Web Service as a Data Source in Sql Server Reporting Services

Suppose this is a simple web method inside a web service in ASP.NET.

[WebMethod]

public string HelloWorld(String FirstName, String LastName) {

return “Hello “ + FirstName+ ” “ + LastName ;

}

Now we would to add the above as a xml data source in out Report.

For this we need to do the following

  • Create a new Report
  • Select <New DataSet..>
  • For Type (inside General Tab) select XML as DataSource type.
  • Inside connection string give the path to the web service.
  • i.e. http://localhost:2584/WebSites/Service.asmx
  • Define query for the data source in the following manner

<Query>

<Method Namespace=http://tempuri.org/ Name=HelloWorld>

</Method>

<SoapAction>http://tempuri.org/HelloWorld</SoapAction>

</Query>

 

We can create report parameters for FirstName and LastName parameters of the method.

Or we want to define default values for these parameters define the query as following

 

<Query>

<Method Namespace=http://tempuri.org/ Name=HelloWorld>

<Parameters>

<Parameter Name=FirstName>

<DefaultValue>Nishant</DefaultValue>

</Parameter>

<Parameter Name=LastName>

<DefaultValue>Rana</DefaultValue>

</Parameter>

</Parameters>

</Method>

<SoapAction>http://tempuri.org/HelloWorld</SoapAction>

</Query>

 

Bye..

Customizing Default IE Test Page for ASP.NET web service

Hi,

When we create ASP.NET web service from visual studio and run the web service a test page opens up in which we can test our web service.

We can easily customize that web service test page. The name of the page is DefaultWsdlHelpGenerator.aspx we can found it in the following directory

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG\ for ASP.NET 2.0.

Open the page in Visual Studio

First and foremost we would find the following things that could be configured

// set this to true if you want to see a POST test form instead of a GET test form
bool showPost = true;

// set this to true if you want to see the raw XML as outputted from the XmlWriter (useful for debugging)
bool dontFilterXml = false;

// set this higher or lower to adjust the depth into your object graph of the sample messages
int maxObjectGraphDepth = 4;

// set this higher or lower to adjust the number of array items in sample messages
int maxArraySize = 2;

// set this to true to see debug output in sample messages
bool debug = false;

To customize the UI good information is provided over here

Customizing Web Service Test Page’s UI Design

By Default the web service can be tested using Http Get (default) and Http Post, but if we want to test using the SOAP we can make use of the information provided in the following link

Testing Web Service with SOAP

Bye

Consuming an Asp.NET web service using SOAP protocol from JavaScript

There are many ways we can consume a web service
The three common protocols for accessing a .NET web service are
HTTP GET, HTTP POST and SOAP.
The trasport protocol used for them is HTTP. However a web sercie can work on any other internet protocol like SMTP, FTP, Jabber, and TCP.

For HTTP GET and HTTP POST method you can refer to these posts
https://nishantrana.wordpress.com/2007/10/22/calling-aspnet-web-service-from-javascript-ajax-passing-parameter/
https://nishantrana.wordpress.com/2007/10/22/calling-aspnet-web-service-from-javascript-ajax-passing-parameter-post/
The proxy class generated by Visual studio for us using the wsdl itself uses the SOAP.
Let’s take an example of calling the simple web service using SOAP through java script.
Say this is our sample web service

[WebService(Namespace = “http://myNamespace/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld(String name) {
return “Hello “+name;
}

}

The javascript code that we can use to call this web service using SOAP request would be this
<script type=”text/javascript”>
var xmlHttp;
function SoapCall()
{
// creatng the xmlHttp object
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
// Calling the web service using post and true means asynchronous call
xmlHttp.open(“post”, “http://localhost/WebSite/WebSite4/Service.asmx&#8221;, true);
// Setting the request header to let the web service identify the soap request we would be sending
xmlHttp.setRequestHeader(“Content-Type”,”text/xml; charset=utf-8″);
// http://myNamespace/HelloWorld – name of the webmethod
//[WebService(Namespace = “http://myNamespace/&#8221;)] which we had applied to our web service class
xmlHttp.setRequestHeader(“SOAPAction”,”http://myNamespace/HelloWorld&#8221;);
xmlHttp.onreadystatechange=doUpdate;
// setting the soap request body
var soapRequest=”<?xml version=’1.0′ encoding=’utf-8′?>” +
“<soap:Envelope xmlns:xsi=’http://www.w3.org/2001/XMLSchema-instance'”+
” xmlns:xsd=’http://www.w3.org/2001/XMLSchema&#8217; xmlns:soap=’http://schemas.xmlsoap.org/soap/envelope/’>”+
“<soap:Body>”+
“<HelloWorld xmlns=’http://myNamespace/’>”+
“<name>Nishant Rana</name> “+
“</HelloWorld>”+
” </soap:Body>”+
“</soap:Envelope>”;


xmlHttp.send(soapRequest);
return false;


}

function doUpdate()
{
debugger;
if(xmlHttp.readyState==4)
{
var responseXMLResult=xmlHttp.responseXML;
var result = responseXMLResult.lastChild.nodeTypedValue;
alert(result);
}
}
</script>

We will receive the following Soap Response
<?xml version=”1.0″ encoding=”utf-8″?>
<soap:Envelope xmlns:soap=”http://schemas.xmlsoap.org/soap/envelope/&#8221; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221; xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<soap:Body>
<HelloWorldResponse xmlns=”http://myNamespace/”&gt;
<HelloWorldResult>Hello Nishant Rana</HelloWorldResult>
</HelloWorldResponse>
</soap:Body>
</soap:Envelope>

We can create our SOAP request by making use of the test page of our Web Service which we can open in IE.

Or else we can use Fiddler tool. (http://www.fiddlertool.com/fiddler/)

Bye..

Good site for understanding System.Net.Mail Namespace

Hi,

Plzz do check out this site if you need to write code for sending mail in asp.net 2.0

http://www.systemnetmail.com/default.aspx

Bye

Unable to generate a temporary class (result=1). error CS2001: Source file ‘C:\WINDOWS\TEMP\filename.cs’ could not be found error CS2008: No inputs specified

Hi,

I was getting this error when I was trying to call a .NET dll from an ASP page.

The dll was making use of a web service.

And while searching for it I found that if we are making use of a web service from

an asp page, the page tries to create a temporary file in windows\temp directory and because it hasn’t got rights for the same we get the error.

 

We can resolve it by giving it the appropriate rights for the windows/temp folder

 

1) Right click the temp folder à Select properties

2) Go to security tab

3) Click on Add and add ASPNET account. ( In locations select your machine )

4) Then add one more account IWAM_D-0824 (i.e. IWAM_YourMachineName)

5) Try running the ASP page again. The page should run without any error.

Bye

Using Forms Authentication in Asp.NET

Hi All,

To use form authentication in asp.net application

1- Create a new website

2- Change the name of the default.aspx to login.aspx

3- Add 2 labels one for username and password and two textboxes name txtUserName and txtPassword

and a button named btnLogin with label Login.

4 -Put the following in the web.config page

<authentication mode=”Forms”>
<forms loginUrl=”login.aspx”>
<credentials passwordFormat=”Clear”>
<user name=”Mickey” password=”Mouse”/>
</credentials>
</forms>
</authentication>
<authorization>
<deny users=”?”/>
</authorization>

5-Put this code in the btnLogin click’s event handler.

protected void btnLogin_Click(object sender, EventArgs e)
{
if(FormsAuthentication.Authenticate(txtUserName.Text,txtPassword.Text))
{
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, false);
}
else
{
lblInfo.Text = “you are not authorized to view the page”; // add one more label lblInfo }
}

6- That’s it your page should work now

We can add more users within the credential section of web.config

We can even encrypt the password we are saving in the web.config

We can even make use of cookie for the same.

Looking forward to include the code for the same

Bye

Creating a simple Hello World ASP.NET AJAX web page.

Hi,

Here we will create a simple ASP.Net Ajax webpage having a button and textbox control in it.
On the click of button we will fill the textbox with “Hello world” string returned from the server without refreshing our webpage.

1) Create a new ASP.NET Ajax web site(Visual Studio 2005)or ASP.NET web site (version 3.5) if we are using Orcas(Visual studio 2008)

2) Add a ScriptManager control in the page( if it isn’t there)

3) Add button and textbox server side control.

<asp:TextBox ID=”TextBox1″ runat=”server” />

<asp:Button ID=”Button1″ runat=”server” Text=”Button” />

4) Add this event Handler for button click event

protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text=”Hello World”;
}

4) Now to make our page AJAX enabled the only thing we need to add is

<asp:UpdatePanel id=up1 runat=server>
<ContentTemplate>

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>
<asp:Button ID=”Button1″ runat=”server” onclick=”Button1_Click” Text=”Button” />

</ContentTemplate>
</asp:UpdatePanel>

Just wrap our server side controls inside update panel control’s content template.

5) That’s it. Now run the application and click on the button the textbox should get filled with Hello World string without any refresh of the page.

Right now what we saw was a server-centric approach using updatePanel control.

We can do the same thing using client-centric approach using ASP.NET AJAX client library. Check this post

https://nishantrana.wordpress.com/2007/11/06/creating-and-calling-aspnet-ajax-web-service/

Bye.