Wednesday, December 31, 2008

How to enable Select, Delete, Update for ObjectDataSource without a SQL database support

http://vinull.com/Post/2007/04/16/aspnet-gridview-and-objectdatasource-wi.aspx

Default values for C# data types

bool: False
byte: 0
char:
decimal: 0
double: 0
float: 0
int: 0
long: 0
object:
short: 0
signed byte: 0
string: null
unsigned int: 0
unsigned long: 0
unsigned short: 0
int?: null

what is the order of the events handling in master page and content page?

If ContentPage derives from BasePage and uses a Master page. The following is the sequence in which events occur when a master page is merged with a content page:

BasePage.Ctor

Content page Ctor

Content page PreInit event.

Master page controls Init event.

Content controls Init event.

Master page Init event.

Content page Init event.

Content page Load event.

Master page Load event.

Master page controls Load event.

Content page controls Load event.

Content page PreRender event.

Master page PreRender event.

Master page controls PreRender event.

Content page controls PreRender event.

Master page controls Unload event.

Content page controls Unload event.

Master page Unload event.

Content page Unload event.


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

Tuesday, December 23, 2008

How to hide control using javascript?

The answer written in the first response is not actually 100% accurate.

We can hide/display the controls using

1) document.getElementById("").style.display="none"/document.getElementById("").style.display="inline"

or

2)
document.getElementById("").style.visibility="visible";/document.getElementById("").style.visibility="hidden";

The difference between the two is using the 1st option, we can hide the control and the space occupied by the controls also gets
removed, i.e if the controls has a certain height and is contained in a table row, the row gets collapsed and when displayed, the control will again take it's place.and the row will again retain its height by displaying the control in it.

On the other hand if we use 2nd option, the control will get hide
but the space occupied by the control will remain as it is and the row will not collapse, i.e the row will still be displayed
as blank containing the control in hidden mode.

From http://www.dotnetspider.com/resources/6563-How-hide-control-using-javascript.aspx

Sunday, December 14, 2008

Why I do not use the onunload for leaving page warning?

When onunload is fired, you cannot cancel the leaving to stay on the original page.

Why I do not use the popup dialog of onbeforeunload for leaving page warning?

Quote from http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx:

"
function closeIt()
{
return "Any string value here forces a dialog box to \
appear before closing the window.";
}
window.onbeforeunload=closeIt;

When a string is assigned to the returnValue property of window.event, a dialog box appears that gives users the option to stay on the current page and retain the string that was assigned to it. The default statement that appears in the dialog box, "Are you sure you want to navigate away from this page? ... Press OK to continue, or Cancel to stay on the current page.", cannot be removed or altered.
"

My experience is that the default string "Are you..." cannot be localized. This is the reason why I do not use in my portal.

Sunday, November 30, 2008

Javascript Events



http://www.w3schools.com/jsref/jsref_events.asp

Friday, November 21, 2008

How to set the signin page to use framed cobranding?

To implement framed cobranding for Windows Live ID sign-in pages, put a Cobranding_Flexible and a Cobranding_CSS element after the general cobranding properties within the Cobranding element.

Saturday, November 15, 2008

What is the difference between p tag, div tag, span tag?

A span element is in-line and usually used for a small chunk of in-line HTML.

A div or a P element is block-line (which is basically equivalent to having a line-break before and after it) and used to group larger chunks of code.

CSS tips

1. Once I wanted to make my side bar on z-index:1 and make it float to the right. Then I found it is impossible for the following reason. To make z-index work, I need position:absolute. Having position:absolute will disable floating. Eventually, I used z-index+position:absolute and some manually alignment to make this work.

Relationships between display, position, and float

Rule 1:
If 'display' has the value 'none', user agents must ignore 'position' and 'float'. In this case, the element generates no box.

Rule 2:
Otherwise, 'position' has the value 'absolute' or 'fixed', 'display' is set to 'block' and 'float' is set to 'none'. The position of the box will be determined by the 'top', 'right', 'bottom' and 'left' properties and the box's containing block.

Rule 3:
Otherwise, if 'float' has a value other than 'none', 'display' is set to 'block' and the box is floated.

Rule 4:
Otherwise, the remaining 'display' properties apply as specified.

http://dbaron.org/css/test/sec0907

Thursday, November 13, 2008

Why height=100% does not work?

body
{
}

#main /* the direct child div under body */
{
width:100%;
height:100%; /* this does not stretch the div to 100% */
background-color:Gray;
}

The reason is that without a parent defined height, the div{height:100%;} has nothing to factor 100% percent of, and will default to a value of div{height:auto;} - auto is an "as needed value" which is governed by the actual content, so that the div{height:100%} will a=only extend as far as the content demands.

So these change will make the height:100% work:
body
{
height:100px;
}

#main /* the direct child div under body */
{
width:100%;
height:100%; /* this does stretch the div to 100% (of body) */
background-color:Gray;
}

Wednesday, November 12, 2008

How to make the content in a DIV center aligned?

Use "margin-left:auto" and "margin-right:auto" for horizontal centering.

