private static void ScriptAndWriteToFile(IScriptable scriptableObject, string basePath, string extensionWithPeriod)
        {
            string script = SqlObjectScripter.Script(scriptableObject);

            if (!string.IsNullOrEmpty(script))
            {
                string fileName        = "[Not assigned]";
                string filePathAndName = "[Not assigned]";
                try
                {
                    fileName        = ((NamedSmoObject)scriptableObject).Name.Replace(@"\", "--"); // for domain names mainly, making sure to not mess up file path
                    fileName        = fileName.Replace(":", "_-COLON-_");
                    filePathAndName = Path.Combine(basePath, fileName);
                    filePathAndName = Path.ChangeExtension(filePathAndName, extensionWithPeriod);
                    using (TextWriter writer = new StreamWriter(filePathAndName, false))
                    {
                        writer.WriteLine(script);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception encountered.");
                    Console.WriteLine("FileName: {0} FilePathAndName: {1}", fileName, filePathAndName);
                    Console.WriteLine(e);
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Script the objects matching the provided list of names.
        /// </summary>
        /// <param name="connectionString">Connection to database to find objects in.</param>
        /// <param name="objectNames">Names of objects to script.</param>
/// <param name="infoMessageCallback">Optional callback to capture information messages sent on connection.</param>
        /// <param name="scrubScript">Value indicating whether or not to scrub the script to make it more readable and remove issues that prvent running.</param>
        /// <returns>Collection of scripted objects matching the provided names.</returns>
        public static System.Collections.Generic.IReadOnlyList <ScriptedObject> ScriptObjectsFromDatabase(string connectionString, System.Collections.Generic.IReadOnlyCollection <string> objectNames, SqlInfoMessageEventHandler infoMessageCallback = null, bool scrubScript = true)
        {
            var ret = new List <ScriptedObject>();

            void Logic(Database database)
            {
                var allScriptableObjects = database.GetAllScriptableObjects();
                var filtered             = allScriptableObjects.Where(_ => objectNames.Contains(_.Name)).ToList();

                ret = filtered.Select(_ => SqlObjectScripter.ScriptToObject(_, scrubScript)).ToList();
            }

            SqlServerSmoDatabaseManager.RunOperationOnSmoDatabase(Logic, connectionString, infoMessageCallback);
            return(ret);
        }