Example #1
0
        // This method returns:
        // 1. NULL if incoming datastream doesn't contain at least 4 bytes
        // 2. Empty String is HTTP method is unknown
        // 3. HTTP method name
        private static String ReadHttpMethodName(Connection connection)
        {
            Byte[] lBuffer = new Byte[4];

            if (connection.Receive(lBuffer, 0, 4) < 4)
            {
                return(null);
            }

            String lHttpMethodName = Encoding.ASCII.GetString(lBuffer, 0, 4);

            if ((lHttpMethodName == "POST") || (lHttpMethodName == "GET ") || (lHttpMethodName == "HTTP") ||
                (lHttpMethodName == "HEAD") || (lHttpMethodName == "PUT "))
            {
                return(lHttpMethodName);
            }

            if (lHttpMethodName == "MERG")
            {
                connection.Read(lBuffer, 0, 1);
                if (lBuffer[0] != (Byte)'E')
                {
                    return(String.Empty);
                }

                return("MERGE");
            }

            if (lHttpMethodName == "DELE")
            {
                connection.Read(lBuffer, 0, 2);
                if (lBuffer[0] != (Byte)'T' || lBuffer[1] != (Byte)'E')
                {
                    return(String.Empty);
                }

                return("DELETE");
            }

            if (lHttpMethodName == "OPTI")
            {
                connection.Read(lBuffer, 0, 3);
                if (lBuffer[0] != (Byte)'O' || lBuffer[1] != (Byte)'N' || lBuffer[2] != (Byte)'S')
                {
                    return(String.Empty);
                }

                return("OPTIONS");
            }

            return(String.Empty);
        }
Example #2
0
        public MoveChangelistRequest(CommandArgs args, Connection conn)
            : base(args, conn)
        {
            Changelist = conn.Read <ChangelistRevision>();
            conn.Read(Assets);

            if (Assets.Count == 0)
            {
                conn.Write(Assets);
                conn.EndResponse();
                Invalid = true;
            }
        }
Example #3
0
        public DownloadRequest(CommandArgs args, Connection conn)
            : base(args, conn)
        {
            TargetDir = conn.ReadLine();
            conn.Read(Revisions);
            conn.Read(Assets);

            if (Assets.Count == 0 || Revisions.Count == 0)
            {
                Assets.Clear();
                conn.Write(Assets);
                conn.EndResponse();
                Invalid = true;
            }
        }
Example #4
0
        /// <summary>
        /// Gets the log to update.
        /// </summary>
        /// <returns>The log to update if it is found.  Null otherwise.</returns>
        private Log GetLogToUpdate()
        {
            var logList = new Log()
            {
                UidWell      = Model.WellUid,
                NameWell     = Model.WellName,
                UidWellbore  = Model.WellboreUid,
                NameWellbore = Model.WellboreName,
                Uid          = Model.LogUid,
                Name         = Model.LogName,
                IndexType    = Model.LogIndexType
            }
            .AsList();

            var result = Connection.Read(new LogList {
                Log = logList
            }, OptionsIn.ReturnElements.HeaderOnly);

            if (!result.Log.Any())
            {
                return(null);
            }

            return(result.Log[0]);
        }
Example #5
0
 public void Read_LdapException()
 {
     Assert.ThrowsAsync <LdapException>(async() =>
     {
         await Connection.Read("ou=scientists,dc=example,dc=com");
     });
 }
Example #6
0
        /// <summary>
        /// Performs a communication session.
        /// </summary>
        public override void Session()
        {
            base.Session();
            Stopwatch stopwatch = Stopwatch.StartNew();

            if (options.ReadMode == ReadMode.Binary)
            {
                if (binStopCond == null)
                {
                    Connection.Read(inBuf, 0, inBuf.Length, PollingOptions.Timeout);
                }
                else
                {
                    Connection.Read(inBuf, 0, inBuf.Length, PollingOptions.Timeout, binStopCond, out _);
                }
            }
            else
            {
                Connection.ReadLines(PollingOptions.Timeout, textStopCond, out _);
            }

            stopwatch.Stop();
            Log.WriteLine(Locale.IsRussian ?
                          "Получено за {0} мс" :
                          "Received in {0} ms", stopwatch.ElapsedMilliseconds);

            FinishRequest();
            FinishSession();
        }
Example #7
0
        public static void OnConnect(object sender, EventArgs args)
        {
            if (!(args is ConnectArgs))
            {
                return;
            }
            Connection connection = ((ConnectArgs)args).connection;

            connections.Add(connection);

            Console.WriteLine("New connection -> " + connection.GetName());
            new Thread(() => Run(connection)).Start();

            while (connection.IsConnected())
            {
                string read = connection.Read();
                Console.WriteLine("[{0}] {1}", connection.GetName(), read);

                foreach (Connection conn in connections)
                {
                    if (conn == connection)
                    {
                        continue;
                    }
                    conn.Write("[" + connection.GetName() + "] " + read);
                }
            }
            * /
        }
