Category Archives: Substitution

[RESOLVED] double entries in querystring when using urlrewrite

I've got the following situation:

I use url rewrite to rewrite /regionname into default.aspx?region=regionname. This works as expected. But when I do a postback on the page I get the region field two times in the querystring, which results in a comma seperated string when getting the value like this:

string RegionName = HttpContext.Current.Request.QueryString["region"];

RegionName gets the value "regionname, regionname".

Does someone knows why the double entry is written in the querystring? If I don't use the rewriting by going to this url: default.aspx?regionname=regionname the postback works fine.

Thanks for your reply,
Willem

The xml for the IIS rewriting module:

<rewrite>
			<rules>
				<rule name="Add trailing slash" stopProcessing="true">
					<match url="^([^.]*)/*$" />
					<conditions>
						<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
						<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
					</conditions>
					<action type="Rewrite" url="default.aspx?region={R:1}" />
				</rule>
				<rule name="Images" stopProcessing="true">
					<match url="(.*)/(.*)/(.*)/Image.aspx" />
					<conditions>
						<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
						<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
					</conditions>
					<action type="Rewrite" url="Image.aspx?id={R:1}&amp;width={R:2}&amp;height={R:3}" appendQueryString="false" />
				</rule>
				<rule name="OffersRequests" stopProcessing="true">
					<match url="(.*)/(.*)/((offers)|(requests)).aspx" />
					<conditions>
						<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
						<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
					</conditions>
					<action type="Rewrite" url="{R:3}.aspx?region={R:1}&amp;type={R:2}" appendQueryString="false" />
				</rule>
				<rule name="ShowAd" stopProcessing="true">
					<match url="(.*)/(.*)/((showad)|(companydetails)).aspx" />
					<conditions>
						<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
						<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
					</conditions>
					<action type="Rewrite" url="{R:3}.aspx?region={R:1}&amp;id={R:2}" appendQueryString="false" />
				</rule>
				<rule name="AllFiles" stopProcessing="true">
                    <match url="(.*)/(.*).aspx" />
					<conditions>
						<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
						<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
					</conditions>
                    <action type="Rewrite" url="{R:2}.aspx?region={R:1}" appendQueryString="false" />
				</rule>
			</rules>

try modifying the line:

.........

 <action type="Rewrite" url="default.aspx?region={R:1}" />

...................
to
<action type="Rewrite" url="default.aspx?region={R:1}" appendQueryString="false" />

hope it will help

It works! Thanks.

But now I get the querystring visible in the address box of the browser. One of the reasons that I use rewriting is to prevent that. I didn't have that before and it worked then too. Somehow I changed something in my application that causes this but I can't find what. In the end this is a solution for a problem that I still don't understand.

Any thoughts about how to get rid of the querystring in the address box?

Thanks again,

Willem

Hi,

Willem de Jong

In the end this is a solution for a problem that I still don't understand.

As far as I know the appendQueryString is used to specify whether the query string from the current URL should be preserved during substitution. By default, if the AppendQueryString flag is not specified, it is assumed to be true. This means that the query string from the original URL is appended to the substituted URL.

Here is an article which describes an overview of the URL Rewrite Module and explains the configuration concepts that are used by the module. Please check it and see whether it helps.

http://learn.iis.net/page.aspx/465/url-rewrite-module-configuration-reference/

Willem de Jong

But when I do a postback on the page I get the region field two times in the querystring

I would like to suggest you to check the link below for a similar thread which provides some solutions for the same issue.

URL Rewrite Module Doubles QueryString Params on Postback

One of the solutions which are provided in the thread above

I was able to solve the issue by adding

Form.Action = Request.RawUrl;

to the Page_Load event. I was able to leave appendQueryString="TRUE" and so far it is working properly.

In addition ,I would recommend that please check the links below for more information about URL Rewriting in ASP.NET.

http://msdn.microsoft.com/en-us/library/ms972974.aspx

http://www.codeproject.com/KB/ISAPI/URLRewriting.aspx

Hope it can help you.

[RESOLVED] How do I create a page that displays a Flash video selected via thumbnails

I want to create an ASP.NET web page whose primary purpose is to display a Flash slideshow chosen from a list of videos that I would provide. I envisage that the user would select his desired video by clicking on one of a group of ImageButtons, each showing a relevant thumbnail. The necessary controls for stepping backwards and forwards and pausing the slideshow would be built into these videos (I need no help with that).

