Javascript: How to cancel leaving page without saving

Preparing the javascript:
string jscript = "var needToSave= false;" +
"window.onbeforeunload = confirmExit;" +
"function confirmExit(){" +
"if (needToSave){" +
"return 'Are you sure you want to leave the page without saving?';" +
"}" +
"}";

Registering the script - safe for ajax:

ScriptManager smgr = ScriptManager.GetCurrent(Page);
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "", false);

On every field that changes the data and requires saving put:
control.Attributes.Add("onkeydown","javascript: needToSave=true;")

on the button that make save postback add:
control.Attributes.Add("onclick","javascript: needToSave=false;")

Page Cannot Be Found Issue on IIS 6 on Windows 2003

Also:
HTTP 404 - File not found

First of all be sure that the default document list contains the page you are requesting (IIS -> Server Node -> Site node -> right mose click -> Properties -> Documents
Also set the necessary permission to the web folder (NETWORK SERVICE must have read/write rights)
Check if the asp.net status is allowed (IIS -> Server Node -> Web Service Extensions -> Asp.net must be allowed). This can be done during the installation of IIS.

ASP.NET Export content to Excel files.

The most common problem during exporting page content to an excel file is the following exception: RegisterForEventValidation can only be called during Render();
The only thing you need to do is to set enableEventValidation ="false" in web.config (affects all your pages) or in the head page line.

If you want to render a control into an excel file (using HTML representation) the VerifyRenderingInServerForm() method must be overridden.

public override void VerifyRenderingInServerForm(Control control){}

This confirms that an HtmlForm control is already rendered.

... and the example - rendering existing gridview control into a xls file:
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=file.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter(); ;
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
htmlWrite.Write("text text");
htmlWrite.WriteBreak();
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

How to recover Mozilla Firefox Bookmarks

Very strange problem. Sometimes firefox' bookmarks dissapear. May be this is connected with NTFS problems (sometimes solved by chkdsk c: /f). But the best way to recover the bookmarks is to get them again from the last firefox archive. They are in

C:\Documents and Settings\[username]\Application Data\Mozilla\Firefox\Profiles\pypbblhs.default\bookmarkbackups

and the last archive must be ranamed and put into

C:\Documents and Settings\[username]\Application Data\Mozilla\Firefox\Profiles\pypbblhs.default

This solved my problem :)

Problems with using SQL Server instance by Windows remote desktop

'Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.'

This problem occurs when the user uses remote desktop and logs into the system for the first time. If the user logs in at first locally and then uses remote desktop the problem doesn't occur.

Microsoft describe the problem in the article
http://support.microsoft.com/?id=896613
It is enough to request them to send you a link for the fix (windows update) and wait a few hours. The fix cannot be downloaded directly because of need of additional testing. But it works fine for me.

A tip for avoiding null values in aggregate functions in sql

Sometimes the aggreagete functions in SQL returns null value - when the data doesn't meet selection criteria defined in the query.
We can return 0 instead NULL with (ISNULL (column, 0)).

For example:
SELECT
(ISNULL (SUM (salary), 0)) As Total
FROM Salaries
WHERE
UserId=@UserId

Using such statement avoids checking for null values in the code.

How to hibernate Windows.

What is Hibernate? This is a process of copying all RAM content to the hard disk and possibility to continue your work from the last state after shutting down the system.
The required things are:
1. Your motherboard must support this Function
2. Hard disk space at least your RAM size.
3. Enabled Hibernation in Windows
(Display Properties -> Screen Saver -> Monitor Power -> Hibernate -> Enable Hibernation check box)

Button "Hibernation" is shown after clicking Shut Down. If you dont have this button, you can show it by pointing "Stand By" button on the shutdown dialog box and hold Shift button. :-) I dont know why? It seems the newer versions of XP doesn't show Hibernate button.

ASP.NET How to access the EmptyDataTemplate controls from OnRowCommand in GridView

The way of getting access to the controls in EmptyDataTemplate is similar to the way of accessing controls in the same data row in the gridview.

For example - inserting value in the empty gridview:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Insert") {
TextBox txt =
(((Control)e.CommandSource).NamingContainer).FindControl("txtTest") as TextBox;

//do insert action
}
}
Another way to do this is by getting EmptyDataTemplate table and its controls:
if (e.CommandName == "Insert")
{
Table table = (Table)GridView1.Controls[0];
TextBox txtTest= (TextBox)table.Rows[0].FindControl("txtTest");

//do insert actions
}

ASP.NET How to set and get key values for every gridrow in a gridview.

Setting primary key values during data binding:

gvUsersInRoles.DataSource=taUsersInRoles.GetData();
gvUsersInRoles.DataKeyNames = new string[] { "UserId", "RoleId" };
gvUsersInRoles.DataBind();
This example uses composite primary key for showing more complicated usage.

Getting primary key values during performing row command (command, insert, delete, update):

Guid uid = new Guid(gvUsersInRoles.DataKeys[e.RowIndex]["UserId"].ToString());
int pid = int.Parse(gvUsersInRoles.DataKeys[e.RowIndex]["RoleId"].ToString());

Getting the the newly created primary key after sql insert operation

INSERT INTO Table(COL1) VALUES('213')

SELECT @@IDENTITY

or

Return SCOPE_IDENTITY()

or