Example #8
0
        //Прослушивание команд: вверх или вниз
        private void ListenCommand()
        {
            while (true)
            {
                TextMessage textMessage = Connection.Read <TextMessage>();
                string      command     = textMessage.ToString();

                //Блокировка потока
                Monitor.Enter(this);
                switch (command)
                {
                case "Up":
                    if (PositionByY + BoardMovement <= OnlineGameSession.TableHeight)
                    {
                        PositionByY += BoardMovement;
                    }
                    break;

                case "Down":
                    if (PositionByY - BoardMovement - BoardHeight >= 0)
                    {
                        PositionByY -= BoardMovement;
                    }
                    break;
                }
                Monitor.Exit(this);
            }
        }
Example #9
0
        protected void CheckSuppliersCount(string filter)
        {
            if (_reportParams.ContainsKey("FirmCodeEqual"))
            {
                var sql = String.Format(@"
select pd.FirmCode
from {0}.OrdersHead oh
	join {0}.OrdersList ol on ol.OrderID = oh.RowID
	join catalogs.products p on p.Id = ol.ProductId
	join catalogs.catalog c on c.Id = p.CatalogId
	join catalogs.catalognames cn on cn.id = c.NameId
	join catalogs.catalogforms cf on cf.Id = c.FormId
	left join catalogs.mnn m on cn.MnnId = m.Id
	left join catalogs.Producers cfc on cfc.Id = ol.CodeFirmCr
	left join Customers.Clients cl on cl.Id = oh.ClientCode
	join customers.addresses ad on ad.Id = oh.AddressId
	join farm.regions rg on rg.RegionCode = oh.RegionCode
	join usersettings.pricesdata pd on pd.PriceCode = oh.PriceCode
	join Customers.suppliers prov on prov.Id = pd.FirmCode
	join farm.regions provrg on provrg.RegionCode = prov.HomeRegion
	join Customers.addresses adr on oh.AddressId = adr.Id
	join billing.LegalEntities le on adr.LegalEntityId = le.Id
	join billing.payers on payers.PayerId = le.PayerId
where
	pd.IsLocal = 0
	{1}"    , OrdersSchema, filter);
                ApplyFilters(sql);
                sql += " group by pd.FirmCode";
                var count = Connection.Read(sql).Count();
                if (count < 3)
                {
                    throw new ReportException($"Фактическое количество прайс листов меньше трех, получено прайс-листов {count}");
                }
            }
        }
Example #10
0
        /// <summary>
        ///     Executes the command against the connection.
        /// </summary>
        public void ExecuteNonQuery()
        {
            verifyConnection();
            sendCommand();
            var res = Connection.Read();

            checkResponse(res);
        }
Example #11
0
        public async Task WithDefaultUser_MailShouldMatch()
        {
            var properties = await Connection.Read(DefaultUserDn);

            var mail = properties.GetAttribute("email");

            Assert.AreEqual(mail.StringValue, "*****@*****.**");
        }
Example #12
0
        public override async Task Start(Models.Simulation model, CancellationToken token, TextEditorViewModel messages, int interval = 5000)
        {
            _messages = messages;

            var generator = new Log131Generator();
            var index     = 0d;

            var logList = new Log()
            {
                UidWell      = model.WellUid,
                NameWell     = model.WellName,
                UidWellbore  = model.WellboreUid,
                NameWellbore = model.WellboreName,
                Uid          = model.LogUid,
                Name         = model.LogName,
                IndexType    = Convert(model.LogIndexType)
            }
            .AsList();

            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                var result = Connection.Read(new LogList()
                {
                    Log = logList
                }, OptionsIn.ReturnElements.HeaderOnly);

                if (!result.Log.Any())
                {
                    Runtime.Invoke(() => Runtime.ShowError("Log not found."));
                    break;
                }

                var log = result.Log[0];

                if (log.IndexType != LogIndexType.datetime && log.EndIndex != null)
                {
                    index = log.EndIndex.Value;
                }

                log.Direction    = LogIndexDirection.increasing;
                log.IndexCurve   = new IndexCurve(model.Channels.Select(x => x.ChannelName).FirstOrDefault());
                log.LogCurveInfo = model.Channels.Select(ToLogCurveInfo).ToList();

                index = generator.GenerateLogData(log, startIndex: index, interval: 0.1);

                //result.Log[0].LogData[0].MnemonicList = generator.Mnemonics(result.Log[0].LogCurveInfo);
                //result.Log[0].LogData[0].UnitList = generator.Units(result.Log[0].LogCurveInfo);

                Connection.Update(result);

                await Task.Delay(interval);
            }
        }
        /// <summary>
        /// Dispatches the command to the client control port and produces a <typeparamref name="T" /> response result.
        /// </summary>
        /// <param name="connection">The control connection where the command should be dispatched.</param>
        /// <returns>
        /// A <typeparamref name="T" /> object instance containing the response data.
        /// </returns>
        protected override CommandResponse Dispatch(Connection connection)
        {
            if (connection.Write("signal newnym"))
            {
                ConnectionResponse response = connection.Read();
                return(new CommandResponse(response.Success));
            }

            return(new CommandResponse(false));
        }
        public void Should_Throws_When_Invalid_Data_Comes()
        {
            var unknownBytes = new byte[] { 0x0A, 0x10, 0x20 };

            using var stream = new MemoryStream(unknownBytes);
            stream.Flush();
            var connection = new Connection(stream);

            Assert.Throws <AggregateException>(() => connection.Read <P0Packet>());
        }
