public CraftingAI(Character user) { OpenFileDialog openfiledialog = new OpenFileDialog(); openfiledialog.Filter = Resources.CraftingAI_CraftingAI_Crafting_AI_Script____csx____csx; if (openfiledialog.ShowDialog() == DialogResult.Cancel) return; _scriptingObject = new ScriptingObject(user); _host = new ScriptingHost(_scriptingObject); _host.ImportNamespace("Chocobot.Utilities.Keyboard"); _host.ImportNamespace("Chocobot.Datatypes"); try { _host.ExecuteFile(openfiledialog.FileName); } catch (Roslyn.Compilers.CompilationErrorException ex) { MessageBox.Show(ex.Diagnostics.ToString(), Resources.CraftingAI_CraftingAI_Scripting_Error, MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.Print(ex.Diagnostics.ToString()); return; } try { var res = _host.Execute("Initialize();"); } catch (Roslyn.Compilers.CompilationErrorException ex) { Console.WriteLine("{0}{1}", Environment.NewLine, ex.Diagnostics); throw; } _valid = true; }
/// <summary> /// Given a collection of candidate scripting objects, filters the items that match /// based on the passed include and exclude criteria. /// </summary> /// <param name="includeCriteria">The include object criteria.</param> /// <param name="excludeCriteria">The exclude object criteria.</param> /// <param name="includeSchemas">The include schema filter.</param> /// <param name="excludeSchemas">The exclude schema filter.</param> /// <param name="includeTypes">The include type filter.</param> /// <param name="excludeTypes">The exclude type filter.</param> /// <param name="candidates">The candidate object to filter.</param> /// <returns>The matching scripting objects.</returns> public static IEnumerable <ScriptingObject> Match( ScriptingObject includeCriteria, ScriptingObject excludeCriteria, string includeSchemas, string excludeSchemas, string includeTypes, string excludeTypes, IEnumerable <ScriptingObject> candidates) { return(Match( includeCriteria == null ? new ScriptingObject[0] : new[] { includeCriteria }, excludeCriteria == null ? new ScriptingObject[0] : new[] { excludeCriteria }, includeSchemas == null ? new List <string>(): new List <string> { includeSchemas }, excludeSchemas == null ? new List <string>(): new List <string> { excludeSchemas }, includeTypes == null ? new List <string>(): new List <string> { includeTypes }, excludeTypes == null ? new List <string>(): new List <string> { excludeTypes }, candidates)); }
private Urn BuildScriptingObjectUrn( Server server, SqlConnectionStringBuilder connectionStringBuilder, ScriptingObject scriptingObject) { string serverName = server.Name.ToUpper(); // remove the port from server name if specified int commaPos = serverName.IndexOf(','); if (commaPos >= 0) { serverName = serverName.Substring(0, commaPos); } // build the URN string urnString = string.Format( "Server[@Name='{0}']/Database[@Name='{1}']/{2}[@Name='{3}' {4}]", serverName, connectionStringBuilder.InitialCatalog, scriptingObject.Type, scriptingObject.Name, scriptingObject.Schema != null ? string.Format("and @Schema = '{0}'", scriptingObject.Schema) : string.Empty); return(new Urn(urnString)); }
public async void VerifyScriptAsCreateTable() { string query = @"CREATE TABLE testTable1 (c1 int) GO CREATE CLUSTERED INDEX [ClusteredIndex-1] ON [dbo].[testTable1] ( [c1] ASC ) GO "; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Create; ScriptingObject scriptingObject = new ScriptingObject { Name = "testTable1", Schema = "dbo", Type = "Table" }; List <string> expectedScripts = new List <string> { "CREATE TABLE [dbo].[testTable1]", "CREATE CLUSTERED INDEX [ClusteredIndex-1] ON [dbo].[testTable1]" }; await VerifyScriptAsForMultipleObjects(query, new List <ScriptingObject> { scriptingObject }, scriptCreateDrop, expectedScripts); }
private string GenerateScriptSelect(Server server, UrnCollection urns) { string script = string.Empty; ScriptingObject scriptingObject = this.Parameters.ScriptingObjects[0]; Urn objectUrn = urns[0]; string typeName = objectUrn.GetNameForType(scriptingObject.Type); // select from service broker if (string.Compare(typeName, "ServiceBroker", StringComparison.CurrentCultureIgnoreCase) == 0) { script = Scripter.SelectAllValuesFromTransmissionQueue(objectUrn); } // select from queues else if (string.Compare(typeName, "Queues", StringComparison.CurrentCultureIgnoreCase) == 0 || string.Compare(typeName, "SystemQueues", StringComparison.CurrentCultureIgnoreCase) == 0) { script = Scripter.SelectAllValues(objectUrn); } // select from table or view else { Database db = server.Databases[databaseName]; bool isDw = db.IsSqlDw; script = new Scripter().SelectFromTableOrView(server, objectUrn, isDw); } return(script); }
private async Task VerifyScriptAs(string query, ScriptingObject scriptingObject, ScriptingOperationType operation, string expectedScript) { await VerifyScriptAsForMultipleObjects(query, new List <ScriptingObject> { scriptingObject }, operation, new List <string> { expectedScript }); }
/// <summary> /// Given a collection of candidate scripting objects, filters the items that match /// based on the passed include and exclude criteria. /// </summary> /// <param name="includeCriteria">The include object criteria.</param> /// <param name="excludeCriteria">The exclude object criteria.</param> /// <param name="candidates">The candidate object to filter.</param> /// <returns>The matching scripting objects.</returns> public static IEnumerable <ScriptingObject> Match( ScriptingObject includeCriteria, ScriptingObject excludeCriteria, IEnumerable <ScriptingObject> candidates) { return(Match( includeCriteria == null ? new ScriptingObject[0] : new[] { includeCriteria }, excludeCriteria == null ? new ScriptingObject[0] : new[] { excludeCriteria }, candidates)); }
public StartPage(Workbench workbench) : base(workbench, null) { address = Path.Combine(Application.StartupPath, Sinapse.WinForms.Properties.Settings.Default.startpage_path); InitializeComponent(); this.scriptingObject = new ScriptingObject(workbench); this.webBrowser1.Url = new Uri(address); this.webBrowser1.ObjectForScripting = scriptingObject; }
/// <summary> /// Runs the async task that performs the scripting operation. /// </summary> private void RunSelectTask(ConnectionInfo connInfo, ScriptingParams parameters, RequestContext <ScriptingResult> requestContext) { ConnectionServiceInstance.ConnectionQueue.QueueBindingOperation( key: ConnectionServiceInstance.ConnectionQueue.AddConnectionContext(connInfo, "Scripting"), bindingTimeout: ScriptingOperationTimeout, bindOperation: (bindingContext, cancelToken) => { string script = string.Empty; ScriptingObject scriptingObject = parameters.ScriptingObjects[0]; try { Server server = new Server(bindingContext.ServerConnection); server.DefaultTextMode = true; // build object URN SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder(parameters.ConnectionString); Urn objectUrn = BuildScriptingObjectUrn(server, connectionStringBuilder, scriptingObject); string typeName = objectUrn.GetNameForType(scriptingObject.Type); // select from service broker if (string.Compare(typeName, "ServiceBroker", StringComparison.CurrentCultureIgnoreCase) == 0) { script = Scripter.SelectAllValuesFromTransmissionQueue(objectUrn); } // select from queues else if (string.Compare(typeName, "Queues", StringComparison.CurrentCultureIgnoreCase) == 0 || string.Compare(typeName, "SystemQueues", StringComparison.CurrentCultureIgnoreCase) == 0) { script = Scripter.SelectAllValues(objectUrn); } // select from table or view else { Database db = server.Databases[connectionStringBuilder.InitialCatalog]; bool isDw = db.IsSqlDw; script = new Scripter().SelectFromTableOrView(server, objectUrn, isDw); } // send script result to client requestContext.SendResult(new ScriptingResult { Script = script }).Wait(); } catch (Exception e) { requestContext.SendError(e).Wait(); } return(null); }); }
private async Task VerifyScriptAs(string query, ScriptingObject scriptingObject, string scriptCreateDrop, string expectedScript) { var testDb = await SqlTestDb.CreateNewAsync(TestServerType.OnPrem, false, null, query, "ScriptingTests"); try { var requestContext = new Mock <RequestContext <ScriptingResult> >(); requestContext.Setup(x => x.SendResult(It.IsAny <ScriptingResult>())).Returns(Task.FromResult(new object())); ConnectionService connectionService = LiveConnectionHelper.GetLiveTestConnectionService(); using (SelfCleaningTempFile queryTempFile = new SelfCleaningTempFile()) { //Opening a connection to db to lock the db TestConnectionResult connectionResult = await LiveConnectionHelper.InitLiveConnectionInfoAsync(testDb.DatabaseName, queryTempFile.FilePath, ConnectionType.Default); var scriptingParams = new ScriptingParams { OwnerUri = queryTempFile.FilePath, ScriptDestination = "ToEditor" }; scriptingParams.ScriptOptions = new ScriptOptions { ScriptCreateDrop = scriptCreateDrop, }; scriptingParams.ScriptingObjects = new List <ScriptingObject> { scriptingObject }; ScriptingService service = new ScriptingService(); await service.HandleScriptingScriptAsRequest(scriptingParams, requestContext.Object); Thread.Sleep(2000); await service.ScriptingTask; requestContext.Verify(x => x.SendResult(It.Is <ScriptingResult>(r => VerifyScriptingResult(r, expectedScript)))); connectionService.Disconnect(new ServiceLayer.Connection.Contracts.DisconnectParams { OwnerUri = queryTempFile.FilePath }); } } catch { throw; } finally { await testDb.CleanupAsync(); } }
public ScriptAI() : base() { IsRanged = true; Name = "Scripting"; OpenFileDialog openfiledialog = new OpenFileDialog(); openfiledialog.Filter = "Class AI Script (*.csx)|*.csx"; if (openfiledialog.ShowDialog() == DialogResult.Cancel) { return; } _scriptingObject = new ScriptingObject(); _host = new ScriptingHost(_scriptingObject); _host.ImportNamespace("Chocobot.Utilities.Keyboard"); _host.ImportNamespace("Chocobot.Datatypes"); _host.ImportNamespace("Chocobot.MemoryStructures.Abilities.Recast"); _host.ImportNamespace("Chocobot.MemoryStructures.Abilities.Hotkeys"); _host.ImportNamespace("Chocobot.Utilities.Memory"); _host.ImportNamespace("Chocobot.Utilities.Memory.MemoryFunctions"); _host.ImportNamespace("Chocobot.MemoryStructures.Character"); _host.ImportNamespace("System.DateTime"); _host.ImportNamespace("Chocobot.Datatypes.Global"); try { _host.ExecuteFile(openfiledialog.FileName); } catch (Roslyn.Compilers.CompilationErrorException ex) { MessageBox.Show(ex.Diagnostics.ToString(), "Scripting Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.Print(ex.Diagnostics.ToString()); return; } try { var res = _host.Execute("Initialize();"); } catch (Roslyn.Compilers.CompilationErrorException ex) { Console.WriteLine("{0}{1}", Environment.NewLine, ex.Diagnostics); throw; } IsRanged = _scriptingObject.IsRanged; _valid = true; }
public static void CreateAsset() { //Create a new instance of our scriptable object ScriptingObject positionManager = ScriptableObject.CreateInstance <ScriptingObject>(); //Create a .Asset file for our new object and save it AssetDatabase.CreateAsset(positionManager, "Assets/newPositionManager.asset"); AssetDatabase.SaveAssets(); //Now switch the inspector to our new object EditorUtility.FocusProjectWindow(); Selection.activeObject = positionManager; }
public void ScriptingObjectEquality() { ScriptingObject scriptingObject1 = new ScriptingObject { Type = "Table", Schema = "test", Name = "test_table" }; ScriptingObject scriptingObject2 = new ScriptingObject { Type = "Table", Schema = "test", Name = "test_table" }; ScriptingObject scriptingObject3 = null; Assert.True(scriptingObject1.Equals(scriptingObject2)); Assert.False(scriptingObject1.Equals(scriptingObject3)); }
/// <summary> /// Wrapper method that calls Resolver.FindCompletions /// </summary> /// <param name="objectName"></param> /// <param name="schemaName"></param> /// <param name="objectType"></param> /// <param name="tempFileName"></param> /// <returns></returns> internal SmoScriptingOperation InitScriptOperation(string objectName, string schemaName, string objectType) { // object that has to be scripted ScriptingObject scriptingObject = new ScriptingObject { Name = objectName, Schema = schemaName, Type = objectType }; // scripting options ScriptOptions options = new ScriptOptions { ScriptCreateDrop = "ScriptCreate", TypeOfDataToScript = "SchemaOnly", ScriptStatistics = "ScriptStatsNone", TargetDatabaseEngineEdition = GetTargetDatabaseEngineEdition(), TargetDatabaseEngineType = GetTargetDatabaseEngineType(), ScriptCompatibilityOption = GetScriptCompatibilityOption(), ScriptExtendedProperties = false, ScriptUseDatabase = false, IncludeIfNotExists = false, GenerateScriptForDependentObjects = false, IncludeDescriptiveHeaders = false, ScriptCheckConstraints = false, ScriptChangeTracking = false, ScriptDataCompressionOptions = false, ScriptForeignKeys = false, ScriptFullTextIndexes = false, ScriptIndexes = false, ScriptPrimaryKeys = false, ScriptTriggers = false, UniqueKeys = false }; List <ScriptingObject> objectList = new List <ScriptingObject>(); objectList.Add(scriptingObject); // create parameters for the scripting operation ScriptingParams parameters = new ScriptingParams { ConnectionString = ConnectionService.BuildConnectionString(this.connectionInfo.ConnectionDetails), ScriptingObjects = objectList, ScriptOptions = options, ScriptDestination = "ToEditor" }; return(new ScriptAsScriptingOperation(parameters, serverConnection)); }
public void ToUrnEscapesAttributes() { var scriptingObject = new ScriptingObject() { Name = "quoted'Name", Schema = "quoted'Schema", Type = "Table" }; var urn = scriptingObject.ToUrn("server", "quoted'db"); Assert.That(urn.ToString, Is.EqualTo("Server[@Name='SERVER']/Database[@Name='quoted''db']/Table[@Name='quoted''Name' and @Schema = 'quoted''Schema']"), "Urn should have escaped Name attributes"); Assert.That(urn.Type, Is.EqualTo("Table"), "Urn Type"); // These assertions are more for educational purposes than for testing, since the methods are Urn methods in SFC. Assert.That(urn.GetNameForType("Database"), Is.EqualTo("quoted'db"), "GetNameForType('Database')"); Assert.That(urn.GetAttribute("Schema"), Is.EqualTo("quoted'Schema"), "GetAttribute('Schema')"); }
public async void VerifyScriptAsDropStoredProcedure() { string query = "CREATE PROCEDURE testSp1 AS BEGIN Select * from sys.all_columns END"; string scriptCreateDrop = "ScriptDrop"; ScriptingObject scriptingObject = new ScriptingObject { Name = "testSp1", Schema = "dbo", Type = "StoredProcedure" }; string expectedScript = "DROP PROCEDURE [dbo].[testSp1]"; await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); }
public ScriptAI() : base() { IsRanged = true; Name = "Scripting"; OpenFileDialog openfiledialog = new OpenFileDialog(); openfiledialog.Filter = "Class AI Script (*.csx)|*.csx"; if (openfiledialog.ShowDialog() == DialogResult.Cancel) return; _scriptingObject = new ScriptingObject(); _host = new ScriptingHost(_scriptingObject); _host.ImportNamespace("Chocobot.Utilities.Keyboard"); _host.ImportNamespace("Chocobot.Datatypes"); _host.ImportNamespace("Chocobot.MemoryStructures.Abilities.Recast"); _host.ImportNamespace("Chocobot.MemoryStructures.Abilities.Hotkeys"); _host.ImportNamespace("Chocobot.Utilities.Memory"); _host.ImportNamespace("Chocobot.Utilities.Memory.MemoryFunctions"); _host.ImportNamespace("Chocobot.MemoryStructures.Character"); _host.ImportNamespace("System.DateTime"); _host.ImportNamespace("Chocobot.Datatypes.Global"); try { _host.ExecuteFile(openfiledialog.FileName); } catch (Roslyn.Compilers.CompilationErrorException ex) { MessageBox.Show(ex.Diagnostics.ToString(), "Scripting Error", MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.Print(ex.Diagnostics.ToString()); return; } try { var res = _host.Execute("Initialize();"); } catch (Roslyn.Compilers.CompilationErrorException ex) { Console.WriteLine("{0}{1}", Environment.NewLine, ex.Diagnostics); throw; } IsRanged = _scriptingObject.IsRanged; _valid = true; }
public async void VerifyScriptAsDropTable() { string query = "CREATE TABLE testTable1 (c1 int)"; string scriptCreateDrop = "ScriptDrop"; ScriptingObject scriptingObject = new ScriptingObject { Name = "testTable1", Schema = "dbo", Type = "Table" }; string expectedScript = "DROP TABLE [dbo].[testTable1]"; await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); }
public async void VerifyScriptAsSelectTable() { string query = "CREATE TABLE testTable1 (c1 int)"; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Select; ScriptingObject scriptingObject = new ScriptingObject { Name = "testTable1", Schema = "dbo", Type = "Table" }; string expectedScript = "SELECT TOP (1000) [c1]"; await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); }
public async void VerifyScriptAsExecuteTableFailes() { string query = "CREATE TABLE testTable1 (c1 int)"; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Execute; ScriptingObject scriptingObject = new ScriptingObject { Name = "testTable1", Schema = "dbo", Type = "Table" }; string expectedScript = null; await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); }
public async void VerifyScriptAsDropView() { string query = "CREATE VIEW testView1 AS SELECT * from sys.all_columns"; string scriptCreateDrop = "ScriptDrop"; ScriptingObject scriptingObject = new ScriptingObject { Name = "testView1", Schema = "dbo", Type = "View" }; string expectedScript = "DROP VIEW [dbo].[testView1]"; await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); }
private static IEnumerable <ScriptingObject> MatchCriteria(ScriptingObject criteria, IEnumerable <ScriptingObject> candidates) { Validate.IsNotNull("criteria", criteria); Validate.IsNotNull("candidates", candidates); IEnumerable <ScriptingObject> matchedObjects = candidates; if (!string.IsNullOrWhiteSpace(criteria.Type)) { matchedObjects = matchedObjects.Where(o => string.Equals(criteria.Type, o.Type, StringComparison.OrdinalIgnoreCase)); } matchedObjects = MatchCriteria(criteria.Schema, (candidate) => { return(candidate.Schema); }, matchedObjects); matchedObjects = MatchCriteria(criteria.Name, (candidate) => { return(candidate.Name); }, matchedObjects); return(matchedObjects); }
/// <summary> /// Creates a SMO Urn instance based on the passed ScriptingObject instance. /// </summary> /// <param name="scriptingObject">The scripting object instance.</param> /// <param name="database">The name of the database referenced by the Urn.</param> /// <returns>The Urn instance.</returns> public static Urn ToUrn(this ScriptingObject scriptingObject, string database) { Validate.IsNotNull("scriptingObject", scriptingObject); Validate.IsNotNullOrWhitespaceString("database", database); Validate.IsNotNullOrWhitespaceString("scriptingObject.Name", scriptingObject.Name); Validate.IsNotNullOrWhitespaceString("scriptingObject.Type", scriptingObject.Type); // Leaving the server name blank will automatically match whatever the server SMO is running against. string urn = string.Format( "Server/Database[@Name='{0}']/{1}[@Name='{2}' {3}]", database, scriptingObject.Type, scriptingObject.Name, scriptingObject.Schema != null ? string.Format("and @Schema = '{0}'", scriptingObject.Schema) : string.Empty); return(new Urn(urn)); }
public CraftingAI(Character user) { OpenFileDialog openfiledialog = new OpenFileDialog(); openfiledialog.Filter = Resources.CraftingAI_CraftingAI_Crafting_AI_Script____csx____csx; if (openfiledialog.ShowDialog() == DialogResult.Cancel) { return; } _scriptingObject = new ScriptingObject(user); _host = new ScriptingHost(_scriptingObject); _host.ImportNamespace("Chocobot.Utilities.Keyboard"); _host.ImportNamespace("Chocobot.Datatypes"); try { _host.ExecuteFile(openfiledialog.FileName); } catch (Roslyn.Compilers.CompilationErrorException ex) { MessageBox.Show(ex.Diagnostics.ToString(), Resources.CraftingAI_CraftingAI_Scripting_Error, MessageBoxButtons.OK, MessageBoxIcon.Error); Debug.Print(ex.Diagnostics.ToString()); return; } try { var res = _host.Execute("Initialize();"); } catch (Roslyn.Compilers.CompilationErrorException ex) { Console.WriteLine("{0}{1}", Environment.NewLine, ex.Diagnostics); throw; } _valid = true; }
public async void VerifyScriptAsExecuteStoredProcedure() { string query = @"CREATE PROCEDURE testSp1 @BusinessEntityID [int], @JobTitle [nvarchar](50), @HireDate [datetime], @RateChangeDate [datetime], @Rate [money], @PayFrequency [tinyint] AS BEGIN Select * from sys.all_columns END"; ScriptingOperationType scriptCreateDrop = ScriptingOperationType.Execute; ScriptingObject scriptingObject = new ScriptingObject { Name = "testSp1", Schema = "dbo", Type = "StoredProcedure" }; string expectedScript = "EXECUTE @RC = [dbo].[testSp1]"; await VerifyScriptAs(query, scriptingObject, scriptCreateDrop, expectedScript); }
private string GenerareScriptAsExecute(Server server, UrnCollection urns, ScriptingOptions options) { string script = string.Empty; ScriptingObject scriptingObject = this.Parameters.ScriptingObjects[0]; Urn urn = urns[0]; // get the object StoredProcedure sp = server.GetSmoObject(urn) as StoredProcedure; Database parentObject = server.GetSmoObject(urn.Parent) as Database; StringBuilder executeStatement = new StringBuilder(); // list of DECLARE <variable> <type> StringBuilder declares = new StringBuilder(); // Parameters to be passed StringBuilder parameterList = new StringBuilder(); if (sp == null || parentObject == null) { throw new InvalidOperationException(SR.ScriptingExecuteNotSupportedError); } WriteUseDatabase(parentObject, executeStatement, options); // character string to put in front of each parameter. First one is just carriage return // the rest will have a "," in front as well. string newLine = Environment.NewLine; string paramListPreChar = $"{newLine} "; for (int i = 0; i < sp.Parameters.Count; i++) { StoredProcedureParameter spp = sp.Parameters[i]; declares.AppendFormat("DECLARE {0} {1}{2}" , QuoteObjectName(spp.Name) , GetDatatype(spp.DataType, options) , newLine); parameterList.AppendFormat("{0}{1}" , paramListPreChar , QuoteObjectName(spp.Name)); // if this is the first time through change the prefix to include a "," if (i == 0) { paramListPreChar = $"{newLine} ,"; } // mark any output parameters as such. if (spp.IsOutputParameter) { parameterList.Append(" OUTPUT"); } } // build the execute statement if (sp.ImplementationType == ImplementationType.TransactSql) { executeStatement.Append("EXECUTE @RC = "); } else { executeStatement.Append("EXECUTE "); } // get the object name executeStatement.Append(GenerateSchemaQualifiedName(sp.Schema, sp.Name, options.SchemaQualify)); string formatString = sp.ImplementationType == ImplementationType.TransactSql ? "DECLARE @RC int{5}{0}{5}{1}{5}{5}{2} {3}{5}{4}" : "{0}{5}{1}{5}{5}{2} {3}{5}{4}"; script = string.Format(CultureInfo.InvariantCulture, formatString, declares, SR.StoredProcedureScriptParameterComment, executeStatement, parameterList, CommonConstants.DefaultBatchSeperator, newLine); return(script); }