Return IDENT_CURRENT('TableName')


SCOPE_IDENTITY and @@IDENTITY return the last identity values that are generated in any table in the current session.

SCOPE_IDENTITY returns values inserted only within the current scope.

@@IDENTITY is not limited to a specific scope. It returns the last identity value after performing all scopes (including triggers).


IDENT_CURRENT returns the last identity value generated for a specific table in any session and any scope. In othe words it teturns the last value inserted into 'Tablename'

Using ASP.NET SQL Server Registration Tool (aspnet_regsql.exe) with SQL Express 2005 databases

The aspnet_regsql can be found in
[HDD Drive]:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

The command used for adding asp.net 2.0 membership stuff is

aspnet_regsql -A all
-C "Data Source=.\EXPRESS;Integrated Security=True;User Instance=True"
-d "[database path]"

-d - specifies the database by actual database path

-A all|m|r|p|c|w -

Adds support for one or more ASP.NET application services. Service identifiers can be specified together or separately. The following identifiers are used for ASP.NET application services:

all - All services, including common tables and stored procedures shared by the services

m - Membership

r - Role Manager

p - Profile

c - Web Parts Personalization

w - Web Events


-C - Specifies the connection string to the computer running SQL Server where the database will be installed, or is already installed. This option is not necessary if you specify only the server (-S) and login (-U and -P, or -E) information.

How to set up SMTP Virtual Server with IIS

Exception: Mailbox unavailable. The server response was: 5.7.1

Check the following settings in IIS

IIS -> Default SMTP Server -> Properties -> Access
1. Authentication -> Anonymous access -> Checked
2. Connection control -> Only the list below -> Add current web server ip
Relay restrictions > Relay > - Only the list below -> Add current web server ip

Also add localhost ip here 127.0.0.1 . If DNS lookup doesnt work you can add alias for 127.0.0.1 in your
C:\WINDOWS\system32\drivers\etc\hosts file.

Also it is necessary to have these lines in web.config


<system.net>
<mailsettings>
<smtp deliverymethod="network" from="user@domain.com">
<network host="localhost" port="25" defaultcredentials="true">
</network>
</smtp>
</mailsettings>
</system.net>

How to validate dates in ASP.NET

The simpliest way is by using range validator control and define date bounds


<asp:textbox id="textbox1" runat="server">
</asp:textbox>
<asp:rangevalidator id="valRange" runat="server" controltovalidate="textbox1"
maximumvalue="31/12/2010"
minimumvalue="1/1/2000" type="Date"
errormessage="*" display="dynamic">
*
</asp:rangevalidator>

Some facts about Sessions in ASP.NET

The kind of objects that can be stored in a session variable depends on which mode is used:
InProc Mode- objects stored in session state are actually live objects, and so you can store whatever object you have created.
State Server or SQL Server mode, objects in the session state will be serialized and deserialized when a request is processed. So make sure your objects are serializable and their classes must be marked as so. If not, the session state will not be saved successfully.

To enable sessions in the asp.net site you need to
include a pages attribute in web.config:


<pages enablesessionstate="true">



or enable SessionState in the Page directive in your page :

<%@ Page enableSessionState = "true" %>

Also, the System.Web.SessionStateModule should exist in your
httpModules section in the application configuration.

<httpModules>
<add type="System.Web.SessionState.SessionStateModule" name="Session" />
</httpModules>

Page attributes in ASP.NET for extending System.Web.UI.Page

PageBaseType – Takes a string value defining the base type that will be used for the bage. The default is System.Web.UI.Page. The value gets overridden by the value in the inherits attribute in the standalone file.

userControlbaseType – specifies the base type for controls to be used when the page is standalone.

After implementing classes that extend System.Web.UI.Page or System.Web.UI.UserControl their type can be determined for all pages in the site by their page attributes in web.config. Another way to define the type of the base class is by explicitly defined property CodeFileBaseClass=... in the Page or Control tag (first row in the page).

The using of Page properties (fields) or custom methods by user control is possible by converting Page field to the base page type:

CType(Me.Page, PageBase).Property
CType(Me.Page, PageBase).Method()

Add/remove columns, changing default values in a SQL Server 2005 table

Add new column in a table with checking for existence.
IF NOT EXISTS(SELECT * FROM syscolumns WHERE id=object_id('ColumnName') and name='TableName')
ALTER TABLE TableName ADD ColumnName bit not null default 0

Changing default values in a SQL Server 2005 table
ALTER TABLE [Table] ADD CONSTRAINT
ConstrName DEFAULT 0 FOR ColumnName

DropDownList in GridView

It is necessary to convert bound field to a template field, then set your DropDownList up. In the example it is bound to an ObjectDataSource. It is possible to use statement like (SelectedValue=<%# Bind("Field") %>), but this way is good only for read-only gridview.
Any postback can throw an exception connected to the Bind/Eval way of binding -
'Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control'.

The better way is by using customized code during processing the ItemUpdating event:


<asp:TemplateField HeaderText="Header text">
<ItemTemplate>
<asp:DropDownList ID="ddlItem"
runat="server" OnDataBound="ddlItems_DataBound"
DataSourceID="ObjectDataSource1" AppendDataBoundItems="false"
DataTextField="Name" DataValueField="Id" >
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>



protected void ddlItems_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow gvr = (GridViewRow)ddl.NamingContainer;
if (gvr.DataItem != null)
{
string id = ((DataRowView)gvr.DataItem)["Id"].ToString();
ddl.ClearSelection();
ListItem li = ddl.Items.FindByValue(id);
if (li != null) li.Selected = true;
}
}

