Search This Blog

Monday, December 31, 2007

<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31b...

Facing issue when my team member try to upload compiled source code from her development machine to new production server.

Server Error in '/' Application.

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

Source Error:

</httphandlers>
<httpmodules>
<add type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="ScriptModule">
</httpmodules>
</SYSTEM.WEB>




I've facing this issue before here. Anyway, here is how the problem can be solved.
  1. Copy AjaxControlToolkit.dll and AjaxControlToolkit.pdb version 1.0.61025.0 from my development machine to my ASP.NET App bin folder. (i install my AjaxControlToolkit in C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\AjaxControlToolkit)
  2. Copy System.Web.Extensions.dll (C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions) and System.Web.Extensions.Design.dll (C:\WINDOWS\assembly\GAC_MSIL\System.Web.Extensions.Design) from my development machine to my ASP.NET App bin folder.
Done.

Sunday, December 30, 2007

New Year Resolution - Happy New Year 2008

"We will open the book. Its pages are blank. We are going to put words on them ourselves. The book is called Opportunity and its first chapter is New Year's Day."
-Edith Lovejoy Pierce-

Wednesday, December 19, 2007

CS0103: The name 'User' does not exist in the current context

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0103: The name 'User' does not exist in the current context

Source Error:
Line 6: <tr>
Line 7: <td colspan="2" align="center">
Line 8: <=User.Identity.Name %>
Line 9: </td>
Line 10: </tr>


Above is the error that i face when compiling my application.
To solve it, change <%=User.Identity.Name %> to <%=Page.User.Identity.Name %>

Sunday, December 16, 2007

Only one instance of a ScriptManager can be added to the page.

Error message "Only one instance of a ScriptManager can be added to the page." when trying to access my web application. Compiled have no error.



The reason for this error is i have include more than one (my case is two) ScriptManager in the same page. In my case in master page and in another page (login.aspx) that include master page.

To solve it, simple remove the ScriptManager in login.aspx. Problem solved.

Saturday, December 15, 2007

Retrive ASP.NET Object value using javascript

I have a checkbox name Checkbox2 runat server, if we try to get value by calling ID= Checkbox2 using javascipt, javascript error: Object not found, this is because server side ID is different with the client side ID. Client side ID for this object is Checkbox2.ClientID.

For example, i need to pass Checkbox2 value to a javascript function during page load, this is what i do.

protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterStartupScript("Onload", "<script language='javascript'>fnCheck('" + Checkbox2.ClientID +"');</script>");
}

fnCheck is a javascript function that i already define some where.

Sunday, December 9, 2007

Test your connection

Most of the time, we are interested to check our MAX Download/Upload speed (commonly referred to as Bandwidth). Here have a very good site to let us to test on it in different country

http://www.dslreports.com/speedtest?more=1

Thursday, December 6, 2007

Shrinking the Transaction Log

Most of the time the transaction log file growth to very huge size until your harddisk not able to take it. What can i do is shrinking the log file.

Remember: Always take full backup before this activity.

There are few ways to do this but i like to use detach and attach method. You can choose whether using enterprise manager or T-SQL. I like to use T-SQL.

t-sql
  • sp_detach_db [dbname]
  • Delete the disk log file.
  • sp_attach_single_file_db [dbname], [filename]where [filename] is the name of the physical data file (.mdf).






Example:
I have a database name RatePost and the .mdf and .ldf physical location
C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\RatePost.mdf
C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\RatePost_log.ldf

  1. Open my enterprise manager and open a new query window.
  2. Type sp_detach_db RatePost in the query window and run the script
  3. Go to "C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\" and delete RatePost_log.ldf
  4. Clear the query window and type
    sp_attach_single_file_db RateMyPosts, 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\RatePost.mdf' and run the script
  5. After you have run your script, you can see in Message window
    File activation failure. The physical file name "C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\RatePost_log.ldf" may be incorrect.
    New log file 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\RatePost_log.ldf' was created.

Now you go to check your log file size reduce and back to around 500Kbyte.

Done.

Sunday, November 25, 2007

Expected identifier, string or number

invoice software
Invoice software