It is said online (in one of Jennifer Sullivan Cassidy's articles) that it is not recommended to use "text-align: center;" for horizontal centering for some reason.

vertical-align is for table only and vertical aligning a div is not a trivial thing.

Here is a good way to vertically align a div:
http://phrogz.net/CSS/vertical-align/index.html

What do the CSS position values mean?

static Default. An element with position: static always has the position the normal flow of the page gives it (a static element ignores any top, bottom, left, or right declarations)

relative An element with position: relative moves an element relative to its normal position, so "left:20" adds 20 pixels to the element's LEFT position

absolute An element with position: absolute is positioned at the specified coordinates relative to its containing block. The element's position is specified with the "left", "top", "right", and "bottom" properties

fixed An element with position: fixed is positioned at the specified coordinates relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties. The element remains at that position regardless of scrolling. Works in IE7 (strict mode)


http://www.w3schools.com/Css/pr_class_position.asp

What is the default height of a div if I do not specify?

The default is auto. The browser calculates the actual height.

If there is control in this div, then the height will be adjusted to fit this control in.

If there is no control in this div, then the height is a standard height which can fit a label in.

Monday, November 10, 2008

ASP.NET page life cycle diagram 2

emanish

ASP.NET page life cycle diagram






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

How to find out whether a NET dll is arch (32-bit or 64-bit) independent or not?

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin\CorFlags.exe

For example, AntiXssLibrary.dll does not have the “32-bit only” bit set. It should work fine in 64-bit.

[1] » corflags AntiXssLibrary.dll
CorFlags : 9
ILONLY : 1
32BIT : 0
Signed : 1

Saturday, November 8, 2008

Wednesday, October 29, 2008

What's the difference between refresh and postback?

1) typing in a url is like going to the page for the first time so its not a postback. If you browser has cached the page, you may actually go nowhere.

2) clicking on an asp:button fires a javascript that submits your form and is detected at the server as a postback for the page.

3) hitting a browser refresh (F5) takes whatever post data is currently in the buffer (from the last time the page form was submitted) and resubmits it. It does not submit current form values.

Item 3 is usually the most problematic to deal with.

If you refresh the page and it has never been posted back, then its like you are hitting it for the first time on each refresh.

If, however, the page had already been posted back, then hitting refresh repeats whatever event cause it to be previously posted back. This repeated event may not be an issue, but there are defineated times when it would be disastrous to repeat a postback event.

There are mechanisms around to detect when a page that has already been posted back is being refreshed.

refer: http://forums.asp.net/t/944619.aspx

Monday, October 27, 2008

What kinds of paging are there?

(1) user interface paging
* It is easier to use,
* Lower performance because all data actually are loaded in the memory of the portal server.
* Support data source like Collection, DataSet, DataTable, DataView. Does not support DataReader. In my portal, the portal calls the web service to create a DataTable, which then is used to render a GridView. So this is a user interface paging. However, the web method can return only one page so as to simulate the paging behavior.

(2) data source paging
* Enable you to write custom logic to retrieve pages of database records.
* Can perform paging for store proc, Linq or a SQL query

Sunday, October 26, 2008

Should ViewState be on or off when displaying a large number of records?

ViewState should be turned off. This way not all data will be transferred via the wire.

Disabling ViewState does not prevent GridView from editting/deleting records, sorting, paging.

How to page in GridView without loading all data into memory?

Use objectDataSource

what is the difference between GridView, DataList, ListView, Repeater, ListControl, DetailsView, FormView?

GridView:
(1)Can select one row to do something.
(3)update, delete records in database, but not insert
(4)Sort, paging
(5)Concurrency handling
(6)Display empty data
(7)Formatting (e.g. alternative row style)
(8)Customize field (e.g. use TemplateField to edit record)
(9)Extend (e.g. create LongTextField for GridView)

ListView:
(1) template driven
(2) can add data to database
(3) can edit, page through, sort database data
(4) ListView is the only control implementing IPageableItemContainer interface, so it is the only one which can use DataPager control.

ListView is the most flexible List control in all. I can safely use ListView in place of GridView.

Repeater:
(1) display database records. It cannot edit/insert records
(2) entirely template driven

DataList:
(1) display database records(can edit?)
(2) entirely template driven
DataList is very similar to Repeater except that DataList's default behavior is rending the content using a table. However, you can override the default behavior.

DetailsView:
(1) Display/edit/delete/Insert records in database
(2) Render a table for a single record. always render each field in a seperate table row.

FormView:
Exactly like DetailsView except that FormView is entirely template driven.

ListControl:
there are RadioButtonList, DropDownList, CheckBoxList, BulletedList, ListBox.

Refer: <>

Friday, October 24, 2008

The type System.Collections.Hashtable is not supported because it implements IDictionary..

My portal cannot consume a WCF web method which has HashTable as the input parameter.

The exception I got is:

exception: System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]: The type System.Collections.Hashtable is not supported because it implements IDictionary..

What made me desperate is that I changed the parameter from HashTable to ArrayList and even object[]. But I still got the same error when calling this web method.

...Eventually, I found at the end of this web method, there is "typeof(HashTable)". That means HashTable cannot be a parameter or exist anywhere in the web method!

The service cannot be activated due to an exception during compilation