It is important to use cast of sender, not direct calling to the GridView1 control. Every GridViewRow is actually DetailsView object.

protected void GridView1_RowUpdating
(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddl =
(DropDownList)(((GridView)sender).Rows[e.RowIndex].FindControl("ddlItems"));
e.NewValues["Id"] = ddl.SelectedValue;
}

Confirmation dialog to a GridView delete option

Actually it is not possible to attach client confirmation to the delete command filed. But it is pretty easy to do this by template field. The only think you have to do is to set command name to be "Delete" (CommandName="Delete"). GridView event handlers are responsible for the other things of delete process.


<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="delete1"
runat="server"
OnClientClick=
"return confirm('Are you sure you want to delete this record?');"
CommandName="Delete">Delete
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

Passing data between two pages with Cross-page Postback and Server.Transfer

The ASP.NET control, that cause postback, post back to the page for processing. That page can be current page or another page. Every control that cause postback can be configured to post to a different page - this postback is called cross postback and is often used for getting information from the pages in the multi page form, especially convenient for creating wizards.

<asp:Button
ID="Button1"
PostBackUrl="~/TargetPage.aspx"
runat="server"
Text="Submit" />

Cross-page post back is similar to Server.Transfer method, but there are some imporrtant differences. Server.Transfer conserves the post data between pages and also it keeps the url. And also it has a documented bug with getting url parameters from the source page. The Server.Transfer method is a server-based operation whereas cross-page postback is a client-based transfer. The main aim of the Server.Transfre method is to reduce client request to the server which makes it faster than Response.Redirect().
Anyway the cross-page postaback can throw the user on another page but with possibility to get the post data.

if (Page.PreviousPage != null)
{
TextBox SourceTextBox =(TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null) { Label1.Text = SourceTextBox.Text;
}
}


there is also possibility to get public properties from the source page with decalring the source:

<%@ PreviousPageType VirtualPath="~/SourcePage.aspx" %>

getting the whole source page:

SourcePage_aspx sourcePage;
sourcePage = (SourcePage_aspx) PreviousPage;
Label1.Text = sourcePage.CurrentCity;

With PreviousPage.IsCrossPagePostBack we can determine whether the page was invoked from a cross-page posting.

Resources:
http://msdn2.microsoft.com/en-us/library/ms178139.aspx
http://www.developer.com/net/asp/article.php/3299641
http://www.codeproject.com/useritems/CrossPagePosting.asp

Script Callbacks in ASP.NET

I am sure that every web developers hates page refresh. And everyone chases the way to make its page more interactive without postback. The best way is client side scripting, but it is not enough to generate all page activity. Javascript based technologies like callbacks and AJAX are at the bottom of the effcicient developer's code.
Here are some good posts for callback technology in ASP.NET 2.0.

http://msdn.microsoft.com/msdnmag/issues/04/08/cuttingedge/

http://www.developer.com/net/asp/article.php/3485991

http://www.mredkj.com/vbnet/scriptCallback.html


At the core, ASP.NET script callbacks consist of some client-side JavaScript code needed for asynchronous communication to the server. The first requirement for using the callbacks is that some server-side code awaits client calls. The client-side callback intermediary manages the call while the user continues to see the old page and interact with it.


Getting fixed number of rows with SQL Select query

The syntax for SQL Server:
SELECT TOP 10 id, name email
FROM person

The syntax for MySQL:
SELECT id, name email
FROM person
LIMIT 10

These examples get the first (top) 10 rows in the query.

I will describe also the paging technology of the asp.net.

Using DataTable (DataView) Filter expressions, Sorting

In some cases it is necessary to be made some calculations or data filtering and sorting of local data - already received from a database. These things can be made with the DataTable or DataView classes in a way similar to SQL Select queries.
When we have a filled DataTable we can easy retrieve only the rows we need with DataView.RowFilter. This property gets or sets the expression used to filter which rows are viewed in the DataView (often used for DataSourse in data components).

DataTable dt= ......... //filling the data table
DataView dv= dt.DefaultView;
dv.RowFilter="AreaId="+searchId+" AND SubAreaName LIKE 's*'; //getting all records for searched area whic name starts with 's'
dv.Sort="Name desc, number asc"; //sorting data

dv.RowFilter = "Name LIKE 's*'" // values that start with "s"'
dv.RowFilter = "Name LIKE '%s%'" // values that contain 's'
dv.RowFilter = "Name NOT LIKE 's*'" // values that don't start with 's'
dv.RowFilter = "Name <> 'MyName'" // values different than 'MyName'
dv.RowFilter = "Name IN ('MyName','MySecondName')" // value equal to 'MyName' or 'MySecondName'


If the pattern string in a LIKE statement contains special characters like * % [ ], they must be escaped in brackets [ ] in this way [*], [%], [[] or []].

RowFilter is an expression string that can be evaluated to true or false, and uses the syntax described in the DataColumn.Expression documentation.

