Wickasitha's tech Blog

blogging everything

Archive for the ‘ASP.NET’ Category

A potentially dangerous Request.Path value was detected from the client (?).

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: A potentially dangerous Request.Path value was detected from the client (?).

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[HttpException (0x80004005): A potentially dangerous Request.
Path value was detected from the client (?).]
   System.Web.HttpRequest.ValidateInputIfRequiredByConfig() +8884233
   System.Web.ValidateRequestExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +35
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Solution

<system.web>

        <httpRuntime requestValidationMode=”2.0″ requestPathInvalidCharacters=”" />
        <pages validateRequest=”false” />
this worked form me.

Image URL is correct but image not showing – Fixed

I have a website on my server. All permissions are set correctly and the image DOES exist. Howeverwhen the page loads the image for the item selected does not show. Here is my code

 imagepath = "~/spaimages/" + currentSpaModel.Name.ToString() + ".png";     
    if (File.Exists(Server.MapPath(imagepath))) { this.spaimage.ImageUrl = Server.MapPath(imagepath); }
spaimage is an ASP control and thr URL that the image is set to is D:\hosting\xxxxxxx
\calspas\spaimages\modelname.png 
Fixed

The file path D:\hosting\xxxxxxx\calspas\spaimages\modelname.png is the folder where theimage resides on the web server. You are sending this as the <img> tag’s src attribute, which tellsthe browser, “Go get the image at D:\hosting\xxxxxxx\calspas\spaimages\modelname.png.”The browser cannot go off to the D drive of the web server, so it looks on its own D drive for that folder and image.

What you mean to do is to have the <img> tag’s src attribute be a path to a folder on the website. You’re just about there – just drop the Server.MapPath part when assigning the image path to theImageUrl property. That is, instead of:

this.spaimage.ImageUrl = Server.MapPath(imagepath);

Do:

this.spaimage.ImageUrl = imagepath; 

it works !!!


If you are working with VS 2010 (any Edition) and cannot open your 2010 solution on VS 2008 then just follow these 3 Steps:

For <PROJECT_NAME>.sln:

1. Open the solution file in your favorite text editor (ex: notepad++).
2. Find the Following:
Microsoft Visual Studio Solution File, Format Version 11.00.
# Visual Studio 2010.
Replace with:
Microsoft Visual Studio Solution File, Format Version 10.00. (I)
# Visual Studio 2008. (II, optinal)

For <Project_name >.csproj/vbproj:

1. Open project file in your favorite text editor (ex: notepad++).
2. Find the Following:
<Project ToolsVersion=”4.0″ DefaultTargets=”Build” xmlns=”http://schemas.microsoft.com/developer/msbuild/2003″>.
Replace with:
<Project ToolsVersion=”3.5″ DefaultTargets=”Build” xmlns=”http://schemas.microsoft.com/developer/msbuild/2003″>. (III)

Thats it..
Now you can open your solution file on VS2008.
Reverse of this will enable VS2008 solution to open in VS2010.

Retrieve value of Dynamic controls in asp.net

The main object of this article is to access value of  asp.net controls which are generated dynamically. For this, we will save viewstate of dynamic controls.
Suppose we have one dropdown and one button. When user selects “Generate” option, the Dynamic table will be generated. In each cell of table there will be textbox. User enters value in the textboxes and click on button then it will display all user entered values.

In aspx page:

<form id="form1" runat="server">
<div>
<asp:Table ID="tbl" runat="server">
</asp:Table>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
<asp:ListItem>Select...</asp:ListItem>
<asp:ListItem>Generate</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSet" runat="server" Text="Button" onclick="btnSet_Click" /> </div>
</form>

To create dynamic control:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (DropDownList1.SelectedIndex == 1)
{
CreateDynamicTable();
}
}
private void CreateDynamicTable()
{
// Fetch the number of Rows and Columns for the table
// using the properties
int tblRows = 5;
int tblCols = 5;
// Now iterate through the table and add your controls
for (int i = 0; i < tblRows; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < tblCols; j++)
{
TableCell tc = new TableCell();
TextBox txtBox = new TextBox();
txtBox.ID = "txt-" + i.ToString() + "-" + j.ToString();
txtBox.Text = "RowNo:" + i + " " + "ColumnNo:" + " " + j;
// Add the control to the TableCell
tc.Controls.Add(txtBox);
// Add the TableCell to the TableRow
tr.Cells.Add(tc);
}
// Add the TableRow to the Table
tbl.Rows.Add(tr);
tbl.EnableViewState = true;
ViewState["tbl"] = true;
}
}
On Button click:
protected void btnSet_Click(object sender, EventArgs e)
{
foreach (TableRow tr in tbl.Controls )
{
foreach (TableCell tc in tr.Controls)
{
if (tc.Controls[0] is TextBox)
{
Response.Write(((TextBox)tc.Controls[0]).Text);
}
}
Response.Write("<br/>");
}
}