Up to now, I have only ever displayed a single pre-determined Flash video on a page using standard SWfObject Javascript markup copied from somewhere or other. I have no Javascript coding skills and don't know how to control the choice of video file via code (VB.NET preferred).

Any assistance would be much appreciated.

David

I did something similar once. What I did was in the embed tags on a boilerplate video page I had something like this

<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="550" height="400" id="movie_name" align="middle">
    <param name="movie" value='<%= filename %>' />
    <!--[if !IE]>-->
    <object type="application/x-shockwave-flash" data='<%= filename %>'
width="550" height="400">
        <param name="movie" value='<%= filename %>' />
    <!--<![endif]-->
        <a href="http://www.adobe.com/go/getflash">
            <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
        </a>
    <!--[if !IE]>-->
    </object>
    <!--<![endif]-->
</object>

You can pass the filenamae as a parameter in a querystring like <a href="boilerplate.aspx?fn=TESTONE.SWF">click here</a> or something like that

Hi DarthSwian,
Many thanks for the suggestion but it's not quite what I am looking for. As I understand it, your solution separates the video selection page from the video display page. I would prefer to to have everything all on the same page and only refresh the video display div whenever a new thumbnail is clicked.

David

That was just an example, not HOW for you to do it.

If you want it all on one page, put the flash code on the same page, in a div with and id="whatever" and runat="server" and on page load - If Not Page.IsPostback Then

    whatever.visible = false

End if

On your link button click even, make whatever visible and load the parameters for the flash stuff. Save the variables in session maybe and only reload the session on button click.

Thanks for the additional info. I've made a start on reading up on how to store and retrieve values from the ASP.NET session state (not something I've ever done before). I've also never used the html <param> tag before.

While I am more than happy to check out these topics, I don't understand how the following line of your markup picks up the required value for the 'movie' parameter. I don't know what  value='<%= filename %>' means. In other words, your simple description "load the parameters for the flash stuff" is a bit over my head. I would be grateful for some further clarification.

<param name="movie" value='<%= filename %>' />

Sure, be happy to help. Let me dig up a sample of what I worked on previously and sort of make it fit your specs. I'm not going to do thumbnails, but a couple linkbuttons should do.

OK, here's a working sample, provide your own flash files. By the way it really isn't necessary to store anything in a session variable in this scenario

Markup:

<%@ Page Title="Home Page" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false"
    CodeBehind="Default.aspx.vb" Inherits="DynamicFlash._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to Dynamic Flash
    </h2>
   
   <div id="links" runat="server">
    <asp:LinkButton ID="lbOne" runat="server" CommandArgument="video1" Text="Video One" OnCommand="videoDisplay"></asp:LinkButton>
    <br />
    <asp:LinkButton ID="lbTwo" runat="server" CommandArgument="video2" Text="Video Two" OnCommand="videoDisplay"></asp:LinkButton>
   </div>

   <div id="flash" runat="server">
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
	codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="399" height="301" id="getController" align="middle">
	<param name="allowScriptAccess" value="sameDomain" />
	<param name="allowFullScreen" value="false" />
	<param name="movie" value="flash/<%=fNameWExt %>" />
	<param name="quality" value="high" />
	<param name="bgcolor" value="#ffffff" />
	<embed src="flash/<%=fNameWExt %>" quality="high"
	    bgcolor="#ffffff" width="399" height="301"
	    name="<%=fName %>" align="middle"
	    allowScriptAccess="sameDomain"
	    allowFullScreen="false" type="application/x-shockwave-flash"
	    pluginspage="http://www.macromedia.com/go/getflashplayer" />
	</object>
   </div>
</asp:Content>

Code behind:
Public Class _Default
Inherits System.Web.UI.Page

' public variables
Public fNameWExt As String = String.Empty
Public fName As String = String.Empty


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' hide flash div if not postback
If Not Page.IsPostBack Then
flash.Visible = False
End If
End Sub

''' <summary>
''' This handles the link button clicks
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Public Sub videoDisplay(sender As Object, e As CommandEventArgs)
Dim video As String = e.CommandArgument.ToString

Select Case video
Case "video1"
flash.Visible = True
fName = "video1"
fNameWExt = "video1.swf"
Case "video2"
flash.Visible = True
fName = "video2"
fNameWExt = "video2.swf"
Case Else
flash.Visible = False
End Select
End Sub

End Class


Many thanks for doing all that extra work on my behalf. It is much appreciated.