The service 'myservice.svc' cannot be activated due to an exception during compilation. The exception message is: The HttpGetEnabled property of ServiceMetadataBehavior is set to true and the HttpGetUrl property is a relative address, but there is no http base address. Either supply an http base address or set HttpGetUrl to an absolute address..

The story is:
My portal cannot consume the web service, then I saw this event log in window log.

I want to check whether the WS deployment is good, so I changed HttpGetEnabled from false to true so that I can see the metadata in IE.

But setting HttpGetEnabled=true also need set HttpGetUrl as an absolute address. To avoid this, I changed the HttpGetEnabled back to false and then this error is gone.

Thursday, October 16, 2008

Could not establish secure channel for SSL/TLS with authority

My portal throws this exception when making a web method call to the web service.

Check list:

1. On server and client side, the server certs and their intermediate and root certs do not expire.

2. On server and client side, the server certs have right permission setting (e.g. giving permission to Network Service).

3. On the client side, the client cert used by WCF web method call and its intermediate and root certs do not expire. This is required because the server IIS SSL setting can be "requiring client cert".

4. On the client side, the client cert used by WCF web method call has right permission setting (e.g. giving permission to Network Service). This is required because the server IIS SSL setting can be "requiring client cert".

5. On server and client side, check the server certs are used by IIS.

6. Another experience: I found when an authenticated page expired, the WLID sign in page shows the sign in dialog in the left.htm frame. I figured out it is because the SSL cert is wrong (not for my portal's url). Then I made the IIS SSL cert to the one using the right portal url. After I changed the SSL cert for the machine where both the portal and the web service are deployed, I verified all above 5 points successfully but still got the error as the subject. Finally, I found the portal's web.config should change the WCF endpoint address from https:\\mymachinename\endpoint.svc to https:\\theportalurl.com\endpoint.svc.

7. Another experience: when my portal and the web service is deployed to 1box using installserver.bat, IIS uses SSL cert myserver.mydomain.com. Usually I use URL https://myportal-int.com and SSL cert myportal-int.com for my portal when it is deployed seperately. I always thought that to establish SSL channel between portal and WS, both side need to have the URL match the SSL cert. However, this is wrong! To establish SSL channel, only server side (WS side)'s SSL cert is verified.
My collegue help me address the issue eventually.
First, he pointed out that client side (portal side) does not need have a SSL cert which matches the portal URL. So I can get out of the trap of trying to make cert and URL match on both server side and client side.
Second, by the exception message: "The remote certificate is invalid according to the validation procedure.", he asked me to try to access web service using IE to see if there is any SSL warning. Under his expectation, IE showed SSL warning when I access the endpoint address.
Third, he logged in my machine and clicked the certificate error icon besides the IE url column. He viewed the https cert by clicking the "View certificate". He found the cert name is something like authmod, which is another site on the 1box. By this clue, he found site authmod also uses port 443 which is used by my portal site. After he removed https binding of authmod site, my portal start working.
I learned a lot from this lesson.

Wednesday, October 15, 2008

How to restore the machine after I ruined an 1box so that a new 1box can be installed on this machine?

I installed an 1box. I copied and deleted some files/folders to try something out. Then I used the uninstall script to uninstall the 1box. When I ran the install script to reinstall the 1box, I found a database cannot be installed. How can I restore my machine so that I can install a new 1box correctly?

I got a solution for this case. When I ran "msiexec /x mydb.msi" to uninstalled this db component, I got error. Then I copied mydb.mdf and mydb.ldf from another machine over and installed this db manually. After this, "msiexec /x mydb.msi" works correctly. After uninstalling mydb, I copied the commandline from the 1box installation script and ran it in a command window. Then this db is installed correctly by this commandline. The commandline for installing coredb is:
"start /wait msiexec /i MyDB.msi SEV_COREDB_NAME=MyDB /l*v installMyDB.log"

Sunday, October 12, 2008

Why RadioButton OnCheckedChanged is not fired?

I added two radio buttons with the corresponding OnCheckedChanged event handlers to my portal. However, when I switched the radio buttons, OnCheckedChanged event was not fired and the event handlers were not called.

The reason is that these event handlers need a postback to be triggered. After I added AutoPostBack="true", it worked.

Why Response.Redirect does not work in Global.asax.cs:Application_Error()?

My portal uses Application_Error() to redirect to my ErrorPage.aspx. But Response.Redirect() does not work. I debugged to know that this statement was executed but redirect did not happen.

Then I created a sample website to find out that Server.ClearError() is critical. Without this statement, Response.Redirect does nothing. On the other hand, customError section is totally irrelevant.

What is the difference between Response.Redirect and Server.Transfer?

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

You can have Response.Redirect("http://www.google.com") but you cannot have Server.Transfer("http://www.google.com");

http://r4r.co.in/ASP.net/index.shtml

Wednesday, October 8, 2008

[ConfigurationErrorsException]: '.', hexadecimal value 0x00, is an invalid character. Line 2, position 1.

I got this error after I used powershell script to change debug="false" to debug="true" for all web.config.

I found nothing wrong by comparing the deployed web.config and the web.config in the source tree.

It turned out an encoding issue after I re-saved the web.config using UTF-8 in notepad.

I modified the string replacing script to control the encoding.

$pattern ='debug="false"'
$replacement ='debug="true"'
$encode="default" # can be utf8 unicode default (it is actually ANSI)
$targetFile="web.config"

foreach ($file in (gci . -name $targetFile -rec)) {

if($file -match "PortalUI")
{
continue;
}
write-host process $file ...
write-host resave file using $encode
$text = get-content $file
$text | out-file $file -encoding $encode

$text = get-content $file

if ($text -match $pattern) {
write-host modifying $file
$text -replace $pattern, $replacement | out-file $file -encoding $encode
}
}

How to debug into web service?

Sometime, I need to debug into web service from my portal. It is easy to get an error dialog telling something like "cannot automatically debug into server" when you step in the web method. After I make 100% sure that the pdbs are absolutely in sync with the dlls, I did two things to make it work:

(1) enable debug in all web.config files.
(2) specifiy the symbols path in the project options.

Another time, when I debug from my portal to web service A and to web service B, service B prompt the same error dialog. I thought it is unsync PDB problem again. But after checking the event log, I found the cert expired for service B. After renewing the cert, I can debug into B.

How to replace strings in multiple files using powershell?

I want to replace string debug="false" with debug="true" for all web.config files in the deployment dir. Here is how to do it:

$pattern ='debug="false"'
$replacement ='debug="true"'
foreach ($file in (gci . -name "web.config" -rec)) {
$text = get-content $file
if ($text -match $pattern) {
$text -replace $pattern, $replacement > $file
}}

http://www.eggheadcafe.com/software/aspnet/29585604/findreplace.aspx

Thursday, October 2, 2008

How to do buddy build using a batch file?

This is my ApplyDPK.cmd:

echo sd revert ...
call sd revert ...

echo delete .\portals\
call rd /s/q .\portals

echo sd sync -f ...
call sd sync -f ...

echo sdp apply %1 -a
call sdp apply %1 -a

echo delete ..\target\debug\i386
call rd /s/q ..\target\debug\i386

echo pushd portals\source
call pushd portals\source

echo build -cZP
call build -cZP

I can quickly do buddy build by running "ApplyDPK 519".

SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.

My portal tries to write an event log but got the error as the subject.

Reason: to enable event log for my portal, I need to register source in the regedit.
For example, to create a source for partner portal on Vista, import the reg file containing below content:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application\PartnerPortal]
"EventMessageFile"="C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll"