For below javascript code, i got error "Expected identifier, string or number" in IE but it's working fine in firefox and safari.
var RealtimeViewer =
{
timer : 5000,
Interval : null,

init: function() {
xxxxxxxxx
xxxxxxxxx
},

RatingUpdate: function(){
xxxxxxxx
xxxxxxxx
},

};
To solve the problem, remove the last "," before close the object RealtimeViewer "};". It will become

var RealtimeViewer = {
timer : 5000,
Interval : null,

init: function()
{
xxxxxxxxx
xxxxxxxxx
},

RatingUpdate: function()
{
xxxxxxxx
xxxxxxxx
}
};

Wednesday, November 14, 2007

MS SQL 2005: generate ID using ROW_NUMBER()

SELECT PVID, AuthorName, ROW_NUMBER() OVER(ORDER BY PVID DESC) AS ID WHERE ID BETWEEN 16 AND 20

PVIDAuthorNameID
34Mitchell16
65Sean17
73John18
90Mogan19
96Chang20

Select DISTINCT column together with Non DISTINCT Column

I have a post rating table named Rate, with Column RateID (auto ID), PostID, DateRated

I want the select the 20 latest rated post with no repeated PostID

Below query help me to get the data needed


SELECT TOP 20 PostID, MAX(RateID) AS RateID, MAX(DateRated ) AS DateRated FROM Rate
GROUP BY PostID
ORDER BY RateID DESC, DateRated DESC

Monday, November 12, 2007

technorati like - News Scroller with jQuery

I have create a real time viewer for blogarate.com in ASP.NET using jQuery. If you not familiar with jquery, you can read more here jquery.com. It's a very powerful javascript library.

Let me explain how the real time viewer/scroller/ticker/ works:

When web user access to realtime.aspx. The page will bind 5 latest rated blog and show on screen. once the user/visitor rate on the blog, the newly rated blog will show on top, the rest will scroll down and the last one will be deleted. To see real example, please check on
http://202.75.40.204/blogarate/Realtime_.aspx

There are few things that we need to take care of in my case:

  • HTML/ASPX
  • CSS
  • Javascript
  • AJAX
HTML/ASPX

I'm using in the scroller <ol> because we have more than one (5) message want to display.

<div id="content">
<ol class="wrapper">
<li class="headline">
Message 1
</li>
<li class="headline">
Message 2
</li>
<li class="headline">
Message 3
</li>
<li class="headline">
Message 4
</li>
<li class="headline">
Message 5
</li>
</ol>
</div>


invoice software

CSS
Create CSS for #content and .wrapper with height: 395px; width: 500px; overflow: hidden; The height: 395px; is the trick here. You will get what i mean when go along.
Each headline will have height: 78px; 5 headline will give total of 390px.


#content {
position: relative;
overflow: hidden;
float:left;
height: 395px;
width: 500px;
clear: both;
}
.wrapper
{
position:relative;
float: left;
margin:0;
overflow:hidden;
width: 500px;
padding-left: 0;
list-style-type: none;
}
.headline {
position: relative;
height: 78px;
width: 500px;
left:5px;
overflow: hidden;
border-bottom: 1px solid #CCC;
float: left;
list-style-type: none;
z-index : 1;
}
.next
{
margin-top: -100px;
/* for IE */
filter: alpha(opacity=40);
/* CSS3 standard */
opacity: 0.4;
/* for Mozilla */
-moz-opacity: 0.4;
}
active
{
background-color:#EEE;
border-bottom: none;
}



invoice software

Javascript