I have copied the key elements of your solution into my own code and got a test version working under a local host. So far so good. However, can you please confirm that your code creates unique values for the fnameWExt and fName variables for each user (as opposed to global variables that are the same for all users). I seem to remember hitting problems with similar variables a long time ago, though I don't remember the details.

David

The fName and fnameWExt are populated by what you pass in. Web pages are instanced, so each user get a fresh version of the page, the values do not persist for the next user.

Thanks for that. As it happens, I proved this for myself by uploading the new code to my ISP server and running the same page in several tabs of my brower - all running a different Flash slideshow. 

Once again, many thanks for explaining how to enable the markup to read the value of a program-controlled variable. That was a definite gap in my VB.NET skills.

David

Just one final question.

What is the name of the variable substitution method that you have described? I cannot find any reference to the <%= filename %> syntax in any of my textbooks and a Google search also yielded no results.

David

Its just a public variable and <%= %> is shorthand for writing out a variable in markup.

I can find no reference to the <%= %> syntax in my copy of the 'HTML, XHTML and CSS Bible'. Are you able to point me to a HTML tutorial website that explains the use of this syntax?

While I'm very happy that it works for my current requirement, I like to read up all the details about any programming trick I have just discovered. 

David

<%= %> is .NET syntax not html or css. Its for rending ASP code in the html markup. Just look for ASP.Net tutorials on this site. Its not a trick, its a standard way of doing ASP.Net

You might want to look at some of the tutorials on this site for a better explanation.

I would be happy to read any relevant tutorial if I could find one! Unfortunately, searching for <%= %> on this site doesn't give any useful results. I've tried both Bing and Google and both just give me a list of general ASP.NET websites. I've also tried the indexes of all three heavy duty ASP.NET textbooks that I own.

It is often the case that the key to a successful search is knowing the answer in advance! In other words, it helps if you know the correct terminology for the thing you are trying to find. In this case, I've no idea what word to look for.

David

This is really basic stuff, I'm surprised you've never run into it, but its about code blocks.

http://msdn.microsoft.com/en-us/library/ms178135.aspx

Many thanks for unearthing a formal Microsoft reference to this technique. However, in defence of my ignorance of such things, I am entirely self-taught in ASP.NET with the help of the following generally well-regarded textbooks (and this forum, of course):

Beginning ASP.NET 3.5 (Wrox)
Professional ASP.NET 3.5 (Wrox)
ASP.NET Unleashed (SAMS)

None of these books make any reference to 'code blocks' or 'embedded code blocks' in their indexes. Also, your Microsoft link provides the following guidance (with my underline):

Embedded code blocks are supported in ASP.NET Web pages primarily to preserve backward compatibility with older ASP technology. In general, using embedded code blocks for complex programming logic is not a best practice, because when the code is mixed on the page with markup, it can be difficult to debug and maintain. In addition, because the code is executed only during the page's render phase, you have substantially less flexibility than with code-behind or script-block code in scoping your code to the appropriate stage of page processing.

All of the above implies that code blocks are not quite the "really basic stuff" that you suggest. That being said, I don't know a more mainstream method for solving my original problem and what works is what matters! It would be interesting if anyone reading this can offer a 'best practice' solution that does not use code blocks.  

David

In fact, the article I provided is misleading as code blocks are EXACTLY how MVC handles the code and markup.

You could attempt to switch out those code blocks for asp:literal controls, writing out the ENTIRE embed code.

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<h2>
Welcome to Dynamic Flash
</h2>

<div id="links" runat="server">
<asp:LinkButton ID="lbOne" runat="server" CommandArgument="video1" Text="Video One" OnCommand="videoDisplay"></asp:LinkButton>
<br />
<asp:LinkButton ID="lbTwo" runat="server" CommandArgument="video2" Text="Video Two" OnCommand="videoDisplay"></asp:LinkButton>
</div>

<div id="flash" runat="server">
<asp:Literal ID="litFlash" runat="server"></asp:Literal>
</div>
</asp:Content>

CODE BEHIND
' public variables
Public fNameWExt As String = String.Empty
Public fName As String = String.Empty


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' hide flash div if not postback
If Not Page.IsPostBack Then
flash.Visible = False
End If
End Sub

''' <summary>
''' This handles the link button clicks
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Public Sub videoDisplay(sender As Object, e As CommandEventArgs)
Dim video As String = e.CommandArgument.ToString
Dim litCode As String

Select Case video
Case "video1"
flash.Visible = True
fName = "video1"
fNameWExt = "video1.swf"
Case "video2"
flash.Visible = True
fName = "video2"
fNameWExt = "video2.swf"
Case Else
flash.Visible = False
End Select