Wednesday, October 1, 2008

Why does the javascript registered by Page.ClientScript.RegisterStartupScript not execute?

On my portal, the javascript registered via Page.ClientScript.RegisterStartupScript does not execute, which I used [script]alert("something")[/script] to confirm.

Since I created my portal web app in VS2008 with AJAX enabled, I thought there is some incompatibility between Page.ClientScript.RegisterStartupScript and AJAX. After searching online, I found a lot of posts about how to use ScriptManager.RegisterStartupScript to replace Page.ClientScript.RegisterStartupScript to make the registered javascript run. But this solution did not resolve my problem - the javascript still did not work.

Then I found below code snippet which I think I can use to test whether my page is using AsyncPostBack or syncPostBack.

if (ScriptManager.GetCurrent(base.Page).IsInAsyncPostBack)
ScriptManager.RegisterStartupScript(this, this.GetType(), “Rating_Script_” + this.ClientID.ToString() , script.ToString(), false);
else
this.Page.ClientScript.RegisterStartupScript(this.GetType(), this.ClientID, script.ToString());

To my surprise, running this code snippet shows my page is using sync post back. So I suspect that my problem may have nothing to do with AJAX.

By looking the code, I found so called "AJAX enabled" web app actually just put [asp:ScriptManager ID="ScriptManager1" runat="server" /] in the master page and that's it. It does not mean you have used any AJAX functionality yet. So my pages are actually just "AJAX enabled" but having no any AJAX functionality (e.g. UpdatePanel).

I stepped back and thought the problem without AJAX. Eventually, I found the problem is with the javascript itself. After I corrected the javascript, the javascript began to execute.

Before correcting:
[javascript]function master_startup() {alert("something")}[/javascript]

After correcting:
[javascript]alert("something")[/javascript]

Tuesday, September 30, 2008

How to quickly get thumbprint of a cert without removing space?

In powershell, you can get the thumbprints of certs with this command:

Get-ChildItem -path cert:\localmachine\my

localmachine can be currentuser.
This command also list the subject clearly so that you can use winhttpcertcfg.exe easily.


To see the detail of a cert, use this command:

Get-ChildItem -path cert:\currentuser\my\EEBAC2D21C1E5B2E22070CC9547CB806EE98B9A8 | format-list -property *

How to debug cert related error?

* After change server cert, make sure it is used in https setting in IIS.

* Check cert permission using winhttpcertcfg.exe or UI in mmc. For example, my portal's app pool uses Network Service account. To setup SSL channel with the web service server, I need to give "Network Service" account permission to both the server authentication cert and the client authentication cert on the portal server. It is easy for me to forget granting permission after updating a cert.

