public void RestoreDatabase(SqlConnectionStringBuilder sqlConnection, String backUpFile)
		{
			ServerConnection serverConnection = null;
			try
			{
				if (!FileManager.FileExists(backUpFile))
				{
					throw new FileNotFoundException();
				}
				serverConnection = new ServerConnection(sqlConnection.DataSource, sqlConnection.UserID, sqlConnection.Password);
				Server sqlServer = new Server(serverConnection);
				Restore restoreDatabase = new Restore()
				{
					Action = RestoreActionType.Database,
					Database = sqlConnection.InitialCatalog,
				};
				BackupDeviceItem backupItem = new BackupDeviceItem(backUpFile, DeviceType.File);
				restoreDatabase.Devices.Add(backupItem);
				restoreDatabase.ReplaceDatabase = true;
				restoreDatabase.SqlRestore(sqlServer);
			}
			finally
			{
				if (serverConnection != null && serverConnection.IsOpen)
				{
					serverConnection.Disconnect();
				}
			}
		}
Exemple #2
0
        public void ParseTablesTest()
        {
            //	#	Arrange.
            const string DatabaseName = "ParseTablesTest.mdf";
            var connectionString = string.Format(ConnectionStringTemplate,
                Path.Combine( Common.Functions.SolutionPath(TestContext), DatabasePath, DatabaseName));
            IList<Table> tables;

            using (var conn = new SqlConnection(connectionString))
            {
                var serverConnection = new ServerConnection(conn);
                var server = new Server(serverConnection);
                var database = server.Databases[
                    Path.Combine(Common.Functions.SolutionPath(TestContext), DatabasePath, DatabaseName)];
                tables = ServerInfo.UT_GetTablesByDatabasePrivate(database);
            }
            var sut = new ParserLogic();

            //	#	Act.
            var res = sut.Parse(tables, "Project");

            //	#	Assert.
            Assert.AreEqual(3, res.Tables.Count);

            var projectTable = res.Tables.Single(t => t.Name == "Project");
            Assert.IsFalse(projectTable.Include);

            var customerTable = res.Tables.Single(t => t.Name == "Customer");
            Assert.IsTrue(customerTable.Include);

            var userTable = res.Tables.Single(t => t.Name == "User");
            Assert.IsTrue(userTable.Include);
        }
        private void ddlCatalog_DropDown(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Application.DoEvents();
            if (ddlAuthType.Text == "SQL Server Authentication")
            {
                ServerConnection svrConn = new ServerConnection(tbServerName.Text);
                svrConn.LoginSecure = false;
                svrConn.Login = tbLogin.Text;
                svrConn.Password = tbPassword.Text;
                _SourceServer = new Server(svrConn);
            }
            else
                _SourceServer = new Server(tbServerName.Text);

            ddlCatalog.Items.Clear();

            try
            {
                foreach (Database db in _SourceServer.Databases)
                {
                    ddlCatalog.Items.Add(db.Name);
                }
            }
            catch (ConnectionFailureException ex)
            {
                MessageBox.Show(this, ex.Message, "Connection Failed!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        public System.Collections.Generic.IReadOnlyList<TableDefinition> GetDefinitions(ISqlConnectionProvider sqlConnectionProvider)
        {
            var conn = sqlConnectionProvider.GetConnection();
            var dbName = conn.Database;
            var serverConnection = new ServerConnection(conn);
            var server = new Server(serverConnection);
            var scripter = new Scripter(server);
            scripter.Options.ScriptDrops = false;
            scripter.Options.WithDependencies = false;
            scripter.Options.NoCollation = true;

            var db = server.Databases[dbName];
            var results = new List<TableDefinition>();

            foreach (Table table in db.Tables)
            {
                if (table.IsSystemObject)
                    continue;
                var id = table.ID;
                var definitions = scripter.Script(new Urn[] {table.Urn});
                var sb = new StringBuilder();
                foreach (var definition in definitions)
                {
                    sb.AppendLine(definition);
                }
                var flattened = sb.ToString();
                results.Add(new TableDefinition(id, flattened));
            }

            return results;
        }
Exemple #5
0
    public void ReplaceDatabase(string connectionString, string dbReplacementPath)
    {
      var connection = new SqlConnectionStringBuilder(connectionString);
      var databaseName = connection.InitialCatalog;
      if (!File.Exists(dbReplacementPath))
      {
        Log.Error($"Can't find file by path {dbReplacementPath}", this);
        return;
      }

      ServerConnection serverConnection = null;
      try
      {
        serverConnection = new ServerConnection(new SqlConnection(connectionString));
        var server = new Server(serverConnection);

        if (server.Databases[databaseName] != null)
        {
          server.KillAllProcesses(databaseName);
          server.DetachDatabase(databaseName, true);
        }

        server.AttachDatabase(databaseName,new StringCollection() {dbReplacementPath}, AttachOptions.RebuildLog);
      }
      catch (Exception ex)
      {
        Log.Error(ex.Message, ex, this);
      }
      finally
      {
        serverConnection?.Disconnect();
      }
    }
        public void TestServerConnection()
        {
            ServerConnection sc = new ServerConnection();

            // User information.
            string emailAddress = "*****@*****.**";
            string password = "******";

            sc.Login(
                emailAddress,
                password,
                new EventDelegates.HTTPResponseDelegate(ProcessResponse),
                new EventDelegates.HTTPFailDelegate(FailRequest));

            sc.GetSightsList(
                new EventDelegates.HTTPResponseDelegate(ProcessResponse),
                new EventDelegates.HTTPFailDelegate(FailRequest));

            // Load photo from file.
            Uri uri = new Uri("img.jpg", UriKind.Relative);
            StreamResourceInfo streamResourceInfo = Application.GetResourceStream(uri);
            Stream imageStream = streamResourceInfo.Stream;
            int imageSize = (int)imageStream.Length;
            BinaryReader binReader = new BinaryReader(imageStream);
            byte[] imageBytes = new byte[imageSize];
            int count = binReader.Read(imageBytes, 0, (int)imageSize);
            binReader.Close();

            sc.UploadPhoto(
                4, // my user ID
                imageBytes,
                new EventDelegates.HTTPResponseDelegate(ProcessResponse),
                new EventDelegates.HTTPFailDelegate(FailRequest));
        }
Exemple #7
0
        private void LoadRegAssembly_Load(object sender, System.EventArgs e)
        {
            ServerConnection myServerConn;
            ServerConnect scForm;
            DialogResult dr;

            // Display the main window first
            this.Show();
            Application.DoEvents();
            
            myServerConn = new ServerConnection();
            scForm = new ServerConnect(myServerConn);
            dr = scForm.ShowDialog(this);
            if ((dr == DialogResult.OK) &&
                (myServerConn.SqlConnectionObject.State
                == ConnectionState.Open))
            {
                mySqlServer = new Server(myServerConn);
                if (mySqlServer != null)
                {
                    this.Text = Properties.Resources.AppTitle + mySqlServer.Name;

                    // Refresh database list
                    ShowDatabases(true);
                    UpdateButtons();
                }
            }
            else
            {
                this.Close();
            }
        }
 public static void RunScript(string scriptText)
 {
     SqlConnection sqlConnection = new SqlConnection(Settings.Default.TestDb);
     ServerConnection svrConnection = new ServerConnection(sqlConnection);
     Server server = new Server(svrConnection);
     server.ConnectionContext.ExecuteNonQuery(scriptText);
 }
Exemple #9
0
        private static void LoadDatabase()
        {
            //Connect to the server
            var connectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=master;Integrated Security=SSPI";
            var con = new SqlConnection(connectionString);
            ServerConnection serverConnection = new ServerConnection(con);
            Server sqlServer = new Server(serverConnection);

            System.IO.FileInfo mdf = new System.IO.FileInfo(@"Buzzle.mdf");
            System.IO.FileInfo ldf = new System.IO.FileInfo(@"Buzzle_log.LDF");

            var dbPath = sqlServer.MasterDBPath;
            var databasePath = dbPath + @"\Buzzle.mdf";
            var databaseLogPath = dbPath + @"\Buzzle_log.LDF";

            File.Copy(mdf.FullName, databasePath, true);
            File.Copy(ldf.FullName, databaseLogPath, true);

            var databasename = mdf.Name.ToLower().Replace(@".mdf", @"");

            System.Collections.Specialized.StringCollection databasefiles = new System.Collections.Specialized.StringCollection();
            databasefiles.Add(databasePath);
            databasefiles.Add(databaseLogPath);

            sqlServer.AttachDatabase(databasename, databasefiles);
        }
        private static bool ExecuteSqlScript(string connectionString, string databaseName, string script)
        {
            bool scriptSucceeded = false;

            var connection = new ServerConnection();
            connection.ConnectionString = connectionString;
            connection.StatementTimeout = 3600;
            connection.Connect();
            Server sqlServer = new Server(connection);
            Database dbTarget = sqlServer.Databases[databaseName];
            if (dbTarget != null)
            {
                connection.BeginTransaction();
                try
                {
                    dbTarget.ExecuteNonQuery(script);
                    connection.CommitTransaction();
                    scriptSucceeded = true;
                }
                catch (Exception ex)
                {
                    connection.RollBackTransaction();
                    throw new Exception("Failed to execute script", ex);
                }
                finally
                {
                    connection.Disconnect();
                }
            }
            return scriptSucceeded;
        }
        public void BackupDatabase(String databaseName, String userName, String password, String serverName, String destinationPath)
        {
            Backup sqlBackup = new Backup();
            
            sqlBackup.Action = BackupActionType.Database;
            sqlBackup.BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString();
            sqlBackup.BackupSetName = "Archive";

            sqlBackup.Database = databaseName;

            BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);
            ServerConnection connection = new ServerConnection(serverName, userName, password);
            Server sqlServer = new Server(connection);
            
            Database db = sqlServer.Databases[databaseName];
            
            sqlBackup.Initialize = true;
            sqlBackup.Checksum = true;
            sqlBackup.ContinueAfterError = true;
            
            sqlBackup.Devices.Add(deviceItem);
            sqlBackup.Incremental = false;

            sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
            sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

            sqlBackup.FormatMedia = false;

            sqlBackup.SqlBackup(sqlServer);
        }
        public override string GenerateSqlScript(bool includeData)
        {
            var serverConn = new ServerConnection((SqlConnection)connection);
            server = new Server(serverConn);
            var db = new Database(server, connection.Database);
            List<Urn> list = new List<Urn>();
            DataTable dataTable = db.EnumObjects(DatabaseObjectTypes.Table);
            foreach (DataRow row in dataTable.Rows)
            {
                list.Add(new Urn((string)row["Urn"]));
            }

            Scripter scripter = new Scripter();
            scripter.Server = server;
            scripter.Options.IncludeDatabaseContext = false;
            scripter.Options.IncludeHeaders = true;
            scripter.Options.SchemaQualify = true;
            scripter.Options.ScriptData = includeData;
            scripter.Options.SchemaQualifyForeignKeysReferences = true;
            scripter.Options.NoCollation = true;
            scripter.Options.DriAllConstraints = true;
            scripter.Options.DriAll = true;
            scripter.Options.DriAllKeys = true;
            scripter.Options.Triggers = true;
            scripter.Options.DriIndexes = true;
            scripter.Options.ClusteredIndexes = true;
            scripter.Options.NonClusteredIndexes = true;
            scripter.Options.ToFileOnly = false;
            var scripts = scripter.EnumScript(list.ToArray());
            string result = "";
            foreach (var script in scripts)
                result += script + Environment.NewLine;
            serverConn.Disconnect();
            return result;
        }
Exemple #13
0
 public Job GetJob()
 {
     ServerConnection connection = new ServerConnection("mi001-ws00071", "SA", "Oberon");
     connection.Connect();
     Server jobserver = new Server(connection);
     return jobserver.JobServer.Jobs["PVX"];
 }
Exemple #14
0
 protected void btnComparison_Click(object sender, EventArgs e)
 {
     try
     {
         ServerConnection conTar = new ServerConnection(this.txtTarServer.Text,
             this.txtTarUid.Text,
             this.txtTarPwd.Text);
         conTar.Connect();
         Session.Add("TarServerName", this.txtTarServer.Text);
         Session.Add("TarUName", this.txtTarUid.Text);
         Session.Add("TarUpwd", this.txtTarPwd.Text);
         ServerConnection conSour = new ServerConnection(this.txgSourName.Text,
             this.txtSourUid.Text,
             this.txtSourPwd.Text);
         conSour.Connect();
         Session.Add("SourServerName", this.txgSourName.Text);
         Session.Add("SourUName", this.txtSourUid.Text);
         Session.Add("SourUpwd", this.txtSourPwd.Text);
         Response.Redirect("DatabasesPage.aspx");
     }
     catch (Exception ex)
     {
         Response.Write("<script>alert('" + ex.Message + "')</script>");
     }
 }
Exemple #15
0
		static void Main(string[] args)	{
			// Configure Resource manager
			string path = System.Configuration.ConfigurationSettings.AppSettings["ResourcePath"];
			if ( path == null ) {
				//throw new System.Configuration.ConfigurationException( "ResourcePath" );
			}
			CurrentMessageProcessor = new MessageProcessor();

			// Initialise required objects
			CurrentServerConnection = new ServerConnection();
			CurrentServerConnection.OnConnect += new ServerConnection.OnConnectHandler( HandleConnect );
			CurrentServerConnection.OnDisconnect += new ServerConnection.OnDisconnectHandler( HandleDisconnect );

			CurrentMainWindow = new Windows.Main();
			CurrentMainWindow.Show();
			//CurrentWorld.InitialiseView( CurrentMainWindow, CurrentMainWindow.RenderTarget, CurrentMainWindow.miniMap.RenderTarget );

			Windows.ChildWindows.Connection con = new Windows.ChildWindows.Connection();
			con.Show();

			while( !CurrentMainWindow.IsDisposed ) {
				// NB: This is a tight renderloop
				// it will chew cpu
				// TODO: could be made nicer by
				// P/Invoke into the Win32 API and call PeekMessage/TranslateMessage/DispatchMessage.  (Doevents actually does something similar, but you can do this without the extra allocations). 
				Application.DoEvents();
				if ( CurrentServerConnection.isRunning ) {
					GameLoop();
				}
				System.Threading.Thread.Sleep( 0 );
			}

			// must terminate all threads to quit
			CurrentServerConnection.Stop();
		}
Exemple #16
0
        private void btnBackupFile_Click(object sender, EventArgs e)
        {
            var fileDialog=new OpenFileDialog
                        {
                           Filter = @"Backup File(*.bak)|*.bak|All File(*.*)|*.*",
                           FilterIndex = 0
                        };

            if (fileDialog.ShowDialog()== DialogResult.OK)
            {

                var cnn = new SqlConnection(_connectionString);
                cnn.Open();
                var conn = new ServerConnection(cnn);
                var myServer = new Server(conn);

                var currentDb = myServer.Databases[_database];
                if (currentDb != null)
                {
                    txtCoSoDuLieu.Text = _database;
                }
                txtTenTapTin.Text = fileDialog.FileName;
                cnn.Close();
            }
        }
        /// <summary>
        /// Constructor of the class. Sets up the commands, variables and the sql-connection.
        /// </summary>
        /// <param name="adminLogIn">Login data of the admin account.</param>
        public UserEditorViewModel(Views.Utils.LogIn adminLogIn)
        {
            AddUserCommand = new RelayCommand(() => _AddUserCommand(), () => true);
            RemoveUserCommand = new RelayCommand(() => _RemoveUserCommand(), () => true);
            DownloadDatabaseCommand = new RelayCommand(() => _BackupDatabaseCommand(), () => true);

            AdminLogIn = adminLogIn;

            sqlConnection = new SqlConnection(@"Data Source = " + adminLogIn.IPAdress + ", " + adminLogIn.Port + "; Network Library = DBMSSOCN; User ID = " + adminLogIn.UserName + "; Password = "******"; ");
            //ServerConnection serverConnection = new ServerConnection(sqlConnection);
            ServerConnection serverConnection = new ServerConnection(adminLogIn.IPAdress + ", " + adminLogIn.Port);
            server = new Server(serverConnection);
            server.ConnectionContext.LoginSecure = false;
            server.ConnectionContext.Login = adminLogIn.UserName;
            server.ConnectionContext.Password = adminLogIn.Password;

            try
            {
                string temp = server.Information.Version.ToString();   // connection is established
            }
            catch (ConnectionFailureException e)
            {
                MessageBox.Show("Login error: " + e.Message, "Error");
                DialogResult = false;
                return;
            }

            Users = new ObservableCollection<MyUser>();

            FillUserList();
        }
        public SQLObjects()
        {
            //GetServers();

            var instances = GetInstances(true);
            var connection = new ServerConnection(@"Brian-THINK\Lenovo", "brian", "brian");

            var server = GetServer(connection);

            //var t = Microsoft.SqlServer.Management.Smo.NamedSmoObject
            //var foreignKeys = Microsoft.SqlServer.Management.Smo.ForeignKey
            //var foreignKeyColumns = Microsoft.SqlServer.Management.Smo.ForeignKeyColumn
            //var fullTextIndicies = Microsoft.SqlServer.Management.Smo.FullTextIndex
            //var logins = Microsoft.SqlServer.Management.Smo.Login

            var db = GetDatabase(server, "MiGANG");

            var foreignKeys = GetForeignKeys(db);
            var foreignKeyss = GetForeignKeys(db, new Table(db, "Meetings"));

            //Database database = server.Databases[1];

            //GetPrimaryKeys(database);
            //GetForeignKeys(database);

            //Database db = server.Databases.Cast<Database>().Where(x => x.Name == "MiGANG").SingleOrDefault();
            //DatabaseObjects dbo = new DatabaseObjects(database);
        }
Exemple #19
0
        public SqlObjectBrowser(ServerConnection serverConn)
        {
            InitializeComponent();

            // Connect to SQL Server
            server = new Server(serverConn);
            try
            {
                server.ConnectionContext.Connect();

                // In case connection succeeded we add the sql server node as root in object explorer (treeview)
                TreeNode tn = new TreeNode();
                tn.Text = server.Name;
                tn.Tag = server.Urn;
                this.objUrn = server.Urn;
                objectBrowserTreeView.Nodes.Add(tn);

                AddDummyNode(tn);

                connected = true;
            }
            catch (ConnectionException)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox();
                emb.Text = Properties.Resources.ConnectionFailed;
                emb.Show(this);
            }
            catch (ApplicationException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
            }
        }
Exemple #20
0
        public Task<BackupResult> CreateBackup(string backupFilePath, string instanceName, string database, string username, string password)
        {
            return new Task<BackupResult>(() =>
            {
                var filePath = string.Format("{0}\\{1}_{2}.bak", backupFilePath, DateTime.Now.ToString("yyyyMMdd_HHmm"), database);

                var backupDeviceItem = new BackupDeviceItem(filePath, DeviceType.File);
                var backup = new Backup
                {
                    Database = database,
                    Initialize = true,
                    Incremental = false,
                    CopyOnly = true,
                    Action = BackupActionType.Database,
                };

                backup.Devices.Add(backupDeviceItem);

                var serverConnection = new ServerConnection(instanceName, username, password);
                var server = new Server(serverConnection);

                backup.PercentComplete += PercentComplete;

                backup.SqlBackup(server);

                return new BackupResult(filePath, BackupType.Sql);
            });
        }
Exemple #21
0
        public SqlServerManager(string serverName, string instanceName)
        {
            string path = string.Format(@"{0}\{1}", serverName, instanceName);
            ServerConnection connection = new ServerConnection(path) {LoginSecure = true};

            _server = new Server(connection);
        }
Exemple #22
0
        static void Main(string[] args)
        {
            ServerConnection serverConnection = new ServerConnection("localhost", "sa", "123456");
            Server server = new Server(serverConnection);
            var clientRegistry = server.Databases
                .Cast<Database>()
                .Single(db => db.Name == "ClientRegistry");

            //foreach (Database db in server.Databases)
            //{
            //    Console.WriteLine("[DATABASE] {0}:", db.Name);
            //    foreach (Table item in db.Tables)
            //    {
            //        Console.WriteLine("\t[TABLE] {0}:", item.Name);
            //        foreach (Column column in item.Columns)
            //        {
            //            Console.WriteLine("\t\t{0}:{1}", column.Name, column.DataType);
            //        }
            //    }
            //}

            Console.WriteLine("[DATABASE] {0}:", clientRegistry.Name);
            foreach (Table item in clientRegistry.Tables)
            {
                Console.WriteLine("\t[TABLE] {0}:", item.Name);
                foreach (Column column in item.Columns)
                {
                    Console.WriteLine("\t\t{0}:{1}", column.Name, column.DataType);
                }
            }
        }
Exemple #23
0
        public bool Execute(ApplyTaskConfiguration configuration, GusTaskExecutionContext context)
        {
            var databaseHelper = new DatabaseHelper(context);
            var fileSystemHelper = new FileSystemHelper(context);

            var connection = databaseHelper.CreateAndOpenConnection(configuration.Server);
            if (connection == null)
            {
                return false;
            }

            var serverConnection = new ServerConnection(connection);
            var server = new Server(serverConnection);

            var database = databaseHelper.InitializeDatabase(server, configuration.Database, configuration.CreateDatabaseIfMissing, configuration.CreateDatabaseIfMissing || configuration.CreateManagementSchemaIfMissing);
            if (database == null)
            {
                return false;
            }

            context.RaiseExecutionEvent("Determining scripts to apply.");
            var scriptsToApply = GetScriptsToApply(configuration.SourcePath, database, databaseHelper, fileSystemHelper);
            if (scriptsToApply == null)
            {
                return false;
            }

            context.ExecutionStepCount = (uint)scriptsToApply.Count;
            context.RaiseExecutionEvent(string.Format("Found {0} scripts to apply.", scriptsToApply.Count));

            var success = ApplyScripts(scriptsToApply, server, database, databaseHelper, fileSystemHelper, configuration.RecordOnly, context, configuration.HaltOnError);

            return success;
        }
Exemple #24
0
        public static void MakeRestore(ServerMessageEventHandler onComplete, Guid id,
            string serverName, string dbName, string uncDir, string userName, string password)
        {
            var sc = new ServerConnection(serverName);
            sc.LoginSecure = false;
            sc.Login = userName;
            sc.Password = password;

            var srv = new Server(sc);
            var rest = new Restore();

            rest.Action = RestoreActionType.Database;
            rest.Database = dbName;
            rest.Devices.AddDevice(Path.Combine(uncDir, rest.Database + ".bak"), DeviceType.File);
            rest.ReplaceDatabase = true;

            var headers = rest.ReadBackupHeader(srv);
            var query = from DataRow row in headers.Rows
                        where (string)row["BackupName"] == id.ToString()
                        select (Int16)row["Position"];

            rest.FileNumber = query.First();

            if (onComplete != null) rest.Complete += onComplete;
            rest.SqlRestore(srv);
        }
Exemple #25
0
        public void CreateDatabase()
        {
            var connectoinStringBuilder = new SqlConnectionStringBuilder(ConnectionString);
            string dbName = connectoinStringBuilder.InitialCatalog;
            connectoinStringBuilder.InitialCatalog = string.Empty;

            using (var connection = new SqlConnection(connectoinStringBuilder.ToString()))
            {
                try
                {
                    var serverConnection = new ServerConnection(connection);
                    var server = new Microsoft.SqlServer.Management.Smo.Server(serverConnection);
                    var db = new Database(server, dbName);
                    db.Create();
                }
                catch (Exception e)
                {
                    throw new Exception(string.Format("Ошибка при создании БД - {0}", e));
                }
                finally
                {
                    if (connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                    }
                }
            }
        }
Exemple #26
0
        private void ManageTables_Load(object sender, System.EventArgs e)
        {
            ServerConnection ServerConn;
            ServerConnect scForm;
            DialogResult dr;

            // Display the main window first
            this.Show();
            Application.DoEvents();

            ServerConn = new ServerConnection();
            scForm = new ServerConnect(ServerConn);
            dr = scForm.ShowDialog(this);
            if ((dr == DialogResult.OK) &&
                (ServerConn.SqlConnectionObject.State == ConnectionState.Open))
            {
                SqlServerSelection = new Server(ServerConn);
                if (SqlServerSelection != null)
                {
                    this.Text = Properties.Resources.AppTitle + SqlServerSelection.Name;

                    // Refresh database list
                    ShowDatabases(true);
                }
            }
            else
            {
                this.Close();
            }
        }
        private static Database GetDatabase(string connectionString)
        {
            var connection = new ServerConnection { ConnectionString = connectionString };
            var server = new Server(connection);

            var connectionStringBuilder = new SqlConnectionStringBuilder(connectionString);
            return server.Databases[connectionStringBuilder.InitialCatalog];
        }
        public ClientGame(IPAddress serverAddress)
            : base()
        {
            this.serverConnection = new ServerConnection(serverAddress, this);

            SetWorldSize m = serverConnection.GetSetWorldSize();
            this.SetWorldSize(m.WorldSize);
        }
 public void GenerateBindingFromProtocolFailsWithUnknownProtocol()
 {
     var connection = new ServerConnection
                          {
                              Address = "unknown://somewhere.com"
                          };
     Assert.Throws<InvalidOperationException>(connection.GenerateBindingFromProtocol);
 }
 public void ConstructorSetsProperties()
 {
     var binding = new NetTcpBinding();
     var address = "net.tcp://somewhere";
     var connection = new ServerConnection(address, binding);
     Assert.AreEqual(connection.Address, address);
     Assert.AreSame(binding, connection.Binding);
 }
 public ScriptAsScriptingOperation(ScriptingParams parameters, ServerConnection serverConnection) : base(parameters)
 {
     Validate.IsNotNull("serverConnection", serverConnection);
     ServerConnection = serverConnection;
 }
        /// <summary>
        /// Standard Main() method used by most SDK samples.
        /// </summary>
        /// <param name="args"></param>
        static public void Main(string[] args)
        {
            try
            {
                // Obtain the target organization's Web address and client logon
                // credentials from the user.
                ServerConnection serverConnect        = new ServerConnection();
                ServerConnection.Configuration config = serverConnect.GetServerConfiguration();

                var app = new BusinessFacility();
                app.Run(config, true);
            }
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
                Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
                Console.WriteLine("Message: {0}", ex.Detail.Message);
                Console.WriteLine("Plugin Trace: {0}", ex.Detail.TraceText);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
            }
            catch (System.TimeoutException ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine("Message: {0}", ex.Message);
                Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
                Console.WriteLine("Inner Fault: {0}",
                                  null == ex.InnerException.Message ? "No Inner Fault" : ex.InnerException.Message);
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("The application terminated with an error.");
                Console.WriteLine(ex.Message);

                // Display the details of the inner exception.
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message);

                    FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> fe = ex.InnerException
                                                                                     as FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault>;
                    if (fe != null)
                    {
                        Console.WriteLine($"Timestamp: {0}", fe.Detail.Timestamp);
                        Console.WriteLine($"Code: {0}", fe.Detail.ErrorCode);
                        Console.WriteLine($"Message: {0}", fe.Detail.Message);
                        Console.WriteLine($"Plugin Trace: {0}", fe.Detail.TraceText);
                        Console.WriteLine($"Inner Fault: {0}",
                                          null == fe.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    }
                }
            }
            // Additional exceptions to catch: SecurityTokenValidationException, ExpiredSecurityTokenException,
            // SecurityAccessDeniedException, MessageSecurityException, and SecurityNegotiationException.

            finally
            {
                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Exemple #33
0
 public void BeginEdit()
 {
     Original = Clone();
 }
Exemple #34
0
 // Start is called before the first frame update
 void Start()
 {
     Cursor.visible = false;
     server         = ServerConnection.getInstance();
 }
Exemple #35
0
        private void LoadProject()
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            openFileDialog.Filter           = "Text Files (*.xml)|*.xml|All Files (*.*)|*.*";
            if (openFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                string FileName = openFileDialog.FileName;

                DataTable dt1 = new DataTable();
                dt1.Columns.Add("ResultSet");
                dt1.Columns.Add("Name");
                dt1.Columns.Add("Type");
                dt1.Columns.Add("Schema");
                dt1.Columns.Add("ObjectDefinition1");
                dt1.Columns.Add("ObjectDefinition2");

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(FileName);

                string db1 = "";
                string db2 = "";



                foreach (XmlNode xmlNode in xmlDocument.ChildNodes)
                {
                    string aa = xmlNode.Name + " " + xmlNode.Value;
                }

                string srv1   = "";
                string login1 = "";
                string pwd1   = "";

                foreach (XmlNode xmlNode in xmlDocument.GetElementsByTagName("Server1"))
                {
                    foreach (XmlNode xmlServerNode in xmlNode.ChildNodes)
                    {
                        switch (xmlServerNode.Name)
                        {
                        case "Server":
                            srv1 = xmlServerNode.InnerText;
                            break;

                        case "Database":
                            db1 = xmlServerNode.InnerText;
                            break;

                        case "Login":
                            login1 = xmlServerNode.InnerText;
                            break;

                        case "Password":
                            pwd1 = xmlServerNode.InnerText;
                            break;
                        }
                    }
                }

                ServerConnection conn = new ServerConnection();
                conn.ServerInstance = srv1;
                if (login1 != "")
                {
                    conn.LoginSecure = false;
                    conn.Login       = login1;
                    conn.Password    = pwd1;
                }
                Server server1 = new Server(conn);

                string srv2   = "";
                string login2 = "";
                string pwd2   = "";

                foreach (XmlNode xmlNode in xmlDocument.GetElementsByTagName("Server2"))
                {
                    foreach (XmlNode xmlServerNode in xmlNode.ChildNodes)
                    {
                        switch (xmlServerNode.Name)
                        {
                        case "Server":
                            srv2 = xmlServerNode.InnerText;
                            break;

                        case "Database":
                            db2 = xmlServerNode.InnerText;
                            break;

                        case "Login":
                            login2 = xmlServerNode.InnerText;
                            break;

                        case "Password":
                            pwd2 = xmlServerNode.InnerText;
                            break;
                        }
                    }
                }

                conn = new ServerConnection();
                conn.ServerInstance = srv2;
                if (login1 != "")
                {
                    conn.LoginSecure = false;
                    conn.Login       = login2;
                    conn.Password    = pwd2;
                }
                Server server2 = new Server(conn);

                foreach (XmlNode xmlNode in xmlDocument.GetElementsByTagName("Object"))
                {
                    DataRow dr = dt1.NewRow();
                    dr["ResultSet"]         = xmlNode.Attributes["ResultSet"].Value;
                    dr["Name"]              = xmlNode.Attributes["Name"].Value;
                    dr["Type"]              = xmlNode.Attributes["Type"].Value;
                    dr["Schema"]            = xmlNode.Attributes["Schema"].Value;
                    dr["ObjectDefinition1"] = xmlNode.Attributes["ObjectDefinition1"].Value;
                    dr["ObjectDefinition2"] = xmlNode.Attributes["ObjectDefinition2"].Value;
                    dt1.Rows.Add(dr);
                }

                ObjectCompare objCompare = new ObjectCompare(false);
                objCompare.SetDatabase1(db1);
                objCompare.SetDatabase2(db2);

                objCompare.SetServer1(server1);
                objCompare.SetServer2(server2);

                objCompare.LoadObjects(dt1);
                objCompare.MdiParent = this;
                objCompare.Show();
            }
        }
