Call Client-Side Script

RegisterStartupScript

Using RegisterStartupScript we can write
JavaScript function in code behind and call it from code-behind or from
HTML. Look at the below code for reference.
Calling & writing JavaScript function from server side code behind

private void Page_Load(object sender, System.EventArgs e)
{
string jScriptValidator;
jScriptValidator=”<script> function ReqFieldValidator()” +
” { if (document.forms[0].txtField.value == ”) \n”;
jScriptValidator+=”{ alert(‘TextBox cannot be empty’) \n “;
jScriptValidator+=”return false; \n”;
jScriptValidator+=”} \n”;
jScriptValidator+=” return true \n”;
jScriptValidator+=” } </script>”;
Page.RegisterStartupScript(“regJSval”,jScriptValidator);
btnSubmit.Attributes.Add(“onclick”,”return ReqFieldValidator()”);

}

Writing JavaScript function in server side code behind and calling from HTML

//Server side
private void Page_Load(object sender, System.EventArgs e)
{
string jScript;
jScript=”<script>function JavScriptFn(){alert” +
” (‘Client Function in javascript is call’)}</script>”;
}

//HTML side
< A onclick=”JavScriptFn()” >
< asp:Label id=”Label1″ runat=”server” Width=”281px”
ForeColor=”#8080FF”>Click to call Javascript function.
</asp:Label> >/A >

Writing JavaScript in HTML and calling it from code-behind

<Head >
<script>

function ReqField1Validator()
{
if (document.forms[0].txtField1.value == ”)
{
alert(‘TextBox cannot be empty’)
return false
}
return true
}

</script>
</Head >

private void Page_Load(object sender, System.EventArgs e)
{
btnOK.Attributes.Add(“onclick”,”return ReqField1Validator()”);
}

RegisterClientScriptBlock

Suppose
we want JavaScript code to be executed but not a function. In that case
we make use of RegisterClientScriptBlock.RegisterClientScriptBlock
which helps to make server side code as well as client side code inline
to each other.

private void btnClientBlock_Click(object sender, System.EventArgs e)
{
string jScript;
jScript=”<script>alert (‘Javascript block of code executed’)</script>”;
Page.RegisterClientScriptBlock(“keyClientBlock”,jScript);
lblSequencial.Text=”Remaining part of the code executed”;
}