Example #15
0
        public RevertChangesRequest(CommandArgs args, Connection conn)
            : base(args, conn)
        {
            conn.Read(Revisions);

            if (Revisions.Count == 0)
            {
                conn.WarnLine("Changes to revert is empty", MessageArea.MARemote);
                conn.EndResponse();
                Invalid = true;
            }
        }
 protected void CheckSupplierCount(int minSupplierCount)
 {
     if (_reportParams.ContainsKey("FirmCodeEqual"))
     {
         var count   = Connection.Read <uint>("select count(*) from usersettings.ActivePrices group by FirmCode").Count();
         var message = $"Фактическое количество прайс листов меньше {minSupplierCount}, получено прайс-листов {count}";
         if (count < minSupplierCount)
         {
             throw new ReportException(message);
         }
     }
 }
        public async Task Should_Read_Packets_Normally_When_Data_Comes_With_A_Time()
        {
            var part0      = new byte[] { 0x00, 0x10, };
            var part1      = new byte[] { 0x20, 0x01, 0x44 };
            var part2      = new byte[] { 0x02, 0x0f, 0x0b };
            var part3      = new byte[] { 0x24, 0x21 };
            var part4      = new byte[] { 0x01 };
            var stream     = new EmulateNetworkBehaviorStream();
            var connection = new Connection(stream);

            _ = Task.Run(async() =>
            {
                await stream.WriteAsync(part0, CancellationToken.None).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
                await Task.Delay(TimeSpan.FromMilliseconds(150)).ConfigureAwait(false);

                await stream.WriteAsync(part1, CancellationToken.None).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
                await Task.Delay(TimeSpan.FromMilliseconds(250)).ConfigureAwait(false);

                await stream.WriteAsync(part2, CancellationToken.None).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
                await Task.Delay(TimeSpan.FromMilliseconds(10)).ConfigureAwait(false);

                await stream.WriteAsync(part3, CancellationToken.None).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
                await Task.Delay(TimeSpan.FromMilliseconds(200)).ConfigureAwait(false);

                await stream.WriteAsync(part4, CancellationToken.None).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
            });

            var p0Packet = connection.Read <P0Packet>();
            var p1Packet = connection.Read <P1Packet>();
            var p2Packet = connection.Read <P2Packet>();

            Assert.Equal(new byte[] { 0x00, 0x10, 0x20 }, p0Packet.ToBytes());
            Assert.Equal(new byte[] { 0x01, 0x44 }, p1Packet.ToBytes());
            Assert.Equal(new byte[] { 0x02, 0x0f, 0x0b, 0x24, 0x21, 0x01 }, p2Packet.ToBytes());
        }
Example #18
0
        public ChangeDescriptionRequest(CommandArgs args, Connection conn)
            : base(args, conn)
        {
            Revision = conn.Read <ChangelistRevision>();

            if (string.IsNullOrEmpty(Revision))
            {
                conn.DataLine("unknown");
                conn.ErrorLine("Cannot get description for empty revision");
                conn.EndResponse();
                Invalid = true;
            }
        }
Example #19
0
        public List <DAO.Voo> ListaTodos()
        {
            string sql = "SELECT * FROM TB_VOO ORDER BY 1";

            DataSet ds = Connection.Read(sql, null);

            if (ds.Tables.Count > 0)
            {
                DataSetList(ds);
            }

            return(ds.Tables.Count > 0 ? lstVoo : new List <DAO.Voo>());
        }
        public void Should_Read_Full_Data_Normally()
        {
            var p0Bytes    = new byte[] { 0x00, 0x10, 0x20 };
            var p1Bytes    = new byte[] { 0x01, 0x44 };
            var p2Bytes    = new byte[] { 0x02, 0x0f, 0x0b, 0x24, 0x21, 0x01 };
            var inputBytes = new List <byte>();

            inputBytes.AddRange(p0Bytes);
            inputBytes.AddRange(p1Bytes);
            inputBytes.AddRange(p2Bytes);
            using var stream = new MemoryStream(inputBytes.ToArray());
            stream.Flush();

            var connection = new Connection(stream);
            var p0Packet   = connection.Read <P0Packet>();
            var p1Packet   = connection.Read <P1Packet>();
            var p2Packet   = connection.Read <P2Packet>();

            Assert.Equal(p0Bytes, p0Packet.ToBytes());
            Assert.Equal(p1Bytes, p1Packet.ToBytes());
            Assert.Equal(p2Bytes, p2Packet.ToBytes());
        }