Exemple #36
0
        /// <summary>
        /// Generates a edit-ready metadata object using SMO
        /// </summary>
        /// <param name="connection">Connection to use for getting metadata</param>
        /// <param name="objectNamedParts">Split and unwrapped name parts</param>
        /// <param name="objectType">Type of the object to return metadata for</param>
        /// <returns>Metadata about the object requested</returns>
        public EditTableMetadata GetObjectMetadata(DbConnection connection, string[] objectNamedParts, string objectType)
        {
            Validate.IsNotNull(nameof(objectNamedParts), objectNamedParts);
            if (objectNamedParts.Length <= 0)
            {
                throw new ArgumentNullException(nameof(objectNamedParts), SR.EditDataMetadataObjectNameRequired);
            }
            if (objectNamedParts.Length > 2)
            {
                throw new InvalidOperationException(SR.EditDataMetadataTooManyIdentifiers);
            }

            // Get a connection to the database for SMO purposes
            SqlConnection sqlConn = connection as SqlConnection;

            if (sqlConn == null)
            {
                // It's not actually a SqlConnection, so let's try a reliable SQL connection
                ReliableSqlConnection reliableConn = connection as ReliableSqlConnection;
                if (reliableConn == null)
                {
                    // If we don't have connection we can use with SMO, just give up on using SMO
                    return(null);
                }

                // We have a reliable connection, use the underlying connection
                sqlConn = reliableConn.GetUnderlyingConnection();
            }

            // Connect with SMO and get the metadata for the table
            ServerConnection serverConnection;

            if (sqlConn.AccessToken == null)
            {
                serverConnection = new ServerConnection(sqlConn);
            }
            else
            {
                serverConnection = new ServerConnection(sqlConn, new AzureAccessToken(sqlConn.AccessToken));
            }
            Server   server = new Server(serverConnection);
            Database db     = new Database(server, sqlConn.Database);

            TableViewTableTypeBase smoResult;

            switch (objectType.ToLowerInvariant())
            {
            case "table":
                smoResult = objectNamedParts.Length == 1
                        ? new Table(db, objectNamedParts[0])                        // No schema provided
                        : new Table(db, objectNamedParts[1], objectNamedParts[0]);  // Schema provided
                break;

            case "view":
                smoResult = objectNamedParts.Length == 1
                        ? new View(db, objectNamedParts[0])                         // No schema provided
                        : new View(db, objectNamedParts[1], objectNamedParts[0]);   // Schema provided
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(objectType), SR.EditDataUnsupportedObjectType(objectType));
            }

            // A bug in SMO makes it necessary to call refresh to attain certain properties (such as IsMemoryOptimized)
            smoResult.Refresh();
            if (smoResult.State != SqlSmoState.Existing)
            {
                throw new ArgumentOutOfRangeException(nameof(objectNamedParts), SR.EditDataObjectNotFound);
            }

            // Generate the edit column metadata
            List <EditColumnMetadata> editColumns = new List <EditColumnMetadata>();

            for (int i = 0; i < smoResult.Columns.Count; i++)
            {
                Column smoColumn = smoResult.Columns[i];

                string defaultValue = null;
                try
                {
                    // The default value may be escaped
                    defaultValue = smoColumn.DefaultConstraint == null
                        ? null
                        : FromSqlScript.UnwrapLiteral(smoColumn.DefaultConstraint.Text);
                }
                catch (PropertyCannotBeRetrievedException)
                {
                    // This exception will be thrown when the user doesn't have view definition privilege,
                    // we can ignore it and use null as the default value;
                }

                EditColumnMetadata column = new EditColumnMetadata
                {
                    DefaultValue = defaultValue,
                    EscapedName  = ToSqlScript.FormatIdentifier(smoColumn.Name),
                    Ordinal      = i,
                };
                editColumns.Add(column);
            }

            // Only tables can be memory-optimized
            Table smoTable          = smoResult as Table;
            bool  isMemoryOptimized = false;

            // TODO: Remove IsSupported check once SMO fixes broken IsMemoryOptimized scenario (TFS #10871823)
            if (smoTable != null)
            {
                isMemoryOptimized = smoTable.IsSupportedProperty("IsMemoryOptimized") && smoTable.IsMemoryOptimized;
            }

            // Escape the parts of the name
            string[] objectNameParts      = { smoResult.Schema, smoResult.Name };
            string   escapedMultipartName = ToSqlScript.FormatMultipartIdentifier(objectNameParts);

            return(new EditTableMetadata
            {
                Columns = editColumns.ToArray(),
                EscapedMultipartName = escapedMultipartName,
                IsMemoryOptimized = isMemoryOptimized
            });
        }