(from : http://www.codeproject.com/aspnet/ClientServer.asp )

world clock javascript

javascript supporting multiple clocks but not showing the correct GMT time:

<table border=”0″ width=”200″ cellspacing=”0″ cellpadding=”3″>
<form name=”where”>
<tr>
<td width=”100%”>
<select name=”city” size=”1″ onchange=”updateclock(this);”>
<option value=”” selected>Local time</option>
<option value=”0″>London GMT</option>
<option value=”1″>Rome</option>
<option value=”7″>Bangkok</option>
<option value=”8″>Hong Kong</option>
<option value=”9″>Tokyo</option>
<option value=”10″>Sydney</option>
<option value=”12″>Fiji</option>
<option value=”-10″>Hawaii</option>
<option value=”-8″>San Francisco</option>
<option value=”-5″>New York</option>
<option value=”-3″>Buenos Aires</option>
</select>

Call Javascript function from codebehind C#

How to call a javascript function from ASPX.cs code behind file?

Set the Body tag in your page/master page to runat=”server” and an id=”MainBody”.

Put the script tag in your page like you normally would with any HTML file
<script src=”popup.js”  type=”text/javascript”></script>

Then in the code behind attach the onload attribute to the body tag .

protected void Page_Load(object sender, EventArgs e)
{
MasterPageBodyTag = (HtmlGenericControl)Page.Master.FindControl(“MainBody”);
MasterPageBodyTag.Attributes.Add(“Onload”, “Popup()”);
}

Or if you are using Master Pages where the body tag is in the Master Page. but only some of the content pages need to use the javascript.

You put this is the content pages that use the javascript.

protected void Page_Load(object sender, EventArgs e)
{
MasterPageBodyTag = (HtmlGenericControl)Page.Master.FindControl(“MainBody”);
MasterPageBodyTag.Attributes.Add(“Onload”, “Popup()”);
}

Let .NET Mobile Web Application support Javascripts

Is JavaScript supported in Mobile web application ? If yes, How ?

Just give some samples:

in web.config

<
system.web>

<
deviceFilters>

<
filter name=”supportsJavaScript” compare=”Javascript” argument=”true”/>

</
deviceFilters>

</system.web>

in aspx

<mobile:Form ID=”Form1″ Runat=”server”>

<mobile:TextBox ID=”TextBox1″ Runat=”server”>

</mobile:TextBox>

<mobile:Command ID=”Command1″ Runat=”server” OnClick=”Command1_Click”>Command</mobile:Command>

<mobile:Panel ID=”Panel1″ Runat=”server”>

<mobile:DeviceSpecific ID=”DeviceSpecific1″ Runat=”server”>

<Choice Filter=”supportsJavaScript” Xmlns=”http://schemas.microsoft.com/mobile/html32template”>

<ContentTemplate>

<script language=”javascript”>

var control;

control = document.Form1.TextBox1;

control.focus();

</script>

</ContentTemplate>

</Choice>

</mobile:DeviceSpecific>

</mobile:Panel>

</mobile:Form>
check if the device supports javascript?

if (Page.Request.Browser.JavaScript ==
true)

Response.Redirect(
“~/SupportsJava.aspx”);

else

Response.Redirect(“~/NotSupportsJava.aspx”);

( from : http://forums.asp.net/thread/1581990.aspx )

How to prevent a page from being copied ?

How to prevent a page from being copied ?  There are many ways but normally people use blocking the right mouse click function and block text selection function . If the visitor tries to right click mouse and would be ready to select text on your page , he/she will see a error message , or nothing will happen. However, visitor still can get your page content by choosing IE menu item “View \ Page Source” or other else menu item. for this, we can encrypt all page text content, so the visitor can not get the original text page content if he wanna copy via “View \ Page Source”.

Here I found a example from http://www.bluehostforum.com/archive/index.php/t-2796.html. I used it for my this website, my steps are :

1: Create a seperate PHP file named preventCopy.php:


/////////////Encripting code

function _fwk_filter_encryptt($content) {
$table = “0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMN OPQRSTUVWXYZ_@”;
$xor = 165;

// Prepare encoding table
$table = array_keys(count_chars($table, 1));
$i_min = min($table);
$i_max = max($table);
for ($c = count($table); $c > 0; $r = mt_rand(0, $c–))
array_splice($table, $r, $c – $r, array_reverse(array_slice($table, $r, $c – $r)));

// Encode sequence
$len = strlen($content);
$word = $shift = 0;
for ($i = 0; $i < $len; $i++)
{
$ch = $xor ^ ord($content[$i]);
$word |= ($ch << $shift);
$shift = ($shift + 2) % 6;
$enc .= chr($table[$word & 0x3F]);
$word >>= 6;
if (!$shift)
{
$enc .= chr($table[$word]);
$word >>= 6;
}
}
if ($shift)
$enc .= chr($table[$word]);

// Decode sequence
$tbl = array_fill($i_min, $i_max – $i_min + 1, 0);
while (list($k,$v) = each($table))
$tbl[$v] = $k;
$tbl = implode(“,”, $tbl);

$fi = “,p=0,s=0,w=0,t=Array({$tbl})”;
$f = “w|=(t[x.charCodeAt(p++)-{$i_min}])<<s;”;
$f .= “if(s){r+=String.fromCharCode({$xor}^w&255);w>>=8;s-=2}else{s=6}”;

// Generate page
$r = “<script language=JavaScript>”;
$r.= “function decrypt_p(x){“;
$r.= “var l=x.length,b=1024,i,j,r{$fi};”;
$r.= “for(j=Math.ceil(l/b);j>0;j–){r=”;for(i=Math.min(l,b);i>0;i–,l–){{$f}}document.write(r)}”;
$r.= “}decrypt_p(\”{$enc}\”)”;
$r.= “</script>”;
return $r;
}

ob_start(“_fwk_filter_encryptt”);

/////COPYRIGHT (No right clic)

echo “<SCRIPT type=\”text/javascript\”>\n”;
echo “<!–\n”;
echo “\n”;
echo “var message=\”Atempting to copy copyrighted content.\”;\n”;
echo “\n”;
echo “///////////////////////////////////\n”;
echo “function clickIE4(){\n”;
echo “if (event.button==2){\n”;
echo “alert(message);\n”;
echo “return false;\n”;
echo “}\n”;
echo “}\n”;
echo “\n”;
echo “function clickNS4(e){\n”;
echo “if (document.layers||document.getElementById&&!document.all){\n”;
echo “if (e.which==2||e.which==3){\n”;
echo “alert(message);\n”;
echo “return false;\n”;
echo “}\n”;
echo “}\n”;
echo “}\n”;
echo “\n”;
echo “if (document.layers){\n”;
echo “document.captureEvents(Event.MOUSEDOWN);\n”;
echo “document.onmousedown=clickNS4;\n”;
echo “}\n”;
echo “else if (document.all&&!document.getElementById){\n”;
echo “document.onmousedown=clickIE4;\n”;
echo “}\n”;
echo “\n”;
echo “document.oncontextmenu=new Function(\”alert(message);return false\”)\n”;
echo “\n”;
echo “//–>\n”;
echo “</SCRIPT>\n\n”;

//////Dont allow to select text

echo “<SCRIPT type=\”text/javascript\”>\n”;
echo “<!–\n”;
echo “\n”;
echo “function disableselect(e){\n”;
echo “return false\n”;
echo “}\n”;
echo “\n”;
echo “function reEnable(){\n”;
echo “return true\n”;
echo “}\n”;
echo “\n”;
echo “//if IE4+\n”;
echo “document.onselectstart=new Function (\”return false\”)\n”;
echo “\n”;
echo “//if NS6\n”;
echo “if (window.sidebar){\n”;
echo “document.onmousedown=disableselect\n”;
echo “document.onclick=reEnable\n”;
echo “}\n”;
echo “//–>\n”;
echo “</SCRIPT>\n\n”;

2: Open my template folder and open index.php:

insert in the index.php, add at the beginning:

<?php
include(“preventCopy.php”);
?>

Actually my index.php :

<?php
//写中文为了存utf8
defined( ‘_VALID_MOS’ ) or die( ‘Direct Access to this location is not allowed.’ );
// needed to seperate the ISO number from the language file constant _ISO
$iso = explode( ‘=’, _ISO );
// xml prolog
echo ‘<?xml version=”1.0″ encoding=”‘. $iso[1] .'”?’ .’>’;

include(“preventCopy.php”);

?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
….

But, since my website is using UTF-8 encoding, this preventCopy.php is just for ISO-8859-1, so I can not use  “Encripting code” part, I have to comment out this part just keep right click bloking and select function blocking.

What is RTM ?

Short for Release To Manufacturing, the version of a software product that is given to manufacturers to bundle into future versions of their hardware products. RTM versions are typically released to manufacturers before they are released to the general public so that the manufacturers can work out any bugs the software may encounter with hardware devices. The release of an RTM version does not necessarily mean that the creators have worked out all the problems with the software; there still may be more versions of the product before it is released to the general public.

URLs in master page of asp.net 2.0

(from : http://www.odetocode.com/Articles/450.aspx )
At runtime, the master page and the content page are in the same control hierarchy – the master page is essentially a user control inside the content page. At design time, however, the master page and content page are two different entities. In fact, the master page and content page may live in different directories. During design time, it’s easy to put URLs and relative paths into our master pages, but we have to be careful when using relative paths. Take the following master page excerpt as an example:.

<div>
<img src=”logo.gif” alt=”Company Logo” />

<asp:ContentPlaceHolder ID=”ContentPlaceHolder1″ runat=”server”>
</asp:ContentPlaceHolder>
</div>

The good news is, the ASP.NET runtime does provide a feature called “URL rebasing”. The runtime will try to “rebase” relative URLs it finds on server-side controls inside a master page. This means the following relative path will work, no matter where the master page and web form live.

<img src=”logo.gif” alt=”Company Logo” runat=”server” />

We’ve added a runat=”server” attribute to the image tag, making the <img> a server-side control. When the master page file and logo are in the root directory, but the web form is in a subdirectory, the ASP.NET runtime will rebase the relative path it finds in the src attribute to point to the root of the website.

The following code will also work, because we are using a server-side Image object.

<asp:Image ImageUrl=”logo.gif” runat=”server” />

The ASP.NET runtime will also rebase paths it finds inside of the head tag. Take the following excerpt from a master page:

<head runat=”server”>
<title>Untitled Page</title>

<link href=”styles/styles.css” type=”text/css” rel=”stylesheet”/>

</head>

If we request a webform from a subdirectory, the runtime will catch the href inside the link tag and rebase the URL to “../styles/styles.css”. However, the runtime doesn’t catch everything. If we included our style sheet with the following code, the runtime won’t rebase the relative href.
<head runat=”server”>

<style type=”text/css” media=”all”>
@import “styles/styles.css”;
</style>

</head>

Also, the runtime doesn’t rebase URLs inside of embedded styles, and not all attributes are covered (the background attribute, for instance).

<body background=”logo.gif” runat=”server”>
<!– the background for the body tag will break –>
<form id=”form1″ runat=”server”>

<div id=”Div1″ style=”background-image: url(‘logo.gif’);” runat=”server”>
<!– My background is also broken. –>
</div>

If you need to use a relative path in an area where the runtime does not provide the rebasing feature, you can compute a client side URL using ResolveClientUrl and passing a relative path. ResolveClientUrl, when called from inside a master page, will take into account the location of the master page, the location specified in the HTTP request, and the location specified by the relative path parameter to formulate the correct relative path to return.

<body background=<%= ResolveClientUrl(“logo.gif”) %> >

When working with image paths in embedded styles, it’s often a good idea to move the style definition into a .css file. The ASP.NET runtime will rebase the path it finds inside a link tag, so we won’t have any problems locating the stylesheet from any webform. Take the following style definition in a .css file:

body
{
background-image:url(‘images\logo.gif’);
}

Relative paths are safe inside a .css file because the browser will always request logo.gif relative to the location of the stylesheet.

sqlcmd command

You can run the SetupDatabase.sql which can be found within the App_Data,which creates the database schema using the following command in your command prompt:
sqlcmd -S SQL_SERVER_NAME -U USERNAME -P PASSWORD -d DATABASE_NAME -i SetupDatabase.sql

(Note:SQLCMD comes with the Visual Studio / SQL Express installation)

How to display/hidden menu items automatically due to logined user in ASP.NET 2.0

How to display/hidden menu items automatically due to logined user in ASP.NET 2.0

.NET 2.0 has the feature of displaying/hidden menu items automatically due to logined user in ASP.NET 2.0, but you have to know how to set up.

Normally, when you create a new .NET project, you can not get this feature, you will find specific menu item can not hidden or display due to the different users.
Just set up by the following steps:

1: Add a XML SiteMap Provider and something else related section in web.config file:

<system.web>
<authentication mode=”Forms”>

<forms loginUrl=”Default.aspx”  name=”.ASPNETAUTH”  path=”/” timeout=”20″ protection=”Validation” />
</authentication>

<authorization>
<allow users=”*”/>
</authorization>

<customErrors mode=”RemoteOnly” defaultRedirect=”CustomError.aspx”/>
<pages theme=”Standard”/>
<membership>
<providers>
<remove name=”AspNetSqlMembershipProvider”/>
<add name=”AspNetSqlMembershipProvider”


</membership>

<profile>
<providers>
<remove name=”AspNetSqlProfileProvider”/>
<add name=”AspNetSqlProfileProvider”


</providers>
</profile>

<roleManager enabled=”true”>
<providers>
<remove name=”AspNetSqlRoleProvider”/>
<add name=”AspNetSqlRoleProvider”


</providers>
</roleManager>

<siteMap defaultProvider=”XmlSiteMapProvider” enabled=”true”>
<providers>
<add name=”XmlSiteMapProvider” description=”SiteMap provider which reads in .sitemap XML files.” type=”System.Web.XmlSiteMapProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” siteMapFile=”web.sitemap” securityTrimmingEnabled=”true”/>
</providers>
</siteMap>

<!– compilation debug=”true”/ –>

</system.web>

2: Add menu items in Web.sitemap file:

<?xml version=”1.0″ encoding=”utf-8″ ?>
<siteMap  xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0″ >
<siteMapNode url=”~/Default.aspx” title=”Home” description=”Home Page” >
<siteMapNode url=”#” title=”Home” description=”Home Page” />
<siteMapNode url=”~/Services.aspx” title=”Services” description=”Our Services”/>
<siteMapNode url=”~/About.aspx” title=”About Us” description=”About Us”/>
<siteMapNode url=”~/Contact.aspx” title=”Contact” description=”Contact Information”/>
<siteMapNode url=”~/Admin/ContactInfoAdm.aspx” title=”Administration” description=”Administration” />
</siteMapNode>
</siteMap>

Note: in the Web.sitemap, for the “Home” menu, there should be add 2 times in Visual Web Developer 2005 Express like the following :

<siteMapNode url=”~/Default.aspx” title=”Home” description=”Home Page” >
<siteMapNode url=”#” title=”Home” description=”Home Page” />
…..

I tried  in Visual Studio 2005 too, It doesn’t need 2 times, just like this:


<?xml version=”1.0″ encoding=”utf-8″ ?>
<siteMap  xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0″ >
<siteMapNode url=”~/Default.aspx” title=”Home” description=”Home Page” >
<siteMapNode url=”~/Services.aspx” title=”Services” description=”Our Services”/>
<siteMapNode url=”~/About.aspx” title=”About Us” description=”About Us”/>
<siteMapNode url=”~/Contact.aspx” title=”Contact” description=”Contact Information”/>
<siteMapNode url=”~/Admin/ContactInfoAdm.aspx” title=”Administration” description=”Administration” />
</siteMapNode>
</siteMap>