// JScript File
var BlogarateRealtime = {
timer : 10, // second
display : 5, // how many item displayed
interval: null,
animation: 500, //milisecond


init: function() {
if (!BlogarateRealtime.interval) {

// stop scrolling when mouseover the message
// start scroll again when mouseout
$("#content .wrapper").mouseover(function(){
BlogarateRealtime.stopScroll();
}).mouseout(function(){
BlogarateRealtime.startScroll();
})
BlogarateRealtime.RatingUpdate();
BlogarateRealtime.startScroll();
}
},

RatingUpdate: function(){
var i;

// add class active when mouseover
// remove class active when mouse out
var cpostItem = $(".wrapper .headline");
$(cpostItem).mouseover(function() {
$(this).addClass("active");
}).mouseout(function() {
$(this).removeClass("active");
});


// xxx.shx return realtime message (rewly post)
var html = $.ajax({
url: http://xxx.ashx/ ,
async: false
}).responseText;
// return 3 value:
//1. PostUpdating[0] - any blog rated
//2. PostUpdating[1] - new blog ID
//3. PostUpdating[2] - new blog information

var PostUpdating = html.split("");

// check if any new blog rated (1 = yes, 0 = no)
if (PostUpdating[0] == "1")
{

// assign currentItem with new blog infomation
var currentItem = PostUpdating[2];
// add class next to currentItem
// pre append currentItem to #content .wrapper
$(currentItem).addClass("next").prependTo("#content .wrapper");
// scrolling (animate) the new blog to marginTop -1
$(".wrapper .next").animate( { marginTop: -1 }, BlogarateRealtime.animation, function() {
// remove marginTop -1, class next and fadeIn new blog
$(".wrapper .next").css("marginTop", -1);
$(".wrapper .next").removeClass("next");
$(".wrapper .next").fadeIn(BlogarateRealtime.animation);
});

var postItem = $(".wrapper .headline");
// fade out and remove the last post
$(postItem[BlogarateRealtime.display]).animate( { opacity: .50 }, BlogarateRealtime.animation, function(){
$(postItem[BlogarateRealtime.display]).remove();
} );
// add class active when mouse over
// remove class active when mouseout
$(postItem).mouseover(function() {
$(this).addClass("active");
}).mouseout(function() {
$(this).removeClass("active");
});
}

},
startScroll: function() {
if (!this.interval) {
this.interval = setInterval("BlogarateRealtime.RatingUpdate()", this.timer * 1000);
}
},
stopScroll: function() {
if (this.interval) {
clearInterval(this.interval);
this.interval = false;
}
}
};
// initial once ducument finish loaded
$(BlogarateRealtime.init);

AJAX
The call of http://xxx.ashx/ will return newly added post if there is any.

You can see the effect in http://202.75.40.204/blogarate/Realtime_.aspx . You will only see the scroll effect if only new post rated. Done.

Leave me a message or a comment if you have any. Thanks

Thursday, November 8, 2007

Global variable In web.config

Let's say want to add a variable deployment in web.config, add
<appsettings><add value="0" key="deployment"></appsettings>to <configuration></configuration>if <appsettings></appsettings>not exist in web.config.


<configuration>
<appsettings>
<add value="0" key="deployment">
</appsettings>
</configuration>


to call the variable in C# code,

string strDeployment = System.Configuration.ConfigurationSettings.AppSettings["deployment"];

Done

Monday, November 5, 2007

jQuery: Exception... "'Permission denied to call method XMLHttpRequest.open' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: ...

I received below error message in firebug when i try to use jQuery Ajax call

var html = $.ajax({
url: "http://www.xxx.com",
async: false
}).responseText;

Where http://www.xxx.com is different domain from my current site.

Exception... "'Permission denied to call method XMLHttpRequest.open' when calling method: [nsIDOMEventListener::handleEvent]" nsresult: "0x8057001e (NS_ERROR_XPC_JS_THREW_STRING)" location: "" data: no]

As far as my understanding, this is not allowed. In order to have the similar result, use Cross Domain getJSON or you can check on my sample in other post which work on cross domain ajax.




Ajax treat http://www.xxx.com and http://xxx.com as two different entry. There are different between url with www and without www. To solve this problem, use location.host to get the url that use by visitors.

example:
var html = $.ajax({
url: "http://"+location.host+ "/Realtime.ashx" + "?PostID=" + PostID,
async: false
}).responseText;


Thursday, November 1, 2007

Dynamic CSS reference in ASP.NET

This sample allowed me to dynamic add CSS link to my ASP.NET page. If css provided via querystring, the page will link to provided css. If not provided then if will refer to the default css.


protected void Page_Load(object sender, EventArgs e)
{
string mycss;

if (Request.QueryString["mycss"] != null)
{
if (Request.QueryString["mycss"].ToString().Trim().Length > 0)
{
mycss= Request.QueryString["mycss"].ToString().Trim();
}
else
{
mycss= "~/default.css";
}
}
else
{
mycss= "~/default.css";
}
AddLinkedStyleSheet(this, mycss);
}

