Introduction

In this article, we are going to learn the process of getting the database backup in C# WinForm application using Stored Procedure.

Create Tables and Stored Procedure

First, we create two tables to store database backup info.
Open SQL Server to create a database with any suitable name and then, create two tables and a stored procedure.
Here, I am using DemoTest as the database name and tblBackupInfo and tblBackupDetails as the tables name.
Tables Structure
  1. CREATE TABLE [dbo].[tblBackupInfo](
  2. [IID] [int] IDENTITY(1,1) NOT NULL,
  3. [DayInterval] [int] NULL,
  4. [NoOfFiles] [int] NULL,
  5. [DatabaseName] [nvarchar](500) NULL,
  6. [Location] [nvarchar](max) NULL,
  7. [SoftwareDate] [datetime] NULL,
  8. [LastEditDate] [datetime] NULL,
  9. [CreationDate] [datetime] NOT NULL
  10. )
  11. CREATE TABLE [dbo].[tblBackupDetails](
  12. [IID] [int] IDENTITY(1,1) NOT NULL,
  13. [BackupName] [varchar](50) NULL,
  14. [Location] [varchar](500) NULL,
  15. [BackupDate] [datetime] NULL,
  16. [BackupType] [varchar](50) NULL,
  17. [CreationDate] [datetime] NOT NULL
  18. )
Stored Procedure
  1. CREATE PROCEDURE [dbo].[DATABASE_BACKUP]
  2. (
  3. @DatabaseName VARCHAR(1000) = NULL,
  4. @Location VARCHAR(1000) = NULL,
  5. @Type VARCHAR(25) = NULL,
  6. @BackupName VARCHAR(500) = NULL,
  7. @FILEPATH VARCHAR(2000) = NULL,
  8. @DATABASE VARCHAR(1000) = NULL,
  9. @DayInterval INT = NULL,
  10. @NoOfFiles INT = NULL,
  11. @SoftwareDate DATE = NULL,
  12. @ACTIONTYPE VARCHAR(50)
  13. )
  14. AS
  15. BEGIN
  16. IF @ACTIONTYPE = 'BACKUP_INFO'
  17. BEGIN
  18. SELECT DATABASENAME,ISNULL(NoOfFiles,0) AS NoOfFiles,LOCATION,DayInterval FROM tblBackupInfo
  19. SELECT TOP 1 BackupType,BackupDate,Location FROM tblBackupDetails ORDER BY IID DESC
  20. END
  21. IF @ACTIONTYPE = 'INSERT_BACKUP_INFO'
  22. BEGIN
  23. IF NOT EXISTS (SELECT * FROM tblBackupInfo)
  24. BEGIN
  25. INSERT INTO tblBackupInfo (DayInterval,NoOfFiles,DatabaseName,Location,SoftwareDate,CreationDate)
  26. VALUES (@DayInterval,@NoOfFiles,@DatabaseName,@Location,@SoftwareDate,GETDATE())
  27. END
  28. ELSE
  29. BEGIN
  30. UPDATE tblBackupInfo SET DayInterval=@DayInterval,NoOfFiles=@NoOfFiles,DatabaseName=@DatabaseName,
  31. Location=@Location,SoftwareDate=@SoftwareDate,LastEditDate=GETDATE()
  32. END
  33. END
  34. IF @ACTIONTYPE = 'DB_BACKUP'
  35. BEGIN
  36. BEGIN TRY
  37. BACKUP DATABASE @DATABASE
  38. TO DISK = @FILEPATH;
  39. INSERT INTO tblBackupDetails VALUES(@BackupName,@FILEPATH,@SoftwareDate,@Type,GETDATE())
  40. END TRY
  41. BEGIN CATCH
  42. SELECT ERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,
  43. ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage;
  44. END CATCH
  45. END
  46. IF @ACTIONTYPE = 'REMOVE_LOCATION'
  47. BEGIN
  48. SELECT Location FROM tblBackupDetails WHERE IID NOT IN (
  49. SELECT TOP (SELECT NoOfFiles FROM tblBackupInfo) IID FROM tblBackupDetails ORDER BY IID DESC)
  50. END
  51. END

Creating Window Application