litCode = "<object classid=""clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" _
& "codebase=""http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0"" width=""399"" height=""301"" id=""getController"" align=""middle"">" _
& "<param name=""allowScriptAccess"" value=""sameDomain"" />" _
& "<param name=""allowFullScreen"" value=""false"" />" _
& "<param name=""movie"" value=""flash/" & fNameWExt & """ />" _
& "<param name=""quality"" value=""high"" />" _
& "<param name=""bgcolor"" value=""#ffffff"" />" _
& "<embed src=""flash/" & fNameWExt & """ quality=""high"" name='" & fName & "' align=""middle"" allowScriptAccess=""sameDomain"" allowFullScreen=""false"" type=""application/x-shockwave-flash"" pluginspage=""http://www.macromedia.com/go/getflashplayer"" />" _
& "</object>"
litFlash.Text = litCode
End Sub

Hi DarthSwian,
Please note that I have sent an apologetic private email to your Hotmail address in response to the first version of your last post (before you made some significant edits).

I only have limited time to devote to website programming and find it difficult to keep up to date with new trends such as MVC, so can't really comment on that point. However, I have made quite a lot of use of literals in the past and as soon as you mentioned them as a possible alternative approach I could understand how to do it and kicked myself for not thinking of it before! Thanks for taking the trouble to provide a fully worked example.

Despite quoting Microsoft's caveats in my previous post, I'm not that fussed about whether or not embedded code blocks are 'best practice'. In some ways they offer a neater solution in this case. Literals can be very useful but I always think that they look rather inelegant.   

Once again, many thanks for all your help. It really has been greatly appreciated. I would be lost in the complex world of ASP.NET without the kind assistance of people like yourself  Smile.

David 

[RESOLVED] Why Master Page not Working

Hello all,

I'm a newbie with asp.net but I already built a simple web app. I found out that if i used master page I will save a lot of time building my web app the problem is..

 

My Master page didn't load to any browser.. I used web developer express edition. Now i'm shifting to pro edition but i have not yet tried it..

Please help me.

 

thanks

 

Neil

Your master page nests your content pages so you can have a uniform design.

First step.

Create a new master page file, name it MasterPage.master (or anything you wish)

Now you must create you rcontent page and set the master page file to your master page. This can be done a few ways

a) directly from the new items window

b) by modifying the header line of the aspx page.

From the Add New Items window (depending on your application)

"Web Form Using Master Page" this will then ask you to select your master page to inherit.

Now you will notice something different about these pages here is a sample

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="Forms.Asp.Net.WebForms.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>

First off there is now a MasterPageFile declaration in the Header. 

Also you now only have <asp:Content> places, only in those places can you add content, and both those content tags correspond to ContentPlaceHolders (with their respective id's) in your master page.

Now whenever you add content inside the place holders.. it will be generated into that part of the master page.

A great example is to simply create a new C# Web application (the microsoft visual studio template) and have alook at their pages, they use a master Page called Site.Master and various content pages. You can use that template to help understand the MasterPage -> Content page relationship.

*** More technical ***

Now to add one more (more technical aspect)to Master Pages -> Content Pages relationships.

At first glance it may look asif the Content (aspx) page is a child page of your master page. Meaning the Master Page generates and then the content page.

I cant stress this enough, The Master Page is a control of the Content page meaning the content page loads first then loads the master page. This is very key to understanding how to access controls and elements between content and master pages.

 

Hope this helps

Thanks for the reply..Correct me if I'm wrong..from my understanding of master page it is natural that my master page didn't load as long as i didn't inherit it? meaning i should create a new webform  and inherit my master page?

Exactly..

You will have to eitherr create a new page with the refernece (in the page declaration) or modify your existing pages to

a) add the masterpagefile declaration

b) must modify the content so it is wrapped inside the <content> tags.

 

Cheers

I don't know what went wrong...but it didn't not load...it says

Server Error in '/UsingMasterPage' Application.

