Wednesday, May 24, 2006

The documentation says to use the “Tools/Code Snippet Manager”. But I don’t have a Code Snippet Manager in my VS2005 IDE?
On the Tools menu, click Import ant Export Settings
Select Reset all settings
Click Next, Select Yes or No on the next page according to your preference
Click Next, Select Visual C# Development Settings
Click Finish

I want all the files located in a folder (folder name known & names of the files not known) to be copied to another location?
DirectoryInfo di = new DirectoryInfo(“foldername_with_complete_path”);
FileInfo[] fiList = di.GetFiles();
foreach(FileInfo fi in fiList)
{
File.Copy(fi, “NewDirName” + “\\” + fi.Name);
}


One of my services I am developing is depending on WMI. I am using WMI notifications and hardware enumeration. When my computer gets restarted my service loads up in a wrong order. It seems like my service is started before the WMI Service. Does anyone know how I can control the load order of my service?
Look into "ServiceInstaller.ServicesDependedOn" option at
http://msdn2.microsoft.com/en-us/system.serviceprocess.serviceinstaller.servicesdependedon.aspx

Wednesday, May 10, 2006

How to recover a deleted folder (shift+delete) from Outlook InBox.
246153 XCLN: How to Recover Items That Have Been Hard Deleted
http://support.microsoft.com/?id=246153
I guess this is set by default with OL2003. If deleted items are not being preserved on the Exchange server, you've got nothing.

