Mar 29, 2013

multiple config in c#

Introduction When building a console app, it is often necessary to provide various settings. Adding an app.config file to your project allows you to store all your settings in a file that is processed at runtime. When compiled, app.config becomes yourapp.exe.config. This is great until you need to run a large collection of different settings depending on the circumstance. There are a few ways I have seen to deal with this: Create a number of config files with the correct keys and before runtime, name the config file you want to use as yourapp.exe.config. Workable, but since you are always renaming files, it may become difficult to determine which settings have been run and which have not. Create custom tags in the app.config (see simple two-dimensional configuration file), then via another key set which section is the setting you want during the current run. This is the solution I have seen a number of times on the Internet. This is a workable solution, but it can lead to unwieldy app.config files, depending on the number of keys and configurations. I was not satisfied with both of these solutions. What I wanted was the ability to specify at runtime which config file to use. In this way, I can keep settings for different configurations neatly separated. Here is how I did this. A Console App Collapse | Copy Code using System; using System.Configuration; using System.Collections.Generic; using System.IO; using System.Text; using System.Data; using System.Data.SqlClient; using System.Net; namespace yournamepace { class Program { static void Main(string[] args) { // get config file from runtime args // or if none provided, request config // via console setConfigFileAtRuntime(args); // Rest of your console app } } protected static void setConfigFileAtRuntime(string[] args) { string runtimeconfigfile; if (args.Length == 0) { Console.WriteLine("Please specify a config file:"); Console.Write("> "); // prompt runtimeconfigfile = Console.ReadLine(); } else { runtimeconfigfile = args[0]; } // Specify config settings at runtime. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); config.AppSettings.File = runtimeconfigfile; config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); } } app.config Collapse | Copy Code Typical Runtime Config File 1 Collapse | Copy Code Typical Runtime Config File 2 Collapse | Copy Code Now, at runtime, you do the following from the command prompt: Collapse | Copy Code c:\> yourapp.exe myruntimeconfigfile1.config c:\> yourapp.exe myruntimeconfigfile2.config Or just double click yourapp.exe, and you will be prompted for a config file. original post http://www.codeproject.com/Articles/14465/Specify-a-Configuration-File-at-Runtime-for-a-C-Co

Feb 1, 2013

How to Automate Database Backups with SQL Server Express

original post at http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=ExpressBackups Jonathan Kehayias, May 1, 2008 One of the items missing from SQL Server Express is the ability to schedule jobs to run at set times since it lacks the SQL Server Agent Service. This makes scheduling automated backups of the databases in a SQL Express Instance difficult to do, though not impossible. There are a more than a few ways to go about creating backups of the databases in SQL Express and this article offers what should be a very easy to implement solution. In order to perform the backups, the following stored procedure will need to be created in a database on your SQL Instance. Make sure that you know where this procedure is created because this is important in later steps. Create Dependent Stored Procedure CREATE PROCEDURE [dbo].[BackupDatabases] ( @BackupDir varchar(400), @DatabaseName sysname = null, @BackupType int = 0 -- 0=Full, 1=Differential, 2=Log ) AS -- -- Begin Test Code -- DECLARE @BackupDir varchar(400) -- SET @BackupDir = 'D:\SQLBackups\Daily\' -- -- End Test Code -- Create worker table DECLARE @DBNames TABLE ( RowID int IDENTITY PRIMARY KEY, DBName varchar(500) ) -- Grab the Database Names from master DB INSERT INTO @DBNames (DBName) SELECT Name FROM master.sys.databases WHERE name = @DatabaseName OR @DatabaseName IS NULL ORDER BY Name -- The below databases are not valid to backup IF @BackupType = 0 BEGIN DELETE @DBNames WHERE DBName IN ('tempdb', 'NorthWind', 'pubs') END ELSE IF @BackupType = 1 BEGIN DELETE @DBNames WHERE DBName IN ('tempdb', 'NorthWind', 'pubs', 'master') END ELSE IF @BackupType = 2 BEGIN DELETE @DBNames WHERE DBName IN ('tempdb', 'NorthWind', 'pubs', 'master', 'msdb', 'model') END IF (@BackupType < 0 OR @BackupType > 2) OR NOT EXISTS (SELECT 1 FROM @DBNames) BEGIN RETURN; END -- Declare Session Variables DECLARE @Now datetime DECLARE @TodayStr varchar(20) DECLARE @BackupName varchar(100) DECLARE @BackupFile varchar(100) DECLARE @DBName varchar(300) DECLARE @LogFileName varchar(300) DECLARE @SQL varchar(2000) DECLARE @Loopvar int -- Begin looping over Databases in the Work Table SELECT @Loopvar = min(rowID) FROM @DBNames WHILE @Loopvar IS NOT NULL BEGIN -- Database Names have to have [dbname] format since some names have a - or _ in the name SET @DBName = '['+(SELECT DBName FROM @DBNames WHERE RowID = @LoopVar)+']' -- Set the current date and time SET @Now = getdate() -- Create backup file date and time in DOS format yyyy_hhmmss Set @TodayStr = convert(varchar, @Now, 112)+ '_'+replace(convert(varchar, @Now, 108), ':', '') -- Create a variable holding the total path\filename.ext for the log backup Set @BackupFile = @BackupDir+REPLACE(REPLACE(@DBName, '[',''), ']','')+'-'+ @TodayStr + '-FULL.BAK' -- Provide the backup a SQL name and name in media Set @BackupName = REPLACE(REPLACE(@DBName, '[',''), ']','')+' full backup for ' + @TodayStr -- Generate the Dynamic SQL script variable to be executed IF @BackupType = 0 BEGIN SET @SQL = 'BACKUP DATABASE ' + @DBName + ' TO DISK = ''' + @BackupFile + ''' WITH INIT, NAME = ''' +@BackupName+''', NOSKIP, NOFORMAT' END ELSE IF @BackupType = 1 BEGIN SET @SQL = 'BACKUP DATABASE ' + @DBName + ' TO DISK = ''' + @BackupFile + ''' WITH DIFFERENTIAL, INIT, NAME = ''' +@BackupName+''', NOSKIP, NOFORMAT' END ELSE IF @BackupType = 2 BEGIN SET @SQL = 'BACKUP LOG ' + @DBName + ' TO DISK = ''' + @BackupFile + ''' WITH INIT, NAME = ''' +@BackupName+''' , NOSKIP, NOFORMAT' END -- Execute the SQL Command EXEC(@SQL) -- Goto the Next Database SELECT @Loopvar = min(rowID) FROM @DBNames WHERE RowID > @LoopVar END /* -- Execute Full Backup of all databases in local named instance of EXPRESS -- to D:\SQLBackups\ using Windows Authentication sqlcmd -S .\EXPRESS -Q "EXEC BackupDatabases @BackupDir='D:\SQLBackups\', @BackupType=0" -- Execute Differential Backup of all databases in local named instance of SQLEXPRESS -- to D:\SQLBackups\Differentials\ using SQL Login BackupUser with Password password. sqlcmd -U BackupUser -P password -S .\SQLEXPRESS -Q "EXEC BackupDatabases @BackupDir='D:\SQLBackups\Differentials\', @BackupType=1" -- Execute Log Backup of all databases in local named instance of EXPRESS -- to D:\SQLBackups\TLogs\ using Windows Authentication sqlcmd -S .\SQLEXPRESS -Q "EXEC BackupDatabases @BackupDir='D:\SQLBackups\TLogs\', @BackupType=2" -- Execute Full Backup of the WebContacts Database in local named instance of EXPRESS -- to D:\SQLBackups\ using Windows Authentication sqlcmd -S .\EXPRESS -Q "EXEC BackupDatabases @BackupDir='D:\SQLBackups\', @DatabaseName='WebContacts', @BackupType=0" */ Return to Top There is a sample usage section at the bottom of this stored procedure in comments, that exists as a reference for its use if there is ever a need to review how it can be called from the operating system. Once this procedure has been created, it can be called from the operating system with the use of the sqlcmd executable. The folder for this executable is generally in the Path variables for the server after SQL is installed, but in case it is not it is located in \90\Tools\Binn. (generally C:\Program Files\Microsoft SQL Server\90\Tools\Binn) The next decision to be made is under what context or security account will the backups be run. Since we will be using the Task Scheduler to run the backups through a batch file we will create momentarily, you have the option to run this under a windows login account. The account will require the BackupOperator Role at a minimum. To test that you have created the user account and configured it correctly, you can run either one of the following commands from the command prompt. To Use Windows Authentication sqlcmd -S .\SQLEXPRESS -Q "EXEC BackupDatabases @BackupDir='c:\', @DatabaseName='master', @BackupType=0" To Use SQL Authentication sqlcmd -U BackupUser -P password -S .\SQLEXPRESS -Q "EXEC BackupDatabases @BackupDir='c:\', @DatabaseName='master', @BackupType=0" If this is all configured correctly, you will have a file beginning with master and ending in FULL.BAK in the root c:\ folder. If this completes successfully, open Notepad up inside of Windows, and paste the corresponding command for what you want done into the file. To save it as a batch file, select File -> Save As, and change the File Type from *.txt to . then put in the filename SQLBackups.bat, and save it to the path where you want it to be maintained from. Then open up the Windows Task Scheduler which is generally in Start -> Programs -> Accessories -> System Tools -> Scheduled Tasks. Create a new Scheduled Task, and point it to the Batch file you just save for its execution. Create the desired schedule for it to run, and then specify the user account that this schedule will run under. If you are using Windows Authentication, it should be the same account that you were logged in with in the tests above. Once you have done this, save the schedule, and you now have an automated backup process for SQL Express. You can expand upon this by creating multiple batch files, one for Full Backups Weekly, one for Daily Differential Backups, and perhaps one for backing up the Transaction Log every four hours. Then you create schedules for each type of backup and you have now implemented Full Recovery for your SQL Express Database Instance. For additional information please see: Performing Common Maintenance Tasks in SQL Express sqlcmd Utility Tutorial http://msdn2.microsoft.com/en-us/library/ms170207.aspx How to: Create a Full Database Backup (Transact-SQL) http://msdn2.microsoft.com/en-us/library/ms191304.aspx How to: Create a Transaction Log Backup (Transact-SQL) http://msdn2.microsoft.com/en-us/library/ms191284.aspx ___________________________________________________________________________________________________________________ Page Created By: Jonathan Kehayias, May 1, 2008

Dec 10, 2012

Database space used

EXECUTE sp_spaceused ur_table; EXECUTE sp_MSforeachtable 'EXECUTE sp_spaceused [?];';

Remote Desktop Connection Manager-RDCMan

You could connect and work multiple remote session at once in a single screen!!!. For Download http://www.microsoft.com/en-us/download/details.aspx?id=21101 For demo video http://www.youtube.com/watch?v=qVTAHo-uUAw Kindly think about the security risk before configure all the remote screens at a single file.

xcopy for fast copy

xcopy c:\dbbk\*.* \\tsclient\e\*.* /E /R /K /Y use this method to copy files from remote or other places. It would be faster than other methods.

Jan 25, 2011

getting backup details

--query 1
SELECT sdb.Name AS DatabaseName,
COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name

--query 2

-- for single db back up history

DECLARE @db_name VARCHAR(100)
SELECT @db_name = DB_NAME()

-- Get Backup History for required database

SELECT TOP ( 30 )
s.database_name,
m.physical_device_name,
cast(CAST(s.backup_size / 1000000 AS INT) as varchar(14))
+ ' ' + 'MB' as bkSize,
CAST(DATEDIFF(second, s.backup_start_date,
s.backup_finish_date) AS VARCHAR(4)) + ' '
+ 'Seconds' TimeTaken,
s.backup_start_date,
CAST(s.first_lsn AS varchar(50)) AS first_lsn,
CAST(s.last_lsn AS varchar(50)) AS last_lsn,
'BackupType'=CASE s.[type]
WHEN 'D' THEN 'Full'
WHEN 'I' THEN 'Differential'
WHEn 'L' THEN 'Transaction Log'
END ,
s.server_name,
s.recovery_model
FROM msdb.dbo.backupset s
inner join msdb.dbo.backupmediafamily m ON s.media_set_id = m.media_set_id
WHERE s.database_name = @db_name
ORDER BY backup_start_date desc,
backup_finish_date

Dec 29, 2010

How to compare two tables in databases

/*
use DMNDB
SELECT
OBJ.NAME as TableName into #dmndbTables
FROM
SYSOBJECTS OBJ
WHERE
OBJ.TYPE = 'U'
go
use DMNqa
SELECT
OBJ.NAME as TableName into #dmnqaTables
FROM
SYSOBJECTS OBJ
WHERE
OBJ.TYPE = 'U'

*/
go

select TableName AS dmndbTables FROM #dmndbTables WHERE TableName NOT IN (SELECT TableName FROM #dmnqaTables)

select TableName AS dmnQATables FROM #dmnQATables WHERE TableName NOT IN (SELECT TableName FROM #dmnDBTables)

---------------------
--we can get table columns
CREATE VIEW V_ALL_USERTABLE_COLUMNS
AS
(
SELECT
OBJ.NAME as TableName,
COL.NAME as ColName,
TYP.NAME AS TYPE

FROM
SYSOBJECTS OBJ,
SYSCOLUMNS COL,
SYSTYPES TYP

WHERE
OBJ.TYPE = 'U'
AND OBJ.ID = COL.ID
AND COL.TYPE = TYP.TYPE
)