It is very useful to use also aggregate functions for calculation. For example
dt.Columns("ItemCount").Expression = "Count(ItemID)"
dt.Columns("ItemCount").Expression = "FirstName = 'John'"   
dt.Columns("ItemCount").Expression = "Date < #1/31/82#" 
dt.Columns("ItemCount").Expression = (LastName = 'Smith' OR LastName = 'Jones') AND FirstName = 'John' 

Here is the MSDN reference for the filter expressions:
http://msdn2.microsoft.com/en-us/library/system.data.datacolumn.expression(VS.71).aspx

SQL Server Express Edition attaching and using problems

"Cannot open user default database. Login failed.
Login failed for user ......"

This problem occurs very often while the developer uses Visual Studio and testing in a browser at the same time. The reason is the already opened connection to the database in the VS environment. For example every time when the developer edit DataSet connected to current database this connection stays opened. The solve this problem the connection to the db has to be closed by the right mouse button -> Close Connection in the Server Explorer tab.

Another problem with attaching database and using its connection is:
"An attempt to attach an auto-named database for file ..... failed. A database with the same name exists, or specified file cannot be Opened, or it is located on UNC share."

1 . The first thing that has to be done is to try to attach the database manually with Microsoft SQL Server Management Studio.

2. The data folder permissions have to be set to "Modify" for ASPNET account and NETWORK SERVICE for windows server 2003

3. Make ASPNET user a member of SQLServer2005MSSQLUser$server$SQLExpress group

4. Add new Login to the SQL Express server for ASPNET (NETWORK SEVICE) user

5. In the connection string User Instance=True has to be checked. It works only if SQL Server uses Windows Authentication mode.
Changing the authetication mode can be done by SQL Server Management Studio with right mouse click on the computer name and Properties -> Security.
When Integrated Security=SSPI in the connection string is used make sure you are using in system.web sections of the web.config and also make sure that a windows account for the "Anonymous User" is selected in the access section in IIS.

6. Also the sql settings in
c:\Documents and Settings\<username>\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\ can be deleted and the sql service restarted.

ASP.NET Request Validation has detected a potentially dangerous client input value

This exception occurs when the server meet content containing un-encoded HTML. This is action for preventing script atacks, for example <script> alert("blabla")</script> can be executed. In this way other harmful code can be executed. The request validation feature of ASP.NET doesn't allow this to be done.
To disable request validation on a page you must set the validateRequest attribute of the Page directive to false. The developer has to ensure that the content is properly encoded.
One more way to disable it is by web.config. You have to set
<configuration>
<system.web>
<pages validaterequest="false">
</pages>
</system.web>
</configuration>

The HTML content can be encoded/decoded using the Server.HtmlEncode(string)/Server.HtmlDecode(string) functions.

How To: Enable Microsoft ASP.NET Ajax Extension V1.0 on an existing site

The fastest way to add ajax fuctionality to your site -
Here is a good explanation of the process of enabling ajax in an asp.net page.
There is also integeration of CTP on an existing site.

How to delete row in a DataTable with C# or VB.NET

When you use a DataRow.Delete() method the row is not actually deleted. It is only marked to be deleted after calling DataTable.AcceptChanges(). It is not good idea to remove row with DataTable.Rows.Remove or RemoveAt methods. They forces row removing and causes by iterating the following exception:
'Collection was modified; enumeration operation may not execute'
One more thing to be sure that the iterating will be performed succesfully is to iterate through returned by DataTable.Select() rows (not DataTable.Rows).

For Each row As DataRow In dt.Select()
If (bool_statement) Then
row.Deleted()
Enf IF
Next

dt.AcceptChanges

If adapter is used changes can be commited by Update method. All rows with DataRow.RowState of 'Deleted' will be deleted.

How to use SQL SERVER 2005 with SQL EXPRESS at the same time.

Error message received by Visual Studio 2005:
"Connections to sql server files (*.mdf) require sql server express 2005 to function properly"
I had installed Visual Studio 2005 and SQL Server 2005 Developer Edition when I received it. To solve the porblem I installed other instance of SQL Server - Express Edition. But to get VS to work with it I had to change its instance name in the VS options. Tools -> Options - > Database Tools -> Data Connections. Now I can work with the two sql server instances - Developer Edition and Express Edition.


To change an existing instance of Microsoft SQL Server 2005 to a different edition of SQL Server 2005, you must run SQL Server 2005 Setup from the command prompt and include the SKUUPGRADE=1 parameter.

Checking for existing Javascript variable

Somethemes it is necessary to know if the variable is already defined. For example when postback methods which register client script block are used.

function isSet( v )
{
return( typeof( v ) != 'undefined' );
}

Default Web Site on IIS doesn't work until changing the default port.

It is a very strange problem that occurs sometimes.
"IS Unexpected error 0x8ffe2740"
Today I have just found the reason - Skype is using the default port 80 for alterantive connection.
Resolve that by:
Skype File, Options, Advanced, Connection
Uncheck "Use Port 80 as an alternatives for incoming connections" and restart default website or IIS

How to get random number or generate random password with VB.NET or C#

The simplest way to get random number is to get instance of the Random class and use the "Next" method.
Dim rand As Random=new Random()
rand.Next() gives you a random nonnegative number
rand.Next(23) gives you a random nonnegative number less than integer value (23 for the example)
rand.Next(23, 89) gives you a random nonnegative number in the specified range