After successfully creating tables and stored procedure, now, let us move to the Windows application.
Open Visual Studio and create a Windows application named as “DBBACKUP”. Delete the default form “Form1” and add a new form named as “FrmDbBackup”. Design the form like the image given below.
Code For FrmBackup.Designer.cs
  1. namespace DBBACKUP
  2. {
  3. partial class FrmDbBackup
  4. {
  5. /// <summary>
  6. /// Required designer variable.
  7. /// </summary>
  8. private System.ComponentModel.IContainer components = null;
  9. /// <summary>
  10. /// Clean up any resources being used.
  11. /// </summary>
  12. /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  13. protected override void Dispose(bool disposing)
  14. {
  15. if (disposing && (components != null))
  16. {
  17. components.Dispose();
  18. }
  19. base.Dispose(disposing);
  20. }
  21. #region Windows Form Designer generated code
  22. /// <summary>
  23. /// Required method for Designer support - do not modify
  24. /// the contents of this method with the code editor.
  25. /// </summary>
  26. private void InitializeComponent()
  27. {
  28. this.components = new System.ComponentModel.Container();
  29. this.Label21 = new System.Windows.Forms.Label();
  30. this.btnClose = new System.Windows.Forms.Button();
  31. this.Panel1 = new System.Windows.Forms.Panel();
  32. this.Label9 = new System.Windows.Forms.Label();
  33. this.ProgressBarEx5 = new System.Windows.Forms.ProgressBar();
  34. this.label6 = new System.Windows.Forms.Label();
  35. this.txtDbName = new System.Windows.Forms.TextBox();
  36. this.label5 = new System.Windows.Forms.Label();
  37. this.label4 = new System.Windows.Forms.Label();
  38. this.label3 = new System.Windows.Forms.Label();
  39. this.DateTimePicker1 = new System.Windows.Forms.DateTimePicker();
  40. this.Label8 = new System.Windows.Forms.Label();
  41. this.LinkLabel1 = new System.Windows.Forms.LinkLabel();
  42. this.Label7 = new System.Windows.Forms.Label();
  43. this.btnSave = new System.Windows.Forms.Button();
  44. this.btnBackup = new System.Windows.Forms.Button();
  45. this.label13 = new System.Windows.Forms.Label();
  46. this.label22 = new System.Windows.Forms.Label();
  47. this.label20 = new System.Windows.Forms.Label();
  48. this.Timer1 = new System.Windows.Forms.Timer(this.components);
  49. this.FolderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
  50. this.linkLabel2 = new System.Windows.Forms.Label();
  51. this.linkLabel3 = new System.Windows.Forms.Label();
  52. this.label1 = new System.Windows.Forms.Label();
  53. this.txtSpan = new System.Windows.Forms.TextBox();
  54. this.txtNoOfFiles = new System.Windows.Forms.TextBox();
  55. this.label2 = new System.Windows.Forms.Label();
  56. this.label10 = new System.Windows.Forms.Label();
  57. this.label11 = new System.Windows.Forms.Label();
  58. this.label12 = new System.Windows.Forms.Label();
  59. this.lblLastBackupInfo = new System.Windows.Forms.Label();
  60. this.Panel1.SuspendLayout();
  61. this.SuspendLayout();
  62. //
  63. // Label21
  64. //
  65. this.Label21.BackColor = System.Drawing.Color.SteelBlue;
  66. this.Label21.Dock = System.Windows.Forms.DockStyle.Top;
  67. this.Label21.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  68. this.Label21.ForeColor = System.Drawing.Color.White;
  69. this.Label21.Location = new System.Drawing.Point(0, 0);
  70. this.Label21.Name = "Label21";
  71. this.Label21.Size = new System.Drawing.Size(542, 25);
  72. this.Label21.TabIndex = 3;
  73. this.Label21.Text = "BACKUP SETTINGS";
  74. this.Label21.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
  75. //
  76. // btnClose
  77. //
  78. this.btnClose.BackColor = System.Drawing.Color.SteelBlue;
  79. this.btnClose.FlatAppearance.BorderSize = 0;
  80. this.btnClose.FlatAppearance.MouseDownBackColor = System.Drawing.Color.MistyRose;
  81. this.btnClose.FlatAppearance.MouseOverBackColor = System.Drawing.Color.MistyRose;
  82. this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  83. this.btnClose.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  84. this.btnClose.ForeColor = System.Drawing.Color.White;
  85. this.btnClose.Location = new System.Drawing.Point(513, 0);
  86. this.btnClose.Name = "btnClose";
  87. this.btnClose.Size = new System.Drawing.Size(28, 24);
  88. this.btnClose.TabIndex = 1284;
  89. this.btnClose.TabStop = false;
  90. this.btnClose.Text = "X ";
  91. this.btnClose.UseVisualStyleBackColor = false;
  92. this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
  93. //
  94. // Panel1
  95. //
  96. this.Panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
  97. this.Panel1.Controls.Add(this.Label9);
  98. this.Panel1.Controls.Add(this.ProgressBarEx5);
  99. this.Panel1.Location = new System.Drawing.Point(58, 138);
  100. this.Panel1.Name = "Panel1";
  101. this.Panel1.Size = new System.Drawing.Size(446, 117);
  102. this.Panel1.TabIndex = 1354;
  103. this.Panel1.Visible = false;
  104. //
  105. // Label9
  106. //
  107. this.Label9.AutoSize = true;
  108. this.Label9.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  109. this.Label9.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  110. this.Label9.Location = new System.Drawing.Point(9, 23);
  111. this.Label9.Name = "Label9";
  112. this.Label9.Size = new System.Drawing.Size(240, 17);
  113. this.Label9.TabIndex = 33;
  114. this.Label9.Text = "Database Backup Initialize, Please Wait...";
  115. //
  116. // ProgressBarEx5
  117. //
  118. this.ProgressBarEx5.Location = new System.Drawing.Point(12, 50);
  119. this.ProgressBarEx5.Name = "ProgressBarEx5";
  120. this.ProgressBarEx5.Size = new System.Drawing.Size(421, 18);
  121. this.ProgressBarEx5.TabIndex = 33;
  122. this.ProgressBarEx5.Visible = false;
  123. //
  124. // label6
  125. //
  126. this.label6.AutoSize = true;
  127. this.label6.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  128. this.label6.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  129. this.label6.Location = new System.Drawing.Point(24, 332);
  130. this.label6.Name = "label6";
  131. this.label6.Size = new System.Drawing.Size(102, 17);
  132. this.label6.TabIndex = 1360;
  133. this.label6.Text = "Database Name";
  134. //
  135. // txtDbName
  136. //
  137. this.txtDbName.Location = new System.Drawing.Point(175, 114);
  138. this.txtDbName.Name = "txtDbName";
  139. this.txtDbName.Size = new System.Drawing.Size(289, 25);
  140. this.txtDbName.TabIndex = 1359;
  141. //
  142. // label5
  143. //
  144. this.label5.AutoSize = true;
  145. this.label5.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  146. this.label5.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  147. this.label5.Location = new System.Drawing.Point(24, 117);
  148. this.label5.Name = "label5";
  149. this.label5.Size = new System.Drawing.Size(113, 17);
  150. this.label5.TabIndex = 1358;
  151. this.label5.Text = "Database Name : ";
  152. //
  153. // label4
  154. //
  155. this.label4.AutoSize = true;
  156. this.label4.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  157. this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  158. this.label4.Location = new System.Drawing.Point(24, 307);
  159. this.label4.Name = "label4";
  160. this.label4.Size = new System.Drawing.Size(78, 17);
  161. this.label4.TabIndex = 1356;
  162. this.label4.Text = "Backup Path";
  163. //
  164. // label3
  165. //
  166. this.label3.AutoSize = true;
  167. this.label3.Enabled = false;
  168. this.label3.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  169. this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  170. this.label3.Location = new System.Drawing.Point(394, 30);
  171. this.label3.Name = "label3";
  172. this.label3.Size = new System.Drawing.Size(47, 17);
  173. this.label3.TabIndex = 1355;
  174. this.label3.Text = "Date : ";
  175. //
  176. // DateTimePicker1
  177. //
  178. this.DateTimePicker1.Enabled = false;
  179. this.DateTimePicker1.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  180. this.DateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Short;
  181. this.DateTimePicker1.Location = new System.Drawing.Point(438, 26);
  182. this.DateTimePicker1.Name = "DateTimePicker1";
  183. this.DateTimePicker1.Size = new System.Drawing.Size(100, 25);
  184. this.DateTimePicker1.TabIndex = 1348;
  185. //
  186. // Label8
  187. //
  188. this.Label8.AutoSize = true;
  189. this.Label8.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  190. this.Label8.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  191. this.Label8.Location = new System.Drawing.Point(8, 273);
  192. this.Label8.Name = "Label8";
  193. this.Label8.Size = new System.Drawing.Size(156, 25);
  194. this.Label8.TabIndex = 1353;
  195. this.Label8.Text = "Manually Backup";
  196. //
  197. // LinkLabel1
  198. //
  199. this.LinkLabel1.AutoSize = true;
  200. this.LinkLabel1.Location = new System.Drawing.Point(173, 63);
  201. this.LinkLabel1.Name = "LinkLabel1";
  202. this.LinkLabel1.Size = new System.Drawing.Size(0, 17);
  203. this.LinkLabel1.TabIndex = 1352;
  204. this.LinkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.LinkLabel1_LinkClicked);
  205. //
  206. // Label7
  207. //
  208. this.Label7.AutoSize = true;
  209. this.Label7.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  210. this.Label7.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  211. this.Label7.Location = new System.Drawing.Point(24, 63);
  212. this.Label7.Name = "Label7";
  213. this.Label7.Size = new System.Drawing.Size(132, 17);
  214. this.Label7.TabIndex = 1351;
  215. this.Label7.Text = "Save Directory Path : ";
  216. //
  217. // btnSave
  218. //
  219. this.btnSave.BackColor = System.Drawing.Color.White;
  220. this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  221. this.btnSave.Font = new System.Drawing.Font("Segoe UI Semibold", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  222. this.btnSave.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  223. this.btnSave.Location = new System.Drawing.Point(223, 153);
  224. this.btnSave.Name = "btnSave";
  225. this.btnSave.Size = new System.Drawing.Size(89, 25);
  226. this.btnSave.TabIndex = 1349;
  227. this.btnSave.Text = "Save";
  228. this.btnSave.UseVisualStyleBackColor = false;
  229. this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
  230. //
  231. // btnBackup
  232. //
  233. this.btnBackup.BackColor = System.Drawing.Color.White;
  234. this.btnBackup.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
  235. this.btnBackup.Font = new System.Drawing.Font("Segoe UI Semibold", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  236. this.btnBackup.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  237. this.btnBackup.Image = global::DBBACKUP.Properties.Resources.database;
  238. this.btnBackup.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
  239. this.btnBackup.Location = new System.Drawing.Point(367, 352);
  240. this.btnBackup.Name = "btnBackup";
  241. this.btnBackup.Size = new System.Drawing.Size(137, 33);
  242. this.btnBackup.TabIndex = 1350;
  243. this.btnBackup.Text = "Backup Database";
  244. this.btnBackup.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
  245. this.btnBackup.UseVisualStyleBackColor = false;
  246. this.btnBackup.Click += new System.EventHandler(this.btnBackup_Click);
  247. //
  248. // label13
  249. //
  250. this.label13.BackColor = System.Drawing.Color.SteelBlue;
  251. this.label13.Dock = System.Windows.Forms.DockStyle.Right;
  252. this.label13.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  253. this.label13.Location = new System.Drawing.Point(540, 25);
  254. this.label13.Name = "label13";
  255. this.label13.Size = new System.Drawing.Size(2, 365);
  256. this.label13.TabIndex = 1362;
  257. //
  258. // label22
  259. //
  260. this.label22.BackColor = System.Drawing.Color.SteelBlue;
  261. this.label22.Dock = System.Windows.Forms.DockStyle.Bottom;
  262. this.label22.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  263. this.label22.Location = new System.Drawing.Point(0, 388);
  264. this.label22.Name = "label22";
  265. this.label22.Size = new System.Drawing.Size(540, 2);
  266. this.label22.TabIndex = 1363;
  267. //
  268. // label20
  269. //
  270. this.label20.BackColor = System.Drawing.Color.SteelBlue;
  271. this.label20.Dock = System.Windows.Forms.DockStyle.Left;
  272. this.label20.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  273. this.label20.Location = new System.Drawing.Point(0, 25);
  274. this.label20.Name = "label20";
  275. this.label20.Size = new System.Drawing.Size(2, 363);
  276. this.label20.TabIndex = 1364;
  277. //
  278. // Timer1
  279. //
  280. this.Timer1.Tick += new System.EventHandler(this.Timer1_Tick);
  281. //
  282. // FolderBrowserDialog1
  283. //
  284. this.FolderBrowserDialog1.SelectedPath = "C:\\ProgramData\\PRM System\\Backup\\";
  285. //
  286. // linkLabel2
  287. //
  288. this.linkLabel2.AutoSize = true;
  289. this.linkLabel2.Location = new System.Drawing.Point(134, 307);
  290. this.linkLabel2.Name = "linkLabel2";
  291. this.linkLabel2.Size = new System.Drawing.Size(0, 17);
  292. this.linkLabel2.TabIndex = 1365;
  293. //
  294. // linkLabel3
  295. //
  296. this.linkLabel3.AutoSize = true;
  297. this.linkLabel3.Location = new System.Drawing.Point(134, 332);
  298. this.linkLabel3.Name = "linkLabel3";
  299. this.linkLabel3.Size = new System.Drawing.Size(0, 17);
  300. this.linkLabel3.TabIndex = 1366;
  301. //
  302. // label1
  303. //
  304. this.label1.AutoSize = true;
  305. this.label1.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  306. this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  307. this.label1.Location = new System.Drawing.Point(24, 88);
  308. this.label1.Name = "label1";
  309. this.label1.Size = new System.Drawing.Size(156, 17);
  310. this.label1.TabIndex = 1367;
  311. this.label1.Text = "Auto Backup Time Span : ";
  312. //
  313. // txtSpan
  314. //
  315. this.txtSpan.Location = new System.Drawing.Point(175, 85);
  316. this.txtSpan.MaxLength = 2;
  317. this.txtSpan.Name = "txtSpan";
  318. this.txtSpan.Size = new System.Drawing.Size(57, 25);
  319. this.txtSpan.TabIndex = 1368;
  320. this.txtSpan.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSpan_KeyPress);
  321. //
  322. // txtNoOfFiles
  323. //
  324. this.txtNoOfFiles.Location = new System.Drawing.Point(373, 85);
  325. this.txtNoOfFiles.MaxLength = 2;
  326. this.txtNoOfFiles.Name = "txtNoOfFiles";
  327. this.txtNoOfFiles.Size = new System.Drawing.Size(57, 25);
  328. this.txtNoOfFiles.TabIndex = 1370;
  329. this.txtNoOfFiles.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSpan_KeyPress);
  330. //
  331. // label2
  332. //
  333. this.label2.AutoSize = true;
  334. this.label2.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  335. this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  336. this.label2.Location = new System.Drawing.Point(240, 89);
  337. this.label2.Name = "label2";
  338. this.label2.Size = new System.Drawing.Size(136, 17);
  339. this.label2.TabIndex = 1369;
  340. this.label2.Text = "No Of Files To Keep : ";
  341. //
  342. // label10
  343. //
  344. this.label10.AutoSize = true;
  345. this.label10.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  346. this.label10.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  347. this.label10.Location = new System.Drawing.Point(8, 28);
  348. this.label10.Name = "label10";
  349. this.label10.Size = new System.Drawing.Size(126, 25);
  350. this.label10.TabIndex = 1371;
  351. this.label10.Text = "Backup Setup";
  352. //
  353. // label11
  354. //
  355. this.label11.BackColor = System.Drawing.Color.LightGray;
  356. this.label11.Font = new System.Drawing.Font("Times New Roman", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  357. this.label11.Location = new System.Drawing.Point(0, 190);
  358. this.label11.Name = "label11";
  359. this.label11.Size = new System.Drawing.Size(540, 2);
  360. this.label11.TabIndex = 1372;
  361. //
  362. // label12
  363. //
  364. this.label12.AutoSize = true;
  365. this.label12.Font = new System.Drawing.Font("Segoe UI", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  366. this.label12.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  367. this.label12.Location = new System.Drawing.Point(8, 196);
  368. this.label12.Name = "label12";
  369. this.label12.Size = new System.Drawing.Size(149, 25);
  370. this.label12.TabIndex = 1373;
  371. this.label12.Text = "Last Backup Info";
  372. //
  373. // lblLastBackupInfo
  374. //
  375. this.lblLastBackupInfo.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
  376. this.lblLastBackupInfo.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64)))));
  377. this.lblLastBackupInfo.Location = new System.Drawing.Point(24, 223);
  378. this.lblLastBackupInfo.Name = "lblLastBackupInfo";
  379. this.lblLastBackupInfo.Size = new System.Drawing.Size(506, 45);
  380. this.lblLastBackupInfo.TabIndex = 1374;
  381. this.lblLastBackupInfo.Text = "Last backup was taken {0} at {1} in location {2}.";
  382. //
  383. // FrmDbBackup
  384. //
  385. this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 17F);
  386. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
  387. this.BackColor = System.Drawing.Color.White;
  388. this.ClientSize = new System.Drawing.Size(542, 390);
  389. this.Controls.Add(this.Panel1);
  390. this.Controls.Add(this.lblLastBackupInfo);
  391. this.Controls.Add(this.label12);
  392. this.Controls.Add(this.label11);
  393. this.Controls.Add(this.label10);
  394. this.Controls.Add(this.txtNoOfFiles);
  395. this.Controls.Add(this.label2);
  396. this.Controls.Add(this.linkLabel3);
  397. this.Controls.Add(this.linkLabel2);
  398. this.Controls.Add(this.label20);
  399. this.Controls.Add(this.label22);
  400. this.Controls.Add(this.label13);
  401. this.Controls.Add(this.label6);
  402. this.Controls.Add(this.txtDbName);
  403. this.Controls.Add(this.label5);
  404. this.Controls.Add(this.label4);
  405. this.Controls.Add(this.btnBackup);
  406. this.Controls.Add(this.DateTimePicker1);
  407. this.Controls.Add(this.Label8);
  408. this.Controls.Add(this.LinkLabel1);
  409. this.Controls.Add(this.Label7);
  410. this.Controls.Add(this.btnSave);
  411. this.Controls.Add(this.btnClose);
  412. this.Controls.Add(this.Label21);
  413. this.Controls.Add(this.txtSpan);
  414. this.Controls.Add(this.label1);
  415. this.Controls.Add(this.label3);
  416. this.Font = new System.Drawing.Font("Segoe UI", 9.75F);
  417. this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
  418. this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
  419. this.Name = "FrmDbBackup";
  420. this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
  421. this.Text = "frmDbBackup";
  422. this.Load += new System.EventHandler(this.FrmDbBackup_Load);
  423. this.Panel1.ResumeLayout(false);
  424. this.Panel1.PerformLayout();
  425. this.ResumeLayout(false);
  426. this.PerformLayout();
  427. }
  428. #endregion
  429. internal System.Windows.Forms.Label Label21;
  430. internal System.Windows.Forms.Button btnClose;
  431. internal System.Windows.Forms.Panel Panel1;
  432. internal System.Windows.Forms.Label Label9;
  433. internal System.Windows.Forms.ProgressBar ProgressBarEx5;
  434. internal System.Windows.Forms.Label label6;
  435. private System.Windows.Forms.TextBox txtDbName;
  436. internal System.Windows.Forms.Label label5;
  437. internal System.Windows.Forms.Label label4;
  438. internal System.Windows.Forms.Label label3;
  439. internal System.Windows.Forms.Button btnBackup;
  440. internal System.Windows.Forms.Label Label8;
  441. internal System.Windows.Forms.LinkLabel LinkLabel1;
  442. internal System.Windows.Forms.Label Label7;
  443. internal System.Windows.Forms.Button btnSave;
  444. internal System.Windows.Forms.Label label13;
  445. internal System.Windows.Forms.Label label22;
  446. internal System.Windows.Forms.Label label20;
  447. internal System.Windows.Forms.Timer Timer1;
  448. internal System.Windows.Forms.FolderBrowserDialog FolderBrowserDialog1;
  449. private System.Windows.Forms.Label linkLabel2;
  450. private System.Windows.Forms.Label linkLabel3;
  451. internal System.Windows.Forms.Label label1;
  452. private System.Windows.Forms.TextBox txtSpan;
  453. internal System.Windows.Forms.DateTimePicker DateTimePicker1;
  454. private System.Windows.Forms.TextBox txtNoOfFiles;
  455. internal System.Windows.Forms.Label label2;
  456. internal System.Windows.Forms.Label label10;
  457. internal System.Windows.Forms.Label label11;
  458. internal System.Windows.Forms.Label label12;
  459. internal System.Windows.Forms.Label lblLastBackupInfo;
  460. }
  461. }
