Hướng dẫn tạo setup project visual studio với Sql server

Hướng dẫn tạo setup project visual studio với Sql server

Tạo Solution có chứa 3 Project bên như dưới:

mysql

Project QLSVApplication: là ứng dụng dùng để hiển thị thông tin sinh viên, chỉ là 1 Datagridview để hiển thị lên.

Project SetupEngine : là Project loại Libraries, project này chúng ta sẽ thêm loại Installer đặt tên là InstallerEngine (Class này có nhiệm vụ cài đặt Cơ sở dữ liệu vào máy tính, với các thông số được truyền vào từ quá trình cài đặt do ta quy định). Ta sẽ nhúng các SQL Script mà SQLServer cung cấp cho ta vào đây với tên sqldata.txt và sqldropcreate.txt (nhớ đặt tên viết thường, ta sẽ đi vào chi tiết ở phần sau)

Ta sẽ biên dịch project này thành dll để sử dụng trong Project QLSVSetup.

Project QLSVSetup : Dùng để cài đặt ứng dụng QLSVApplication vào máy tính, và ra lệnh cho SetupEngine cài đặt cơ sở dữ liệu

Bước  1: Tạo ứng dụng sử dụng

Project QLSVApplication:

Trong project này đơn giản chỉ là hiển thị thông tin, chuỗi kết nối sẽ được đọc từ app.config. Chuỗi này sẽ được cấp nhập trong quá trình cài đặt vào máy tính.

Bước 2: Tạo Project để cài đặt CSDL

Project SetupEngine: Project dùng để tạo CSDL, Project này chúng ta nhớ chọn loại Libraries

-          Để tạo class Installer như trong project: Bấm chuột phải vào Project/ chọn Add / New Item . Trong của sổ mới hiện lên chúng ta tìm tới loại Installer Class, đặt tên class là InstallerEngine

-          Đặt tên class InstallerEngine rồi nhấn Add

-          Tiếp tục tạo 2 Text File để lưu SQL Script (các Script này được lấy bằng công cụ SQL Server cho lẹ).  Ở đây ta chia làm 2 tập tin  SQL Script bởi vì lý do sau: Thao tác tạo CSDL cần phải có thời gian chờ để nó kịp update vào SQL Server. Ta cho chờ 1 thời gian sau đó mới tiếp tục chạy các SQL Script về tạo bảng, insert dữ liệu…

-          Để tạo Text File: Bấm chuột phải vào Project / Add/ New Item / chọn Text  File và nhập tên

-          Trên đây là tạo Text File tên sqldropcreate.txt , chú ý nhớ đặt tên viết thường toàn bộ.

-          Sau khi tạo xong tập tin sqldropcreate.txt, chép đoạn Script tạo CSDL vào đây (xem hình ):

–>Các script này có sẵn do SQL Server tự  tạo nên ta chỉ cần copy từ đó vào đây (nhớ bỏ hết các dòng có chữ Go)

-          Tiếp theo ta phải cấu hình để 2 Text File này được nhúng vào Resource sau khi biên dịch.

-          Trong Properties: Lần lượt chọn 2 Text File trên và chọn Embedded Resource trong Build Action

-          Bây giờ chúng ta tiến hành chỉnh sủa class InstallerEngine:


using System;using System.Collections;using System.Collections.Generic;

using System.ComponentModel;

using System.Configuration.Install;

using System.Linq;

using System.IO;

using System.Reflection;

using System.Data.SqlClient;

using System.Xml;

using System.Collections.Specialized;

namespace SetupEngine