Example #21
0
        public BaseFileSetRequest(CommandArgs args, Connection conn)
            : base(args, conn)
        {
            Assets.Clear();
            conn.Read(Assets);

            if (Assets.Count == 0)
            {
                Assets.Clear();
                conn.Write(Assets);
                conn.EndResponse();
                Invalid = true;
            }
        }
Example #22
0
        public OutgoingAssetsRequest(CommandArgs args, Connection conn)
            : base(args, conn)
        {
            Revision = conn.Read <ChangelistRevision>();

            if (string.IsNullOrEmpty(Revision))
            {
                VersionedAssetList assets = new VersionedAssetList();
                conn.Write(assets);
                conn.ErrorLine("Cannot get assets for empty revision");
                conn.EndResponse();
                Invalid = true;
            }
        }
Example #23
0
        /// <summary>
        ///     Excutes CommandText for read
        /// </summary>
        /// <param name="propList">
        ///     Optional:CSV of properies. limits number of Fileds that will be returned in result. it can
        ///     increase performance.
        /// </param>
        /// <param name="queryConditions">
        ///     Optional: Limits rows by condition on fields. Default logic is AND. You can change it in
        ///     Logic argument of this method
        /// </param>
        /// <param name="logic">The logic.</param>
        /// <returns>A collection of string in raw format of API result.</returns>
        public IEnumerable <string> ExecuteReader(string propList = null,
                                                  MKCommandParameterCollection queryConditions = null, MKQueryLogicOperators logic = MKQueryLogicOperators.And)
        {
            verifyConnection();

            if (!string.IsNullOrEmpty(propList))
            {
                Parameters.Add(".proplist", propList);
            }
            //*******************************************

            if (CommandText.Contains(@"/where/"))
            {
                if (queryConditions == null)
                {
                    queryConditions = new MKCommandParameterCollection();
                }
                queryConditions.AddRange(getCommandTextQueries(CommandText));
            }

            if (queryConditions != null)
            {
                foreach (var q in queryConditions)
                {
                    q.Name = "?" + q.Name;
                    Parameters.Add(q);
                }
                if (queryConditions.Count > 1)
                {
                    switch (logic)
                    {
                    case MKQueryLogicOperators.And:
                        Parameters.Add("?#", "&");
                        break;

                    case MKQueryLogicOperators.Or:
                        Parameters.Add("?#", "|");

                        break;
                    }
                }
            }

            sendCommand();
            var res = Connection.Read();

            checkResponse(res);
            return(res);
        }
Example #24
0
        private void RunDiscoIteration()
        {
            {
                var clienData = dataC;
                discoClient.Write(clienData, 0, clienData.Length);

                var  bufClient = new byte[100];
                byte lastByte  = 0;
                do
                {
                    var readByes = discoClient.Read(bufClient, 0, bufClient.Length);
                    lastByte = bufClient[readByes - 1];
                } while (lastByte != 255);
            }
        }
        public async Task Test_DeleteAsync()
        {
            // prepare
            using var roleStore = new RoleStore(Connection);
            var role = new IdentityRole <long> {
                Name = "name"
            };
            await roleStore.CreateAsync(role, CancellationToken.None);

            // act
            var result = await roleStore.DeleteAsync(role, CancellationToken.None);

            // assert
            Assert.Equal(IdentityResult.Success, result);
            Assert.False(Connection.Read("select 1 from role").Any());
        }
Example #26
0
        public List <DAO.Voo> Consulta(int id)
        {
            string sql = "SELECT * FROM TB_VOO WHERE ID_VOO = @ID_VOO";

            // Aqui eu crio a variavel sqlParamenter
            var sqlParameter = new List <SQLiteParameter>();

            // Aqui eu monto os parametros com os valores para a consulta
            sqlParameter.Add(new SQLiteParameter("@ID_VOO", id));

            DataSet ds = Connection.Read(sql, null);

            if (ds.Tables.Count > 0)
            {
                DataSetList(ds);
            }

            return(ds.Tables.Count > 0 ? lstVoo : new List <DAO.Voo>());
        }
        public void Should_Throws_When_Timeout_Expires()
        {
            var part0      = new byte[] { 0x00, 0x10 };
            var part1      = new byte[] { 0x20 };
            var stream     = new EmulateNetworkBehaviorStream();
            var connection = new Connection(stream);

            _ = Task.Run(async() =>
            {
                await stream.WriteAsync(part0, CancellationToken.None).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
                await Task.Delay(TimeSpan.FromMilliseconds(300)).ConfigureAwait(false);

                await stream.WriteAsync(part1, CancellationToken.None).ConfigureAwait(false);
                await stream.FlushAsync().ConfigureAwait(false);
                await Task.Delay(TimeSpan.FromMilliseconds(300)).ConfigureAwait(false);
            });
            Assert.Throws <AggregateException>(() => connection.Read <P0Packet>(150));
        }
        /// <summary>
        /// Sends a logout command to the ImapConnection.
        /// </summary>
        /// <exception cref="ImapAuthenticationException" />
        public void Logout()
        {
            string response;

            if (Connection.ConnectionState == ConnectionState.Closed)
            {
                throw new ImapConnectionException("Connection already closed can not logout.");
            }
            try
            {
                Connection.Write("LOGOUT\r\n");
                response = Connection.Read();
                Connection.ConnectionState = ConnectionState.Closed;
            }
            catch (Exception ex)
            {
                Connection.ConnectionState = ConnectionState.Broken;
                throw new ImapAuthenticationException("Error on connection can not logout: " + Connection.Read(), ex);
            }
        }