Unable to validate data.

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: Unable to validate data.

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): Unable to validate data.]
   System.Web.Configuration.MachineKeySection.EncryptOrDecryptData(Boolean fEncrypt, Byte[] buf, Byte[] modifier, Int32 start, Int32 length, Boolean useValidationSymAlgo, Boolean useLegacyMode, IVType ivType, Boolean signData) +1081
   System.Web.UI.Page.EncryptStringWithIV(String s, IVType ivType) +120
   System.Web.Handlers.AssemblyResourceLoader.FormatWebResourceUrl(String assemblyName, String resourceName, Int64 assemblyDate, Boolean htmlEncoded) +51
   System.Web.Handlers.AssemblyResourceLoader.GetWebResourceUrlInternal(Assembly assembly, String resourceName, Boolean htmlEncoded, Boolean forSubstitution, IScriptManager scriptManager) +1644
   System.Web.Handlers.AssemblyResourceLoader.GetWebResourceUrl(Type type, String resourceName, Boolean htmlEncoded, IScriptManager scriptManager) +722
   System.Web.UI.ClientScriptManager.GetWebResourceUrl(Page owner, Type type, String resourceName, Boolean htmlEncoded, IScriptManager scriptManager) +167
   System.Web.UI.ClientScriptManager.RegisterClientScriptResource(Type type, String resourceName) +67
   System.Web.UI.ClientScriptManager.RegisterClientScriptResource(Control control, Type type, String resourceName) +73
   System.Web.UI.WebControls.MenuRendererStandards.AddScriptReference() +592
   System.Web.UI.WebControls.MenuRendererStandards.PreRender(Boolean registerScript) +82
   System.Web.UI.WebControls.Menu.OnPreRender(EventArgs e) +235
   System.Web.UI.Control.PreRenderRecursiveInternal() +103
   System.Web.UI.Control.PreRenderRecursiveInternal() +175
   System.Web.UI.Control.PreRenderRecursiveInternal() +175
   System.Web.UI.Control.PreRenderRecursiveInternal() +175
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2496



Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225

 

i already did what you have told me...i suspect it's in the server i guess...any suggestions?

 

Thanks for the replies..I've already know what's going to do.

Hey i am getting the same error what was the issue and how you have fixed, same code runs fine in my colleague machine?

Cache Substitution while OverRiding Page.Render

I recently setup page caching in my application, and inserted a few cache substitutions to allow for minimal dynamic content on cached pages.

When I try to override the page's Render event and manually call base.render to extract a string and write the rendering myself using that string, the cache substitutions are written incorrectly and are placed at the top of the page (as if I had called Response.Write and just passed a string).

protected override void Render(HtmlTextWriter writer)
{
 StringWriter w = new StringWriter();
 HtmlTextWriter myoutput = new HtmlTextWriter(w);
 base.Render(myoutput);
 myoutput.Close();
 string outputText = w.GetStringBuilder().ToString();
 writer.Write(outputText);       
}

With this code running, all cache substitutions, regardless of where I put them, come up at the top of the page (before the <html> tag). 

 

Hi,

I'm not very sure where you put your substitution code.

I try to write one use regular expression to replace "html" with "HTML", I hope this is want you want though regular expresssion is not that effecient!

    protected override void Render(HtmlTextWriter writer)
    {
        string pattern = @"html";
        Regex rgx = new Regex(pattern);

        StringWriter w = new StringWriter();
        HtmlTextWriter myoutput = new HtmlTextWriter(w);
        base.Render(myoutput);
        myoutput.Close();
        string outputText = w.GetStringBuilder().ToString();


        string outputStr = rgx.Replace(outputText, "HTML");

        writer.Write(outputStr);
    }

You can find out from your client that "html" is successfully replace with "HTML"

 

 

Sorry, I totally misunderstand this, it should be cache substitutions
I know, but the problem is that the cache substitutions I put in get written at the top of the page instead of where I put them.  I think this has something to do with my not doing a normal base.Render, but I can't figure out why.

 I still haven't figured this out, and actually have found another project team in a different company having the same issue.

Help, anyone?

 

yrhein

I recently setup page caching in my application, and inserted a few cache substitutions to allow for minimal dynamic content on cached pages.

When I try to override the page's Render event and manually call base.render to extract a string and write the rendering myself using that string, the cache substitutions are written incorrectly and are placed at the top of the page (as if I had called Response.Write and just passed a string).

protected override void Render(HtmlTextWriter writer)
{
 StringWriter w = new StringWriter();
 HtmlTextWriter myoutput = new HtmlTextWriter(w);
 base.Render(myoutput);
 myoutput.Close();
 string outputText = w.GetStringBuilder().ToString();
 writer.Write(outputText);       
}

With this code running, all cache substitutions, regardless of where I put them, come up at the top of the page (before the <html> tag). 

 

 

In writing a string to the writer yourself you broke the ability for ASP.NET to insert the dynamic region markers requried for substitution.

See here.