* Carefully check whether all certs on the chain exist. Note: I came across the situation where the cert status shows normal but actually one middle cert does not exist. Furthermore, I got server authentication cert and client auth cert from the same site so they have the same chain. When one middle cert does not exist, the server auth cert works fine but the client auth cert does not. So anything can happen.

* Whether the correct thumbprint is used in WCF's web.config.

* If any built-in accounts (e.g. networkservice, localsystem) are used, make sure the required cert is installed in LocalMachine and the web.config is searching cert in LocalMachine.

How to configure certs for my portal which uses WCF services?

The portal server need:

1. client authentication cert: needed for the portal to resolve the web reference of WCF service, to send request to the web service server, to setup SSL channel.

2. server authentication cert: needed for the portal to setup SSL channel (encryption) with the web service server.

Note, server authentication cert is not used for client authentication. In other words, in the web service's web.config, section should use portal server's client authentication cert. In the portal's web.config, section should also use portal server's client authentication cert.

Note: both client auth cert and server auth cert are required for SSL channel setup.

How to disable SSL so that I can use svcutil to generate proxy for a WCF service?

Two steps:
1. Disable SSL for this web service in IIS.
2. Set clientCredentialType="None" in web.config.

Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation 'LocalMachine', FindType 'FindBySubjectName'

I tried to hook up my portal with a WCF service but got error: Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation CurrentUser, FindType 'FindBySubjectName', FindValue.

The app pool of this portal uses NetworkService account. The cert is there in CurrentUser store. Why portal server cannot find this cert?

It is because NetworkService will not search cert in CurrentUser store. Current User is only my logon account. Since the portal can run without a user logon or with multple users logon, NetworkService may not know which "CurrentUser" account to search the cert.

Two solutions:

(1) Use a cert in LocalMachine then NetworkService is able to find it.

(2) Using my own logon account instead of the built-in accounts for the app pool also resolved the problem.

Possible solution:
You may use NetworkService account but create a CurrentUser cert store for NetworkService. To do this, in MMC, create a cert store for WWW service. Then NetworkService may consider this store as its "CurrentUser" store and seach certs in it. I have not tried this.

On 2/26/2009, I encountered the same issue. I did not find anything wrong by doing all verification. The cert is not expired, the permission is correct, cert chain is normal, etc. Finally, I had to delete and reinstall the cert. Then it worked. This means the cert store can cheat somehow.

How to check the permission of a certificate?

When I hook up my portal with the WCF service, I got "Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation 'CurrentUser', FindType 'FindByThumbprint', FindValue 'b55d97f9f04d6115d138416b65f9b4100884339f'. "

I suspect maybe I have not grant the permission of the client certificate to the right account(s).

To check which accounts have been granted access to a cert, use:
winhttpcertcfg.exe -l -c Current_User\my -s "Issued to"

I used below command to grant permission to iis related accounts, use:
winhttpcertcfg.exe -g -c Current_User\my -s "Issued to" -a "ASPNET"
winhttpcertcfg.exe -g -c Current_User\my -s "Issued to" -a "IIS_WPG"

A lesson is "Issued to" (which is subject actually) will find the first cert matching(or including) the searching keyword. If you have two certs sharing the same "Issued to", then you have no way to use winhttpcertcfg to check the permission of the second cert.
So remember when you apply cert, pay attention to giving a good subject.

Granting these permissions did not resolve the issue described at the beginning of this article. I need to investigate further.

Monday, September 29, 2008

Why context.User.Identity.Name is null or empty?

Problem:
I set my portal to use window auth but context.User.Identity.Name is always null or empty. I checked the iis log and found my alias has been corrected used.

Solution: add below section resolved the problem.


Saturday, September 27, 2008

How to use DataTable and DataView

DataView cannot exist without a DataTable (or a Linq query).

Here is how to create a DataTable programmatically:
1. Define table schema by adding columns;

2. Adding row. To add rows to a DataTable, you must first use the NewRow method to return a new DataRow object. The NewRow method returns a row with the schema of the DataTable

Why I got NullReferenceException when using DataView.AddNew()?

Code:
DataView dv = new DataView();
DataRowView drv = dv.AddNew(); // throw NullReferenceException

Reason:
If you create a DataView using the constructor that does not take any arguments, you will not be able to use the DataView until you have set the Table property.
http://msdn.microsoft.com/en-us/library/hy5b8exc(VS.71).aspx

Friday, September 26, 2008

What is the difference between RegisterClientScriptBlock and RegisterStartupScript?

The RegisterClientScriptBlock method inserts the client-side script immediately below the opening tag of the Page object’s [form runat=”server”] element. The code cannot access any of the form’s elements because, at that time, the elements haven’t been instantiated yet. This explains why hdnView variable had a null value in my case. The RegisterStartupScript method inserts the specified client-side script just before the closing tag of the Page object’s [form runat=”server”] element. The code can access any of the form’s elements because, at that time, the elements have been instantiated. The choice of which method to use really depends on the “order” in which you want your script to be run by the browser when rendering the page.