Example #29
0
        private void PrepareDiscoServer(Config serverConfig, int port)
        {
            this.tlsListener = new TcpListener(IPAddress.Loopback, port);
            this.tlsListener.Start();
            Task.Factory.StartNew(
                () =>
            {
                using (this.client = this.tlsListener.AcceptTcpClient())
                {
                    using (var listener = new Connection(this.client.GetStream()))
                    {
                        listener.AuthenticateAsServer(serverConfig);
                        while (true)
                        {
                            try
                            {
                                var buf       = new byte[100];
                                byte lastByte = 0;
                                var iter      = 0;
                                do
                                {
                                    iter++;
                                    var readByes = listener.Read(buf, 0, buf.Length);
                                    lastByte     = buf[readByes - 1];
                                }while (lastByte != 255);

                                var data = dataC;
                                listener.Write(data, 0, data.Length);
                            }
                            catch (Exception)
                            {
                                break;
                            }
                        }
                    }
                }

                this.tlsListener.Stop();
            });
        }
Example #30
0
        public override void Session()
        {
            base.Session();
            lastCommSucc = false;

            // чтение данных пока не будет получен конец строки, заполнен буфер или превышен таймаут
            bool   stopReceived;
            string logText;

            inBufLen = Connection.Read(inBuf, 0, InBufSize, ReqParams.Timeout, StopCond,
                                       out stopReceived, CommUtils.ProtocolLogFormats.String, out logText);
            WriteToLog(logText);

            // обработка полученных данных
            if (Connection.Connected && DecodeResponse())
            {
                lastCommSucc = true;
            }

            // завершение запроса и расчёт статистики
            FinishRequest();
            CalcSessStats();
        }
Example #31
0
 internal void LoadEnumsFromTable(Type t, Connection conn)
 {
     t = (t.IsGenericType ? t.GetGenericArguments()[0] : t);
     conn.ExecuteQuery("SELECT * FROM " + _enumTableMaps[t]);
     Dictionary<string, int> vals = new Dictionary<string, int>();
     while (conn.Read())
         vals.Add(conn[1].ToString(), conn.GetInt32(0));
     conn.Close();
     if (_enumValuesMap.ContainsKey(t))
         _enumValuesMap.Remove(t);
     if (_enumReverseValuesMap.ContainsKey(t))
         _enumReverseValuesMap.Remove(t);
     if (vals.Count == 0)
         InsertEnumIntoTable(t, conn);
     else
     {
         foreach (string str in Enum.GetNames(t))
         {
             if (!vals.ContainsKey(str))
             {
                 vals = _SyncMissingValues(vals, t, conn);
                 break;
             }
         }
         _enumValuesMap.Add(t, vals);
         Dictionary<int, string> revs = new Dictionary<int, string>();
         foreach (string str in vals.Keys)
             revs.Add(vals[str], str);
         _enumReverseValuesMap.Add(t, revs);
     }
 }