Exemple #37
0
        private List <ServerConnection> GetXIVServerIPList()
        {
            var connections = new List <ServerConnection>();

            var id          = Config.CurrentProcessID;
            var tcpTable    = IntPtr.Zero;
            var dwOutBufLen = 0;
            var error       = 0;

            for (var index = 0; index < 5; ++index)
            {
                error = (int)UnsafeNativeMethods.GetExtendedTcpTable(tcpTable, ref dwOutBufLen, false, 2U, UnsafeNativeMethods.TCP_TABLE_CLASS.OWNER_PID_ALL, 0U);
                if (error != 0)
                {
                    if (tcpTable != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(tcpTable);
                    }
                    tcpTable = Marshal.AllocHGlobal(dwOutBufLen);
                }
                else
                {
                    break;
                }
            }
            try
            {
                if (error != 0)
                {
                    throw new Win32Exception(error);
                }
                var size    = Marshal.ReadInt32(tcpTable);
                var pointer = IntPtr.Add(tcpTable, 4);
                for (var index = 0; index <= size - 1; ++index)
                {
                    var mibTcprowEx = (UnsafeNativeMethods.MIB_TCPROW_EX)Marshal.PtrToStructure(pointer, typeof(UnsafeNativeMethods.MIB_TCPROW_EX));
                    if (mibTcprowEx.dwProcessId == id)
                    {
                        var newConnections = connections;
                        var connection     = new ServerConnection();
                        connection.SourceAddress      = mibTcprowEx.dwRemoteAddr;
                        connection.SourcePort         = (ushort)mibTcprowEx.dwRemotePort;
                        connection.DestinationAddress = mibTcprowEx.dwLocalAddr;
                        connection.DestinationPort    = (ushort)mibTcprowEx.dwLocalPort;
                        newConnections.Add(connection);
                    }
                    pointer = IntPtr.Add(pointer, Marshal.SizeOf(typeof(UnsafeNativeMethods.MIB_TCPROW_EX)));
                }
            }
            catch
            {
                throw new Win32Exception(error);
            }
            finally
            {
                Marshal.FreeHGlobal(tcpTable);
            }
            return(connections);

            /*
             * var tables = IPHelper.GetExtendedTCPTable(true);
             * return (tables.Cast<TCPRow>()
             *            .Where(table => table.ProcessId == Constants.ProcessModel.ProcessID)
             *            .Select(table => new ServerConnection
             *            {
             *                SourceAddress = BitConverter.ToUInt32(table.RemoteEndPoint.Address.GetAddressBytes(), 0),
             *                SourcePort = (ushort)table.RemoteEndPoint.Port,
             *                DestinationAddress = BitConverter.ToUInt32(table.LocalEndPoint.Address.GetAddressBytes(), 0),
             *                DestinationPort = (ushort)table.LocalEndPoint.Port
             *            })).ToList();
             */
        }
