SQL Server Express permissions

Fix for exceptions like these:
"CREATE DATABASE permission denied in database 'master'",
"EXECUTE permission denied on object "
"SELECT permission denied on object"

Asp.NET uses the NETWORK SERVICE account (for Windows Server 2003) and ASPNET user for Windows XP. If we use windows authetincation for using sql express we need to add these users as sql server logins:
SQL Server manager -> Security -> Logins -> add "NT AUTHORITY\NETWORK SERVICE" or ASPNET
Then click on the properties menu of the login and make the login dbcreator. This will fix the first of the exceptions above. Then with User Mapping setting we can add permissions explicitly to the desired database -> dbowner gives all needed permission.

How to get Profile instance out of asp.net page,

The way of getting Profile instance from a page context is Profile.GetProfile(). But how to do this when you need to get it from App_Code for instance. Here is the way:

MembershipUser mUser = Membership.GetUser(UserId);
ProfileCommon prof = (ProfileCommon)System.Web.Profile.ProfileBase.Create(mUser.UserName);

the object "prof" has all profile fields as in a page.

How to set page/script timeout on an asp.net page

The solution is pretty simple. Use Server.ScriptTimeout to set the timeout for the script in a page. The value is measured in seconds.

Server.ScriptTimeout = 3600

Use this in Page_Load event. The example makes the timeout to be an hour.

NOTE: using compilation debug="true" will ignore script timeout and it won't work. Make sure the debug value is false on the release version of web.config

FormsAuthentication.Authenticate vs Membership.ValidateUser

FormsAuthentication.Authenticate can be used with clear passwods to check user authentication:
if(FormsAuthentication.Authenticate(Username.Text, Password.Text))
{
FormsAuthentication.RedirectFromLoginPage(Username.Text, false);
}

This doesn't work if the password format is not clear. Asp.NET membership provider offers you Clear, MD5 or SHA1 represented passwords.
In case of using MD5 or SHA1 (specified in web.config, SHA1 is default for hashed passwords) the checking for user credentials should be done by Membership.ValidateUser which delivers the provider model for user authentication.

if( Membership.ValidateUser(curentUserName, pwd)){
FormsAuthentication.RedirectFromLoginPage(Username.Text, chkPersistent.Cheked);
}

The other things of authentication process can be left to the Asp.Net provider.

See also for web.config: authentication and authorization, machine key generation, password format, password salt ...

How to use SQL Express database for more than one application

Somethimes we need to use one database for more than one application, web, desktop or service.
The only thing to do is to get rid of the generation of a new user instance by the connection string in web.config. Assure that User Instance=False in the connection string and try again.

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'