With this class you can generate also double values and bytes.

Here is an way for generating random password using guid.
So simple, so effective.

Public Function GetRandomPassword(ByVal length As Integer) As String
Dim rand As String = System.Guid.NewGuid().ToString()
rand = rand.Replace("-", String.Empty)

If length <= 0 OrElse length > rand.Length Then
Throw New ArgumentException("Length must be between 1 and " & rand.Length)
End If

Return rand.Substring(0, length)
End Function

Fire Default button on enter on an Asp.NET page

I found two ways to get this to work. By Default the first button in the form is the default button. When you push Enter an fire event of this button occur. Current solution is enough to get Login control on asp.net form to work. Here is the code:


Dim ctl As Control = Login1.FindControl("LoginLinkButton")
If Not (ctl Is Nothing) Then
Login1.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) {__doPostBack('" + ctl.UniqueID + "',''); return false;}")
End If

Fix: return false will break the firing of other buttons. Just to ensure right behaviour.

It works fine for all browsers.
There is one more way to do this but unfortinately it doesn't work with firefox.

Login1.Attributes.Add("onkeypress", String.Format("javascript:return WebForm_FireDefaultButton(event, '{0}')", ctl.ClientID))

How to install PHP on IIS

PHP installation on IIS 7.0 (Windows VISTA)
I will not explain how to do it, just see this good article:
http://blondr.blogspot.com/2006/11/set-up-iis-7-w-mysql-and-php-5.html
It includes also the settings for MySQL and php session' permission.


PHP installation on IIS 5.1

1) add to path c:\PHP
2) rename php.ini-recomended to php.ini

doc_root = c:\inetpub\wwwroot // for IIS/PWS
doc_root = c:\apache\htdocs // for Apache
extension_dir = "c:\php\ext"
cgi.force_redirect = 0
set browscap to c:\windows\system32\inetsrv\browscap.ini

If you want to use the CGI binary, do the following:

* Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
* Change the Execute Permissions to 'Scripts only'
* Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate CGI file. An example PHP 5 value is: C:\php\php-cgi.exe Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
*

Set up the appropriate security. (This is done in Internet Service Manager), and if your NT Server uses NTFS file system, add execute rights for I_USR_ to the directory that contains php.exe / php-cgi.exe.

To use the ISAPI module, do the following:

* If you don't want to perform HTTP Authentication using PHP, you can (and should) skip this step. Under ISAPI Filters, add a new ISAPI filter. Use PHP as the filter name, and supply a path to the php4isapi.dll / php5isapi.dll.
* Under 'Home Directory', 'Virtual Directory', or 'Directory', do the following:
* Change the Execute Permissions to 'Scripts only'
* Click on the 'Configuration' button, and choose the Application Mappings tab. Click Add and set the Executable path to the appropriate ISAPI DLL. An example PHP 5 value is: C:\php\php5isapi.dll Supply .php as the extension. Leave 'Method exclusions' blank, and check the 'Script engine' checkbox. Now, click OK a few times.
* Stop IIS completely (NET STOP iisadmin)
* Start IIS again (NET START w3svc)
3) add user rights to php directory (IIS user - modify, IUSR_MASNINENAME - read)

How to get window size and scroll by javascript

Here is a nice explanation of the browser incompatibility with getting window size:
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}

It works fine for all browsers.

ASP.NET Membership Tips and Tricks

Change email/username.
http://www.aspcode.net/Update-email-username-with-verification.aspx
By default asp.net memberhip provider does not offer changing of the username. This post gives us a suggestion how to do this with a custom stored procedure.

Read and Write to configuration's files

Reading:
string value = ConfigurationManager.AppSettings["Setting1"];

Writing:
System.Configuration.Configuration config =ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Setting1"].Value = "3";
config.AppSettings.Settings["Setting2"].Value = "blabla";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

When use configuration settings in your web.config you have tou use
WebConfigurationManager class.

Postback in ASP.NET

This post is a short explanation of the postback "magic" used in asp.net. Check this out.
If you have to change data in a popup and also this information have to be changed in the parent page you can use window.openere.document.__doPostBack('',''); to do postback on the parent page and refresh the information there. The event target id can be passed by session variable or page parameter to the popup. The actual actions in the popup are these:

window.close();
var theform = window.opener.document.aspnetForm;
theform.__EVENTTARGET.value = id
theform.__EVENTARGUMENT.value = '';
theform.submit();

Using javascript for managing asp:ListBox, Add/Remove ListItem

Here is a wonderful tutorial about using javascript with "select" html control:

http://www.mredkj.com/tutorials/tutorial_mixed2b.html

There are also related javascript tutorials. Here is presented the javascript and html code for managing select control. The asp:ListBox is wrapped select control with additional functionality. There is no problem to use select control in your code instead this one. I personally prefer using asp:ListBox:


<asp:ListBox ID="lstItems" runat="server" DataSourceID="ODSItems" DataTextField="Name" DataValueField="Id" Width="170px"></asp:ListBox>

<asp:Button ID="btnAddItem" runat="server" Text=">" />


<br />

<asp:Button ID="btnRemoveItem" runat="server" Text="<" />
<asp:ListBox ID="SelectedItems" runat="server" Width="170px">
<asp:ListItem Value="all" Text="All"></asp:ListItem>
</asp:ListBox>