In the above form there are three section one is Backup Setup, Last Backup Info and Manually Backup.

In “Backup Setup” section we have to provide the database setup info like Database Name, Save Directoty Path, Auto Backup Time Span, No of Files To Keep.
Save Directoty Path: To where we have save the database backup file.
Auto Backup Time Span: Interval of time (In Days) to take backup autometically. This fields for take backup autometically. Here we use manually.
No of Files To Keep: How many backup files you want to keep in backup folder.
Database Name : Name of database.

In “Last Backup Info” shows when the last backup was taken.

“Manually Backup” section is used to take database backup manually by click on Database Backup button.

DataBase Backup Operation

After designing the form, now, we will do the database setup manually take database coding. For that, we need to import the following namespaces.
  1. using System;
  2. using System.IO;
  3. using System.Data;
  4. using System.Drawing;
  5. using System.Windows.Forms;
  6. using System.Data.SqlClient;
Before going to the database backup operation, we have to set the connection to the database and declare Connection variables.
For that, we will use the conString variable like below.
  1. SqlCommand cmd;
  2. SqlConnection sqlCon;
  3. string conString = "Data Source=.; Initial Catalog=DemoTest; User Id=sa; Password=password;";
In the above “conString”, Data Source is your server name, Initial Catalog is your database name, and User Id & Password are your login credentials for logging in to the SQL Server. Now, initialize the connection inside the page constructor.
  1. public FrmDbBackup()
  2. {
  3. InitializeComponent();
  4. sqlCon = new SqlConnection(conString);
  5. sqlCon.Open();
  6. }