(http://treasure4developer.wordpress.com/2008/02/05/difference-between-registerclientscriptblock-and-registerstartupscript/)

RegisterClientScriptBlock is meant for functions that should
be "available" to the page. For this they are rendered at the start
of the HTML file.

RegisterStartupScript is meant for commands that should execute on
page load (at the client), so tha page needs to be available for the
script. This script is rendered at the end of the HTML file.

(http://bytes.com/forum/thread278475.html)

What is the order of content page_load and master page_load?

This is the sequence of events that get fired when a content page is
merged with a master:

Master page controls Init event
Content controls Init event

Master page Init event
Content page Init event

Content page Load event
Master page Load event

Content page PreRender event
Master page PreRender event

Master page controls PreRender event
Content controls PreRender event


From http://www.velocityreviews.com/forums/t123348-master-pages-pageload-is-backwards.html

Thursday, September 25, 2008

Why my controls are displayed but disabled?

This took me a lot of time to figure out and is a big lesson for me.

The reason is I set z-index=-1 for the div containing these controls.

I think any layer with z-index<0 is not editable.

Setting z-index=0 or removing z-index setting (0 by default) resolved the issue.

Wednesday, September 24, 2008

How to copy all files and sub-folders from one folder to another?

xcopy /E/I/V bin\_PublishedWebsites\PartnerPortal %sitedir%

How to delete all files and sub-folders in a folder?

rd /s/q c:\temp

What is the reason of certificate error on IE address bar?



Reason: there is problem with server cert.

For example, if server SSL cert is applied for mymachine.mydomain.com and you try to access the site using http://mymachine/myservice.svc, then the cert "issued to" does not match the host name. In this case, using http://mymachine.mydomain.com/myservice.svc will resolve the cert issue.

Another possiblity is that the root of the server cert is not installed in the client machine. Check your root and intermediate stores to see whether you need to install them.

Where are bcz defined in CoreXT?

C:\enlistments\maa2\tools\build\aliases\aliases.pub

This file also defines below variables:

.. cd .. && cd $*
... cd ..\.. && cd $*
.... cd ..\..\.. && cd $*

This file defines team-wide aliases.

developer\build\aliases.pub defines personal aliases.

IIS KBs

IIS KBs - October 2007 (More IIS 7 Status Code)
942067 Error message when you try to run a Web application that is hosted on a server that is running IIS 7.0: "HTTP Error 403.7 - Forbidden"
942057 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 502.2 – Bad Gateway"
942032 Error message when users visit a Web site that is hosted on a server that is running Internet Information Services 7.0: "HTTP Error 404.3 - Not Found"
942036 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 403.2 - Forbidden"
942053 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 404.5 – URL Sequence Denied"
942065 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 403.1 - Forbidden"
942061 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 403.16 - Forbidden"
942077 Error message when you visit a Web site that is hosted on a server that is running Internet Information Services 7.0: "HTTP Error 404.10 - REQUEST_HEADER_TOO_LONG"
942076 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 404.11 – URL_DOUBLE_ESCAPED"
942038 Error message when you try to visit a Web page that is hosted on Internet Information Services 7.0: "HTTP Error 403.17 (Forbidden) - The client certificate has expired"
942040 Error message when you try to visit a Web page that is hosted on IIS 7.0: "HTTP Error 404.2 – Not Found"
942050 Error message when you visit a Web site that is hosted on a server that is running Internet Information Services 7.0: "HTTP Error 406 - Not Acceptable"
942055 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 500.19 – Internal Server Error"
942059 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 502.1 – Bad Gateway"
942063 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 403.13 - Forbidden"
942074 Error message when you visit a Web site that is hosted on a server that is running Internet Information Services 7.0: "HTTP Error 404.13 - CONTENT_LENGTH_TOO_LARGE"
942079 Error message when you visit a Web site that is hosted on IIS 7.0: "HTTP Error 401.4 – Authorization failed by filter"
942078 Error message when you visit a Web site that is hosted on a computer that is running IIS 7.0: "HTTP Error 401.5 – Authorization failed by ISAPI/CGI application"
942051 Error message when a user visits a Web site that is hosted on a server that is running Internet Information Services 7.0: "HTTP Error 405.0 - Method not allowed"
942071 Error message when you visit a Web site that is hosted on a server that is running IIS 7.0: "HTTP Error 404.15 – Not Found"
942034 You are not prompted to select a client certificate from the local certificate store in IIS 7.0
943240 FIX: Error message when IIS 6.0 receives the entity body for an HTTP POST request while an application pool is recycled: "The underlying connection was closed"

From http://msmvps.com/blogs/bernard/archive/2007/11/14/iis-kbs-october-2007-more-iis-7-status-code.aspx

NotSupportedException: The SSL settings for the service 'None' does not match those of the IIS 'Ssl, SslNegotiateCert, SslRequireCert, Ssl128'.

Problem:
I deployed a WCF service in IIS7. This WCF requires client cert. When I browsed the SVC using IE, I got error page: NotSupportedException: The SSL settings for the service 'None' does not match those of the IIS 'Ssl, SslNegotiateCert, SslRequireCert, Ssl128'.

Reason:
I should select "Require client certificate" in IIS7 to match the WCF configuration. Ignore or accept client certificate does not work.

WCF service on IIS7, Window 2k8 server: HTTP Error 404.3 - Not Found

How to debug:
1. see the error messages: "It is possible that a handler mapping is missing", "The feature you are trying to use may not be installed".

2. check handler mappings in IIS7 to see whether there is svc type. I did not find svc.

3. start optionalfeatures.exe to see whether WCF activation is enabled or not.


4. enabled WCF activation, then you can see svc appears in handler mappings.

5. 404.3 error goes away.

Monday, September 22, 2008

Friday, September 19, 2008

What does ".Buttons a.Enabled" in CSS mean?

.Buttons a.Enabled
{
background-image: url("./images/NavigationButtonEnabled.png");
}







Explain: LinkButton will be parsed as a link. So ".Button a.Enabled" means any descendant LinkButton (in this example) having Enabled attribute under the div whose class is Buttons.

System.Resources.MissingManifestResourceException was unhandled by user code

Problem:
My localization of a web app throws exception:"Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "MyResource.resources" was correctly embedded or linked into assembly "WebApplication1" at compile time, or that all the satellite assemblies required are loadable and fully signed.".

Solution:
You cannot use VS 2005 way in VS2008.

In VS2005, you can use:
Assembly asm = Assembly.Load(assemblyName);
ResourceManager rm = new ResourceManager(baseName, asm);

In VS2008, you have to include the web application name in basename:
ResourceManager rm = new ResourceManager(".", Assembly.GetExecutingAssembly(), null);

Furthermore, I found I cannot put the resource files in App_GlobalResources directory. It may be possible but it is not straightforward at least. I have to create a new resource file under the project root directory.

Wednesday, September 17, 2008

How to open a link in a new window when clicking a button by using javascript?

OnClientClick="Javascript:window.open('Privacy.aspx','mywindow', 'width=500,height=600');return false;"

CS0433: The type 'CLASS' exists in both 'dll1 and 'dll2'

Problem:
I used VS2008 to create a web app and deployed it to windows server 2k8.
For WLID, I copied the expirecookie.aspx from the sample to my wlid directory.
Note: this expirecookie.aspx does not have code behind file. Instead, it has inline script.
Then when I tried to access https://mysite.com/mysite/wlid/expirecookie.aspx, it throws the error message as the subject.

Reason:
Either net3.5 or the project created in VS2008 does not support the aspx file having inline script. After I added a new aspx having a code behind file in VS2008, the error went away.

Tuesday, September 16, 2008

How to check how much battery left in a laptop?

Use windows mobility center.
Shortcut: windows+x

How to get more diagnostic info when building project using corext+msbuild?

set msbuild_verbosity=diag

msbuild_verbosity modes: QUIET, MINIMAL, NORMAL, DETAILED, DIAGNOSTIC. Default=NORMAL

Saturday, September 13, 2008

Why I cannot sign out WLID on Vista, IIS7?

Reason: the expirecookies.aspx is not created for signout.

You should be able to browse https://mysite.com/wlid/expirecookies.aspx to verify whether this page is ready or not.

This problem has nothing to do with OS although it is known that RPS has been fully tested on win server 2k3 and win server 2k8.

Friday, September 12, 2008

How to cobrand WLID sign in page?

Assume using RPS6.0 http module, there is the steps.

Steps:
1. Add string IDs in Login UI section in MSM;
2. Add localized strings for each ID and each locale in Localization section in MSM;
3. Set propbag to load these cobranding strings:

LiveIdentity LiveID = HttpContext.Current.User.Identity as LiveIdentity;
Microsoft.Passport.RPS.RPSPropBag authPropBag = LiveID.CreateNewRPSPropBag();
authPropBag["WLContext"] = "mytitle$mysubtitle$myimage$myupselltext1$myupselltext2$myupselllearnmorelink";
WLIDSignInOutLiteral.Text = LiveID.GetTextTag("mysite", "nexus.passport-int.com/public/partner/rpsnetwork4.xml", authPropBag);

How to make return url effect when using RPS 6.0 httpmodule

Problem:
Environment: IIS7, vista, RPS 6.0.5135.0

Repro:
1) Install rps;
2) Configure RPS http module according to RPS beta doc;
3) Register my site in MSM, providing return url as “….\landing.aspx”;
4) Configure rpsserver.xml, specifying the same return url in the site node;
5) Open ie and go to the un-authed page default.aspx;
6) Click sign in button;
7) On the signin page, you can see the return url embedded in the request url is “…\default.aspx” instead of “landing.aspx”.
8) After signin, it directs to default.aspx instead of landing.aspx.