In the Page.Load Event you have to add the followed code:

btnAddItem.Attributes.Add("onclick", "javascript:moveOptions('" + lstItems.ClientID + "','" + SelectedItems.ClientID + "');return false;") btnRemoveItem.Attributes.Add("onclick", "javascript:moveOptions('" + SelectedItems.ClientID + "','" + lstItems.ClientID + "');return false;")

I have added additional functionality for one more option field: all items. And also this code is optimized for asp pages - see the client id-s handling. This is the new javascript code:


var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);

function addOption(theSel, theText, theValue)
{
var newOpt = new Option(theText, theValue);
var selLength = theSel.length;
theSel.options[selLength] = newOpt;


// Removing the option with all value
var selLength = theSel.length;
var i;
if (selLength>1) {
for(i=selLength-1; i>=0; i--)
{
if (theSel.options[i].value=="all"){
deleteOption(theSel, i);
}
}
}
}

function deleteOption(theSel, theIndex)
{


var selLength = theSel.length;
if(selLength>0)
{
theSel.options[theIndex] = null;
}



//adding all
if (theSel.length==0){
addOption(theSel, "Всички","all");
}

}

function moveOptions(theSelFromId, theSelToId)
{

theSelFrom=document.getElementById(theSelFromId);
theSelTo=document.getElementById(theSelToId);

var selLength = theSelFrom.length;
var selectedText = new Array();
var selectedValues = new Array();
var selectedCount = 0;

var i;

// Find the selected Options in reverse order
// and delete them from the 'from' Select.
for(i=selLength-1; i>=0; i--)
{
if(theSelFrom.options[i].selected)
{
if (theSelFrom.options[i].value=="all"){
return;
}
selectedText[selectedCount] = theSelFrom.options[i].text;
selectedValues[selectedCount] = theSelFrom.options[i].value;
deleteOption(theSelFrom, i);
selectedCount++;
}
}

// Add the selected text/values in reverse order.
// This will add the Options to the 'to' Select
// in the same order as they were in the 'from' Select.
for(i=selectedCount-1; i>=0; i--)
{
addOption(theSelTo, selectedText[i], selectedValues[i]);
}

if(NS4) history.go(0);
}

ASP.NET GridView RowDeleting event fires twice!

This is a well known bug (for Microsoft) when using ImageButton. Of course you can use standard button or link button to go round the problem.

Here is a solution with image button:

<asp:ImageButton runat=server id="ImageButton1" CommandName="Delete"
ImageUrl="..." CommandArgument='<%# DataBinder.Eval(Container,
"RowIndex") %>' OnCommand="ImageButton1_Command">

protected void ImageButton1_Command(object sender, CommandEventArgs e) {
GridView1.DeleteRow(Int32.Parse(e.CommandArgument.ToString() ));
}

SQL Server Management Studio - How to connect to database server

1. Start SQL Server Management Server Studio
2. Click on the 'Register Servers' button
3. Right click on the node Database Engine and select New > Server Registration.
4. Select server type to be Database Engine
5. Server Name: Write down the IP address of the database server, followed by port number separated with comma (server ip, port)
6. Choose authentication type to be SQL Server Authentication
7. Login and Password: The database username you created in your Database Manager within your Control Panel.
That is all!

VS 2005 Required components missing

Problem: Visual studio 2005 cannot connect to sql server express database. This is so boring problem... Here is a short summarize of similiar issue:
http://www.sqljunkies.com/WebLog/ktegels/archive/2005/11/15/17401.aspx

However my problem continued. The reason was that I have had installed Standard Edition of Sql Server 2005. When I installed SQL Server Express Edition I received the problem. The solution I found was so simple, I had to change database options of Visual Studio:
Tools -> Options -> Database Tools -> Data Connections. I changed SQL Server Instance Name to the new instance name (name of sql server express edition). This needed restart of Visual Studio. Now it works fine :-)

There is a way to run ASP.NET on Apache server

There is a way to run ASP.NET on Apache server :-) . I read some posts about it and found a good articles to make this possible:
This is enough to do it
http://weblogs.asp.net/israelio/archive/2005/09/11/424852.aspx

One problem: there are ASP.NET controls that don't work in this way. Use it only for simple asp.net pages.

VS 2005 "Extensibility DTE object unavailable"

This occured after removing Visual Studio .NET 2003. When I trying to show dataset I recieved this error message.
I read many posts for this problem but the only way I found was repairing VS. This didn't solve the my problem. It was neccessary to remove totally VS 2005 and install it again.

ASP.NET C# How to send mail with SMTP Authetication.

To send email from ASP.NET hosting account it is necessary to use credentials for smtp authentication.
Here is a way to do this with help function for sending mail.

private void sendEmail(string strTo, string strFrom,
string strSubject, string strBody, Attachment item, bool isHTML)
{

MailAddress maFrom = new MailAddress(strFrom, "sender");
MailAddress maTo = new MailAddress(strTo);
MailMessage mail = new MailMessage(maFrom, maTo);
mail.Attachments.Add(item);
mail.IsBodyHtml = isHTML;
mail.Subject = strSubject;
mail.Body = strBody;
SmtpClient sc = new SmtpClient();
System.Net.NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("email account", "password");

sc.Credentials = basicAuthenticationInfo;
sc.Host = "mail.xxxx.xxx";
sc.Port = 25;
sc.Send(mail);
}