Code for FrmDbBackup.cs
  1. using System;
  2. using System.IO;
  3. using System.Data;
  4. using System.Drawing;
  5. using System.Windows.Forms;
  6. using System.Data.SqlClient;
  7. namespace DBBACKUP
  8. {
  9. public partial class FrmDbBackup : Form
  10. {
  11. SqlCommand cmd;
  12. SqlConnection sqlCon;
  13. string conString = "Data Source=.; Initial Catalog=DemoTest; User Id=sa; Password=password;";
  14. public FrmDbBackup()
  15. {
  16. InitializeComponent();
  17. sqlCon = new SqlConnection(conString);
  18. sqlCon.Open();
  19. }
  20. private void FrmDbBackup_Load(object sender, EventArgs e)
  21. {
  22. LoadBackinfo();
  23. if (LinkLabel1.Text == string.Empty)
  24. {
  25. LinkLabel1.Text = "Click To Set Directory Path";
  26. }
  27. }
  28. private void LoadBackinfo()
  29. {
  30. if (sqlCon.State == ConnectionState.Closed)
  31. {
  32. sqlCon.Open();
  33. }
  34. DataSet dsData = new DataSet();
  35. cmd = new SqlCommand("DATABASE_BACKUP", sqlCon);
  36. cmd.CommandType = CommandType.StoredProcedure;
  37. cmd.Parameters.AddWithValue("@ACTIONTYPE", "BACKUP_INFO");
  38. SqlDataAdapter sda = new SqlDataAdapter(cmd);
  39. sda.Fill(dsData);
  40. if (dsData.Tables.Count > 0)
  41. {
  42. if (dsData.Tables[0].Rows.Count > 0)
  43. {
  44. LinkLabel1.Text = dsData.Tables[0].Rows[0]["LOCATION"].ToString();
  45. txtNoOfFiles.Text = dsData.Tables[0].Rows[0]["NoOfFiles"].ToString();
  46. txtSpan.Text = dsData.Tables[0].Rows[0]["DayInterval"].ToString();
  47. txtDbName.Text = dsData.Tables[0].Rows[0]["DATABASENAME"].ToString();
  48. linkLabel2.Text = dsData.Tables[0].Rows[0]["LOCATION"].ToString();
  49. linkLabel3.Text = dsData.Tables[0].Rows[0]["DATABASENAME"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyHHmmssfff") + ".bak";
  50. }
  51. if (dsData.Tables[1].Rows.Count > 0)
  52. {
  53. lblLastBackupInfo.Text = string.Format("Last backup was taken {0} at {1} in location {2}.", dsData.Tables[1].Rows[0]["BackupType"].ToString(),
  54. dsData.Tables[1].Rows[0]["BackupDate"].ToString(), dsData.Tables[1].Rows[0]["Location"].ToString());
  55. }
  56. else
  57. lblLastBackupInfo.Text = "No Backups !!!";
  58. }
  59. }
  60. private void btnSave_Click(object sender, EventArgs e)
  61. {
  62. if (LinkLabel1.Text == "Click To Set Directory Path")
  63. {
  64. MessageBox.Show("Click To Set Directory Path", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  65. }
  66. else if (txtSpan.Text == string.Empty)
  67. {
  68. MessageBox.Show("Enter how many last backup files required ", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  69. }
  70. else
  71. {
  72. int numFlag;
  73. if (sqlCon.State == ConnectionState.Closed)
  74. {
  75. sqlCon.Open();
  76. }
  77. cmd = new SqlCommand("DATABASE_BACKUP", sqlCon);
  78. cmd.CommandType = CommandType.StoredProcedure;
  79. cmd.Parameters.AddWithValue("@ACTIONTYPE", "INSERT_BACKUP_INFO");
  80. cmd.Parameters.AddWithValue("@DatabaseName", txtDbName.Text); // Your Database Name
  81. cmd.Parameters.AddWithValue("@Location", LinkLabel1.Text);
  82. cmd.Parameters.AddWithValue("@DayInterval", txtSpan.Text);
  83. cmd.Parameters.AddWithValue("@SoftwareDate", DateTimePicker1.Text);
  84. cmd.Parameters.AddWithValue("@NoOfFiles", txtNoOfFiles.Text);
  85. numFlag = cmd.ExecuteNonQuery();
  86. if (numFlag > 0)
  87. {
  88. MessageBox.Show("Data saved successfully.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  89. LoadBackinfo();
  90. }
  91. else
  92. {
  93. MessageBox.Show("Data not saved. Plaese Try Again.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  94. }
  95. }
  96. }
  97. private void Timer1_Tick(object sender, EventArgs e)
  98. {
  99. ProgressBarEx5.Value += 1;
  100. if (ProgressBarEx5.Value == 100)
  101. {
  102. ProgressBarEx5.Visible = false;
  103. Timer1.Stop();
  104. Panel1.Visible = false;
  105. ProgressBarEx5.Text = "Finished";
  106. }
  107. }
  108. private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  109. {
  110. FolderBrowserDialog1.ShowDialog();
  111. LinkLabel1.Text = FolderBrowserDialog1.SelectedPath;
  112. }
  113. private void btnBackup_Click(object sender, EventArgs e)
  114. {
  115. if (linkLabel2.Text == string.Empty)
  116. {
  117. MessageBox.Show("Please Set Backup Setting", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  118. }
  119. else if (linkLabel3.Text == string.Empty)
  120. {
  121. MessageBox.Show("Please Set Backup Setting", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  122. }
  123. else
  124. {
  125. string filaPath;
  126. if (!linkLabel2.Text.EndsWith(@"\"))
  127. {
  128. filaPath = linkLabel2.Text + @"\" + linkLabel3.Text;
  129. }
  130. else
  131. {
  132. filaPath = linkLabel2.Text + linkLabel3.Text;
  133. }
  134. int numFlag;
  135. if (sqlCon.State == ConnectionState.Closed)
  136. {
  137. sqlCon.Open();
  138. }
  139. cmd = new SqlCommand("DATABASE_BACKUP", sqlCon);
  140. cmd.CommandType = CommandType.StoredProcedure;
  141. cmd.Parameters.AddWithValue("@ACTIONTYPE", "DB_BACKUP");
  142. cmd.Parameters.AddWithValue("@DATABASE", txtDbName.Text); // Your Database Name
  143. cmd.Parameters.AddWithValue("@FILEPATH", filaPath);
  144. cmd.Parameters.AddWithValue("@BackupName", linkLabel3.Text);
  145. cmd.Parameters.AddWithValue("@SoftwareDate", DateTimePicker1.Text);
  146. cmd.Parameters.AddWithValue("@Type", "Manually");
  147. numFlag = cmd.ExecuteNonQuery();
  148. DataTable dtLoc = new DataTable();
  149. cmd = new SqlCommand("DATABASE_BACKUP", sqlCon);
  150. cmd.CommandType = CommandType.StoredProcedure;
  151. cmd.Parameters.AddWithValue("@ACTIONTYPE", "REMOVE_LOCATION");
  152. SqlDataAdapter da = new SqlDataAdapter(cmd);
  153. da.Fill(dtLoc);
  154. for (int i = 0; i < dtLoc.Rows.Count; i++)
  155. {
  156. string delLoc = dtLoc.Rows[i][0].ToString();
  157. string filepath = delLoc;
  158. if (File.Exists(filepath))
  159. {
  160. File.Delete(filepath);
  161. }
  162. }
  163. if (numFlag > 0)
  164. {
  165. Panel1.Visible = true;
  166. Panel1.Location = new Point(58, 138);
  167. Panel1.Height = 117;
  168. Panel1.Width = 446;
  169. ProgressBarEx5.Visible = true;
  170. ProgressBarEx5.Value = 0;
  171. Timer1.Start();
  172. LoadBackinfo();
  173. }
  174. else
  175. {
  176. MessageBox.Show("Plaese Try Again.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
  177. }
  178. }
  179. }
  180. private void btnClose_Click(object sender, EventArgs e)
  181. {
  182. this.Close();
  183. }
  184. private void txtSpan_KeyPress(object sender, KeyPressEventArgs e)
  185. {
  186. if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 46 || e.KeyChar == 8)
  187. {
  188. e.Handled = false;
  189. }
  190. else
  191. {
  192. e.Handled = true;
  193. }
  194. }
  195. }
  196. }
Now, build and run the project.

First we have set Backup Setup where we have to fill
Save Directoty Path: To where we have save the database backup file. Click on “Click To Set Directory Path” and select a location where you want to save backup files.
Auto Backup Time Span: Interval of time (In Days) to take backup autometically. This fields for take backup autometically. Here we are for manual so put 0(Zero).
No of Files To Keep: Give how many backup files you want to keep in backup folder.
Database Name : Name of your database.
Then click on “Save” button. It will save the setup details to the database and look like this.
After save Backup Setup details you will see Backup Path and Database Name value is coming in Manually Backup section.
Now click on Backup Database button it will create a database backup file and stored in our given folder
and also show the last backup info in Last Backup Info section look like below image.