Friday, March 1, 2013

Generate scripts to create DB Users and their membership from existing DB


-- Create script to create the DB Users
SELECT 'CREATE USER [' + name + '] for login [' + name + ']' + char(13) + 'GO'
 from sys.database_principals
 where Type = 'S' AND default_schema_name='dbo'

-- Create script to create the Users' membership
SELECT 'EXECUTE sp_AddRoleMember ''' + roles.name + ''', ''' + users.name + '''' + char(13) + 'GO'
 from sys.database_principals users
  inner join sys.database_role_members link
   on link.member_principal_id = users.principal_id
  inner join sys.database_principals roles
   on roles.principal_id = link.role_principal_id
 WHERE users.Type = 'S' AND users.default_schema_name='dbo'

Generate scripts to create DB role and its securables from existing DB

declare @RoleName varchar(50) = 'RoleName'

-- Create script to create DB Role
select 'CREATE ROLE [' + @RoleName + ']' + char(13) + 'GO'

-- Create script to grant pemission of securable of the DB Role
select 'GRANT ' + prm.permission_name + ' ON [' + OBJECT_NAME(major_id) + '] TO [' + rol.name + ']' + char(13) COLLATE Latin1_General_CI_AS + 'GO'
from sys.database_permissions prm
    join sys.database_principals rol on
        prm.grantee_principal_id = rol.principal_id
where rol.name = @RoleName

Thursday, June 7, 2012

MS SQL Server : Move TempDB to another location

First use the following codes to check the name of the files.
 
USE TempDB
GO
EXEC sp_helpfile
GO


By default, the names of the files are : tempdev and templog.

Then, you could run the following codes to move .mdf and .ldf files.

USE master
GO
ALTER DATABASE TempDB MODIFY FILE
(NAME = tempdev, FILENAME = 'd:tempdb_data.mdf')
GO
ALTER DATABASE TempDB MODIFY FILE
(NAME = templog, FILENAME = 'e:tempdb_log.ldf')
GO

Tuesday, May 15, 2012

Grant EXECUTE permission to all stored procedures

SELECT 'GRANT EXECUTE ON OBJECT::[' + ROUTINE_NAME + '] TO ' + @TO + ';'
FROM INFORMATION_SCHEMA.ROUTINES


Where @TO is the database role or user


Thursday, May 3, 2012

Remove Hypothetical Indexes Generated by SQL DTA

Here is the sql statement to generate the scripts to drop hypothetical indexes that were generated by SQL Database Engine Tunning Advisor (DTA).


SELECT 'DROP INDEX [' + s.[name] + '] ON [' + object_name(s.[object_id]) +'] '
FROM sys.stats AS s
INNER JOIN sys.indexes AS i
    ON s.name=i.name
WHERE i.is_hypothetical=1 and s.[name] LIKE '_dta_ind%'


SELECT 'DROP STATISTICS  [' + object_name(s.[object_id]) + '].[' + s.[name] + '] '
FROM sys.stats AS s
WHERE s.name like '_dta_stat%'

Monday, November 21, 2011

IIS 6.0 : Web Farm Share Resources via UNC share

1) Create a User Account (eg. "WebFarmUser") in UNC Share server and IIS Servers

2) Share the folder and set the permission (R and W) to the "WebFarmUser" account.

3) Assign "WebFarmUser" user account as the account running the App Pool in IIS Server.

4) Assign the web application to the App Pool

5) Create a virtual directory to the UNC shared folder.

6) if you still get the access denied issue, explicitly set the "Connect AS" of the virtual directory to use "WebFarmUser" account.


7)
  • ASP.NET 2.0 is configured to run with a user account.
  • The SerializeAs attribute of the Profile property in ASP.NET 2.0 is set to Xml
In this scenario, ASP.NET 2.0 may not save the user profile, and you may receive an error message that is similar to the following:

[InvalidOperationException: Unable to generate a temporary class (result=1).
error CS2001: Source file 'D:\WINDOWS\TEMP\d0lurtzx.0.cs' could not be found
error CS2008: No inputs specified

To resolve this issue, grant the user account the List Folder Contents and Read permissions on the %windir%\Temp folder.


Thursday, October 6, 2011

IIS 6.0 Compression

1) Backup the metabase. This is done by right-clicking on the server in the IIS snap-in and selecting All Tasks -> Backup/Restore Configuration.

2) Create Compression Folder (optional)

The first thing I do is create a folder on the D drive where the static file compression will be cached. You can call it anything you want or leave the default of “%windir%\IIS Temporary Compressed Files” if that works for you. The IUSR_{machinename} will need write permission to the folder. If you use custom anonymous users, make sure to assign the proper user. IIS will still work even if the permissions are wrong but the compression won't work properly. Once running, it's worth double checking Event Viewer to see if any errors are occurring that keep IIS Compression from working.

3) Enable Compression in IIS

- From the IIS snap-in, right-click on the Web Sites node and click on Properties
- Select the Service tab - Enable Compress application files
- Enable Compress static files
- Change Temporary Directory to the folder that you created above, or leave it at it's default
- Set the max size of the temp folder to something that the hard drive can handle. i.e. 1000.
- Save and close the Web Site Properties dialog

Note: The temporary compress directory is only used for static pages. Dynamic pages aren't saved to disk and are recreated every time so there is some CPU overhead used on every page request for dynamic content.

4) Metabase changes

To enable metabase edit-while-running using IIS Manager
  1. In IIS Manager, right-click the local computer, and then click Properties.
  2. Select the Enable Direct Metabase Edit check box.
- Open the metabase located at C:\Windows\system32\inetsrv\metabase.xml in Notepad
- Search for deflate and one for gzip. Basically they are two means of compression that IIS supports.
- First thing to do is add aspx, asmx, php and any other extension that you need to the list extensions in HcScriptFileExtensions.

HcDynamicCompressionLevel has a default value of 0. Basically this means at if you did everything else right, the compression for dynamic contact is at the lowest level. The valid range for this is from 0 to 10.

The compression level -vs- CPU usage which showed that the CPU needed for levels 0 - 9 is fairly low but for level 10 it hits the roof. Yet the compression for level 9 is nearly as good as level 10.

5) Restart IIS

Origianl Post : http://weblogs.asp.net/owscott/archive/2004/01/12/57916.aspx

Tuesday, October 4, 2011

Precompile an ASP.NET Web site in place

To precompile an ASP.NET Web site in place

  1. Open a command window and navigate to the folder containing the .NET Framework.

    The .NET Framework is installed in the following location.

    %windir%\Microsoft.NET\Framework\version
  2. Run the aspnet_compiler command by typing the following at a command prompt.

    aspnet_compiler -v /virtualPath

    The virtualPath parameter indicates the Internet Information Services (IIS) virtual path of your Web site.

    If your Web site is not an IIS application, and therefore has no entry in the IIS metabase, type the following command at a command prompt.

    aspnet_compiler -p physicalOrRelativePath -v /

    In this case, the physicalOrRelativePath parameter refers to the fully qualified directory path in which the Web site files are located, or a path relative to the current directory. The period (.) operator is allowed in the physicalOrRelativePath parameter. The -v switch specifies a root that the compiler will use to resolve application-root references (for example, with the tilde (~) operator). When you specify the value / for the -v switch, the compiler will resolve the paths by using the physical path as the root.

Thursday, May 12, 2011

Setting Default parameter when opening PDF

For example, a scale value of 100 indicates a zoom value of 100%. e.g. zoom=100

The file of more details is located on :

http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParameters.pdf#page=5&zoom=50&scrollbar=0

Wednesday, May 11, 2011

How to Disable the ASP.NET v4.0 Extensionless URL feature on IIS 6.0

You can disable the v4.0 ASP.NET extensionless URL feature on IIS6 by setting a DWORD at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET\4.0.30319.0\EnableExtensionlessUrls = 0. After changing the value, you will need to restart IIS in order for us to pick up the change, because it is only read once when IIS starts.

Note that for Wow64 (i.e., 32-bit worker process running on 64-bit OS), this registry key must be set at HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\ASP.NET\4.0.30319.0\EnableExtensionlessUrls.

Please refere to this URL for details: https://blogs.msdn.com/b/tmarq/archive/2010/06/18/how-to-disable-the-asp-net-v4-0-extensionless-url-feature-on-iis-6-0.aspx

Friday, April 29, 2011

The way to get control ID from custom Text source of RadSpell

Here is the way to get the TextBox ID from the custom text source of RadSpell.

this.sources[i].get_element().id

Monday, March 14, 2011

Save the scroll position when doing Ajax

var scrollTop;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);

function BeginRequestHandler(sender, args)
{
var elem = document.getElementById('<%= scrollBar.ClientID %>');
scrollTop=elem.scrollTop;
}

function EndRequestHandler(sender, args)
{
var elem = document.getElementById('<%= scrollBar.ClientID %>');
elem.scrollTop = scrollTop;
}

Wednesday, November 17, 2010

ASP.NET with SQL 2005 Cache Dependence

1) Check to see Service Broker is enabled

SELECT name, is_broker_enabled FROM sys.databases

2) To enable the Service Broker on your database

ALTER DATABASE Pubs SET ENABLE_BROKER
GO

3) Inform SQL Server that the user running IIS has permission to subscribe to query notificatoins.

GRANT SUBSCRIBE QUERY NOTIFICATIONS TO "IIS_SERVER\ASPNET"

4) Create a connectionStrings in the web.config

<connectionstrings>
<add name="myDbConnectionString" connectionstring="Data Source=localhost;Initial Catalog=MyDB;Integrated Security=True" providername="System.Data.SqlClient">
</connectionstrings>

5) Enable the website to be able to receive notifications.

protected void Application_Start(object sender, EventArgs e)
{
SqlDependency.Start(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
}

The following code also stops the listener:

protected void Application_End(object sender, EventArgs e)
{
SqlDependency.Stop(ConfigurationManager.ConnectionStrings["myDbConnectionString"].ConnectionString);
}

6) Sets up the cach dependency. Example code.

string tableName = query.Context.Mapping.GetTable(typeof(T)).TableName;
List result = HttpContext.Current.Cache[tableName] as List;

if (result == null)
{
using (SqlConnection cn = new SqlConnection(query.Context.Connection.ConnectionString))
{
cn.Open();
SqlCommand cmd = new SqlCommand(query.Context.GetCommand(query).CommandText, cn);
cmd.Notification = null;
cmd.NotificationAutoEnlist = true;
SqlCacheDependencyAdmin.EnableNotifications(query.Context.Connection.ConnectionString);
if (!SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(query.Context.Connection.ConnectionString).Contains(tableName))
{
SqlCacheDependencyAdmin.EnableTableForNotifications(query.Context.Connection.ConnectionString, tableName);
}

SqlCacheDependency dependency = new SqlCacheDependency(cmd);
cmd.ExecuteNonQuery();

result = query.ToList();
HttpContext.Current.Cache.Insert(tableName, result, dependency);
}
}

Friday, November 5, 2010

Re-Associate the dbo to sa login after db restored

You could use the following SQL script to relink the dbo user of a db to login.

ALTER AUTHORIZATION ON DATABASE::[db name] TO [login name]

Wednesday, October 27, 2010

Tuesday, October 26, 2010

Required components of IIS7.0 for installing SQL Server 2005 on Windows 7

When you try to install SQL Server 2005 on Window 7, you may receive the following warning message for the IIS Feature Requirement item on the System Configuration Check page in the SQL Server 2005 Setup program:

Microsoft Internet Information Services (IIS) is either not installed or is disabled. IIS is required by some SQL Server features. Without IIS, some SQL Server features will not be available for installation. To install all SQL Server features, install IIS from Add or Remove Programs in Control Panel or enable the IIS service through the Control Panel if it is already installed, and then run SQL Server Setup again. For a list of features that depend on IIS, see Features Supported by Editions of SQL Server in Books Online.

This problem occurs because not all the IIS 7.0 components that SQL Server depends on are installed on the computer. The following table lists the affected components.

Component
Folder
Static ContentCommon HTTP Features
Default DocumentCommon HTTP Features
HTTP RedirectionCommon HTTP Features
Directory BrowsingCommon HTTP Features
ASP.NetApplication Development
ISAPI ExtensionApplication Development
ISAPI FiltersApplication Development
Windows AuthenticationSecurity
IIS MetabaseManagement Tools
IIS 6 WMIManagement Tools

Monday, March 29, 2010

Add Date Time stamp to the Windows Backup File Name

1. Use the Windows Backup GUI interface to create a backup job. Make sure to
specify that it should not run now but later.

2. Open the Task Scheduler, then open the backup job that you just created.

3. Mark & copy the whole command line.

4. Create the new batch file "MyBackup.bat"

5. Paste the backup command line into it.

6. Create some blank lines at the top of the file, then paste the following
code into the empty space.

@echo off
set MyDate=%date:/=_%_%time::=_%
ntbackup /.. /.. /.. /F d:\Backups\%MyDate%_File_Backup.bkf

7. Adjust the last line of the above code so that it matches your own
switches, then remove the original Windows Backup command line.

8. Use the Task Scheduler to create a task that will invoke
"MyBackup.bat" instead of your previous Windows Backup command

Tuesday, February 23, 2010

SQL 2005 : Database Mail Setup

  1. Enable Database Mail feature via Surface Area Configuration for Features.
  2. In SSMS, Use Database Mail Configuratin Wizard to create account and profile.
  3. Select a default profile.
  4. Create Operator.
  5. If you would use Alert to notifiy operator, enable Mail Profile in Alert system option of SQL Server Agent.
  6. Restart the SQL Server Agent.
  7. You are ready to use Database Mail to notify the operator now.

ASP.NET Page Events Lifecycle

This is for my own reference purpose. The The original info comes from : http://weblogs.asp.net/ricardoperes/archive/2009/03/08/asp-net-page-events-lifecycle.aspx

When using master pages, the normal page event lifecycle is a little different. Here is the actual order:

  1. Page.OnPreInit
  2. MasterPageControl.OnInit (for each control on the master page)
  3. Control.OnInit (for each contol on the page)
  4. MasterPage.OnInit
  5. Page.OnInit
  6. Page.OnInitComplete
  7. Page.LoadPageStateFromPersistenceMedium
  8. Page.LoadViewState
  9. MasterPage.LoadViewState
  10. Page.OnPreLoad
  11. Page.OnLoad
  12. MasterPage.OnLoad
  13. MasterPageControl.OnLoad (for each control on the master page)
  14. Control.OnLoad (for each control on the page)
  15. OnXXX (control event)
  16. MasterPage.OnBubbleEvent
  17. Page.OnBubbleEvent
  18. Page.OnLoadComplete
  19. Page.OnPreRender
  20. MasterPage.OnPreRender
  21. MasterPageControl.OnPreRender (for each control on the master page)
  22. Control.OnPreRender (for each control on the page)
  23. Page.OnPreRenderComplete
  24. MasterPageControl.SaveControlState (for each control on the master page)
  25. Control.SaveControlState (for each control on the page)
  26. Page.SaveViewState
  27. MasterPage.SaveViewState
  28. Page.SavePageStateToPersistenceMedium
  29. Page.OnSaveStateComplete
  30. MasterPageControl.OnUnload (for each control on the master page)
  31. Control.OnUnload (for each control on the page)
  32. MasterPage.OnUnload
  33. Page.OnUnload

Friday, February 19, 2010

Steps to install dotProject

Add "dp_user" user to the MySQL.
1) Install Apache web server.

2) Install PHP to your web server.

PHP should support GD and MySQL

3) Install MySQL.

4) Add "dp_user" user to the MySQL.

5) Create a schema (Database) "dotproject" and assign user "dp_user" has full permission of this DB.

6) Copy all dotProject files to the htdocs folder.

- Open browser to access http://Your Domain/dotProject/install/index.php

- follow the step to complete the installation.

7) The default admin login is :

User Id : admin
Password : passwd