Email account you can register with the hosting control panel (if you don't have already). The host is usually mail.+ domain name.

ASP.NET Globalization, using UTF-8 or any other encoding

There are some difficulties by setting globalization of a web site. By default .Net framework use unicode. Therefore it is not necessary to set this. If you have to use different encoding you can set this in web.config:
<globalization fileEncoding="utf-8" requestEncoding="utf-8" responseEncoding="utf-8" culture="bg-BG" uiCulture="bg-BG">

Check the following links for more information:

http://samples.gotdotnet.com/quickstart/aspplus/doc/internationalization.aspx

http://www.kbalertz.com/Feedback.aspx?kbNumber=893663

And here is a explanation of the Visual Studio behavior. VS may cause some problems if you don't know these issues.
http://blogs.msdn.com/mikhailarkhipov/archive/2004/08/07/210769.aspx

The last link helped me to decide my problem. I had to save all my files with utf-8 encoding to get Cyrillic encoded response.

ASP.NET How to use nested DataList

<asp:DataList ID="dlParent" runat="server">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"></asp:Label>
<br/>
<asp:DataList ID="dlNested" runat="server">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:DataList>

</ItemTemplate>
</asp:DataList>



Private Sub dlParent_ItemDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataListItemEventArgs) Handles
dlParent.ItemDataBound

If Not e Is Nothing Then
Dim lbl As Label
Dim dlNested As DataList
lbl = CType(e.Item.FindControl("ParentLabel"), Label)
dlNested = CType(e.Item.FindControl("dlChild"), DataList)

lbl.Text = "content"

AddHandler dlNested .ItemDataBound, AddressOf dlNested_ItemDataBound

dlNested.DataSource = AnyDataSource
dlNested.DataBind()
End If
End Sub

Private Sub dlNested_ItemDataBound(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.DataListItemEventArgs)
Dim lbl As Label

If Not e Is Nothing Then
lbl = CType(e.Item.FindControl("lbl"), Label)
lbl = DataBinder.Eval(e.Item.DataItem, "LabelContent").ToString()
End If

End Sub


The key moment is adding new Handler for nested DataList.

Note: AnyDataSource must have field (column) "LabelContent".

XHTML Special Characters

They are well known, but I often forget the syntax of some of them.

http://msconline.maconstate.edu/tutorials/XHTML/Appendix/XHTMLCharacters.htm

ASP.NET AJAX - Validators doesn't work after postback by UpdatePanel

There is a tedious problem with asp.net validation control when AJAX Update panel is used.
A solution at the moment is this extension of validator controls including script manager.

http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx

It is pretty simple to integrate - just follow the instructions of Matt Gibbs.

ASP.NET/Javascript - Handling Enter click for submitting the active form.

There are some ways to do this.
The most simple way is to use the default submit button - this is by default the first button in the which performs postback (link button, image button, button). If the button you would like to use by default is not the first you can add one more button on the top of page (for example image button with 1x1 pixels picture - invisible). This guaranties that the pressing enter will cause postback independant of the browser - it works with every browser (that I know :-)).

However, we can use simple javascript code to handle the event of pressing enter button:
<body onkeydown="if(event.keyCode == 13){document.getElementById('" + ImageButton1.ClientID + "').click();}">

One more way: DataList1.Attributes.Add("onkeypress", String.Format("javascript:return WebForm_FireDefaultButton(event, '{0}')", ImageButton1.ClientID)) - this performs postback when the focus is on the datalist1. Of course we can use every control that has child controls.
But my experience shows that this doesn't work good with Firefox.

Here is also way to add javascript event dynamically:

<script type="text/javascript">
addEvent(window, 'load', function() {
document.getElementById('myfield').focus()
});

function addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, true);
return true;
} else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
</script>



C#, VB.NET - How to convert string to Guid

string str="565G6B7D-8H7D-8J7D-A0C6-908H7D868H7D";
Guid g= new Guid(str);


Dim str As String="565G6B7D-8H7D-8J7D-A0C6-908H7D868H7D";
Dim g As System.Guid = New Guid(str);

HTML Hyphenation

There are two ways of hyphenation - with plain hyphen and soft hyphen. The plain hyphen is interpreted like a plain symbol, but soft hyphen is used only if it is necessary. The soft hyphen is represented by the character entity reference & s h y ; . This will solve many formatting problems like list text indent.

ASP.NET Using connection string from web.config in TableAdapters for Typed Datasets

To view this string the connection string tag must have: providerName="System.Data.SqlClient" (SQL Server). The string works also without this property but Visual Studio requires it to display existing connection string for datasets.

ASP.NET Exception Details: System.InvalidCastException: Unable to cast object of type 'ProfileCommon' to type 'ProfileCommon'.

SOLVED. It is a very strange issue. I have read many forums described this case. And the only way I found is:
1. Change web config line
profile defaultProvider="ProfileProvider" enabled="true"
to be
profile defaultProvider="ProfileProvider" enabled="false"

2. Save and refresh the web page.

3. Change web config line
profile defaultProvider="ProfileProvider" enabled="false"
to be
profile defaultProvider="ProfileProvider" enabled="true"