public static void AddLinkedStyleSheet(Page page, string stylesheet)
{
HtmlLink link = new HtmlLink();
link.Href = page.ResolveUrl(stylesheet);
link.Attributes["text"] = "text/css";
link.Attributes["rel"] = "stylesheet";
page.Header.Controls.Add(link);
}

credit give to
Rich Sturim

Wednesday, October 31, 2007

window.location.search

window.location.search is a very useful script that able to return all querystring for further usage like pass to another page/AJAX.

To test on the usage, save below page as locationsearch.htm. To see the result, add querystring to the page called: locationsearch.htm?p=testing&l=javascript

<html>
<head>
<script language="JavaScript">

function onload()
{
alert(window.location.search);
}

</script>
</head>

<body onLoad="onload()">

</body>
</html>

Monday, October 29, 2007

Top 100 living geniuses

Top 100 living geniuses


1=Albert Hoffman(Swiss)Chemist27
1=Tim Berners-Lee(British)Computer Scientist27
3George Soros(American)Investor & Philanthropist25
4Matt Groening(American)Satirist & Animator24
5=Nelson Mandela(South African)Politician & Diplomat23
5=Frederick Sanger(British)Chemist23
7=Dario Fo(Italian)Writer & Dramatist22
7=Steven Hawking(British)Physicist22
9=Oscar Niemeyer(Brazilian)Architect21
9=Philip Glass(American)Composer21
9=Grigory Perelman(Russian)Mathematician21
12=Andrew Wiles(British)Mathematician20
12=Li Hongzhi(Chinese)Spiritual Leader20
12=Ali Javan(Iranian)Engineer20
15=Brian Eno(British)Composer19
15=Damian Hirst(British)Artist19
15=Daniel Tammet(British)Savant & Linguist19
18Nicholson Baker(AmericanWriter18
19Daniel Barenboim(N/A)Musician17
20=Robert Crumb(American)Artist16
20= Richard Dawkins(British)Biologist and philosopher16
20=Larry Page & Sergey Brin(American)Publishers16
20=Rupert Murdoch(American)Publisher16
20= Geoffrey Hill(British)Poet16
25Garry Kasparov(Russian)Chess Player15
26=The Dalai Lama(Tibetan)Spiritual Leader14
26=Steven Spielberg(American)Film maker14
26=Hiroshi Ishiguro(Japanese)Roboticist14
26=Robert Edwards(British)Pioneer of IVF treatment14
26=Seamus Heaney(Irish)Poet14
31Harold Pinter(British)Writer & Dramatist13
32=Flossie Wong-Staal(Chinese)Bio-technologist12
32=Bobby Fischer(American)Chess Player12
32=Prince(American)Musician12
32=Henrik Gorecki(Polish)Composer12
32= Avram Noam Chomski(American)Philosopher & linguist12
32=Sebastian Thrun(German)Probabilistic roboticist12
32=Nima Arkani Hamed(Canadian)Physicist12
32=Margaret Turnbull(American)Astrobiologist12
40=Elaine Pagels(American)Historian11
40=Enrique Ostrea(Philippino)Pediatrics & neonatology11
40=Gary Becker(American)Economist11
43=Mohammed Ali(American)Boxer10
43=Osama Bin Laden(Saudi)Islamicist10
43=Bill Gates(American)Businessman10
43=Philip Roth(American)Writer10
43=James West(American)Invented the foil electrical microphone10
43= Tuan Vo-Dinh(Vietnamese)Bio-Medical Scientist 10
49=Brian Wilson(American)Musician9
49=Stevie Wonder(American)Singer songwriter9
49=Vint Cerf(American)Computer scientist9
49=Henry Kissinger(American)Diplomat and politician9
49=Richard Branson(British)Publicist9
49=Pardis Sabeti(Iranian)Biological anthropologist9
49=Jon de Mol(Dutch)Television producer9
49=Meryl Streep (American)Actress9
49=Margaret Attwood(Canadian)Writer9
58=Placido Domingo(Spanish)Singer8
58=John Lasseter(American)Digital Animator8
58=Shunpei Yamazaki(Japanese)Computer scientist & physicist8
58=Jane Goodall(British)Ethologist & Anthropologist8
58=Kirti Narayan Chaudhuri(Indian)Historian8
58=John Goto(British)Photographer8
58=Paul McCartney(British)Musician8
58=Stephen King(American)Writer8
58=Leonard Cohen(American)Poet & musician8
67=Aretha Franklin(American)Musician7
67=David Bowie(British)Musician7
67=Emily Oster(American)Economist7
67=Steve Wozniak(American)Engineer and co-founder of Apple Computers7
67=Martin Cooper(American)Inventor of the cell phone7
72=George Lucas(American)Film maker6
72=Niles Rogers(American)Musician6
72=Hans Zimmer(German)Composer6
72=John Williams(American)Composer6
72=Annette Baier(New Zealander)Philosopher6
72=Dorothy Rowe(British)Psychologist6
72=Ivan Marchuk(Ukrainian)Artist & sculptor6
72= Robin Escovado(American)Composer6
72=Mark Dean(American)Inventor & computer scientist6
72=Rick Rubin (American)Musician & producer6
72=Stan Lee(American)Publisher6
83=David Warren(Australian)Engineer5
83=Jon Fosse(Norwegian)Writer & dramatist
83=Gjertrud Schnackenberg(American)Poet5
83=Graham Linehan(Irish)Writer & dramatist5
83=JK Rowling(British)Writer5
83= Ken Russell(British)Film maker5
83=Mikhail Timofeyevich Kalashnikov(Russian)Small arms designer5
83=Erich Jarvis(American)Neurobiologist5
91=. Chad Varah(British)Founder of Samaritans4
91=Nicolas Hayek(Swiss)Businessman and founder of Swatch4
91=Alastair Hannay(British)Philosopher4
94=Patricia Bath(American)Ophthalmologist
94=Thomas A. Jackson (American)Aerospace engineer 3
94=Dolly Parton(American)Singer 3
94=Morissey(British)Singer3
94=Michael Eavis(British)Organiser of Glastonbury 3
94=Ranulph Fiennes(British)Adventurer 3
100=. Quentin Tarantino(American) Filmmaker2


Extract from http://www.telegraph.co.uk/

Saturday, October 27, 2007

Hot topic in town - Facebook

Plan starting to develop a facebook application, not sure where to start and i found this wiki really help .... have a look .. Facebook for .Net developers ..
http://wiki.developers.facebook.com/index.php/ASP.NET

Thursday, October 25, 2007

System.Net.Mail.SmtpFailedRecipientsException

I'm migrating my existing application to a new application server. When test on the suggestion box which involve SMTP, i get below error message:



System.Net.Mail.SmtpFailedRecipientsException: Unable to send to all recipients. ---> System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: No such user here --- End of inner exception stack trace --- at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception) at System.Net.Mail.SmtpClient.Send(MailMessage message)