Example #32
0
 private void _CreateTablesForType(Type type, Connection conn)
 {
     List<Type> types = new List<Type>();
     types.Add(type);
     if (new List<Type>(type.GetInterfaces()).Contains(typeof(IClassView)))
     {
         ClassViewAttribute cva = conn.Pool[type];
         foreach (Type t in cva.Query.RequiredTypes)
         {
             if (!types.Contains(t))
                 types.Add(t);
             types = _RecurLoadTypesForTable(_pool.Mapping[t], types);
         }
     }
     else
         types = _RecurLoadTypesForTable(_pool.Mapping[type], types);
     for (int x = 1; x < types.Count; x++)
     {
         if (_createdTypes.Contains(types[x]))
         {
             types.RemoveAt(x);
             x--;
         }
     }
     List<ExtractedTableMap> tables;
     List<Trigger> triggers;
     List<Generator> generators;
     List<IdentityField> identities;
     List<View> views;
     List<StoredProcedure> procedures;
     ExtractExpectedStructure(ref types, out tables, out triggers, out generators, out identities, out views, out procedures, conn);
     List<string> createdTables = _UpdateStructure(tables, triggers, generators, identities, views, procedures,conn);
     foreach (Type t in types)
     {
         if (Utility.IsEnum(t))
         {
             if (createdTables.Contains(_pool.Enums[t]))
                 _pool.Enums.InsertEnumIntoTable(t, conn);
             else
                 _pool.Enums.LoadEnumsFromTable(t, conn);
         }
     }
     _createdTypes.AddRange(types);
     _UpdateAddiontalData(triggers, generators, identities, views, procedures);
     if (!_pool.DebugMode && (_translations.Count > 0))
     {
         foreach (Type t in types)
         {
             if (_translations.ContainsKey(t))
             {
                 foreach (EnumTranslationPair etp in _translations[t])
                 {
                     conn.ExecuteNonQuery(String.Format(
                         "UPDATE {0} SET {1} = '{3}' WHERE {1} = '{2}'",
                         new object[]{
                         _pool.Enums[t],
                         _pool.Translator.GetEnumValueFieldName(t,conn),
                         etp.OriginalName,
                         etp.NewName}
                     ));
                     conn.Close();
                 }
             }
             Dictionary<string, int> enumValuesMap = new Dictionary<string, int>();
             Dictionary<int, string> enumReverseValuesMap = new Dictionary<int, string>();
             List<string> enumNames = new List<string>(Enum.GetNames(t));
             List<int> deletes = new List<int>();
             conn.ExecuteQuery(String.Format("SELECT ID,{1} FROM {0}",
                 _pool.Enums[t],
                 _pool.Translator.GetEnumValueFieldName(t, conn)));
             while (conn.Read())
             {
                 if (enumNames.Contains(conn[1].ToString()))
                 {
                     enumValuesMap.Add(conn[1].ToString(), (int)conn[0]);
                     enumReverseValuesMap.Add((int)conn[0], conn[1].ToString());
                     enumNames.Remove(conn[1].ToString());
                 }
                 else
                     deletes.Add((int)conn[0]);
             }
             conn.Close();
             if (deletes.Count > 0)
             {
                 foreach (int i in deletes)
                 {
                     conn.ExecuteNonQuery(String.Format("DELETE FROM {0} WHERE ID = {1}",
                         _pool.Enums[t],
                         i));
                     conn.Close();
                 }
             }
             if (enumNames.Count > 0)
             {
                 foreach (string str in enumNames)
                 {
                     conn.ExecuteNonQuery(String.Format("INSERT INTO {0}({1}) VALUES('{2}')",
                         _pool.Enums[t],
                         _pool.Translator.GetEnumValueFieldName(t, conn),
                         str));
                     conn.Close();
                     conn.ExecuteQuery(String.Format("SELECT ID FROM {0} WHERE {1}='{2}'",
                         _pool.Enums[t],
                         _pool.Translator.GetEnumValueFieldName(t, conn),
                         str));
                     conn.Read();
                     enumValuesMap.Add(str, (int)conn[0]);
                     enumReverseValuesMap.Add((int)conn[0], str);
                     conn.Close();
                 }
             }
             conn.Commit();
             _pool.Enums.AssignMapValues(t, enumValuesMap, enumReverseValuesMap);
         }
     }
 }
Example #33
0
 public void Init(Connection conn)
 {
     _tables = new List<ExtractedTableMap>();
     _triggers = new List<Trigger>();
     _generators = new List<Generator>();
     _identities = new List<IdentityField>();
     _views = new List<View>();
     _procedures = new List<StoredProcedure>();
     _createdTypes = new List<Type>();
     conn.ExecuteQuery(conn.Pool.queryBuilder.SelectTriggers());
     while (conn.Read())
     {
         //patch to handle long trigger code from mssql
         if (_triggers.Count > 0)
         {
             if (_triggers[_triggers.Count - 1].Name == (string)conn[0])
                 _triggers[_triggers.Count - 1] = new Trigger((string)conn[0], (string)conn[1], _triggers[_triggers.Count - 1].Code + (string)conn[2]);
             else
                 _triggers.Add(new Trigger((string)conn[0], (string)conn[1], (string)conn[2]));
         }else
             _triggers.Add(new Trigger((string)conn[0], (string)conn[1], (string)conn[2]));
     }
     conn.Close();
     conn.ExecuteQuery(conn.Pool.queryBuilder.SelectProcedures());
     while (conn.Read())
     {
         _procedures.Add(new StoredProcedure(conn[0].ToString(), conn[1].ToString(), conn[2].ToString(), conn[3].ToString(), conn[4].ToString()));
     }
     conn.Close();
     conn.ExecuteQuery(conn.queryBuilder.SelectViews());
     while (conn.Read())
         _views.Add(new View((string)conn[0], (string)conn[1]));
     conn.Close();
     conn.ExecuteQuery(conn.queryBuilder.SelectTableNames());
     while (conn.Read())
     {
         _tables.Add(new ExtractedTableMap((string)conn[0]));
     }
     conn.Close();
     for (int x = 0; x < _tables.Count; x++)
     {
         ExtractedTableMap etm = _tables[x];
         etm.Indices = conn.queryBuilder.ExtractTableIndexes(etm.TableName, conn);
         conn.ExecuteQuery(conn.queryBuilder.SelectTableFields(etm.TableName));
         while (conn.Read())
         {
             etm.Fields.Add(new ExtractedFieldMap(conn[0].ToString(), conn[1].ToString(),
                                                  long.Parse(conn[2].ToString()), bool.Parse(conn[3].ToString()), bool.Parse(conn[4].ToString()),
                                                  bool.Parse(conn[5].ToString()),
                                                  (conn.IsDBNull(6) ? null : conn[6].ToString())));
         }
         conn.Close();
         conn.ExecuteQuery(conn.queryBuilder.SelectForeignKeys(etm.TableName));
         while (conn.Read())
         {
             etm.ForeignFields.Add(new ForeignRelationMap(conn[5].ToString(), conn[0].ToString(), conn[1].ToString(),
                                                          conn[2].ToString(), conn[3].ToString(), conn[4].ToString()));
         }
         conn.Close();
         _tables.RemoveAt(x);
         _tables.Insert(x, etm);
     }
     if (conn.UsesGenerators)
     {
         conn.ExecuteQuery(conn.queryBuilder.SelectGenerators());
         while (conn.Read())
         {
             _generators.Add(new Generator((string)conn[0]));
         }
         conn.Close();
         for (int x = 0; x < _generators.Count; x++)
         {
             Generator gen = _generators[x];
             conn.ExecuteQuery(conn.queryBuilder.GetGeneratorValue(gen.Name));
             conn.Read();
             gen.Value = long.Parse(conn[0].ToString());
             conn.Close();
             _generators.RemoveAt(x);
             _generators.Insert(x, gen);
         }
     }
     if (conn.UsesIdentities)
     {
         conn.ExecuteQuery(conn.queryBuilder.SelectIdentities());
         while (conn.Read())
         {
             _identities.Add(new IdentityField((string)conn[0], (string)conn[1], (string)conn[2], (string)conn[3]));
         }
         conn.Close();
     }
 }