I’ve written a media player and need to copy the window while in pause mode. 6 pack of fav beverage for solution.
Google is full of Pinvoke ([DllImport) samples, I’d prefer a GDI+ .net solution.
If you are using CLR 2.0, you can avoid PInvoke by using the Graphics::CopyFromScreen method.
http://msdn2.microsoft.com/en-us/library/system.drawing.graphics.copyfromscreen.aspx

When using terminal services client to connect to a server, how can you change the background?
On the machine with TS, go into TS Configuration, select Server Settings and Enable Active Desktop

I want users to download my content to their client computer rather than simply viewing it in the browser. But how do you override the browser's determination to render known MIME types itself?
Suppose you've written an ASP page that contains a link to a known MIME type, but you want the user to download the file instead of viewing it. Add the following to your script:
response.addHeader "content-disposition", "attachment;filename=filename.ext"
Then substitute the actual filename and extension, and it's as good as done.

Monday, April 24, 2006

How can I programmatically “grant permissions to a specific user to access a specific windows folder share”. using C#?
Using this library and the following code you can grant permissions to user for a folder share programmatically.
SecurityDescriptor desc = SecurityDescriptor.GetNamedSecurityInfo (

shareHandle,
SE_OBJECT_TYPE.SE_LMSHARE,
SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);
Dacl dacl = null;

if (desc == null)
{
desc = new SecurityDescriptor();
desc.AllocateAndInitializeSecurityDescriptor();
dacl = new Dacl();
}
else
{
dacl = desc.Dacl;
}

dacl.AddAce (new AceAccessAllowed (new Sid ("BUILTIN\\Administrators"), AccessType.GENERIC_ALL));
dacl.AddAce (new AceAccessAllowed (new Sid ("Everyone"),

AccessType.GENERIC_READ
AccessType.GENERIC_EXECUTE
AccessType.READ_CONTROL
AccessType.STANDARD_RIGHTS_READ));
desc.SetDacl(dacl);
desc.SetNamedSecurityInfo(faxShare,
SE_OBJECT_TYPE.SE_LMSHARE ,
SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);

A web page needs a read-only TextBox, the value of which will be set by client-side JavaScript (that pops up a picklist and chooses a value…). Users should not be able to modify the TextBox contents directly. To disable user input, we tried setting the TextBox’s properties “ReadOnly=true” and separately “Enabled=false”. This worked in ASP.Net 1.1.
However, ASP.NET 2.0, a security enhancement was made so that changes to values in ReadOnly or Disabled TextBoxes are ignored; the original value, stored in ViewState is presented on the server.
What is a valid work-around for this situation?
We added the HTML attribute “ReadOnly” to the TextBox manually, using code like:
TextBox1.Attributes.Add("ReadOnly", "true");
This ended up working: it appears that the browser respects the HTML tag, and ASP.NET is tricked into thinking the control is not read only. Is this the best workaround, or is there a better hook?

In ASP.NET 2.0 when you are using ReadOnly property, user can’t enter anything in textbox by any wayTo restrict user entry you should use:
TextBox1.Attributes.Add("contentEditable", "false");


We are using Forms Authentication.It was working fine for us until we started using a load balancer with three IIS boxes. We are not setting an encryption key anywhere. We are using the encryption provided by ASP.NET 2.0 We are getting the following exception now. I believe it is failing when consecutive requests are going to different IIS boxes and the different IIS boxes are not sharing an encryption key. Any idea?
Good start to resolve this would be: How To: Configure MachineKey in ASP.NET 2.0
More:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag2/html/paght000007.asp
What's New in ASP.NET Data Access
ASP.NET version 2.0 continues to offer managed data access using ADO.NET and managed classes for XML. But ASP.NET 2.0 also includes new features to make data access in Web pages easier to implement and manage.More: http://msdn2.microsoft.com/en-us/library/06t2w7da(VS.80).aspx


The Visual Studio 2005 Web Application Project Model
This is a new web project option for Visual Studio 2005 that provides the same conceptual web project approach as VS 2003 (a project file based structure where all code in the project is compiled into a single assembly) but with all the new features of VS 2005 (refactoring, class diagrams, test development, generics, etc) and ASP.NET 2.0 (master pages, data controls, membership/login, role management, Web Parts, personalization, site navigation, themes, etc). More: http://www.asp.net/webproject


Abortable thread pools
I want to share an excellent article on Abortable thread pools in March 2006 edition of MSDN mag.
http://msdn.microsoft.com/msdnmag/issues/06/03/NETMatters/

Tuesday, March 21, 2006

SQL Server 2005 introduces DDL Triggers

When you wanted to audit changes for the underlying schema in earlier versions of SQL Server and it was very difficult, now with SQL Server 2005 introduces DDL Triggers to address this issue. A DDL Trigger can now be created either at a server or database level and can be set to fire on creation, alteration, or deletion of virtually every SQL Server object type.

-- Example of DDL Trigger @ Database Level:
CREATE TRIGGER safety
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You must disable Trigger "safety" to drop or alter tables!'
ROLLBACK ;

In the next example, a DDL trigger prints a message if any CREATE LOGIN, ALTER LOGIN, or DROP LOGIN event occurs on the current server instance. It uses the EVENTDATA function to retrieve the text of the corresponding Transact-SQL statement.

-- Example of DDL Trigger @ Server Level:
CREATE TRIGGER ddl_trig_login
ON ALL SERVER
FOR DDL_LOGIN_EVENTS
AS
PRINT 'Login Event Issued.'
SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
GO
DROP TRIGGER ddl_trig_login
ON ALL SERVER
GO

Thursday, March 16, 2006

SQL 2005 - SQLCMD command-line tool

SQLCMD command-line tool allows you to pass variables from the command line into the SQL Script itself. In SQL 2005 now, you’ll can able to use SQLCMD as below example:
- Database build scripts where you need to pass values specific to a certain environment. - Hot fixes and patches.
- Any scenario where use of stored procedures (with it’s built-in parameters) is not an option and you must rely on a SQL script.
In this example SQLCMDTest.SQL [NOTE: That you must delimit character strings with a single quote]
declare @DaysToAdd datetime,
@MyString varchar(32)

SELECT @DaysToAdd =$(daystoAdd),
@MyString='$(mystring)'

SELECT GETDATE()+@DaysToAdd,
@MyString

Then, you call the SQL Script passing in the values as:
SQLCMD -b -w4000 -l10 -E -i"SQLCMDTest.sql" -v daystoAdd="10" -v mystring="CeltoGrass"

SQL 2005 - Share Job Schedule

With SQL Server 2005 you can now share job schedules that are owned by same user. In SQL Server 2005 Agent, User can create a single schedule (for instance, occurring every day at midnight), and attach it to one or more jobs, provided he is the owner of the jobs.

Consider the following example:
User1 creates a job called "Job1" with a schedule called "Schedule1". Since he was told only to run jobs starting at the time defined in Schedule1 by the product team, User1 wants to create his second job, called Job2, with this same schedule.


The simplest to do this would be from SQL Server Management Studio by clicking on the job schedule properties and selecting the "Pick" button which will allow him to select the schedules from the listed job. This would also allow User1 to view all the other jobs that has same schedule. He would be able to see only those jobs that were created by him unless he is a system administrator.

Monday, March 13, 2006

In SQL Server 2005 Implicit conversion from string to datetime (Ex: in "where" clause "where BirthDay='01/01/1980'") is considered not-deterministic and can't be present in Indexed View definition.
-- Example:
Create view v_test with SCHEMABINDING as
Select c1,c2 from dbo.t_test where c2 = '01/01/1980'
go
Create unique clustered index idx_v_test on v_test(c1)
go
-- Result:Cannot create index on view 'db_test.dbo.v_test' because the view uses an implicit
-- conversion from string to datetime or smalldatetime. Use an explicit CONVERT with a
-- deterministic style value.


-- Solution: You can use explicit conversion specifying style value for example:
Create view v_test with SCHEMABINDING as
Select c1,c2 from dbo.t_test where c2 = convert(datetime,'01/01/1980',120)
go

-- In this case string will be converted to datetime input as yyyy-mm-dd hh:mi:ss (24h).
Create unique clustered index idx_v_test on v_test(c1)
go
--Result:Command(s)
-- completed successfully.

In SQL Server 2005 Control permission is special cased. Control grant chains are always rooted at the owner unless you explicitly use an AS clause. This is to prevent orphaned grant arcs for other permissions that Control covers.
Example:
1. You give User1 Control permission on an object with GRANT OPTION;
2. User1 give User2 Control permission on the object;
3. You REVOKE Control permission on the object from User1 with CASCADE option.
4. User2 still have Control permission on the object.

Grant Control on T to usr1 WITH GRANT OPTION
go
Execute as user = 'usr1'
go
Grant Control on T to usr2
go
REVERT
go
Revoke Control on T from usr1 Cascade
go

-- Usr2 still has control permission on T. To be able to revoke control permission from all users
-- who's been given this permission by User1.

-- User1 should be specified explicitly when granting permission to User2:
Grant Control on T to usr2 AS usr1
go

SQL 2005 - OUTPUT clause with DML

SQL Server 2005 now introduces an OUTPUT clause as a part of DML statements that can help you in tracking changes made during any DML operation. The OUTPUT clause can save the resultset in a table or table variable. This functionality is similar to what triggers had with INSERTED and DELETED tables which used to access the rows that have been modified during the DML operation.

Example: Let's change the address from the address table to the reverse of the original value.
--Create the address table
Create Table Address (ProductID Int, SupplierID Int, Address Varchar(255))
--Insert data
Insert into Address Values (234,567,'1234 One SQL Way, Microsoft City, U.S.')
Insert into Address Values (345,678,'1234 One Windows Way, Microsoft City, WA')
--Declare a table variable
Declare @Recordchanges table (change Varchar(255))
--Update the address
Update Supplier.Address Set Address=reverse(address)
--Record the updates into the table variable
OUTPUT 'Original Value:' + DELETED.Address+' has been changed to: '+ INSERTED.Address+'' into @RecordChanges
--Query the changes from table variable
Select * from @RecordChanges

--Result-set
------------------------
Original Value:'1234 One SQL Way, City, U.S.' has been changed to: '.S.U ,ytiC,yaW LQS enO 4321'
Original Value:'1234 One Windows Way, City, WA' has been changed to: 'AW ,ytiC ,yaW swodniW enO 4321'

Query Notification in SQL 2005

Query Notification in SQL 2005 can be used to send a query to SQL Server and request that a notification be generated if executing the same query produces different results from those obtained initially. That means if any row in one of the tables included in the query is changed, .NET code will get an automatic notification.
MSDN Link:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnvs05/html/querynotification.asp

SQL 2005 - SYNONYMS

Remember how uneasy it was to write multiple queries which had four part object names
(ServerName.DatabaseName.OwnerName.ObjectName). Using SYNONYMS (new in SQL Server 2005) you can create an alias for objects.

Example:
-- Without SYNONYMS you would use the query the following way:
Select * from LongServerName.LongDatabaseName.LongOwnerName.LongObjectName
-- With SYNONYMS CREATE SYNONYM LNG FOR LongServerName.LongDatabaseName.LongOwnerName.LongObjectName
-- Once you create the SYNONYM you can use the above query as follows
Select * from LNG

SQL 2005 - Excute Remotely

Prior to SQL Server 2005 you could execute EXECUTE command only on the local server, with SQL Server 2005 we have AT parameter which can be used for executing the statement on a remote linked server.
Example: Setup a linked server using SP_AddLinkedServer:
-- Add the linked server to the local machine
EXEC sp_addlinkedserver 'SQLSERVER2', 'SQL Server'

--Enable the linked server to allow RPC calls
Exec SP_Serveroption 'SQLSERVER2','RPC OUT',TRUE

-- Now you are ready to execute T-SQL statements across linked servers using AT command
EXEC('Select * from AdventureWorksDW..DatabaseLog') AT SQLSERVER2

DBCC DBREINDEX - Deprecated

DBCC DBREINDEX is deprecated in SQL Server 2005. With SQL Server 2000 and earlier versions we used to use DBCC DBREINDEX for rebuilding/defragging/repairing indexes, etc. But with SQL Server 2005 this command is being deprecated.
SQL Server 2005 introduces ALTER INDEX command with REBUILD option.This command can help you perform ONLINE or OFFLINE re-indexing operations (not like DBCC DBREINDEX which was an offline operation only)

Tuesday, February 28, 2006

SQL statement along with its active SPIDS

Find out the actual SQL statement along with its active SPIDS that are currently running and not just the last statement sent to SQL server (as DBCC INPUTBUFFER displays). Below scripts will display the current activity of ALL spids that are currently active along with its SQL statements.

--SQL 2000 Syntax

SET NOCOUNT ON
GO
DECLARE
@SPID INT,
@last_Batch datetime,
@hostname varchar(32),
@loginame varchar(32),
@bHandle BINARY(20),
@stmt_start INT,
@stmt_end INT,
@waittime int

--Get spids in loop, only where there is some statement in the buffer.
SET @SPID=(SELECT MIN(SPID) FROM Master.dbo.SYSPROCESSES WHERE (stmt_start<>0 or stmt_end<>0) and SPID<>@@SPID)

WHILE @SPID IS NOT NULL
BEGIN
SELECT
@last_Batch=last_batch,
@hostname=hostname,
@loginame=loginame,
@bHandle=sql_handle,
@stmt_start = stmt_start/2,
@stmt_end = stmt_end/2,
@waittime = waittime
FROM
MASTER.DBO.SYSPROCESSES
WHERE SPID = @SPID AND ecid = 0

IF @stmt_end = 0
SELECT @SPID,@last_batch,
@hostname,
@loginame,
SUBSTRING(text,@stmt_start,8000)
FROM ::fn_get_sql(@bHandle)
ELSE
SELECT @SPID,@last_batch,
@hostname,
@loginame,
SUBSTRING(text,@stmt_start,@stmt_end - @stmt_start)
FROM ::fn_get_sql(@bHandle)

--GET NEXT SPID
SET @SPID=(SELECT MIN(SPID)
FROM Master.dbo.SYSPROCESSES
WHERE (stmt_start<>0 or stmt_end<>0)
AND SPID<>@@SPID
AND SPID>@SPID)
END
GO

--SQL 2005 Syntax
SELECT
s2.session_id,
s2.start_time,
s1.host_name,
s1.login_name,
s2.command,
s2.open_transaction_count,
(SELECT TOP 1 SUBSTRING(s3.text, statement_start_offset / 2,
((CASE WHEN statement_end_offset = -1 THEN
(LEN(CONVERT(nvarchar(max),s3.text)) * 2)
ELSE statement_end_offset
END) - statement_start_offset) / 2)) AS sql_statement
FROM Master.sys.dm_exec_sessions s1
INNER JOIN Master.sys.dm_exec_requests s2 on s1.session_id=s2.session_id
CROSS APPLY Master.sys.dm_exec_sql_text(s2.sql_handle) AS s3
WHERE s2.sql_handle is NOT NULL
AND s2.session_id<>@@SPID

SQL Server backup across more than one file

You can stripe a SQL Server’s database backup across more than one file. Striping a SQL Server backup across more than one backup file can provide performance advantages as well as make it possible to backup a VLDB where there is no single drive available with enough free space. Striped backups are supported in SQL Server 2000 & SQL Server 2005.

-- take a striped backup of the DB. Can be many more files than just two.
backup database northwind
to disk='\\Server1\t$\northwind1.bak',
disk='\\Server2\h$\northwind2.bak'

-- take a look at the logical files in the DB so we can move them on restore
restore filelistonly
from disk='\\Server1\t$\northwind1.bak',
disk='\\Server2\h$\northwind2.bak'

-- restore a DB from a striped backup
restore database northwind
from disk='\\Server1\t$\northwind1.bak',
disk='\\Server2\h$\northwind2.bak'
with move 'northwind_Data' to 't:\northwind2.mdf',
move 'northwind_Log' to 'h:\northwind2.ldf',
replace

Wednesday, February 22, 2006

GotDotNet Code Gallery

Are you looking for a place where you can share, find, download, evaluate and discuss evolving .NET applications, uncompiled code, ideas, and technical documents?
You have a greate place to go now, CodeGallery at
http://www.gotdotnet.com/codegallery/

Tuesday, February 21, 2006

SQL Server 2005 - Default Trace

SQL Server 2005 out of the box comes with a default trace that's always running which tracks configurational changes and process level information. You may obtain this information from SQL Server Management Studio by higlighting the registered server and selecting "Reports" from the summary page:

You will find:
Configuration change history
Schema Changes History
Memory Consumption
All Blocking Transactions
Top Sessions
Top Connections
Top Transactions by Age
Top Queries by Average CPU time
Top Queries by Average IO & lot of other information

You may also query the default trace file using the below query:
SELECT * FROM fn_trace_gettable ('C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\LOG\log.trc', default)

GO

SQL 2005 COPY_ONLY Backup

In SQL Server 2000 or it's earlier versions, if you perform a backup of a database out of sequence/chain (Full & Diffrential or Full & Log, etc) it used to break the sequence of the backups. Meaning you had to reset the backup sequence everytime you had to take a seperate out of sequence backups of the database. Taking a backup normally changes the database, in turn affecting other backups and how they are restored. Sometimes, however, a backup must be taken for a special purpose that should not affect the overall backup and restore sequence or procedures for the database.

With SQL Server 2005, you can now perform an out of sequence backups using "COPY_ONLY" option with the backup statement and this option is available for all types of backups.

Note:
A Full backup taken with the COPY_ONLY option cannot be used as a base backup and does not affect any existing differential backups.
A Diffrential backup taken with the COPY_ONLY option is identical to a regular diffrential backup.
A Log backup taken with COPY_ONLY option causes the backup to retain the current log archive point and also the Transaction log is not truncated by a log backup.
Important: SQL Server Management Studio does not support COPY_ONLY backup/restore functionality, but you can use BACKUP & RESTORE commands using T-SQL for COPY_ONLY backup of a database.
Example:
Backup database AdventureWorks to Disk='D:\AdventureWorks.bak' with COPY_ONLY