Right Now, No output because dynamic controls are lost in postback .So we need to save dynamic controls value and generate dynamic controls again.we need to maintain viewstate.

protected override object SaveViewState()
{
object[] newViewState = new object[2];
List<string> txtValues = new List<string>();
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox)
{
txtValues.Add(((TextBox)cell.Controls[0]).Text);
}
}
}
newViewState[0] = txtValues.ToArray();
newViewState[1] = base.SaveViewState();
return newViewState;
}
protected override void LoadViewState(object savedState)
{
//if we can identify the custom view state as defined in the override for SaveViewState
if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[] )
{
object[] newViewState = (object[])savedState;
string[] txtValues = (string[])(newViewState[0]);
if (txtValues.Length > 0)
{
//re-load tables
CreateDynamicTable();
int i = 0;
foreach (TableRow row in tbl.Controls)
{
foreach (TableCell cell in row.Controls)
{
if (cell.Controls[0] is TextBox && i < txtValues.Length)
{
((TextBox)cell.Controls[0]).Text = txtValues[i++].ToString();
}
}
}
}
//load the ViewState normally
base.LoadViewState(newViewState[1]);
}
else
{
base.LoadViewState(savedState);
}
}

Last night I managed to get my new company website uploaded to the GoDaddy.  And generally its cool now :) .

Unfortunately though sending emails using System.Net.Mail doesn’t work, so the site can’t send out emails when people make inquiries.  Obviously this has to be addressed.

At that moment I had “smtpout.secureserver.net” with port 80 set on the SMTPClient object, and the error message I get is

“Request for the permission of type ‘System.Net.Mail.SmtpPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed.”

Solution

After doing more Googling around, it seems that smtpout.secureserver.net was not the correct outgoing server to use, since using this comes back with error messages such as “Mailbox name not allowed” and “not allowed in the list of rctphosts” and such.

The answer is to use an alternative called relay-hosting.secureserver.net.  Therefore the code below below should work for you as it now does for me :-

Dim objMailMessage As New System.Net.Mail.MailMessage

With objMailMessage
.IsBodyHtml = False
.From = New MailAddress("fromaddress@youremailaccount.com")
.To.Add("destinationaddress@whoever.com") .Subject = "Your Subject"
.Body = "Body Text"
End With

Dim objSMTPClient As New System.Net.Mail.SmtpClient("relay-hosting.secureserver.net", 25) objSMTPClient.Credentials = CredentialCache.DefaultNetworkCredentials objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network objSMTPClient.Send(objMailMessage)

Canceling an async postback – ASP.NET AJAX

  • Tuesday May 11,2010 12:38 AM
  • By wickasitha
  • In AJAX, ASP.NET

Recently a new requirement came for cancel an async operation.  Being aware of the abortPostBack method the PageRequestManager, I figured that it would be pretty simple to implement this feature.  I added a ‘Cancel’ button to my progress indicator and wired the onclick handler to invoke the abortPostBack method.

Clicking cancel did abort the async postback however, because the OnUpdated animation only runs when the UpdatePanel is updated my indicator was never being hidden and it was appearing as if the application was hanging.   My approach to solving this was to look-up the animation component and invoke the animation myself.  like this:

 function abort(){
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if(prm get_isInAsyncPostBack()){
            //  abort the postback
            prm abortPostBack();
            //  get the reference to the animation for the gridview
            var animation = $find('animation');
            //  simulate stopping by replaying the animation
            animation._postBackPending = false;
            animation.get_OnUpdatingBehavior().quit();
            animation.get_OnUpdatedBehavior().play();
        }
    }
SOURCE
 (more...)

How to create the aspnetdb.mdf

VS2005, VS2008, VS2010 all supports the following ways to create aspnetdb.mdf file:

1. After create Visual Studio website or web application, Click “ASP.NET Configuration” menu item inside Website menu (for website project) or Project menu (for web project).

2. Commandline aspnet_regsql method to create the aspnetdb schema in any SQL database

In VS2010 all editions, the default .NET Framework 4.0 ASP.NET Web Site and Web Application template create default website with following connection string in theweb.config:

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



To get the aspnetdb.mdf created , one can simply Ctrl-F5 to run the web site or web      application.  Click “Log In” button to let the ASP.NET Development Server or IIS server  process to create the aspnetdb.mdf file.

If the web site or web application runs as virtual application in IIS server, create  thedatabase process may fail depending on the directory accessibility and IIS application  pool .  For example, in IIS7, ApplicationPoolIdentity normally does not have permission  to create database by default.  Also, ASP.NET web application project might meet SQL    expres slimitation if the project is under the default project location

Read more here:http://support.microsoft.com/?kbid=2002980)

Pages (2): 1 2 »

RSS Feeds

QR Code

qr code

QR code created by QR code Widget

Fun with .NET

Visitors

Your Ads Here
Promote your products