Exemple #38
0
 private async Task ProccessTcpConnection(TcpClient TcpConnection)
 {
     using (ServerConnection CurrentServerConnection = new ServerConnection(TcpConnection, this))
         await CurrentServerConnection.ProcessAsync();
 }
Exemple #39
0
        private void cboDataBase_Click(object sender, EventArgs e)
        {
            //limpa o combobox dos databases
            cboDataBase.Items.Clear();
            try
            {
                //se foi selecionado um servidor
                if (cboServidor.SelectedItem != null && cboServidor.SelectedItem.ToString() != "")
                {
                    this.Cursor = Cursors.WaitCursor;
                    // Cria uma nova conexão com o servidor selecionado
                    ServerConnection srvConn = new ServerConnection(cboServidor.SelectedItem.ToString());
                    // Faz o Login usando a autenticacao SQL ao invés da autenticação do Windows
                    srvConn.LoginSecure = true;

                    //tipo de conexão não exige usuário e senha(usa a autenticação do windows)
                    if (chkIntegratedSecurity.CheckState == CheckState.Checked)
                    {
                        // Cria um novo objeto SQL Server usando a conexão criada
                        servidor = new Server(srvConn);
                        // percorre a lista de banco de dados
                        foreach (Database dbServer in servidor.Databases)
                        {
                            // Adiciona o banco de dados na combobox
                            cboDataBase.Items.Add(dbServer.Name);
                        }
                    }

                    //tipo de conexão exige usuário e senha
                    if (chkIntegratedSecurity.CheckState == CheckState.Unchecked)
                    {
                        // atribui o nome do usuário
                        srvConn.Login = txtUsuario.Text;
                        // atribui a senha
                        srvConn.Password = txtSenha.Text;
                        // Cria um novo objeto SQL Server usando a conexão criada
                        servidor = new Server(srvConn);
                        // percorre a lista de banco de dados
                        foreach (Database dbServer in servidor.Databases)
                        {
                            // Adiciona o banco de dados na combobox
                            cboDataBase.Items.Add(dbServer.Name);
                        }
                    }
                }
                else
                {
                    // Um servidor não foi selecionado exibe um erro
                    MessageBox.Show("ERROR: Contate o Administrador!!", "Servidor", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception)
            {
                // Inicie o serviço do SQL Server Browser se não conseguir carregar os servidores.(http://msdn.microsoft.com/en-us/library/ms165734(v=sql.90).aspx
                MessageBox.Show("ERROR: Ocorreu um erro durante a carga dos banco de dados disponíveis", "Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }
        /// <summary>
        /// Enumerates files and folders that are immediate children of the given path on the server
        /// </summary>
        /// <param name="enumerator"></param>
        /// <param name="connection"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        internal static IEnumerable <FileInfo> EnumerateFilesInFolder(Enumerator enumerator, ServerConnection connection, string path)
        {
            var request = new Request
            {
                Urn         = "Server/File[@Path='" + Urn.EscapeString(path) + "']",
                Fields      = new[] { "Name", "IsFile", "FullName" },
                OrderByList = new[]
                {
                    new OrderBy
                    {
                        Field = "IsFile"
                    },
                    new OrderBy
                    {
                        Field = "Name"
                    }
                }
            };

            using (DataSet ds = enumerator.Process(connection, request))
            {
                if (IsValidDataSet(ds))
                {
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        bool isFile = Convert.ToBoolean((object)row[1], CultureInfo.InvariantCulture);
                        yield return(new FileInfo
                        {
                            path = isFile ? path : Convert.ToString((object)row[2], CultureInfo.InvariantCulture),
                            fileName = isFile ? Convert.ToString((object)row[0], CultureInfo.InvariantCulture) : String.Empty,
                            folderName = isFile ? String.Empty : Convert.ToString((object)row[0], CultureInfo.InvariantCulture),
                            fullPath = isFile ? Convert.ToString((object)row[2], CultureInfo.InvariantCulture) : String.Empty
                        });
                    }
                }
            }
        }
        /// <summary>
        /// Enumerates the FileInfo objects associated with drives
        /// </summary>
        /// <param name="enumerator"></param>
        /// <param name="connection"></param>
        /// <returns></returns>
        internal static IEnumerable <FileInfo> EnumerateDrives(Enumerator enumerator, ServerConnection connection)
        {
            // if not supplied, server name will be obtained from urn
            Request req       = new Request();
            bool    clustered = false;

            req.Urn    = "Server/Information";
            req.Fields = new string[] { "IsClustered", "PathSeparator", "HostPlatform" };

            var pathSeparator = @"\";
            var hostPlatform  = HostPlatformNames.Windows;

            try
            {
                using (DataSet ds = enumerator.Process(connection, req))
                {
                    if (IsValidDataSet(ds))
                    {
                        clustered = Convert.ToBoolean(ds.Tables[0].Rows[0][0],
                                                      CultureInfo.InvariantCulture);
                        pathSeparator = Convert.ToString(ds.Tables[0].Rows[0][1], CultureInfo.InvariantCulture);
                        hostPlatform  = Convert.ToString(ds.Tables[0].Rows[0][2], CultureInfo.InvariantCulture);
                    }
                }
            }
            catch (UnknownPropertyEnumeratorException)
            {
                //there can be no clusters on 7.0 server
            }

            // we need to issue different queries to get all fixed drives on a normal server, and
            // shared drives on a cluster
            req.Urn    = clustered ? "Server/AvailableMedia[@SharedDrive=true()]" : "Server/Drive";
            req.Fields = new[] { "Name" };

            using (DataSet ds = enumerator.Process(connection, req))
            {
                if (IsValidDataSet(ds))
                {
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        var fileInfo = new FileInfo
                        {
                            fileName = string.Empty,
                            path     = Convert.ToString(ds.Tables[0].Rows[i][0], System.Globalization.CultureInfo.InvariantCulture)
                        };

                        // if we're looking at shared devices on a clustered server
                        // they already have \ on the drive
                        // sys.dm_os_enumerate_fixed_drives appends a \ on Windows for sql17+
                        if (!clustered && hostPlatform == HostPlatformNames.Windows && !fileInfo.path.EndsWith(pathSeparator))
                        {
                            fileInfo.path += pathSeparator;
                        }

                        yield return(fileInfo);
                    }
                }
            }
        }
Exemple #42
0
 void Login(ServerConnection sc)
 {
     sc.Login(userString, hashString);
     sc.PossessMobile(App.Rand.Next());
 }
Exemple #43
0
        private void ParseNetworkData(SocketObject asyncState, byte[] byteData, int nReceived)
        {
            if (byteData == null || byteData[9] != 6)
            {
                return;
            }
            var startIndex  = (byte)((byteData[0] & 15) * 4);
            var lengthCheck = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(byteData, 2));

            if (nReceived < lengthCheck || startIndex > lengthCheck)
            {
                return;
            }
            var IP  = new IPHeader(byteData, nReceived);
            var TCP = new TCPHeader(byteData, nReceived);
            var serverConnection = new ServerConnection
            {
                SourceAddress      = (uint)BitConverter.ToInt32(byteData, 12),
                DestinationAddress = (uint)BitConverter.ToInt32(byteData, 16),
                SourcePort         = (ushort)BitConverter.ToInt16(byteData, startIndex),
                DestinationPort    = (ushort)BitConverter.ToInt16(byteData, startIndex + 2),
                TimeStamp          = DateTime.Now

                                     /*
                                      *  // these don't return the right ports for some reason
                                      *  DestinationAddress = BitConverter.ToUInt32(IP.DestinationAddress.GetAddressBytes(), 0),
                                      *  DestinationPort = Convert.ToUInt16(TCP.DestinationPort),
                                      *  SourcePort = Convert.ToUInt16(TCP.SourcePort),
                                      *  SourceAddress = BitConverter.ToUInt32(IP.SourceAddress.GetAddressBytes(), 0),
                                      *  TimeStamp = DateTime.Now
                                      */
            };

            lock (Lock)
            {
                var found = Enumerable.Contains(ServerConnections, serverConnection);
                if (!found)
                {
                    if (Enumerable.Contains(DroppedConnections, serverConnection))
                    {
                        return;
                    }
                    UpdateConnectionList();
                    if (!Enumerable.Contains(ServerConnections, serverConnection))
                    {
                        DroppedConnections.Add(serverConnection);
                        return;
                    }
                }
            }
            if (startIndex + 12 > nReceived)
            {
                return;
            }
            var nextTCPSequence = (uint)IPAddress.NetworkToHostOrder(BitConverter.ToInt32(byteData, startIndex + 4));
            var cut             = (byte)(((byteData[startIndex + 12] & 240) >> 4) * 4);
            var length          = nReceived - startIndex - cut;

            if (length < 0 || length > 0x10000)
            {
                return;
            }

            if (lengthCheck == startIndex + cut)
            {
                return;
            }

            lock (asyncState.SocketLock)
            {
                var connection = asyncState.Connections.FirstOrDefault(x => x.Equals(serverConnection));
                if (connection == null)
                {
                    connection = new NetworkConnection
                    {
                        SourceAddress      = serverConnection.SourceAddress,
                        SourcePort         = serverConnection.SourcePort,
                        DestinationAddress = serverConnection.DestinationAddress,
                        DestinationPort    = serverConnection.DestinationPort
                    };
                    asyncState.Connections.Add(connection);
                }
                if (length == 0)
                {
                    return;
                }
                var destinationBuffer = new byte[length];
                Array.Copy(byteData, startIndex + cut, destinationBuffer, 0, length);
                if (connection.StalePackets.ContainsKey(nextTCPSequence))
                {
                    connection.StalePackets.Remove(nextTCPSequence);
                }
                var packet = new NetworkPacket
                {
                    TCPSequence = nextTCPSequence,
                    Buffer      = destinationBuffer,
                    Push        = (byteData[startIndex + 13] & 8) != 0
                };
                connection.StalePackets.Add(nextTCPSequence, packet);


                if (!connection.NextTCPSequence.HasValue)
                {
                    connection.NextTCPSequence = nextTCPSequence;
                }
                if (connection.StalePackets.Count == 1)
                {
                    connection.LastGoodNetworkPacketTime = DateTime.Now;
                }

                if (!connection.StalePackets.Any(x => x.Key <= connection.NextTCPSequence.Value))
                {
                    if (DateTime.Now.Subtract(connection.LastGoodNetworkPacketTime)
                        .TotalSeconds <= 10.0)
                    {
                        return;
                    }
                    connection.NextTCPSequence = connection.StalePackets.Min(x => x.Key);
                }
                while (connection.StalePackets.Any(x => x.Key <= connection.NextTCPSequence.Value))
                {
                    NetworkPacket stalePacket;
                    uint          sequenceLength = 0;
                    if (connection.StalePackets.ContainsKey(connection.NextTCPSequence.Value))
                    {
                        stalePacket = connection.StalePackets[connection.NextTCPSequence.Value];
                    }
                    else
                    {
                        stalePacket = connection.StalePackets.Where(x => x.Key <= connection.NextTCPSequence.Value)
                                      .OrderBy(x => x.Key)
                                      .FirstOrDefault()
                                      .Value;
                        sequenceLength = connection.NextTCPSequence.Value - stalePacket.TCPSequence;
                    }
                    connection.StalePackets.Remove(stalePacket.TCPSequence);
                    if (connection.NetworkBufferPosition == 0)
                    {
                        connection.LastNetworkBufferUpdate = DateTime.Now;
                    }
                    if (sequenceLength >= stalePacket.Buffer.Length)
                    {
                        continue;
                    }
                    connection.NextTCPSequence = stalePacket.TCPSequence + (uint)stalePacket.Buffer.Length;
                    Array.Copy(stalePacket.Buffer, sequenceLength, connection.NetworkBuffer, connection.NetworkBufferPosition, stalePacket.Buffer.Length - sequenceLength);
                    connection.NetworkBufferPosition += stalePacket.Buffer.Length - (int)sequenceLength;
                    if (stalePacket.Push)
                    {
                        ProcessNetworkBuffer(connection);
                    }
                }
            }
        }
Exemple #44
0
        private void InitializeCommunication()
        {
            ServerConnection bootstrapper = new ServerConnection();

            bootstrapper.Start();
        }
 public ListNewsGroups(ServerConnection conn)
 {
     this.Connection = conn;
     this.ThisType   = typeof(ListNewsGroups);
 }
Exemple #46
0
 public MainViewModel(ServerConnection connection, Navigator navigator) : base(connection, navigator)
 {
     this.model            = new MainModel(connection);
     this.CurrentViewModel = new LoginViewModel(this.connection, this.navigator);
 }
Exemple #47
0
        public void Script(ServerConnection ServerConn, bool scriptOnly)
        {
            try
            {
                serverName = ServerConn.ServerInstance;
                serverConn = ServerConn;

                if (m_dbName == null)
                {
                    return;                     // there is no DB to script
                }
                foreach (Database db in m_sqlserver.Databases)
                {
                    if (m_dbName.ToLower() == db.Name.ToLower())
                    {
                        string dest = m_workingFolder + "\\" + m_sqlserver.Name + "\\" + db.Name;
                        if (Directory.Exists(dest))
                        {
                            DeleteDirectory(dest);
                        }

                        System.IO.Directory.CreateDirectory(m_workingFolder);

                        if (scriptOnly == false)
                        {
                            CheckoutFromSourcesafe(db, dest);
                        }

                        ScriptDatabase(db, dest);

                        if (errorsOccurred == false)
                        {
                            if (scriptOnly == false)
                            {
                                AddToSourcesafe(db, dest);

                                // The sourcesafe bit above removes each file but we still need to kill the folder.
                                DeleteDirectory(m_workingFolder);
                            }
                        }
                        break;
                    }
                }
                if (errorsOccurred)
                {
                    string logFile = Maple.Logger.GetLogFilePathAndName(true);

                    Funcs.EmailReport("DB script error",
                                      string.Format("See the log file for more info\r\n\r\n {0}", logFile));
                    ApplicationStatus.SetStatus(string.Format("Scripting of {0}.{1}.", serverName, m_dbName), "Error", "An error occurred", 1450);
                }
                else
                {
                    ApplicationStatus.SetStatus(string.Format("Scripting of {0}.{1}.", serverName, m_dbName), "OK", "", 1450);
                }
            }
            catch (Exception ex) {            //end up here in case of abort
                throw ex;
            }
            if (ScriptDone != null)
            {
                ScriptDone(scriptOnly);
            }
        }
Exemple #48
0
 private void LoginControl_DisconnectRequest(object sender, System.EventArgs e)
 {
     // disconnect
     ServerConnection.Disconnect();
 }
Exemple #49
0
                public BaseObject Create()
                {
                    ServerConnection emptyInstance = new ServerConnection(CreatedWhenConstruct.CWC_NotToCreate);

                    return(emptyInstance);
                }
Exemple #50
0
 public void EndEdit()
 {
     Original = null;
 }
Exemple #51
0
        private void btnRestore_Click(object sender, RoutedEventArgs e)
        {
            string blankDBFile          = string.Empty;
            string dbScriptsDefaultPath = string.Empty;
            string backupFileName       = string.Empty;
            string sSQLServerDetails    = string.Empty;
            bool   bDBExists            = false;

            try
            {
                Cursor = System.Windows.Input.Cursors.Wait;

                sSQLServerDetails = GetConnectionString();
                bDBExists         = DBSettings.CheckDBExists(sSQLServerDetails, txtDataBases.Text, 60);

                if (bDBExists == true)
                {
                    MessageBox.ShowText(string.Format("{0} {1}", txtDataBases.Text, FindResource("MessageID50")), BMC_Icon.Information);
                    LogManager.WriteLog(string.Format("{0} {1}", txtDataBases.Text, FindResource("MessageID50")), LogManager.enumLogLevel.Info);
                }
                else
                {
                    dbScriptsDefaultPath = ConfigurationManager.AppSettings.Get("DBScriptsDefaultPath");

                    if (this.strType.ToUpper() == "EXCHANGE")
                    {
                        blankDBFile = ConfigurationManager.AppSettings.Get("ExchangeBlankDB");
                    }
                    if (this.strType.ToUpper() == "TICKETING")
                    {
                        blankDBFile = ConfigurationManager.AppSettings.Get("TicketingBlankDB");
                    }
                    if (this.strType.ToUpper() == "EXTSYSMSG")
                    {
                        blankDBFile = ConfigurationManager.AppSettings.Get("EXTSYSMSGBlankDB");
                    }

                    backupFileName = string.Format("{0}\\{1}", dbScriptsDefaultPath, blankDBFile);

                    // Create a new connection to the Server
                    ServerConnection serverConnection = new ServerConnection(cmbServers.SelectedItem.ToString());

                    // Log in using SQL authentication instead of Windows authentication
                    serverConnection.LoginSecure = false;

                    // Give the login username
                    serverConnection.Login = txtUsername.Text;

                    // Give the login password
                    serverConnection.Password = txtPassword.Password;

                    // Create a new SQL Server object using the connection we created
                    Server server = new Server(serverConnection);

                    // Create a new database restore operation
                    Restore rstDatabase = new Restore();

                    // Set the restore type to a database restore
                    rstDatabase.Action = RestoreActionType.Database;

                    // Set the database that we want to perform the restore on
                    rstDatabase.Database = txtDataBases.Text;

                    // Set the backup device from which we want to restore the db
                    BackupDeviceItem bkpDevice = new BackupDeviceItem(backupFileName, DeviceType.File);

                    // Add the backup device to the restore type
                    rstDatabase.Devices.Add(bkpDevice);

                    // Optional. ReplaceDatabase property ensures that any existing copy of the database is overwritten.
                    rstDatabase.ReplaceDatabase = true;

                    // Perform the restore
                    rstDatabase.SqlRestore(server);

                    LogManager.WriteLog(string.Format("{0} - {1}", "Database Restore Complete. Running Updgrade Scripts for database", txtDataBases.Text), LogManager.enumLogLevel.Info);

                    if (this.strType.ToUpper() == "EXCHANGE" | this.strType.ToUpper() == "TICKETING")
                    {
                        if (Convert.ToBoolean(ConfigurationManager.AppSettings.Get("AutoRunUpgradeScriptAfterDBRestore")))
                        {
                            try
                            {
                                RunDatabaseUpgradeScripts();
                            }
                            catch (Exception ex)
                            {
                                ExceptionManager.Publish(ex);

                                if (this.strType.ToUpper() == "EXCHANGE")
                                {
                                    MessageBox.ShowBox("MessageID106", BMC_Icon.Error);
                                }
                                if (this.strType.ToUpper() == "TICKETING")
                                {
                                    MessageBox.ShowBox("MessageID107", BMC_Icon.Error);
                                }
                            }
                        }

                        LogManager.WriteLog(string.Format("{0} - {1}", "Updgrade Scripts run successfully for database", txtDataBases.Text), LogManager.enumLogLevel.Info);
                    }

                    MessageBox.ShowText(string.Format("{0} {1} {2}.", FindResource("MessageID53"), txtDataBases.Text, FindResource("MessageID54")), BMC_Icon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.ShowBox("MessageID74", BMC_Icon.Error);
                ExceptionManager.Publish(ex);
            }
            finally
            {
                btnRestore.IsEnabled = true;
                Cursor = System.Windows.Input.Cursors.Arrow;
            }
        }
Exemple #52
0
        private static bool interrogationHandler(object parameter, ServerConnection connection, ASDU asdu, byte qoi)
        {
            Console.WriteLine("Interrogation for group " + qoi);

            ConnectionParameters cp = connection.GetConnectionParameters();

            try {
                connection.SendACT_CON(asdu, false);

                // send information objects
                ASDU newAsdu = new ASDU(cp, CauseOfTransmission.INTERROGATED_BY_STATION, false, false, 2, 1, false);

                newAsdu.AddInformationObject(new MeasuredValueScaled(100, -1, new QualityDescriptor()));

                newAsdu.AddInformationObject(new MeasuredValueScaled(101, 23, new QualityDescriptor()));

                newAsdu.AddInformationObject(new MeasuredValueScaled(102, 2300, new QualityDescriptor()));

                connection.SendASDU(newAsdu);

                newAsdu = new ASDU(cp, CauseOfTransmission.INTERROGATED_BY_STATION, false, false, 3, 1, false);

                newAsdu.AddInformationObject(new MeasuredValueScaledWithCP56Time2a(103, 3456, new QualityDescriptor(), new CP56Time2a(DateTime.Now)));

                connection.SendASDU(newAsdu);

                newAsdu = new ASDU(cp, CauseOfTransmission.INTERROGATED_BY_STATION, false, false, 2, 1, false);

                newAsdu.AddInformationObject(new SinglePointWithCP56Time2a(104, true, new QualityDescriptor(), new CP56Time2a(DateTime.Now)));

                connection.SendASDU(newAsdu);

                // send sequence of information objects
                newAsdu = new ASDU(cp, CauseOfTransmission.INTERROGATED_BY_STATION, false, false, 2, 1, true);

                newAsdu.AddInformationObject(new SinglePointInformation(200, true, new QualityDescriptor()));
                newAsdu.AddInformationObject(new SinglePointInformation(201, false, new QualityDescriptor()));
                newAsdu.AddInformationObject(new SinglePointInformation(202, true, new QualityDescriptor()));
                newAsdu.AddInformationObject(new SinglePointInformation(203, false, new QualityDescriptor()));
                newAsdu.AddInformationObject(new SinglePointInformation(204, true, new QualityDescriptor()));
                newAsdu.AddInformationObject(new SinglePointInformation(205, false, new QualityDescriptor()));
                newAsdu.AddInformationObject(new SinglePointInformation(206, true, new QualityDescriptor()));
                newAsdu.AddInformationObject(new SinglePointInformation(207, false, new QualityDescriptor()));

                connection.SendASDU(newAsdu);

                newAsdu = new ASDU(cp, CauseOfTransmission.INTERROGATED_BY_STATION, false, false, 2, 1, true);

                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(300, -1.0f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(301, -0.5f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(302, -0.1f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(303, .0f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(304, 0.1f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(305, 0.2f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(306, 0.5f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(307, 0.7f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(308, 0.99f));
                newAsdu.AddInformationObject(new MeasuredValueNormalizedWithoutQuality(309, 1f));

                connection.SendASDU(newAsdu);

                connection.SendACT_TERM(asdu);
            }
            catch (ConnectionException) {
                Console.WriteLine("Client exception closed unexpectedly");
            }

            return(true);
        }
Exemple #53
0
 static void ExecuteSqlFile(ServerConnection connection, string filePath)
 {
     connection.ExecuteNonQuery(System.IO.File.ReadAllText(filePath));
 }