3. Save and refresh.

Strange but works.

ASP.NET - A simple way to change dinamically the css link

in the asp page we can make the link tag to be maintained from the server side
ink id="css" runat="server"  rel="stylesheet" type="text/css" 
and then we can change it dynamic
Sub Page_Load(Sender As Object, E As EventArgs)
If Not (Page.IsPostBack) Then
css.Attributes.Add("href","/.css")
End If
End Sub

This the easiest way to do it. Here is more complex css management in the Scott Gu' Blog:
http://weblogs.asp.net/scottgu/archive/2006/05/02/CSS-Control-Adapter-Toolkit-for-ASP.NET-2.0-.aspx

Javascript - How to set and get cookie variable

This code searches for cookie value by key:

function get_cookie(Name) {
var search = Name + '='
var returnvalue = '';

if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
// if cookie exists
if (offset != -1) {
offset += search.length
// set index of beginning of value
end = document.cookie.indexOf(";", offset);
// set index of end of cookie value
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}

Setting cookie value:
document.cookie=key+"=" +value;

ASP.NET Managing url-s with examples

URL: http://www.sample.com/app/folder/default.aspx?id=2&cat=67

Request.ApplicationPath returns:
/app

Request.Url.AbsolutePath:
/app/folder/default.aspx

Request.Url.PathAndQuery:
/app/folder/default.aspx?id=2&cat=67

Request.Url.LocalPath:
/app/folder/default.aspx

Request.Url.Query:
?id=2&cat=67

Request.Url.OriginalString
http://www.sample.com:80/app/folder/default.aspx?id=2&cat=67

Request.Uri.MakeRelativeUri Method determines the differeneces between two Uri instances and returns relative path:
http://www.sample.com/
http://www.sample.com/app/folder/default.aspx?id=2&cat=67
the relative difference is:
app/folder/default.aspx?id=2&cat=67

Request.Url.DnsSafeHost /Host
www.sample.com

Request.UserHostAddress
192.168.67.5

Request.UserHostName gets the DNS name
sample.com

Request.RawUrl:
/app/folder/default.aspx?id=2&cat=67


Request.Url.Segments:
/
app/
folder/
default.aspx

Request.PhysicalApplicationPath:
E:\folder\appfolder\

Request.PhysicalPath:
E:\folder\appfolder\folder\default.aspx

Request.Path:
/app/folder/default.aspx

Request.QueryString:
id=2&cat=67

Request.MapPath(".")
E:\folder\appfolder\folder\

Request.FilePath:
/app/folder/default.aspx

Server.MachineName:
COMPUTERNAME

w3: A tool to troubleshoot client side issues.

HTTP Debugging Proxy:
http://www.fiddlertool.com/dl/FiddlerSetup.exe
It is good tool for analyzing http request by client side. You can view some errors that the server response don't show you.

Visual Studio 2005 - If there isn't Database Name File for Access database file

You have to change a registry key:


HKEY_CLASSES_ROOT\CLSID\{F9AE8980-7E52-11d0-8964-00C04FD611D7}

Underneath this key should be a sub-key called "ProgID" with a value of "MSIDXS.1". If you can't find this, it is causing the problem you are seeing. Adding this back should fix the issue.

Visual Studio - 'Unable to get the Project file from the Web server'

A solution to the 'Unable to get the Project file from the Web server' that has worked for us is to go into C:\Documents and Settings\(your user)\VSWebCache and delete everything in there."

Java Script - Closing window and reload the parent.

window.parent.close(); window.opener.location.href=window.opener.location.href;

if you want to do postback use this:

window.parent.close(); window.opener.__doPostBack('','')

Javascript - How to create navigation url for popup.

The popup don't have toolbar, statusbar and scrollbar.
javascript:my_window=window.open('" & Url & "',
'my_window','width=XXX,height=XXX,top=XXX,left=XXX,
toolbar=no,location=no,directories=no,resizable=no,
status=no,menubar=no,scrollbars=no');my_window.focus()"

ASP.NET - How to keep the user always logged in?

This functionality is natural extension of "remember me" which is part of Microsoft integrated Login Control. "Remember me" check box allow the user to stay logged in if he leaves the page or closes the browser.
But if you don't make a request for 30 minutes you will be logged out. The aim of "keep me logged in" is to hold the user logged in always until he clicks logout.

First you must change the forms timeout in web.config to be bigger than default value of 30 minutes - something like 300000. This guarantees that forms authentication ticket will live longer. This is enough to hold the user logged in for days.
"Remember me" check box makes the authentication cookie persistent and live even if you close the browser.
Users that are logged in without click checking remmeber me will stay logged in until they click logout or close the browser (authentication cookie is not persistent). If you want to specify a timeout for this user session you can do this:

1. Creating client cookie after logged in with value the session expiration time. Other way is to use Session state initiated by Session_Start(ByVal sender As Object, ByVal e As EventArgs).
You must change the session timeout in web.config to be equal or bigger than desired timeout and smaller than forms timeout.

2. Checking user authentication on every request in global.asax -> Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs). If user is autheticated and the timeout is expired you have to sign out and redirect to login form.
If the timeout is not expired you have to change the expiration time of the session like slide expiration of forms.
Be careful: Don't make client cookie to expire. This will make it persistent and closing the browser will not log out the user.