{

[RunInstaller(true)]

public partial class InstallerEngine : System.Configuration.Install.Installer

{

private string logFilePath =”";

private string pathApp = “”;

public InstallerEngine()

{

InitializeComponent();

}

private string GetSql(string Name)

{

try

{

// Gets the current assembly.

Assembly Asm = Assembly.GetExecutingAssembly();

// Resources are named using a fully qualified name.

Stream strm = Asm.GetManifestResourceStream(Asm.GetName().Name + “.” + Name);

// Reads the contents of the embedded file.

StreamReader reader = new StreamReader(strm);

string sInfor = reader.ReadToEnd();

Log(sInfor);

reader.Close();

return sInfor;

}

catch (Exception ex)

{

Log(ex.ToString());

throw ex;

}

}

private void ExecuteSql(string serverName, string dbName, string userid, string password, string Sql)

{

string connStr = “server =” + serverName + “;database =” + dbName + “;uid=” + userid + “;pwd=” + password;

using (SqlConnection conn = new SqlConnection(connStr))

{

try

{

SqlCommand cmd = new SqlCommand(Sql);

conn.Open();

cmd.Connection = conn;

int n = cmd.ExecuteNonQuery();

Log(” n= ” + n);

conn.Close();

}

catch (Exception ex)

{

Log(ex.ToString());

}

}

}

protected void AddDBTable(string serverName, string userid, string password)

{

try

{

// Creates the database and installs the tables.

string strScript = GetSql(“sqldropcreate.txt”);

ExecuteSql(serverName, “master”, userid, password, strScript);

System.Threading.Thread.Sleep(60 * 1000);

strScript = GetSql(“sqldata.txt”);

ExecuteSql(serverName, “dbqlsv”, userid, password, strScript);

System.Threading.Thread.Sleep(60 * 1000);

string connStr = “server =” + serverName + “;database =dbqlsv;uid=” + userid + “;pwd=” + password;

Log(“AppPath=” + pathApp);

XmlDocument xmlDom = new XmlDocument();

xmlDom.Load(pathApp);

// Get XML node

XmlNode xmlNode = xmlDom.SelectSingleNode(

“configuration/appSettings/add[@key='MYCONN']“);

xmlNode.Attributes["value"].Value = connStr;

// Updating connection string in file

Log(“Followind node of config file will be updated: ” + xmlNode.InnerXml);

// Save to disk

xmlDom.Save(pathApp);

}

catch (Exception ex)

{

//Reports any errors and abort.

Log(ex.ToString());

throw ex;

}

}

protected override void OnAfterInstall(IDictionary savedState)

{

base.OnAfterInstall(savedState);

}

public override void Install(System.Collections.IDictionary stateSaver)

{

base.Install(stateSaver);

string assemPath = this.Context.Parameters["assemblypath"];

int pos = assemPath.LastIndexOf(“\\”);

logFilePath = assemPath .Substring(0,pos+1)+ “\\SetupLog117.txt”;

pathApp = assemPath.Substring(0, pos + 1) + “\\QLSVApplication.exe.config”;

Log(“—-Setup started—-”);

Log(“Server=” + this.Context.Parameters["servername"] + ” ; User Id=” + this.Context.Parameters["userid"] + ” ; pwd=” + this.Context.Parameters["password"]);

foreach (DictionaryEntry s in this.Context.Parameters)

{

Log(“Parameter : “+s.Key +” ; value =”+s.Value);

}

AddDBTable(this.Context.Parameters["servername"], this.Context.Parameters["userid"], this.Context.Parameters["password"]);

}

public void Log(string str)

{

StreamWriter Tex;

try

{

Tex = File.AppendText(this.logFilePath);

Tex.WriteLine(DateTime.Now.ToString() + ” ” + str);

Tex.Close();

}

catch

{ }

}

}

}

Giải thích một số dòng lệnh bên trên:

Hàm GetSql(string Name) : Dùng để đọc 2 Text File Sql Script. Vì 2 tập tin này chúng ta nhúng vào Assembly nên cơ chế đọc tập tin sẽ là như vậy (xem code).

Lệnh : this.Context.Parameters["assemblypath"]; lấy đúng đường dẫn mà lúc cài đặt chương trình người sử dụng chọn.

Key assemblypath là có sẵn, phải viết y chang.

this.Context.Parameters["servername"], this.Context.Parameters["userid"], this.Context.Parameters["password"]

còn servernam, userid, password là do chúng ta quy định, do chúng ta đặt bên Project Setup, 3 biến này phải đặt y chang như 3 biến mà bên Project Setup ta đã đặt.

void AddDBTable(string serverName, string userid, string password) có nhiệm vụ xóa và tạo mới  CSDL sau đó tạo các bảng, dữ liệu. sau khi tạo xong thì tự động cập nhập file App.config cho chương trình (dùng xml).

Bước 3: Tạo Project Setup

Chọn Setup project: đặt tên QLSVSetup rồi bấm OK.

Bấm chuột phải vào QLSVSetup/ chọn File System:

Tại cửa sổ này ta bấm chuột vào thư mục Application Folder, để có được thông tin như bên phải của hình ta làm như sau:

Bấm chuột phải vào Application Folder / Add/ Project Output…

Tiếp tục thêm các tập tin ứng dụng và app.config bên Project QLSVApplication vào đây:

Bấm chuột phải vào Application Folder / Add/ File:

Kết quả:

Để tạo Shortcut cho ứng dụng sau khi cài đặt thì ta bấm chuột phải vào QLSVApplication.exe

Sau đó cắt vào User’s Desktop hay User’s programs Menu, ta có thể tạo bất kỳ thư mục nào bên nhánh trái, rồi chép Shortcut vào đó, có thể tạo nhiều shortcut.

Tiếp theo ta cấu hình giao diện cài đặt, bấm chuột vào QLSVSetup, bên trên ta chọn Icon User Interface Editor:

Màn hình User interface sẽ xuất hiện:

Cửa sổ Add Dialog hiển thị lên:

Cấu hình  TextBoxes (A) như hình chụp bên dưới:

Các tên : CUSTOMTEXTA1, CUSTOMTEXTA2, CUSTOMTEXTA3 là do ta đặt để bên Custom Action có thể tham chiếu lấy giá trị từ màn hình cài đặt. Không dùng Edit4Property nên to cho Edit4Visible =false

-          Tiếp theo, cấu hình Custom Action: Bấm chuột phải vào QLSVSetup/ chọn View/ chọn Custom Actions

Tại cửa sổ Custom Actions, Bấm chuột phải vào Install / chọn Add Custom Action…

Chọn Primary ouput from SetupEngine (active) rồi bấm OK.

Sau đó click chuột vào Primary output, quan sát Properties, Ta cấu hình CustomActionData như hình:

/servername=[CUSTOMTEXTA1] /userid=[CUSTOMTEXTA2] /password=[CUSTOMTEXTA3]

Ta viết y chang như trên, chú ý là 3 biến servername, userid, password ta đặt bên này được sử dụng cho bên SetupEngine :

this.Context.Parameters["servername"], this.Context.Parameters["userid"], this.Context.Parameters["password"]

Tức là ở đây ta đặt tên gì thì bên SetupEngine phải lấy đúng tên ta đặt bên này

CUSTOMTEXTA1 , CUSTOMTEXTA2, CUSTOMTEXTA3 là do ta đặt cho các EditPropertie của Textboxes (A)

Bước 4: biên dịch và cài đặt

-          Cấu hình QLSVSetup như bên dưới

Chọn Rebuild để biên dịch Setup.

Sau đó chọn Install để cài đặt:

Các bước cài đặt:

  1. BẤM next, tự động xuất hiện màn hình cấu hình CSDL (chính là Textboxes (A))

2. Nhập thông tin và bấm Next:

3. Chọn đường dẫn cài đặt và bấm Next … cứ vậy là xong. Chương trình sẽ cài đặt ứng dụng đồng thời cài đặt SQL luôn (có cập nhật kết nối cho ta luôn)

Kết quả quan sát màn hình Desktop và khởi động chương trình:

Hướng dẫn tạo setup project visual studio với Sql server

Tải tập tin hướng dẫn chi tiết tại đây : http://www.mediafire.com/view/?n3qjzbvthnt9q3n

Tải source code tại đây: http://www.mediafire.com/download.php?vzqfjsaiqk5n8sg

Chúc các bạn thành công

Tags: 
Bạn thấy bài viết này như thế nào?: 
No votes yet
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Bình luận (0)

 

Add Comment

Filtered HTML

  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Các thẻ HTML được chấp nhận: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Tự động ngắt dòng và đoạn văn.

Plain text

  • No HTML tags allowed.
  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Tự động ngắt dòng và đoạn văn.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Hãng Blackmagic Design ra mắt phiên bản Davinci Resolve 16

Hãng Blackmagic Design ra mắt phiên bản Davinci Resolve 16

Cách đây không lâu, hãng Blackmagic Design đã cho ra mắt phiên bản Davinci Resolve 16 tại NAB Show 2019 và giành chiến thắng ở giải thưởng “Best Editing Software” của Videomaker.

Google, Email Quickly

Gmail Tip – Add Multiple attachments on Email Quickly

Gmail is one of the popular email service which has lots of new feature and addons. If you are the Gmail user like us then here a Gmail Tip which allows you to add multiple attachments on Email quickly.

Android

Tỷ lệ sử dụng Android và iOS toàn cầu rất cao

Theo thống kê của hãng Flurry, tỷ lệ thiết bị chạy hệ điều hành iOS và Android trên toàn cầu đã vượt qua tất cả thiết bị điện tử tiêu dùng từ trước cho tới nay xuyên suốt quá trình lịch sử phát triển của công nghệ.

Công ty diệt chuột T&C

 

Diet con trung