Example #34
0
 internal override List<Index> ExtractTableIndexes(string tableName, Connection conn)
 {
     List<Index> ret = new List<Index>();
     conn.ExecuteQuery("SELECT TRIM(ind.RDB$INDEX_NAME),ind.RDB$UNIQUE_FLAG,(CASE WHEN ind.RDB$INDEX_TYPE IS NULL THEN 0 ELSE 1 END) FROM RDB$INDICES ind "+
         "WHERE ind.RDB$RELATION_NAME = '" + tableName + "' AND ind.RDB$INDEX_NAME NOT IN (SELECT RDB$INDEX_NAME FROM RDB$RELATION_CONSTRAINTS WHERE RDB$RELATION_NAME = '" + tableName + "' AND RDB$INDEX_NAME IS NOT NULL) ORDER BY ind.RDB$INDEX_ID");
     while (conn.Read())
     {
         ret.Add(new Index(conn[0].ToString(), null, conn[1].ToString() == "1", conn[2].ToString() == "0"));
     }
     conn.Close();
     for (int x = 0; x < ret.Count; x++)
     {
         conn.ExecuteQuery("SELECT TRIM(ind.RDB$FIELD_NAME) FROM RDB$INDEX_SEGMENTS ind WHERE TRIM(ind.RDB$INDEX_NAME) = '" + ret[0].Name + "' ORDER BY ind.RDB$FIELD_POSITION");
         List<string> fields = new List<string>();
         while (conn.Read())
         {
             fields.Add(conn[0].ToString());
         }
         conn.Close();
         Index ind = ret[x];
         ind.Fields = fields.ToArray();
         ret.RemoveAt(x);
         ret.Insert(x, ind);
     }
     return ret;
 }
Example #35
0
        // This method returns:
        // 1. NULL if incoming datastream doesn't contain at least 4 bytes
        // 2. Empty String is HTTP method is unknown
        // 3. HTTP method name
        private static String ReadHttpMethodName(Connection connection)
        {
            Byte[] lBuffer = new Byte[4];

            if (connection.Receive(lBuffer, 0, 4) < 4)
                return null;

            String lHttpMethodName = Encoding.ASCII.GetString(lBuffer, 0, 4);

            if ((lHttpMethodName == "POST") || (lHttpMethodName == "GET ") || (lHttpMethodName == "HTTP") ||
                    (lHttpMethodName == "HEAD") || (lHttpMethodName == "PUT "))
                return lHttpMethodName;

            if (lHttpMethodName == "MERG")
            {
                connection.Read(lBuffer, 0, 1);
                if (lBuffer[0] != (Byte)'E')
                    return String.Empty;

                return "MERGE";
            }

            if (lHttpMethodName == "DELE")
            {
                connection.Read(lBuffer, 0, 2);
                if (lBuffer[0] != (Byte)'T' || lBuffer[1] != (Byte)'E')
                    return String.Empty;

                return "DELETE";
            }

            if (lHttpMethodName == "OPTI")
            {
                connection.Read(lBuffer, 0, 3);
                if (lBuffer[0] != (Byte)'O' || lBuffer[1] != (Byte)'N' || lBuffer[2] != (Byte)'S')
                    return String.Empty;

                return "OPTIONS";
            }

            return String.Empty;
        }