Few things that i test on new server:
  1. Install SMTP - check on document provided
  2. Testing with the Pickup directory
    You can also compose a simple e-mail text file based on the SMTP specifications (RFC 822). Here is the content of a sample text file typed in Notepad:

    From: myname@mydomain.com
    To: someone@somedomain.com
    Subject: testing
    This is the test message body.

    Simply copy or move the text file into the Pickup directory where SMTP was installed. (The default path should be "\Inetpub\mailroot\Pickup" but if you have Exchange installed then the path will be "\Program Files\Exchsrvr\Mailroot\Vsi 1\Pickup".)
  3. Set Relay Restrictions in the IIS admin. Put your app server IP Address/Domain Name in the Relay Resctictions.


  4. After all, remember to restart your machine. Restart IIS or Virtual SMTP server won't help. Restart the server do the best.

Done

CS0030: Cannot convert type 'ASP.login_aspx' to 'System.Web.UI.WebControls.Login'

Facing an error below and found that i'm not alone.

Posted by Microsoft on 9/29/2005 at 4:46 PM
If you have used a Page that effectively uses a codebehind classname that is the same as say the Login control, that is Login, e.g. your page was called Login.aspx, then when you pre-compile (publish) the web site as an updateable web site, the aspx is retained and tries to compile against a type called Login in the code behind.


Server Error in '/' Application.
--------------------------------------------------------------------------------
Compilation Error


Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0030: Cannot convert type 'ASP.login_aspx' to 'System.Web.UI.WebControls.Login'


Source Error:

Line 118: public login_aspx() {

Line 119: string[] dependencies;
Line 120: ((Login)(this)).AppRelativeVirtualPath = "~/Login.aspx";
Line 121: if ((global::ASP.login_aspx.@__initialized == false)) {
Line 122: dependencies = new string[6];

Source File: c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\3e0e0b67\701b7b2\App_Web_login.aspx.cdcab7d2.fhpe1ais.0.cs Line: 120






Many post and solutions can get from the internet. Among them is

  1. Rename Login.aspx to others name like signin.aspx
  2. Try using a classname for your codebehind and defined in the inherits that does not clash with a type in System.Web, e.g. LoginPage, or qualify the class and therefore the inherits statement with a namespace, e.g.<%@ page ... inherits="theNs.Login" %.namespace theNs { public partial class Login : System.Web.UI.Page { .. } }
  3. uncheck “Allow this precompiled site to be updatable” when Publish Web Site in Visual Studio 2005.
Solution no. 3 is good for me. Less work and works 100%.

Wednesday, October 24, 2007

A generic error occurred in GDI+.

Error Message received when try to upload picture to my web application:

Server Error in '/' Application.

A generic error occurred in GDI+.

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.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.


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:

[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +396978
System.Drawing.Image.Save(String filename, ImageFormat format) +69
Account.WarpImageDimensions(String filePath, String fileName, Bitmap imageToSave) +301
Account.ImageButton1_Click(Object sender, ImageClickEventArgs e) +350
System.Web.UI.WebControls.ImageButton.OnClick(ImageClickEventArgs e) +86
System.Web.UI.WebControls.ImageButton.RaisePostBackEvent(String eventArgument) +115
System.Web.UI.WebControls.ImageButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746



Solve this by:
1. check the permission for upload folder
2. check the correct upload path

problem solved.

Select top xx from DataTable

I was trying to figure out how to sort and select top 20 from a DataTable. Understand from the reading, DataTable have no "select top" feature. Some suggest use below method

DataTable outputTable = SourceTable.Clone();
for(int i=0;i<20;i++)
outputTable.ImportRow(SourceTable.Rows[i]);

In my case, i need to sort my DataTable oldTable and select top 20 after the sorting. I use DataView dView to sort it and copy it into a new DataTable newTable. For the display purpose, i use "for loop" to select top 20 from the new DataTable newTable.

Sample Code:

int maxDisplay = 20;
DataView dView = oldTable.DefaultView;
dView.Sort = " [Count] DESC ";
DataTable newTable = dView.ToTable();



int dCount = newTable.Rows.Count;
if (maxDisplay > dCount )
maxDisplay = dCount ;
if (dCount > 0)
{
for (int i = 0; i < maxDisplay ; i++)

{
xxxxxx;
xxx + newTable.Rows[i]["name"].ToString();

xxxxxx;
}
}

text wrapping in table : Firefox and IE

My case:
I'm using C# StringBuilder object to generate a long string with all blog Tags with link and without any white space between them. I've tried below code.


.hardbreak
{
width: 190px;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
<table style="TABLE-LAYOUT: fixed; WIDTH: 210px" cellpadding="'3'">

<tr>
<td class="hardbreak" style="WIDTH: 200px">

xxxx return StringBuilder code over here xxxx
</td>

</tr>
</table>

Result in IE: working fine. Even the word can be wrapped.



Result in Firefox: not working



this give me a problem.

I've try to google around and finally i found that i should insert a white space " " after every single tag before append to StringBuilder. Surprisingly, without using the class above, my problem solved.

Friday, October 19, 2007

Server Error in '/'Application. Configuration Error

Error Message on web.config when setting up a new application.

Server Error in '/'Application.

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: Unrecognized attribute 'requirePermission'.

Change the ASP.NET version to the correct version.



Problem solved.

Thursday, October 18, 2007

Must declare the scalar variable "@UserId".

We are doing server migration testing. I've restored a DB from production to staging server. I setup up a ASP.NET application and point to production server, everything work fine but when point to staging server, error below appear. By the way, we are using MS SQL 2005 standard edition in both server.

Server Error in '/' Application.

Must declare the scalar variable "@UserId".
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.Data.SqlClient.SqlException: Must declare the scalar variable "@UserId".

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:


[SqlException (0x80131904): Must declare the scalar variable "@UserId".]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +862234
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +739110
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +188
System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +1956
System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +31
System.Data.SqlClient.SqlDataReader.get_MetaData() +62
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +903
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +132
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +122
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) +62
Dal.GetRecentRater(Int32 PostId, DataTable dt) +190
Post.BindBlogPost() +1295
Post.Page_Load(Object sender, EventArgs e) +49
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1061










At this point, i suspect something wrong with the staging server DB. So i access to the staging server and execute the stored procedure in Query Panel and it give me some error message.
Must declare the scalar variable "@UserId".







I open and check the stored procedure and the stored procedure is simple

ALTER PROCEDURE [dbo].[GetUserDetails]
@UserId int
as
select * from Users where UserId = @UserID


After check for a while, i change the @UserID to @UserId and magic happened. Problem solved. It's case sensitive.

It's strange because this stored procedure running in production server without any problem. Collation for both MS SQL 2005 DB are SQL_Latin1_General_CP1_CI_AS.

Tuesday, October 16, 2007

DataList Paging

There are always a problem to customize paging for DataList as below.

I'm able to develop a DataList Paging for my own application. Credit should give to Netomatix.
Please download and check the sample source code from my testing.
For testing purpose, i use Northwind database and i've created a new stored proc called: GetProductByCategory










Stored Procedure: GetProductByCategory

CREATE PROCEDURE [dbo].[GetProductByCategory]
@PageIndex INT,
@NumRows INT,
@Discontinued BIT = 1
AS
BEGIN
SET NOCOUNT ON
DECLARE @StartRowIndex INT;
SET @StartRowIndex = (@PageIndex * @NumRows) + 1;
WITH myProducts AS(
SELECT ProductID, ProductName, UnitPrice,
CategoryName, Description, UnitsInStock,
ROW_NUMBER() OVER(ORDER BY ProductID DESC) as Row,
count(*) over() AS ResultRowCount, Discontinued
FROM Products P
INNER JOIN Categories C
ON P.CategoryID = C.CategoryID
WHERE Discontinued = @Discontinued
)
SELECT * FROM myProducts
WHERE Row BETWEEN @StartRowIndex AND (@StartRowIndex + @NumRows)-1
ORDER BY ProductID ASC
SET NOCOUNT OFF
END

Monday, October 15, 2007

Could not load type '_Default'

Server Error in '/DataListPage' Application.

Parser Error

Description
: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type '_Default'.

Source Error:

Line 1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" % >
Line 2:
Line 3: http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">

I'm able to run my application in Visual Studio, when try to open the application directly from IE, i get this error. After check for a while, i found that it's the problem for the ASP.NET Version that selected. After i change to ASP.NET 2.0.50727, problem solved.

ASP.NET wrapper for Twitter API

I was developing a ASP.NET wrapper for Twitter API and end up using the wrapper provided by Yedda. Credit should to Yedda.

Download the wrapper from Yedda. Unzip the files and you can play around with the project.

What i do is
  1. Create a new class name TwitterWrapper in my App_Code
  2. Copy the code from Twitter.cs and paste in TwitterWrapper.cs

to twitter your message:

string xmlOutput = "";
string TwitterUserName = "username";
string TwitterPassword = "password";

string TwitterMessage = "Hello twitter";

if (TwitterUserName != "" && TwitterPassword != "")
{
try
{
TwitterWrapper twitter = new TwitterWrapper();
xmlOutput = twitter.Update(TwitterUserName, TwitterPassword, TwitterMessage, TwitterWrapper.OutputFormatType.XML);
}
catch (Exception ex)
{ }
finally
{ }
}

Sunday, October 14, 2007

System.Web.HttpParseException: Could not load the assembly App_Web_xxxx. Make sure that it is compiled before accessing the page.

I always received error message from the web application after the last deployment.

System.Web.HttpParseException: Could not load the assembly 'App_Web_fsfkjwna'. Make sure that it is compiled before accessing the page. ---> System.Web.HttpParseException: Could not load the assembly 'App_Web_fsfkjwna'. Make sure that it is compiled before accessing the page. ---> System.Web.HttpParseException: Could not load the assembly 'App_Web_fsfkjwna'. Make sure that it is compiled before accessing the page. ---> System.Web.HttpException: Could not load the assembly 'App_Web_fsfkjwna'. Make sure that it is compiled before accessing the page.at System.Web.UI.TemplateParser.GetType(String typeName, Boolean ignoreCase, Boolean throwOnError)at System.Web.UI.TemplateParser.ProcessInheritsAttribute(String baseTypeName, String codeFileBaseTypeName, String src, Assembly assembly)at System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData)--- End of inner exception stack trace ---at System.Web.UI.TemplateParser.ProcessException(Exception ex)at System.Web.UI.TemplateParser.PostProcessMainDirectiveAttributes(IDictionary parseData)at System.Web.UI.PageParser.PostProcessMainDirectiveAttributes(IDictionary parseData)at System.Web.UI.TemplateParser.ProcessMainDirective(IDictionary mainDirective)at System.Web.UI.TemplateControlParser.ProcessMainDirective(IDictionary mainDirective)at System.Web.UI.PageParser.ProcessMainDirective(IDictionary mainDirective)at System.Web.UI.TemplateParser.ProcessDirective(String directiveName, IDictionary directive)at System.Web.UI.BaseTemplateParser.ProcessDirective(String directiveName, IDictionary directive)at System.Web.UI.TemplateControlParser.ProcessDirective(String directiveName, IDictionary directive)at System.Web.UI.PageParser.ProcessDirective(String directiveName, IDictionary directive)at System.Web.UI.TemplateParser.ParseStringInternal(String text, Encoding fileEncoding)--- End of inner exception stack trace ---at System.Web.UI.TemplateParser.ProcessException(Exception ex)at System.Web.UI.TemplateParser.ParseStringInternal(String text, Encoding fileEncoding)at System.Web.UI.TemplateParser.ParseString(String text, VirtualPath virtualPath, Encoding fileEncoding)--- End of inner exception stack trace ---at System.Web.UI.TemplateParser.ParseString(String text, VirtualPath virtualPath, Encoding fileEncoding)at System.Web.UI.TemplateParser.ParseFile(String physicalPath, VirtualPath virtualPath)at System.Web.UI.TemplateParser.ParseInternal()at System.Web.UI.TemplateParser.Parse()at System.Web.Compilation.BaseTemplateBuildProvider.get_CodeCompilerType()at System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider buildProvider)at System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders()at System.Web.Compilation.BuildProvidersCompiler.PerformBuild()at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile)at System.Web.Compilation.BuildManager.GetVirtualPathObjectFactory(VirtualPath virtualPath, HttpContext context, Boolean allowCrossApp, Boolean noAssert)at System.Web.Compilation.BuildManager.CreateInstanceFromVirtualPath(VirtualPath virtualPath, Type requiredBaseType, HttpContext context, Boolean allowCrossApp, Boolean noAssert)at System.Web.UI.PageHandlerFactory.GetHandlerHelper(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)at System.Web.UI.PageHandlerFactory.System.Web.IHttpHandlerFactory2.GetHandler(HttpContext context, String requestType, VirtualPath virtualPath, String physicalPath)at System.Web.HttpApplication.MapHttpHandler(HttpContext context, String requestType, VirtualPath path, String pathTranslated, Boolean useAppConfig)at System.Web.HttpApplication.MapHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)




After struggling for a while, i found that by doing 2 steps can solve this problem.




  1. Create a new Application Pool.

  2. Change the application pool for my application to the newly created pool.


Create new Application Pool in Internet Information Server 6 (Windows Server 2003)




  1. Open IIS 6


  2. Right click on Application Pools node from the tree view


  3. Select New -> Application Pool ... from the context menu


  4. Enter Application pool ID (myAppPool) and click OK.


  5. New Application Pool Created.



  6. Change the application pool for my application to the newly created pool.

  7. Open IIS
  8. From the explorer view, open the Web Sites folder.


  9. Point to the web application that want to change the Application Pool (mysite.com)


  10. Right click on mysite.com


  11. Select Properties


  12. A new Properties window pop up, Select "Home Directory" tab


  13. Change the Application Pool to "myAppPool" and click OK.


  14. Application Pool Changed


  15. Done.

    For Windows XP developer, when face this error, Kill aspnet_wp.exe process,

    go to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files and delete all the temporary files. Try to compile your project again.