I also tried this:
1) Open IE and go to landing.aspx;
2) Click sign in button;
3) On the signin page, you can see the return url embedded in the request url is “…\landing.aspx”;
4) After sign in, it directs to landing.aspx.

According to above repro, it sounds like WLID always use the incoming url to construct the return url and ignore any configured return url in my case.

I have downloaded the site xml and verified that the return url is landing.aspx.

How can I make the return url effect?


Solution:
Use PropBag when setting WLIDSignInOutLiteral.Text. The PropBag will load the configuration of this site node in rpsserver.xml. So if you set return url correctly in rpsserver.xml for this site, then it takes effect.

Microsoft.Passport.RPS.RPSPropBag authPropBag = LiveID.CreateNewRPSPropBag();
WLIDSignInOutLiteral.Text = LiveID.GetTextTag("Sitename", "nexus.passport-int.com/public/partner/rpsnetwork4.xml", authPropBag);

Thursday, September 11, 2008

Why windows live signup does not work on my site?

Problem:
I used windows live signup by:
(1)check "Windows live enabled" checkbox in MSM (this makes sign in page use Windows live theme);
(2)fill up the "Windows Live upsell URL" textbox using "https://signup.live.com/signup.aspx" (this makes signup page use Windows live theme).

However, when I click signup button on the signin page, I got error image:


