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..

CallerOrigin property of Plugin Context


We had one of our workflow running on create of lead which was updating one of the attribute in the lead. When the workflow was updating the record one of our plugin registered on the post update event of the lead was getting triggered. This was resulting in an error , so we had to update the post update plugin to include the callerOrigin to handle the things properly

if (context.CallerOrigin.ToString() != “Microsoft.Crm.Sdk.AsyncServiceOrigin”)

////////// our logic

}

CallerOrigin -Using it we can determine the origin of the call. Possible Values are

Static Property Description
Application Gets the caller orgin for the application.
AsyncService Gets the caller orgin for the async service.
WebServiceApi Gets the caller orgin for the Web services.

Bye…

Used SharedVariables in Microsoft Dynamics CRM 4.0


Today we wrote a plugin which was making use of new shared variables concept for plugin in Microsoft Dynamics CRM 4.0

We had one of our plugin registered in post create event of opportunity which was generating a unique number/id for that opportunity record (i.e auto-numbering).
Than we had to write one more plugin again for the same post create event of opportunity but in that plugin we wanted to access the value of that auto generated unique id.
So first what we did was changing the rank of the above two plugin i.e. execution order, if we are registering through plugin-registration tool.
For first plugin which used to generate the unique id we set the rank as 1
and for the second plugin we set it as 2.
But still we were not able to access the value of the unique id attribute in the second plugin.
Than we finally thought of making use of shared variables concept.

The SharedVariables property allows plug-ins to share data with each other. So the plugin which is getting fired first could put some data in the SharedVariables propertybag which than could be accessed by a plugin which is getting fired later.The order of execution of plugin depends on the rank set for it. However we should be careful of not creating too much dependencies among plug-ins.

So, in our first plugin we put the value in the shared variable
context.Properties.Add( new PropertyBagEntry(“MySharedVariable”, myAutoNumber));
and accessed it in the second plugin as following
String mySharedVariable = (string)context.[“MySharedVariable”];

Bye..

SharePoint and Javascript


The following links explains how to use javascript within SharePoint

Using JavaScript to manipulate a list form field.

http://blogs.msdn.com/sharepointdesigner/archive/2007/06/13/using-javascript-to-manipulate-a-list-form-field.aspx

Hide a field from NewForm.aspx

http://edinkapic.blogspot.com/2007/08/hide-field-from-newformaspx.html

Using Simple JavaScript in SharePoint

http://www.sharepointkings.com/2008/06/using-simple-javascript-in-sharepoint.html

and few other links

http://sharepointsolutions.blogspot.com/2007/09/make-selected-links-in-links-list-open.html

http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/941940cb-acef-434f-830f-233713773b99/

http://www.codeproject.com/KB/sharepoint/Control_validation.aspx

Bye….

Checking for null or blank value in case of post update plugin using ForceSubmit


We were supposed to write a plugin against say entity A which would be updating a related entity B  only if the value of one of the attribute(string)  in entity A is blank.

The plugin was a post update one , so even though we had registered pre/post image with that particular attribute and as it was null, the property/value wasn’t getting passed.

So there was no way to access it in the entity images.

Only way to access the value was to make use of query expression class to get the value saved in the table for that entity. But we decided to use another approach.

Normally if we set a ForceSubmit on a particular field it is passed as one of the property of inputparameters of the context.

So what we did was set ForceSubmit on the field and then converted the inputparameters properties as Dynamic Entity and were able to get the value of that attribute even in case when it was null/blank.

DynamicEntity entity = (DynamicEntity)context.InputParameters.Properties[“Target”];

if (entity.Properties.Contains(“new_attSchemaName”))
{
String   myAttrValue = (string)entity.Properties[“new_attSchemaName”];
if (myAttrValue == “”)
{

//

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 …