Example #36
0
 private Dictionary<string, int> _SyncMissingValues(Dictionary<string, int> vals, Type t, Connection conn)
 {
     t = (t.IsGenericType ? t.GetGenericArguments()[0] : t);
     string[] keys = new string[vals.Count];
     vals.Keys.CopyTo(keys, 0);
     foreach (string str in Enum.GetNames(t))
     {
         if (!vals.ContainsKey(str))
         {
             conn.ExecuteNonQuery(string.Format("INSERT INTO {0}({1}) VALUES({2});",new object[]{ 
                 _enumTableMaps[t],
                 _pool.Translator.GetEnumValueFieldName(t, conn),
                 conn.CreateParameterName("value")}),
             new System.Data.IDbDataParameter[]{
                         conn.Pool.CreateParameter(conn.CreateParameterName("id"),null,Org.Reddragonit.Dbpro.Structure.Attributes.FieldType.INTEGER,4),
                         conn.CreateParameter(conn.CreateParameterName("value"),str)
                     });
             conn.ExecuteQuery("SELECT ID FROM " + _enumTableMaps[t] + " WHERE " + _pool.Translator.GetEnumValueFieldName(t, conn) + " = " + conn.CreateParameterName("value"),
                 new IDbDataParameter[]{
                     conn.CreateParameter(conn.CreateParameterName("value"),str)
                 });
             conn.Read();
             vals.Add(str, conn.GetInt32(0));
             conn.Close();
         }
     }
     return vals;
 }
 internal override List<Index> ExtractTableIndexes(string tableName, Connection conn)
 {
     List<Index> ret = new List<Index>();
     Dictionary<string, string> objIds = new Dictionary<string, string>();
     List<string> indexIds = new List<string>();
     conn.ExecuteQuery(@"select ind.object_id,ind.index_id,ind.name,ind.is_unique from sys.indexes ind, sysobjects tbl 
         WHERE ind.object_id = tbl.id AND tbl.xtype='U' AND ind.name IS NOT NULL AND ind.is_primary_key=0 AND tbl.name = '"+tableName+"'");
     while (conn.Read())
     {
         ret.Add(new Index(conn[2].ToString(), null, conn[3].ToString() == "1", false));
         objIds.Add(conn[2].ToString(), conn[0].ToString());
         indexIds.Add(conn[1].ToString());
     }
     conn.Close();
     for (int x = 0; x < ret.Count; x++)
     {
         List<string> fields = new List<string>();
         bool asc = false;
         conn.ExecuteQuery("SELECT c.COLUMN_NAME,indcol.is_descending_key FROM sys.index_columns indcol,INFORMATION_SCHEMA.COLUMNS c " +
             "WHERE indcol.object_id = '"+objIds[ret[x].Name]+"' AND indcol.index_id = "+indexIds[x]+" AND c.table_name = '"+tableName+"' AND c.ORDINAL_POSITION = indcol.column_id ORDER BY index_id,key_ordinal");
         while (conn.Read())
         {
             fields.Add(conn[0].ToString());
             asc = conn[1].ToString() == "0";
         }
         conn.Close();
         Index ind = ret[x];
         ret.RemoveAt(x);
         ret.Insert(x, new Index(ind.Name,fields.ToArray(),ind.Unique,asc));
     }
     return ret;
 }
 internal override List<Index> ExtractTableIndexes(string tableName, Connection conn)
 {
     List<Index> ret = new List<Index>();
     conn.ExecuteQuery("SHOW INDEX FROM " + tableName + " FROM " + ((MySqlConnectionPool)conn.Pool).DbName+" WHERE Key_Name <> 'PRIMARY' AND "+
         "Key_Name NOT IN (SELECT CONSTRAINT_NAME FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '" + ((MySqlConnectionPool)conn.Pool).DbName+"' AND TABLE_NAME='"+tableName+"')");
     string curName = null;
     bool unique=false;
     List<string> fields = new List<string>();
     while (conn.Read())
     {
         if (curName!=null){
             if (curName!=conn[2].ToString()){
                 ret.Add(new Index(curName,fields.ToArray(),unique,false));
                 curName = conn[2].ToString();
                 fields=new List<string>();
             }
         }
         fields.Add(conn[4].ToString());
         unique = conn[1].ToString()=="0";
     }
     if (curName!=null){
         ret.Add(new Index(curName,fields.ToArray(),unique,false));
     }
     conn.Close();
     return ret;
 }
Example #39
0
 public NameTranslator(ConnectionPool pool, Connection conn)
 {
     _pool = pool;
     _nameTranslations = new Dictionary<string, string>();
     conn.ExecuteQuery(conn.queryBuilder.GetAllObjectDescriptions());
     while (conn.Read())
     {
         Logger.LogLine(string.Format("Adding Description: {0} = {1}",
             conn[0].ToString(),
             conn[1].ToString()));
         if (conn[0].ToString().Trim().StartsWith(string.Format(_VIEW_DESCRIPTION,""))&&conn[0].ToString().Trim().EndsWith("]"))
             _nameTranslations.Add(conn[0].ToString().Trim().Substring(0,conn[0].ToString().Trim().IndexOf("\t")), conn[1].ToString().Trim());
         else
             _nameTranslations.Add(conn[0].ToString().Trim(), conn[1].ToString().Trim());
     }
     conn.Close();
     _createDescriptions = new List<string>();
 }