Note: my return url is not in live.com domain.

Answer:
This is an answer got from an expert.

The return URL can only be to a URL with the following domains.

PROD
live.com,microsoft.com,msn.com,live.jp,windowslive.jp,msn.co.jp

INT
live-int.com,microsoft-int.com,msn-int.com,live-int.jp,windowslive-int.jp,msn-int.co.jp,live.com,microsoft.com,msn.com,live.jp,windowslive.jp,msn.co.jp

You realize that the signup page you are using is designed for Windows Live and not partners outside of Windows Live such as MSDN and Microsoft.com.

However, we heard from other experts that windows live signup can be used by sites outside of live.com. So I still need to follow up.

What do the parameters mean in WLID url?

ru - return url

regru - return url after WLID registration. If there is no regru, then ru is used after registration.

wreply - the url overriding the default return url

wa - ?

wasignin=1.0 This parameter triggers RPS to look for RPS Compact ticket and process it if one is present

What is the shortcut of turning on/off features on Vista?

optionalfeatures.exe

Wednesday, September 10, 2008

Why window authentication does not prompt credential dialog

Problem:I created a website (which has only a default.htm for testing purpose) and enabled window authentication by doing:
(1) Enable window authentication in IIS;
(2) Disable anonymous access in IIS;
However, there is no credential dialog popping up when I visit default.htm.

Solution: here is how to debug.
Windows Integrated Authentication will be silently submitted by Internet Explorer if the web server challenges the user.

Looking at your web logs (C:\inetpub\logs\LogFiles\W3SVC1) for the website, you should see one or two 401s before a 200 response containing the username - this means it is working.

If you do not, and only ever see blank-username 200s, authentication isn't configured correctly yet.

If you desire a prompt, disable IE's Automatic Logon settings in Internet Options -> Security tab -> Custom level.

WLID sign up button does not work in WLID sign in page

Problem:
I registered my site in http://msm.live.com. In the WLID sign in page, the sign in button works fine but sign up button directs to a page containing the error message.



Solution:

In msm.live.com, edit the upsell textbox with https://signup.live-int.com/signup.aspx

How to tackle the issue that using hosts prohibits accessing internet?

Problem: if I disable "automatically detect proxy" in IE for enabling hosts, the internet access is disabled. How to enable both at the same time?

Solution: install ISA firewall client.

Tuesday, September 9, 2008

What is the location of AppCmd.exe?

%systemroot%\system32\inetsrv\

Explain the certificate formats

Personal Information Exchange (PKCS #12)

The Personal Information Exchange format (PFX, also called PKCS #12) enables the transfer of certificates and their corresponding private keys from one computer to another or from a computer to removable media.

Because exporting a private key might expose it to unintended parties, the PKCS #12 format is the only format supported in this version of Windows for exporting a certificate and its associated private key.


Cryptographic Message Syntax Standard (PKCS #7)
The PKCS #7 format enables the transfer of a certificate and all the certificates in its certification path from one computer to another, or from a computer to removable media


DER Encoded Binary X.509

DER (Distinguished Encoding Rules) for ASN.1, as defined in ITU-T Recommendation X.509, might be used by certification authorities that are not on computers running Windows Server 2003, so it is supported for interoperability. DER certificate files use the .cer extension.


Base64 Encoded X.509

This is an encoding method developed for use with Secure/Multipurpose Internet Mail Extensions (S/MIME), which is a popular, standard method for transferring binary attachments over the Internet.

Because all MIME-compliant clients can decode Base64 files, this format might be used by certification authorities that are not on computers running Windows Server 2003, so it is supported for interoperability. Base64 certificate files use the .cer extension.


IIS7 document

what are the differences between CEK cert and SSL cert?

(1) CEK (cookie encryption key) cert can be obtained from local hosted Microsoft certificate services included in windows server 2k3, or micorosoft internal cert application sites.

SSL cert must be obtained from a public certificate authority, such as Verisign.

(2) CEK cert name does not need to match the site while SSL cert must match.

Monday, September 8, 2008

How to load a txt file using notepad in powershell scripts?

function hosts
{
[System.Diagnostics.Process]::Start('notepad.exe', 'C:\Windows\System32\drivers\etc\hosts');
}

no alias needed.

Sunday, September 7, 2008

How to edit the profile for powershell?

1. create a new profile:
new-item -type file force $profile

2. edit it
notepad $profile