├── MSSQLDump.suo
├── MSSQLDump.v11.suo
├── _LAST_BUILD
├── System.dll
├── MSSQLDump.exe
├── System.Data.dll
├── System.Xml.dll
├── Microsoft.SqlServer.Smo.dll
├── Microsoft.SqlServer.SqlEnum.dll
├── Microsoft.SqlServer.ConnectionInfo.dll
└── Microsoft.SqlServer.Management.Sdk.Sfc.dll
├── _MSSQL_DLLs
├── Microsoft.SqlServer.Smo.dll
├── Microsoft.SqlServer.SqlEnum.dll
├── Microsoft.SqlServer.ConnectionInfo.dll
├── Microsoft.SqlServer.SqlClrProvider.dll
└── Microsoft.SqlServer.Management.Sdk.Sfc.dll
├── .gitignore
├── App.config
├── .gitattributes
├── MSSQLDump.csproj.user
├── MSSQLDump.sln
├── README.md
├── Properties
└── AssemblyInfo.cs
├── csFile.cs
├── MSSQLDump.csproj
├── _DB.cs
├── LICENSE
└── Program.cs
/MSSQLDump.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/MSSQLDump.suo
--------------------------------------------------------------------------------
/MSSQLDump.v11.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/MSSQLDump.v11.suo
--------------------------------------------------------------------------------
/_LAST_BUILD/System.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/System.dll
--------------------------------------------------------------------------------
/_LAST_BUILD/MSSQLDump.exe:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/MSSQLDump.exe
--------------------------------------------------------------------------------
/_LAST_BUILD/System.Data.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/System.Data.dll
--------------------------------------------------------------------------------
/_LAST_BUILD/System.Xml.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/System.Xml.dll
--------------------------------------------------------------------------------
/_LAST_BUILD/Microsoft.SqlServer.Smo.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/Microsoft.SqlServer.Smo.dll
--------------------------------------------------------------------------------
/_MSSQL_DLLs/Microsoft.SqlServer.Smo.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_MSSQL_DLLs/Microsoft.SqlServer.Smo.dll
--------------------------------------------------------------------------------
/_LAST_BUILD/Microsoft.SqlServer.SqlEnum.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/Microsoft.SqlServer.SqlEnum.dll
--------------------------------------------------------------------------------
/_MSSQL_DLLs/Microsoft.SqlServer.SqlEnum.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_MSSQL_DLLs/Microsoft.SqlServer.SqlEnum.dll
--------------------------------------------------------------------------------
/_LAST_BUILD/Microsoft.SqlServer.ConnectionInfo.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/Microsoft.SqlServer.ConnectionInfo.dll
--------------------------------------------------------------------------------
/_MSSQL_DLLs/Microsoft.SqlServer.ConnectionInfo.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_MSSQL_DLLs/Microsoft.SqlServer.ConnectionInfo.dll
--------------------------------------------------------------------------------
/_MSSQL_DLLs/Microsoft.SqlServer.SqlClrProvider.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_MSSQL_DLLs/Microsoft.SqlServer.SqlClrProvider.dll
--------------------------------------------------------------------------------
/_LAST_BUILD/Microsoft.SqlServer.Management.Sdk.Sfc.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_LAST_BUILD/Microsoft.SqlServer.Management.Sdk.Sfc.dll
--------------------------------------------------------------------------------
/_MSSQL_DLLs/Microsoft.SqlServer.Management.Sdk.Sfc.dll:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/georgekosmidis/mssql-schema-dump/HEAD/_MSSQL_DLLs/Microsoft.SqlServer.Management.Sdk.Sfc.dll
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | bin/
2 | obj/
3 |
4 | # OS generated files #
5 | ######################
6 | .DS_Store
7 | .DS_Store?
8 | ._*
9 | .Spotlight-V100
10 | .Trashes
11 | ehthumbs.db
12 | Thumbs.db
--------------------------------------------------------------------------------
/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
4 | # Custom for Visual Studio
5 | *.cs diff=csharp
6 |
7 | # Standard to msysgit
8 | *.doc diff=astextplain
9 | *.DOC diff=astextplain
10 | *.docx diff=astextplain
11 | *.DOCX diff=astextplain
12 | *.dot diff=astextplain
13 | *.DOT diff=astextplain
14 | *.pdf diff=astextplain
15 | *.PDF diff=astextplain
16 | *.rtf diff=astextplain
17 | *.RTF diff=astextplain
18 |
--------------------------------------------------------------------------------
/MSSQLDump.csproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | ShowAllFiles
5 |
6 |
7 | -h dev4 -u sa -p epsilonsa -c -b ess
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/MSSQLDump.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 2012
4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MSSQLDump", "MSSQLDump.csproj", "{3452B7D9-0DA3-41B0-84B1-FFE470E023E6}"
5 | EndProject
6 | Global
7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
8 | Debug|Any CPU = Debug|Any CPU
9 | Release|Any CPU = Release|Any CPU
10 | EndGlobalSection
11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
12 | {3452B7D9-0DA3-41B0-84B1-FFE470E023E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13 | {3452B7D9-0DA3-41B0-84B1-FFE470E023E6}.Debug|Any CPU.Build.0 = Debug|Any CPU
14 | {3452B7D9-0DA3-41B0-84B1-FFE470E023E6}.Release|Any CPU.ActiveCfg = Release|Any CPU
15 | {3452B7D9-0DA3-41B0-84B1-FFE470E023E6}.Release|Any CPU.Build.0 = Release|Any CPU
16 | EndGlobalSection
17 | GlobalSection(SolutionProperties) = preSolution
18 | HideSolutionNode = FALSE
19 | EndGlobalSection
20 | EndGlobal
21 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
MS SQL schema dump v1 Beta
2 | Exports MS SQL Server database schema, that includes:
3 |
4 | DB
5 | Schema, User Types, User Table Types, Triggers, Full Text Catalogues,
6 | Full Text StopLists, Stored Procedures, Functions
7 | DB.Tables
8 | Schema, Triggers, Indexes, DRI, Statistics
9 | DB.Views
10 | Schema, Triggers, Indexes, DRI, Statistics
11 |
12 | Pass a junk parameter to start with default values shown below!
13 |
14 | Usage:
15 |
16 | mssqldump -h data-source-host -u username -p password [-d path/for/files] [-c] [-s] [-a] [-b DB1[,DB2[,DB3]]]
17 |
18 |
19 | Options:
20 |
21 | -h : SQL server host, defaults to (local)
22 | -u : username, defaults to sa
23 | -p : password, defaults to sa
24 | -d : Local path for saved files, defaults to C:\\\_SQL_SCHEMA_DUMP
25 | -c : Delete all files and folders from local path, defaults to false
26 | -s : Also export statistics, defaults to false
27 | -a : Use DAC to try decrypt encrypted objects, defaults to false
28 | -b : Comma separated value of databases to export, defaults to empty string
29 |
--------------------------------------------------------------------------------
/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle( "MSSQL Schema Dump" )]
9 | [assembly: AssemblyDescription( "" )]
10 | [assembly: AssemblyConfiguration( "" )]
11 | [assembly: AssemblyCompany( "George Kosmidis" )]
12 | [assembly: AssemblyProduct( "MSSQLDump" )]
13 | [assembly: AssemblyCopyright( "Copyright © 2013" )]
14 | [assembly: AssemblyTrademark( "" )]
15 | [assembly: AssemblyCulture( "" )]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible( false )]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid( "c8bc726d-a577-491f-aeb6-b508dd204cc5" )]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion( "1.0.0.0" )]
36 | [assembly: AssemblyFileVersion( "1.0.0.0" )]
37 |
--------------------------------------------------------------------------------
/csFile.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.IO;
5 |
6 | namespace MSSQLDump {
7 | class csFile {
8 | public static string CreateFolder( string path, string folder ) {
9 | path = System.IO.Path.Combine( path, folder );
10 | if (!Directory.Exists( path ))
11 | System.IO.Directory.CreateDirectory( path );
12 | return path;
13 | }
14 | public static void writeFile( string filePath, string c, bool append ) {
15 | string s = ReadFile( filePath );
16 | TextWriter tw = new StreamWriter( filePath );
17 | try {
18 | if (append)
19 | tw.WriteLine( s + c );
20 | else
21 | tw.WriteLine( c );
22 | }
23 | finally {
24 | tw.Close();
25 | }
26 | }
27 |
28 | public static string ReadFile( string filePath ) {
29 | byte[] buffer;
30 | try {
31 | FileStream fileStream = new FileStream( filePath, FileMode.Open, FileAccess.Read );
32 | try {
33 | int length = (int)fileStream.Length; // get file length
34 | buffer = new byte[length]; // create buffer
35 | int count; // actual number of bytes read
36 | int sum = 0; // total number of bytes read
37 |
38 | // read until Read method returns 0 (end of the stream has been reached)
39 | while ((count = fileStream.Read( buffer, sum, length - sum )) > 0)
40 | sum += count; // sum is a buffer offset for next reading
41 | }
42 | finally {
43 | fileStream.Close();
44 | }
45 | System.Text.Encoding enc = System.Text.Encoding.UTF8;
46 | return enc.GetString( buffer );
47 | }
48 | catch {
49 | return "";
50 | }
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/MSSQLDump.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {3452B7D9-0DA3-41B0-84B1-FFE470E023E6}
8 | Exe
9 | Properties
10 | MSSQLDump
11 | MSSQLDump
12 | v4.0
13 | 512
14 | Client
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 | false
26 | false
27 |
28 |
29 | AnyCPU
30 | pdbonly
31 | true
32 | bin\Release\
33 | TRACE
34 | prompt
35 | 4
36 | false
37 |
38 |
39 |
40 | True
41 |
42 |
43 | False
44 | C:\Program Files (x86)\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
45 | True
46 |
47 |
48 | False
49 | C:\Program Files (x86)\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Management.Sdk.Sfc.dll
50 | False
51 | True
52 |
53 |
54 | False
55 | C:\Program Files (x86)\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
56 | True
57 |
58 |
59 | False
60 | C:\Program Files (x86)\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SqlEnum.dll
61 | True
62 |
63 |
64 | True
65 |
66 |
67 | True
68 |
69 |
70 | True
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
107 |
--------------------------------------------------------------------------------
/_DB.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Data.SqlClient;
5 | using System.Data;
6 | using System.Text.RegularExpressions;
7 |
8 | namespace MSSQLDump {
9 | class _DB {
10 | private SqlConnection cn = new SqlConnection();
11 | private SqlCommand cmd = new SqlCommand();
12 |
13 | private string _host = "";
14 | private string _user = "";
15 | private string _password = "";
16 |
17 | public _DB( string host, string user, string password ) {
18 | _host = host;
19 | _user = user;
20 | _password = password;
21 |
22 | cn.ConnectionString = "packet size=4096;user id=" + _user + ";Password=" + _password + ";data source=" + _host + ";persist security info=True;initial catalog=master;";
23 | cmd.Connection = cn;
24 | cmd.CommandTimeout = 3600;
25 | cmd.Prepare();
26 | }
27 |
28 | public void TryEnableDAC() {
29 |
30 | cmd.CommandText = "exec sp_configure 'show advanced options', 1" + Environment.NewLine;
31 | cmd.CommandText += "RECONFIGURE WITH OVERRIDE" + Environment.NewLine;
32 | cmd.CommandText += "exec sp_configure 'remote admin connections', 1" + Environment.NewLine;
33 | cmd.CommandText += "RECONFIGURE WITH OVERRIDE" + Environment.NewLine;
34 |
35 | if (cmd.Connection.State == ConnectionState.Closed)
36 | cmd.Connection.Open();
37 |
38 | cmd.ExecuteNonQuery();
39 |
40 | }
41 | public void TryDisableDAC() {
42 |
43 | cmd.CommandText = "exec sp_configure 'show advanced options', 0" + Environment.NewLine;
44 | cmd.CommandText += "RECONFIGURE WITH OVERRIDE" + Environment.NewLine;
45 | cmd.CommandText += "exec sp_configure 'remote admin connections', 0" + Environment.NewLine;
46 | cmd.CommandText += "RECONFIGURE WITH OVERRIDE" + Environment.NewLine;
47 |
48 | if (cmd.Connection.State == ConnectionState.Closed)
49 | cmd.Connection.Open();
50 |
51 | cmd.ExecuteNonQuery();
52 |
53 | }
54 | public void ChangeDB( string db ) {
55 | cmd.CommandText = "USE " + db + ";";
56 |
57 | if (cmd.Connection.State == ConnectionState.Closed)
58 | cmd.Connection.Open();
59 |
60 | cmd.ExecuteNonQuery();
61 | }
62 |
63 | ///
64 | ///
65 | ///
66 | /// Name of encrypted object
67 | /// VIEW, PROCEDURE, TRIGGER
68 | ///
69 | public DataTable GetDecryptedObject( string objName, string objType ) {
70 | cmd.CommandText = @"DECLARE @encrypted NVARCHAR(MAX)
71 | SET @encrypted = (
72 | SELECT TOP 1 imageval
73 | FROM sys.sysobjvalues
74 | WHERE OBJECT_NAME(objid) = '" + objName + @"'
75 | )
76 | DECLARE @encryptedLength INT
77 | SET @encryptedLength = DATALENGTH(@encrypted) / 2
78 |
79 | DECLARE @procedureHeader NVARCHAR(MAX)
80 | SET @procedureHeader = N'ALTER " + objType.ToUpper() + @" dbo." + objName + @" WITH ENCRYPTION AS '
81 | SET @procedureHeader = @procedureHeader + REPLICATE(N'-',(@encryptedLength - LEN(@procedureHeader)))
82 |
83 | EXEC sp_executesql @procedureHeader
84 | DECLARE @blankEncrypted NVARCHAR(MAX)
85 | SET @blankEncrypted = (
86 | SELECT TOP 1 imageval
87 | FROM sys.sysobjvalues
88 | WHERE OBJECT_NAME(objid) = '" + objName + @"'
89 | )
90 |
91 | SET @procedureHeader = N'CREATE " + objType.ToUpper() + @" dbo." + objName + @" WITH ENCRYPTION AS '
92 | SET @procedureHeader = @procedureHeader + REPLICATE(N'-',(@encryptedLength - LEN(@procedureHeader)))
93 |
94 | DECLARE @cnt SMALLINT
95 | DECLARE @decryptedChar NCHAR(1)
96 | DECLARE @decryptedMessage NVARCHAR(MAX)
97 | SET @decryptedMessage = ''
98 | SET @cnt = 1
99 | WHILE @cnt <> @encryptedLength BEGIN
100 | SET @decryptedChar =
101 | NCHAR(
102 | UNICODE(SUBSTRING(
103 | @encrypted, @cnt, 1)) ^
104 | UNICODE(SUBSTRING(
105 | @procedureHeader, @cnt, 1)) ^
106 | UNICODE(SUBSTRING(
107 | @blankEncrypted, @cnt, 1))
108 | )
109 | SET @decryptedMessage = @decryptedMessage + @decryptedChar
110 | SET @cnt = @cnt + 1
111 | END
112 | SELECT @decryptedMessage AS [script]";
113 | return this.GetDatatable( cmd );
114 | }
115 | // public void Test() {
116 | // cmd.CommandText = @"SELECT *
117 | // FROM sys.sysobjvalues
118 | // WHERE OBJECT_NAME(objid) = 'Network_ExecuteNonQuery' ";
119 | // var dt = GetDatatable( cmd );
120 |
121 | // }
122 | public DataTable GetObjects( string db, string type ) {
123 | cmd.CommandText = "SELECT * FROM [" + db + "].dbo.sysobjects WHERE xtype = '" + type + "';";
124 | return this.GetDatatable( cmd );
125 | }
126 |
127 | private DataTable GetDatatable( SqlCommand cmd ) {
128 | if (cmd.Connection.State == ConnectionState.Closed)
129 | cmd.Connection.Open();
130 |
131 | SqlDataAdapter da = new SqlDataAdapter();
132 | da.SelectCommand = cmd;
133 | DataTable dt = new DataTable();
134 | da.Fill( dt );
135 |
136 | cmd.Connection.Close();
137 |
138 | return dt;
139 | }
140 | }
141 | }
142 |
143 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Data;
4 | using System.Data.SqlClient;
5 | using System.IO;
6 | using System.Linq;
7 | using System.Threading;
8 | using Microsoft.SqlServer.Management.Common;
9 | using Microsoft.SqlServer.Management.Smo;
10 |
11 | namespace MSSQLDump {
12 | class Program {
13 | private static string HOST = "(local)";
14 | private static string USER = "sa";
15 | private static string PASS = "sa";
16 | private static string SavePath = @"C:\_SQL_SCHEMA_DUMP\";
17 | private static bool CleanDir = false;
18 | private static bool ExportStatistics = false;
19 | private static bool UseDAC = false;
20 | private static List DBs = new List();
21 | private static _DB DB = new _DB( HOST, USER, PASS );
22 |
23 | static void Main( string[] args ) {
24 | if ( args.Count() == 0 ) {
25 | WriteHelp();
26 | return;
27 | }
28 | if ( !ReadArguments( args ) )
29 | return;
30 | //Clean Dir
31 | if ( CleanDir && Directory.Exists( SavePath + Path.DirectorySeparatorChar + pathify( HOST ) ) ) {
32 | Console.WriteLine( "Cleaning Directory '" + SavePath + Path.DirectorySeparatorChar + pathify( HOST ) + "'" );
33 | var b = DeleteDirectory( SavePath + Path.DirectorySeparatorChar + pathify( HOST ) );
34 | if ( !b )
35 | return;
36 | Console.Clear();
37 | }
38 |
39 | //Use DAC
40 | if ( UseDAC ) {
41 | Console.WriteLine( "Trying to enable DAC..." );
42 | try {
43 | DB.TryEnableDAC();
44 | }
45 | catch {
46 | Console.WriteLine( "ERROR!" );
47 | Console.WriteLine( "DAC cannot be enabled, retry without the option but encrypted objects will be omitted!" );
48 | return;
49 | }
50 |
51 | DB = new _DB( "ADMIN:" + HOST, USER, PASS );
52 | Console.Clear();
53 | }
54 | var cn = new SqlConnection( "packet size=4096;user id=" + USER + ";Password=" + PASS + ";data source=" + HOST + ";persist security info=True;initial catalog=master;" );
55 | try {
56 | cn.Open();
57 | cn.Close();
58 | }
59 | catch ( Exception ex ) {
60 | Console.Clear();
61 | Console.WriteLine( "ERROR!" );
62 | Console.WriteLine( ex.Message );
63 | Console.WriteLine( "(Server:" + HOST + ", User:" + USER + ", PASS: " + PASS.Substring( 0, 1 ) + (new String( '*', PASS.Length - 2 )) + PASS.Substring( PASS.Count() - 1, 1 ) + ")" );
64 | Console.ReadKey();
65 | return;
66 | }
67 | var sc = new ServerConnection( cn );
68 | Server server = new Server( sc );
69 |
70 | //START
71 | SavePath = csFile.CreateFolder( SavePath, pathify( HOST ) );
72 |
73 | //SERVER
74 | var filePath = PrepareSqlFile( "*", "", "SERVER", HOST, SavePath, "" );
75 | WriteSQLInner( "*", "", "SERVER", HOST, filePath, server, ScriptOption.DriAll );
76 |
77 | foreach ( var db in server.Databases.Cast().AsQueryable().Where( o => o.IsSystemObject == false ) ) {
78 | if ( db.IsSystemObject )
79 | continue;
80 | if ( DBs.Count() > 0 && !DBs.Contains( db.Name.ToLower() ) )
81 | continue;
82 | var dbPath = csFile.CreateFolder( SavePath, pathify( db.Name ) );
83 |
84 | Console.WriteLine( "=================================================" );
85 | Console.WriteLine( "DB: " + db.Name );
86 | Console.WriteLine( "-------------------------------------------------" );
87 |
88 | //var schema = "dbo";
89 | var filename = "";
90 | var objPath = "";
91 | //System.Collections.Specialized.StringCollection cs = new System.Collections.Specialized.StringCollection();
92 | //////////////////////////////////////////////////////////////////////////
93 | //DB
94 | var currentPath = dbPath;
95 | filePath = PrepareSqlFile( db.Name, "", "DB", db.Name, currentPath, "" );
96 | WriteSQLInner( db.Name, "", "DB", db.Name, filePath, db, ScriptOption.Default );
97 |
98 | //////////////////////////////////////////////////////////////////////////
99 | //SCHEMA
100 | foreach ( var schema2 in db.Schemas.Cast().AsQueryable() ) {
101 | filePath = PrepareSqlFile( db.Name, "", "Schema", schema2.Name, currentPath, "" );
102 | WriteSQLInner( db.Name, "", "Schema", schema2.Name, filePath, schema2, ScriptOption.Default );
103 | }
104 |
105 | //////////////////////////////////////////////////////////////////////////
106 | //DB USER TYPES
107 | currentPath = csFile.CreateFolder( dbPath, pathify( "UTYPE" ) );
108 | foreach ( UserDefinedType o in db.UserDefinedTypes ) {
109 | filePath = PrepareSqlFile( db.Name, o.Schema, "UTYPE", o.Name, currentPath, "" );
110 | WriteSQLInner( db.Name, o.Schema, "UTYPE", o.Name, filePath, o, ScriptOption.Default );
111 | }
112 |
113 | //////////////////////////////////////////////////////////////////////////
114 | //DB TRIGGERS
115 | currentPath = csFile.CreateFolder( dbPath, pathify( "TRIGGER" ) );
116 | foreach ( DatabaseDdlTrigger o in db.Triggers.Cast().AsQueryable().Where( o => o.IsSystemObject == false ) ) {
117 | filePath = PrepareSqlFile( db.Name, "dbo", "TRIGGER", o.Name, currentPath, "" );
118 | WriteSQLInner( db.Name, "dbo", "TRIGGER", o.Name, filePath, o, ScriptOption.Default );
119 | }
120 |
121 | //////////////////////////////////////////////////////////////////////////
122 | //DB USER TABLE TYPES
123 | currentPath = csFile.CreateFolder( dbPath, pathify( "TTYPES" ) );
124 | foreach ( UserDefinedTableType o in db.UserDefinedTableTypes ) {
125 | filePath = PrepareSqlFile( db.Name, o.Schema, "TTYPES", o.Name, currentPath, "" );
126 | WriteSQLInner( db.Name, o.Schema, "TTYPES", o.Name, filePath, o, ScriptOption.Default );
127 | }
128 |
129 | //////////////////////////////////////////////////////////////////////////
130 | //DB FULLTEXT CATALOGS
131 | currentPath = csFile.CreateFolder( dbPath, pathify( "FTC" ) );
132 | foreach ( FullTextCatalog o in db.FullTextCatalogs ) {
133 | filePath = PrepareSqlFile( db.Name, "dbo", "FTC", o.Name, currentPath, "" );
134 | WriteSQLInner( db.Name, "dbo", "FTC", o.Name, filePath, o, ScriptOption.Default );
135 | }
136 |
137 | //////////////////////////////////////////////////////////////////////////
138 | //DB FULLTEXT STOPLISTS
139 | currentPath = csFile.CreateFolder( dbPath, pathify( "FTL" ) );
140 | foreach ( FullTextStopList o in db.FullTextStopLists ) {
141 | filePath = PrepareSqlFile( db.Name, "dbo", "FTL", o.Name, currentPath, "" );
142 | WriteSQLInner( db.Name, "dbo", "FTL", o.Name, filePath, o, ScriptOption.Default );
143 | }
144 |
145 | //////////////////////////////////////////////////////////////////////////
146 | //STORED PROCEDURES
147 | currentPath = csFile.CreateFolder( dbPath, pathify( "PROCEDURE" ) );
148 | foreach ( StoredProcedure o in db.StoredProcedures.Cast().AsQueryable().Where( o => o.IsSystemObject == false ) ) {
149 | filePath = PrepareSqlFile( db.Name, o.Schema, "PROCEDURE", o.Name, currentPath, "" );
150 | WriteSQLInner( db.Name, o.Schema, "PROCEDURE", o.Name, filePath, o, ScriptOption.Default );
151 | }
152 |
153 | //////////////////////////////////////////////////////////////////////////
154 | //FUNCTIONS
155 | currentPath = csFile.CreateFolder( dbPath, pathify( "FUNCTION" ) );
156 | foreach ( UserDefinedFunction o in db.UserDefinedFunctions.Cast().Where( oo => oo.IsSystemObject == false ) ) {
157 | filePath = PrepareSqlFile( db.Name, o.Schema, "FUNCTION", o.Name, currentPath, "" );
158 | WriteSQLInner( db.Name, o.Schema, "FUNCTION", o.Name, filePath, o, ScriptOption.Default );
159 | }
160 |
161 | //////////////////////////////////////////////////////////////////////////
162 | //TABLE
163 | foreach ( Table o in db.Tables.Cast().AsQueryable().Where( o => o.IsSystemObject == false ) ) {
164 |
165 | currentPath = csFile.CreateFolder( dbPath, pathify( "TABLE" ) );
166 | filePath = PrepareSqlFile( db.Name, o.Schema, "TABLE", o.Name, currentPath, "" );
167 | WriteSQLInner( db.Name, o.Schema, "TABLE", o.Name, filePath, o, ScriptOption.Default );
168 | WriteSQLInner( db.Name, o.Schema, "TABLE", o.Name, filePath, o, ScriptOption.Indexes );
169 | WriteSQLInner( db.Name, o.Schema, "TABLE", o.Name, filePath, o, ScriptOption.DriAll );
170 |
171 |
172 | //////////////////////////////////////////////////////////////////////////
173 | //TABLE TRIGGERS
174 | currentPath = csFile.CreateFolder( dbPath, pathify( "TRIGGER" ) );
175 | foreach ( Trigger ot in o.Triggers.Cast().AsQueryable().Where( oo => oo.IsSystemObject == false ) ) {
176 | filePath = PrepareSqlFile( db.Name, o.Schema, "TRIGGER", ot.Name, currentPath, "TABLE_" + o.Name );
177 | WriteSQLInner( db.Name, o.Schema, "TRIGGER", ot.Name, filePath, ot, ScriptOption.Default );
178 | }
179 |
180 | //////////////////////////////////////////////////////////////////////////
181 | //TABLE STATISTICS
182 | if ( ExportStatistics ) {
183 | currentPath = csFile.CreateFolder( dbPath, pathify( "STATISTIC" ) );
184 | foreach ( Statistic ot in o.Statistics.Cast().AsQueryable() ) {
185 | filePath = PrepareSqlFile( db.Name, o.Schema, "STATISTIC", ot.Name, currentPath, "TABLE_" + o.Name );
186 | WriteSQLInner( db.Name, o.Schema, "STATISTIC", ot.Name, filePath, ot, ScriptOption.OptimizerData );
187 | }
188 | }
189 | }
190 |
191 | //////////////////////////////////////////////////////////////////////////
192 | //VIEWS
193 | foreach ( View o in db.Views.Cast().AsQueryable().Where( o => o.IsSystemObject == false ) ) {
194 |
195 | currentPath = csFile.CreateFolder( dbPath, pathify( "VIEW" ) );
196 | filePath = PrepareSqlFile( db.Name, o.Schema, "VIEW", o.Name, currentPath, "" );
197 | WriteSQLInner( db.Name, o.Schema, "VIEW", o.Name, filePath, o, ScriptOption.Default );
198 | WriteSQLInner( db.Name, o.Schema, "VIEW", o.Name, filePath, o, ScriptOption.Indexes );
199 | WriteSQLInner( db.Name, o.Schema, "VIEW", o.Name, filePath, o, ScriptOption.DriAllConstraints );
200 |
201 | //////////////////////////////////////////////////////////////////////////
202 | //VIEW TRIGGERS
203 | currentPath = csFile.CreateFolder( dbPath, pathify( "TRIGGER" ) );
204 | foreach ( Trigger ot in o.Triggers.Cast().AsQueryable().Where( oo => oo.IsSystemObject == false ) ) {
205 | filePath = PrepareSqlFile( db.Name, o.Schema, "TRIGGER", ot.Name, currentPath, "VIEW_" + o.Name );
206 | WriteSQLInner( db.Name, o.Schema, "TRIGGER", ot.Name, filePath, ot, ScriptOption.Default );
207 | }
208 |
209 | //////////////////////////////////////////////////////////////////////////
210 | //VIEW STATISTICS
211 | if ( ExportStatistics ) {
212 | currentPath = csFile.CreateFolder( dbPath, pathify( "STATISTIC" ) );
213 | foreach ( Statistic ot in o.Statistics.Cast().AsQueryable() ) {
214 | filePath = PrepareSqlFile( db.Name, o.Schema, "STATISTIC", ot.Name, currentPath, "VIEW_" + o.Name );
215 | WriteSQLInner( db.Name, o.Schema, "STATISTIC", ot.Name, filePath, ot, ScriptOption.OptimizerData );
216 | }
217 | }
218 | }
219 |
220 | }
221 |
222 | if ( UseDAC )
223 | DB.TryDisableDAC();
224 |
225 | Console.WriteLine( Environment.NewLine );
226 | Console.WriteLine( "Done!" );
227 | Console.ReadKey();
228 |
229 | }
230 |
231 | #region Helpers
232 | private static void WriteHelp() {
233 | Console.WriteLine( "***MS SQL schema dump v1 Beta (http://github.com/georgekosmidis/mssql-schema-dump)***" );
234 | Console.WriteLine( "Exports MS SQL Server database schema, that includes:" );
235 | Console.WriteLine( "DB" );
236 | Console.WriteLine( " Schema, User Types, User Table Types, Triggers, Full Text Catalogues," );
237 | Console.WriteLine( " Full Text StopLists, Stored Procedures, Functions" );
238 | Console.WriteLine( "DB.Tables" );
239 | Console.WriteLine( " Schema, Triggers, Indexes, DRI, Statistics" );
240 | Console.WriteLine( "DB.Views" );
241 | Console.WriteLine( " Schema, Triggers, Indexes, DRI, Statistics" );
242 | Console.WriteLine( "Pass a junk parameter to start with default values shown below!" );
243 | Console.WriteLine( "" );
244 | Console.WriteLine( "Usage: mssqldump -h data-source-host -u username -p password" );
245 | Console.WriteLine( " mssqldump [-d path/for/files] [-c] [-s] [-a] [-b DB1[,DB2[,DB3]]]" );
246 | Console.WriteLine( "" );
247 | Console.WriteLine( "Options:" );
248 | Console.WriteLine( " -h : SQL server host, defaults to (local)" );
249 | Console.WriteLine( " -u : username, defaults to sa" );
250 | Console.WriteLine( " -p : password, defaults to sa" );
251 | Console.WriteLine( " -d : Local path for saved files, defaults to C:\\_SQL_SCHEMA_DUMP\\" );
252 | Console.WriteLine( " -c : Delete all files and folders from local path, defaults to false" );
253 | Console.WriteLine( " -s : Also export statistics, defaults to false" );
254 | Console.WriteLine( " -a : Use DAC to try decrypt encrypted objects, defaults to false" );
255 | Console.WriteLine( " -b : Comma separated value of databases to export, defaults to empty string" );
256 | Console.ReadKey();
257 | }
258 | private static bool ReadArguments( string[] args ) {
259 | try {
260 | for ( int i = 0; i < args.Count(); i++ ) {
261 | switch ( args[i] ) {
262 | case "-h":
263 | if ( args[i + 1].Substring( 0, 1 ) != "-" )
264 | HOST = args[i + 1];
265 | i++;
266 | continue;
267 | case "-u":
268 | if ( args[i + 1].Substring( 0, 1 ) != "-" )
269 | USER = args[i + 1];
270 | i++;
271 | continue;
272 | case "-p":
273 | if ( args[i + 1].Substring( 0, 1 ) != "-" )
274 | PASS = args[i + 1];
275 | i++;
276 | continue;
277 | case "-d":
278 | if ( args[i + 1].Substring( 0, 1 ) != "-" )
279 | SavePath = args[i + 1];
280 | i++;
281 | continue;
282 | case "-c":
283 | CleanDir = true;
284 | continue;
285 | case "-s":
286 | ExportStatistics = true;
287 | continue;
288 | case "-a":
289 | UseDAC = true;
290 | continue;
291 | case "-b":
292 | if ( args[i + 1].Substring( 0, 1 ) != "-" ) {
293 | DBs = args[i + 1].Split( ',' ).ToList().ConvertAll( d => d.ToLower() );
294 | }
295 | continue;
296 | }
297 | }
298 | }
299 | catch {
300 | Console.Clear();
301 | Console.WriteLine( "ERROR!" );
302 | Console.WriteLine( "You have an error in your arguments passed." );
303 | Console.WriteLine( "Press any key to read help" );
304 | Console.ReadKey();
305 | Console.Clear();
306 | WriteHelp();
307 | return false;
308 | }
309 | return true;
310 | }
311 | private static bool WriteSQLInner( string db, string schema, string objType, string objName, string filePath, T o, ScriptingOptions so ) where T : SqlSmoObject {
312 | if ( schema == "" )
313 | schema = "dbo";
314 | if ( db == "*" )
315 | Console.WriteLine( objType + ": " + objName );
316 | else
317 | Console.WriteLine( objType + ": " + db + "." + schema + "." + objName + " (" + so.ToString() + ")" );
318 |
319 |
320 | System.Collections.Specialized.StringCollection cs = new System.Collections.Specialized.StringCollection();
321 | try {
322 | cs = (o as dynamic).Script( so );
323 | }
324 | catch ( Exception ex ) {
325 | if ( UseDAC ) {
326 | try {
327 | DB.ChangeDB( db );
328 | var dt = DB.GetDecryptedObject( objName, objType );
329 | cs.Clear();
330 | cs.Add( dt.Rows[0]["script"].ToString() );
331 | }
332 | catch ( Exception ex2 ) {
333 | Console.WriteLine( ex2.Message );
334 | return false;
335 | }
336 | }
337 | else {
338 | Console.WriteLine( ex.Message );
339 | return false;
340 | }
341 | }
342 |
343 | if ( cs != null ) {
344 | var ts = "";
345 | foreach ( var s in cs )
346 | ts += s + Environment.NewLine;
347 | if ( !String.IsNullOrWhiteSpace( ts.Trim() ) ) {
348 | if ( !File.Exists( filePath ) )
349 | csFile.writeFile( filePath, sqlComments( db, schema, objType, objName ), true );
350 | csFile.writeFile( filePath, ts + ";" + Environment.NewLine, true );
351 | }
352 | }
353 |
354 | return true;
355 | }
356 | private static string PrepareSqlFile( string db, string schema, string objType, string objName, string objPath, string filePrefix ) {
357 | filePrefix = filePrefix != "" ? filePrefix + "_" : filePrefix;
358 | var filePath = objPath + Path.DirectorySeparatorChar + pathify( filePrefix + objType + "_" + schema + "_" + objName ) + ".sql";
359 |
360 | return filePath;
361 | }
362 | private static string pathify( string s ) {
363 | foreach ( var c in System.IO.Path.GetInvalidFileNameChars() )
364 | s = s.Replace( c, '_' );
365 | return s;
366 | }
367 | private static string sqlComments( string db, string schema, string type, string name ) {
368 | var s = "--****************************************************" + Environment.NewLine;
369 | s += "--MS SQL schema dump v1 Beta" + Environment.NewLine;
370 | s += "--Latest Version on GitHub: http://github.com/georgekosmidis/mssql-schema-dump" + Environment.NewLine;
371 | s += "--George Kosmidis " + Environment.NewLine;
372 | s += "-------------------------------------------------------" + Environment.NewLine;
373 | s += "--DB: " + db + Environment.NewLine;
374 | s += "--SCHEMA: " + schema + Environment.NewLine;
375 | s += "--" + type + ": " + name + Environment.NewLine;
376 | s += "--" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + Environment.NewLine;
377 | s += "--****************************************************" + Environment.NewLine + Environment.NewLine;
378 | return s;
379 | }
380 | private static bool DeleteDirectory( string target_dir ) {
381 | string[] files = Directory.GetFiles( target_dir );
382 | string[] dirs = Directory.GetDirectories( target_dir );
383 |
384 | foreach ( string file in files ) {
385 | try {
386 | File.SetAttributes( file, FileAttributes.Normal );
387 | File.Delete( file );
388 | }
389 | catch {
390 | Console.WriteLine( "ERROR!" );
391 | Console.WriteLine( "File '" + file + "' is locked." );
392 | Console.WriteLine( "R: Retry, any other key to exit" );
393 |
394 | var k = Console.ReadKey();
395 | if ( k.Key.ToString().ToLower() == "r" )
396 | return DeleteDirectory( target_dir );
397 |
398 | return false;
399 | }
400 | }
401 | Thread.Sleep( 200 );
402 |
403 | foreach ( string dir in dirs ) {
404 | var b = DeleteDirectory( dir );
405 | }
406 |
407 | try {
408 | Directory.Delete( target_dir, false );
409 | }
410 | catch {
411 | Console.WriteLine( "ERROR!" );
412 | Console.WriteLine( "Directory '" + target_dir + "' is locked." );
413 | Console.WriteLine( "R: Retry, any other key to exit" );
414 |
415 | var k = Console.ReadKey();
416 | if ( k.Key.ToString().ToLower() == "r" )
417 | return DeleteDirectory( target_dir );
418 |
419 | return false;
420 | }
421 | return true;
422 | }
423 |
424 | #endregion
425 | }
426 | }
427 |
--------------------------------------------------------------------------------