예제 #1
0
        /// <summary>
        /// Get the variable value.
        /// </summary>
        /// <returns></returns>
        public Result GetResult()
        {
            Result result = new Result( 1 );
            result.Add( new object[]{Value} );

            return result;
        }
예제 #2
0
파일: Finder.cs 프로젝트: MrKevHunter/Katas
        private List<Result> GetListOfPeopleWithBirthDateDifference()
        {
            var results = new List<Result>();

            foreach (var person in _people)
            {
                foreach (Person otherPerson in _people.Except(new List<Person> {person}))
                {
                    var result = new Result();
                    result.Add(person);
                    result.Add(otherPerson);
                    result.BirthDateDifference = result.Person2.BirthDate - result.Person1.BirthDate;
                    result.BirthDateDifference = new TimeSpan(Math.Abs(result.BirthDateDifference.Ticks));
                    results.Add(result);
                }
            }

            return results;
        }
예제 #3
0
        /*
         * Assignation
         * [Type] [Identifier] = [ExpressionNode]
         */
        public override void EnterAssignationStatement([NotNull] AssignationStatementContext context)
        {
            AssignationStatement statement = new AssignationStatement(Parent, context);

            ExpressionListener listener = new ExpressionListener(statement);

            context.right.EnterRule(listener);
            ExpressionNode value = listener.GetResult();

            statement.Value = value;

            listener = new ExpressionListener(statement);
            context.left.EnterRule(listener);

            statement.Target = listener.GetResult().Get <VariableNameExpression>(0);

            statement.Operator = '=';

            Result.Add(statement);
        }
예제 #4
0
        protected override void Mapper(IDataRecord record)
        {
            var schema     = record.GetString("owner_name").TrimEnd();
            var tableName  = record.GetString("table_name").TrimEnd();
            var name       = record.GetString("constraint_name").TrimEnd();
            var expression = record.GetString("expression");
            var constraint = new DatabaseConstraint
            {
                ConstraintType = ConstraintType.Check,
                Expression     = expression,
                SchemaOwner    = schema,
                TableName      = tableName,
                Name           = name,
            };

            if (!Result.Exists(x => x.Name == name))
            {
                Result.Add(constraint);
            }
        }
예제 #5
0
        protected override void Mapper(IDataRecord record)
        {
            var owner = record.GetString("schemaname");
            var name  = record.GetString("sequencename");
            //these are actually bigInts, but they are likely to be ints
            var increment = record.GetNullableInt("increment_by");
            var min       = record.GetNullableLong("start_value");
            var max       = record.GetNullableLong("max_value");

            var sequence = new DatabaseSequence
            {
                SchemaOwner  = owner,
                Name         = name,
                IncrementBy  = increment ?? 0,
                MinimumValue = min,
                MaximumValue = max
            };

            Result.Add(sequence);
        }
예제 #6
0
        /// <summary>
        /// Files at the bottom of the hierarchy (see note on sibling folders for Top)
        /// </summary>
        /// <param name="FileInfos"></param>
        /// <returns></returns>
        public FileInfo [] Bottom(FileInfo[] FileInfos)
        {
            List <FileInfo> Result  = new List <FileInfo>();
            int             MaxDirs = int.MaxValue;

            foreach (FileInfo fi in FileInfos)
            {
                string[] Dirs = fi.FullName.Split(new string[] { @"\/" }, StringSplitOptions.RemoveEmptyEntries);
                if ((Result.Count == 0) || (Dirs.Length < MaxDirs))
                {
                    if (Dirs.Length > MaxDirs)
                    {
                        Result = new List <FileInfo>();                       //if it's lower than existing file list, then clear and start again
                    }
                    Result.Add(fi);
                    MaxDirs = Dirs.Length;
                }
            }
            return(Result.ToArray());
        }
예제 #7
0
        protected override void Mapper(IDataRecord record)
        {
            var schema     = record.GetString("SchemaOwner");
            var tableName  = record.GetString("TableName");
            var columnName = record.GetString("ColumnName");
            var seed       = record.GetNullableLong("IdentitySeed").GetValueOrDefault();
            var increment  = record.GetNullableLong("IdentityIncrement").GetValueOrDefault();
            var column     = new DatabaseColumn
            {
                SchemaOwner        = schema,
                TableName          = tableName,
                Name               = columnName,
                IsAutoNumber       = true,
                IdentityDefinition = new DatabaseColumnIdentity {
                    IdentityIncrement = increment, IdentitySeed = seed
                },
            };

            Result.Add(column);
        }
예제 #8
0
        public bool UpdateMongoProduct(int ProductID)
        {
            IsResult = false;
            var sv  = new ProductService();
            var sql = @"select  it.* FROM view_ProductMobileApp AS it 
     WHERE  ProductID = " + ProductID; //322138
            //      AND RowFlag IN (4,5,6) AND CompRowFlag IN (2,4)
            //AND CompIsDelete = 0) AND ( IsShow = 1 AND IsJunk = 0
            var products = sv.qDB.ExecuteQuery <view_ProductMobileApp>(sql).ToList();

            if (products != null && products.Count() > 0)
            {
                var svAddress = new AddressService();
                var provinces = svAddress.GetProvinceAll();

                foreach (var item in products)
                {
                    var res = new ResultMsg();
                    if (item.IsDelete == false &&
                        item.CompIsDelete == false &&
                        item.IsShow == true &&
                        item.IsJunk == false &&
                        (item.RowFlag == 4 || item.RowFlag == 5 || item.RowFlag == 6) &&
                        (item.CompRowFlag == 2 || item.CompRowFlag == 4))
                    {
                        var ProvinceName = provinces.Where(m => m.ProvinceID == item.CompProvinceID).FirstOrDefault().ProvinceName;
                        res.IsResult = SaveKeywordMongo(item, ProvinceName);
                        res.Id       = item.ProductID;
                        res.Comment  = "save";
                    }
                    else
                    {
                        res.IsResult = RemoveProductKeywordMongo(item.ProductID);
                        res.Id       = item.ProductID;
                        res.Comment  = "remove";
                    }
                    Result.Add(res);
                }
            }
            return(IsResult);
        }
예제 #9
0
        public IList <DatabaseColumn> Execute(DbConnection connection)
        {
            var tables = new Tables(_tableName, new string[0], _commandTimeout).Execute(connection);

            foreach (var table in tables)
            {
                var tableName = table.Name;
                using (var cmd = connection.CreateCommand())
                {
                    cmd.CommandText = string.Format(PragmaSql, tableName);
                    int ordinal = 0;
                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var colName = dr.GetString("name");
                            var col     = new DatabaseColumn
                            {
                                TableName = tableName,
                                Name      = colName,
                                Ordinal   = ordinal,
                                //type will be like "nvarchar(32)".
                                //Lengths /precisions could be parsed out (nb remember this is Sqlite)
                                DbDataType   = dr.GetString("type"),
                                Nullable     = dr.GetBoolean("notnull"),
                                DefaultValue = dr.GetString("dflt_value"),
                                IsPrimaryKey = dr.GetBoolean("pk"),
                            };
                            if (col.IsPrimaryKey && col.DbDataType == "INTEGER")
                            {
                                col.IsAutoNumber = true;
                            }
                            Result.Add(col);
                            ordinal++;
                        }
                    }
                }
            }

            return(Result);
        }
예제 #10
0
        private void CalculateDueTime()
        {
            DateTime     dateTime    = DateTime.UtcNow;
            TimeZoneInfo time        = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
            var          currentTime = TimeZoneInfo.ConvertTimeFromUtc(dateTime, time);

            //16:03
            //var aux = objReplyTrain.ToList().Where(o => o.Scharrival.Contains(":")).Select(o => ConvertTimeStringToDatetime(o.Scharrival) >= DateTime.Now).ToList();
            var auxConvert = objReplyTrain.Where(o => o.Scharrival.Contains(":")).Select(o => new ItemRailTimeResult()
            {
                Time = ConvertTimeStringToDatetime(o.Scharrival), Name = o.Direction, Delay = o.Late
            });
            var aux = auxConvert.Where(o => o.Time > currentTime).OrderBy(o => o.Time).ToList();

            foreach (var item in aux)
            {
                int dueMin = (int)item.Time.Subtract(currentTime).TotalMinutes;
                item.DueTime = dueMin + item.Delay; //Add the Delay to the Due Time - SHaridas
                Result.Add(item);
            }
        }
예제 #11
0
        protected override void Mapper(IDataRecord record)
        {
            string pack     = null;
            var    owner    = record.GetString("OWNER");
            var    name     = record.GetString("OBJECT_NAME");
            var    procName = record.GetString("PROCEDURE_NAME");

            if (procName != null)
            {
                pack = name;
                name = procName;
            }
            var sproc = new DatabaseStoredProcedure
            {
                SchemaOwner = owner,
                Package     = pack,
                Name        = name,
            };

            Result.Add(sproc);
        }
예제 #12
0
 protected override void OnLoad(EventArgs e)
 {
     if (Session["Account"] == null || string.IsNullOrEmpty(Session["Account"].ToString()))
     {
         if (string.IsNullOrEmpty(helper.GetParam("action")))
         {
             Response.Redirect("~/Login.aspx");
         }
         else
         {
             Result result = new Result();
             result.Add("Sorry,您尚未登录或登录已经超时!");
             helper.Result = result;
             helper.ResponseResult();
         }
     }
     else
     {
         base.OnLoad(e);
     }
 }
예제 #13
0
        /// <summary>
        /// 获得关注的用户列表
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="secret"></param>
        /// <param name="nextopenid"></param>
        /// <param name="json"></param>
        /// <returns></returns>
        public static Result GetUserList(string appid, string secret, string nextopenid, out string json)
        {
            json = "";
            Result rlt = new Result();

            try
            {
                string token = "";
                rlt.Join(Init(appid, secret, out token));
                if (rlt.IsValid)
                {
                    string url = string.Format("https://api.weixin.qq.com/cgi-bin/user/get?access_token={0}&next_openid={1}", token, nextopenid);
                    json = PostAndGet.GetResponseString(url);
                }
            }
            catch (Exception ex)
            {
                rlt.Add("错误:" + ex.Message);
            }
            return(rlt);
        }
예제 #14
0
        public virtual Result CanSend(User user)
        {
            int maxMinutes = config.Instance.Site.UserSendConfirmEmailInterval;

            Result      result = new Result();
            UserConfirm ac     = db.find <UserConfirm>("User.Id=" + user.Id + " order by Id desc").first();

            if (ac == null)
            {
                return(result);
            }

            if (DateTime.Now.Subtract(ac.Created).Minutes < maxMinutes)
            {
                result.Add(string.Format("{0} 分钟之内,最多只能发送一次", maxMinutes));

                return(result);
            }

            return(result);
        }
예제 #15
0
        public void Remove(string name)
        {
            int count = 0;

            foreach (string comp in Installed)
            {
                var temp = Dependencies.FirstOrDefault(x => x.Name == comp);
                if (temp != null)
                {
                    foreach (var components in temp.Dependants)
                    {
                        if (components.Name == name)
                        {
                            count++;
                        }
                    }
                }
            }
            if (count == 0)
            {
                dependantCount = 1;
                Result.Add("   Removing " + name);
                Installed.Remove(name);
                var temp = Dependencies.FirstOrDefault(x => x.Name == name);
                if (temp != null)
                {
                    foreach (var components in temp.Dependants)
                    {
                        if (!ExplicitlyInstalled.Contains(components.Name))
                        {
                            Remove(components.Name);
                        }
                    }
                }
            }
            else if (count > 0 && dependantCount != 1)
            {
                Result.Add("   " + name + " is still needed");
            }
        }
예제 #16
0
        public void LoadFromTable(DataTable in_DataTale)
        {
            DataTable oDT = in_DataTale;

            int k3 = 0; // 초기 컬럼 스타트 지점

            foreach (KeyValuePair <string, dynamic> tablename in Table_entity)
            {
                List <dynamic> result     = new List <dynamic>();
                Type           Class      = tablename.Value.GetType(); //객체의 타입 가져오기
                PropertyInfo[] Properties = Class.GetProperties(BindingFlags.Instance | BindingFlags.Public);
                //필요 없는 칼럼 제거
                var removed_properties = from prt in Properties
                                         where !except_members.Contains(prt.Name)
                                         select prt;

                Properties = removed_properties.ToArray();

                int k2 = k3; //한 객체 row 칼럼 완전 iteration 돌고 난 다음 컬럼 스타트 지점
                for (int i = 0; i < oDT.Rows.Count; i++)
                {
                    int k1 = k2; // 객체 row 한번 iteration 돌고 난 다음 컬럼 스타트
                    for (int j = 0; j < Properties.Length; j++)
                    {
                        //객체의 멤버에 db필드값 지정
                        string member = oDT.Rows[i][k1].ToString();
                        Properties[j].SetValue(tablename.Value, member, null);
                        k1++;
                    }
                    k3 = k1; // 진행된 칼럼 순서 저장

                    dynamic copyObject = tablename.Value.Copy();

                    result.Add(copyObject);
                }
                Result.Add(result);
            }

            //todo
        }
예제 #17
0
        protected override void Mapper(IDataRecord record)
        {
            var schema    = record.GetString("SchemaName");
            var tableName = record.GetString("TableName");
            var name      = record.GetString("IndexName");
            var index     = Result.FirstOrDefault(f => f.Name == name && f.SchemaOwner == schema && f.TableName.Equals(tableName, StringComparison.OrdinalIgnoreCase));

            if (index == null)
            {
                index = new DatabaseIndex
                {
                    SchemaOwner = schema,
                    TableName   = tableName,
                    Name        = name,
                    IndexType   = record.GetString("INDEX_TYPE"),
                    IsUnique    = record.GetBoolean("IsUnique"),
                };
                if (record.GetBoolean("IsPrimary"))
                {
                    //by default SqlServer pks have clustered indexes. If they are not, we need to record it.
                    index.IndexType = string.Equals("NONCLUSTERED", index.IndexType, StringComparison.OrdinalIgnoreCase) ?
                                      "PRIMARY NONCLUSTERED" :
                                      "PRIMARY";
                }
                Result.Add(index);
            }
            var colName = record.GetString("ColumnName");

            if (string.IsNullOrEmpty(colName))
            {
                return;
            }

            var col = new DatabaseColumn
            {
                Name = colName,
            };

            index.Columns.Add(col);
        }
예제 #18
0
        public IList <DatabaseConstraint> Execute(IConnectionAdapter connectionAdapter)
        {
            var tables = new Tables(_tableName).Execute(connectionAdapter);

            foreach (var table in tables)
            {
                var tableName = table.Name;
                using (var cmd = connectionAdapter.DbConnection.CreateCommand())
                {
                    cmd.CommandText = string.Format(PragmaSql, tableName);
                    int ordinal = 0;
                    using (var dr = cmd.ExecuteReader())
                    {
                        List <string> columns = new List <string>();
                        while (dr.Read())
                        {
                            var  colName      = dr.GetString("name");
                            bool isPrimaryKey = dr.GetBoolean("pk");
                            if (isPrimaryKey == false)
                            {
                                continue;
                            }

                            columns.Add(colName);
                        }

                        DatabaseConstraint con = new DatabaseConstraint
                        {
                            TableName      = tableName,
                            SchemaOwner    = "",
                            ConstraintType = ConstraintType.PrimaryKey,
                        };
                        con.Columns.AddRange(columns);
                        Result.Add(con);
                    }
                }
            }

            return(Result);
        }
        /// <summary>
        /// Read the node
        /// </summary>
        /// <param name="node"></param>
        protected override void ReadNode(string api, XmlNode node)
        {
            var nameText               = node.SelectSingleNode("./wb:name/text()", namespaceManager);
            var sourceText             = node.SelectSingleNode("./wb:source/text()", namespaceManager);
            var sourceNoteText         = node.SelectSingleNode(".//wb:sourceNote/text()", namespaceManager);
            var sourceOrganizationText = node.SelectSingleNode(".//wb:sourceOrganization/text()", namespaceManager);

            var indicatorsData = new IndicatorsTable
            {
                Id                = node.Attributes["id"].Value,
                TopicId           = TopicId,
                Name              = nameText?.Value,
                SourceId          = Convert.ToInt32(node.SelectSingleNode("./wb:source", namespaceManager).Attributes["id"].Value),
                Source            = sourceText?.Value,
                SourceNote        = sourceNoteText?.Value,
                SourceOrgaisation = sourceOrganizationText?.Value,
            };

            logger.Info($"Read indicator id '{indicatorsData.Id} for Topic '{TopicId}' on request Uri '{api}'");

            Result.Add(indicatorsData);
        }
예제 #20
0
        /// <summary>
        /// List of files at the top of the hierarchy, not necessarily in the same folder, but at the same level
        /// e.g. one/a, one/b and two/c, two/d returns [one/a,one/b,two/c,two/d] as they're all at level one.
        /// </summary>
        /// <param name="FileInfos"></param>
        /// <returns></returns>
        public FileInfo [] Top(FileInfo[] FileInfos)
        {
            //Result is probably FileInfos[0] if the directory scan was sensible, but can't rely on that so use the full path name.
            //Also, there can be more than one file in the top directory, so we have to return a list
            List <FileInfo> Result  = new List <FileInfo>();
            int             MinDirs = 0;

            foreach (FileInfo fi in FileInfos)
            {
                string [] Dirs = fi.FullName.Split(new string [] { @"\/" }, StringSplitOptions.RemoveEmptyEntries);
                if ((Result.Count == 0) || (Dirs.Length < MinDirs))
                {
                    if (Dirs.Length < MinDirs)
                    {
                        Result = new List <FileInfo>();                       //if it's higher up than existing file list, then clear and start again
                    }
                    Result.Add(fi);
                    MinDirs = Dirs.Length;
                }
            }
            return(Result.ToArray());
        }
예제 #21
0
        /// <summary>
        /// 根据散列获取相应 List
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public void GetList(string key, List <int> fileds)
        {
            try
            {
                using (var client = ConnectionMultiplexer.Connect(Profile.redisIp + ",abortConnect=false"))
                {
                    var cv = client.GetDatabase();
                    if (fileds.Count > 0)
                    {
                        foreach (var t in fileds)
                        {
                            var result = cv.SortedSetRangeByScore(key, t, t);

                            for (int i = 0; i < result.Length; i++)
                            {
                                Result.Add(System.Text.Encoding.UTF8.GetString(result[i]));
                            }
                        }
                    }
                    else
                    {
                        var result = cv.SortedSetRangeByRank(key, 0, -1);
                        for (int i = 0; i < result.Length; i++)
                        {
                            Result.Add(System.Text.Encoding.UTF8.GetString(result[i]));
                        }
                    }
                    Sucess = true;
                    Count  = Result.Count();
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
                Message = ex.Message;
                Code    = ErrorCode.ReadRedisErrorCode;
                Sucess  = false;
            }
        }
예제 #22
0
        /// <summary>
        /// Parse individual node and save into result
        /// </summary>
        /// <param name="node"></param>
        protected override void ReadNode(string api, XmlNode node)
        {
            var id             = Convert.ToInt32(node.Attributes["id"].Value);
            var valueText      = node.SelectSingleNode(".//wb:value/text()", namespaceManager);
            var sourceNoteText = node.SelectSingleNode(".//wb:sourceNote/text()", namespaceManager);

            Result.Add(new TopicsTable
            {
                Id         = id,
                Value      = (valueText == null) ? null : valueText.Value,
                SourceNote = (sourceNoteText == null) ? null : sourceNoteText.Value,
            });

            // For each topic fetch indicators
            logger.Info($"Fetch all indicators for topic '{id}'");
            var indicatorsRestObj = new WBIndicatorsPerTopicWebServiceRest(
                id, config.PersistenceManager, config.Database, tasksConsumerService);

            indicatorsRestObj.Read();

            //// Topics and Indicators relation
            //var topicsIndicatorsList = new List<TopicsIndicatorsRelationTable>();
            //foreach (var item in indicatorsRestObj.Result)
            //{
            //    logger.Info($"Save indicator id '{item.Id}' for topic '{id}'");
            //    config.Database.Indicators.Save(item, config.PersistenceManager);
            //    topicsIndicatorsList.Add(new TopicsIndicatorsRelationTable()
            //    {
            //        IndicatorsId = item.Id,
            //        TopicsId = id
            //    });
            //}

            //var valueList = topicsIndicatorsList.Select(item => $"{item.IndicatorsId},{item.TopicsId}").ToList();
            //var valuesQuery = string.Join("\n", valueList);
            //logger.Info(valuesQuery);

            //config.Database.TopicsIndicators.Save(topicsIndicatorsList, config.PersistenceManager);
        }
예제 #23
0
파일: CPara.cs 프로젝트: axinken/MyProject
        public CStatTest(int idNo, string name, int flowId, string flowName, int slotMax)
        {
            this._idNo = idNo;

            this._name = name;

            this._slotMax = slotMax;

            this.FlowId = flowId;

            this.FlowName = flowName;

            for (int i = 0; i < slotMax; i++)
            {
                SerialNo.Add("");
                ResultName.Add("");
                ResultId.Add(0);
                Result.Add(0);
                Value.Add("");
                TranOK.Add(false);
            }
        }
예제 #24
0
        internal override bool ExecuteCsvSource(TemplateItem item, ISource source, Result result)
        {
            if (source is not CsvSource csvSource)
            {
                return(false);
            }

            var template = DotLiquid.Template.Parse(item.Text);

            using (var stringReader = new StringReader(csvSource.SourceText))
            {
                var csvConfig = new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    HasHeaderRecord = false,
                    Delimiter       = ","
                };
                using var csv = new CsvReader(stringReader, csvConfig);
                while (csv.Read())
                {
                    var ind  = 0;
                    var list = new List <string>();
                    while (csv.TryGetField(ind, out string value))
                    {
                        list.Add(value);
                        ind++;
                    }

                    var par    = Expression.Parameter(typeof(List <string>), "c");
                    var lambda = DynamicExpressionParser.ParseLambda(new[] { par }, null, item.OutputKey);
                    var c      = lambda.Compile();
                    var key    = (string)c.DynamicInvoke(list);

                    var output = template.Render(Hash.FromAnonymousObject(new { c = list }));
                    result.Add(key, output);
                }
            }

            return(true);
        }
예제 #25
0
        protected override void Mapper(IDataRecord record)
        {
            var schema    = record["table_schema"].ToString();
            var tableName = record["table_name"].ToString();
            var name      = record["column_name"].ToString();
            var table     = new DatabaseColumn
            {
                SchemaOwner       = schema,
                TableName         = tableName,
                Name              = name,
                Ordinal           = record.GetInt("ordinal_position"),
                DbDataType        = record.GetString("data_type"),
                Length            = record.GetNullableInt("character_maximum_length"),
                Precision         = record.GetNullableInt("numeric_precision"),
                Scale             = record.GetNullableInt("numeric_scale"),
                Nullable          = record.GetBoolean("is_nullable"),
                DefaultValue      = record.GetString("column_default"),
                DateTimePrecision = record.GetNullableInt("datetime_precision"),
            };

            Result.Add(table);
        }
예제 #26
0
        private void cTrick_CheckStateChanged(object sender, EventArgs e)
        {
            var checkbox = (CheckBox)sender;
            var tricks   = (HashSet <string>)checkbox.Tag;

            if (checkbox.Checked)
            {
                foreach (var trick in tricks)
                {
                    Result.Add(trick);
                }
            }
            else
            {
                foreach (var trick in tricks)
                {
                    Result.Remove(trick);
                }
            }

            CalculateCategoryCheckboxes();
        }
예제 #27
0
        protected override void Mapper(IDataRecord record)
        {
            var schema     = record.GetString("SchemaOwner");
            var tableName  = record.GetString("TableName");
            var columnName = record.GetString("ColumnName");
            var column     = new DatabaseColumn
            {
                SchemaOwner        = schema,
                TableName          = tableName,
                Name               = columnName,
                IdentityDefinition = new DatabaseColumnIdentity(),
            };
            var options = record.GetString("IDENTITY_OPTIONS");

            ParseIdentityOptions(column.IdentityDefinition, options);
            if (string.Equals(record.GetString("GENERATION_TYPE"), "BY DEFAULT", StringComparison.OrdinalIgnoreCase))
            {
                column.IdentityDefinition.IdentityByDefault = true;
            }

            Result.Add(column);
        }
예제 #28
0
        protected override void doWork(byte[] source)
        {
            var data = source.AsSpan();

            int         pos           = 0;
            List <bool> tmp           = new List <bool>();
            bool        isDetectEmpty = false;

            while (pos < data.Length)
            {
                var result = detectBit(source.AsSpan(pos), isDetectEmpty);
                if (result.isSuccess && !isDetectEmpty)
                {
                    tmp.Add(result.code.Value);
                }
                pos += result.length;
            }
            if (tmp.Count > 0)
            {
                Result.Add(tmp);
            }
        }
예제 #29
0
        public IList <DatabaseColumn> Execute(IConnectionAdapter connectionAdapter)
        {
            var views = new Views(_viewName).Execute(connectionAdapter);

            foreach (var view in views)
            {
                var viewName = view.Name;
                using (var cmd = connectionAdapter.DbConnection.CreateCommand())
                {
                    cmd.CommandText = string.Format(PragmaSql, viewName);
                    int ordinal = 0;
                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var colName = dr.GetString("name");
                            var col     = new DatabaseColumn
                            {
                                TableName   = viewName,
                                SchemaOwner = "",
                                Name        = colName,
                                Ordinal     = ordinal,
                                //type will be like "nvarchar(32)".
                                //Lengths /precisions could be parsed out (nb remember this is Sqlite)
                                DbDataType   = dr.GetString("type"),
                                Nullable     = dr.GetBoolean("notnull"),
                                DefaultValue = dr.GetString("dflt_value"),
                                IsPrimaryKey = dr.GetBoolean("pk"),
                            };
                            Result.Add(col);
                            ordinal++;
                        }
                    }
                }
            }

            return(Result);
        }
예제 #30
0
        public IList <DatabaseConstraint> Execute(IConnectionAdapter connectionAdapter)
        {
            var tables = new Tables(_tableName).Execute(connectionAdapter);

            foreach (var table in tables)
            {
                var tableName = table.Name;
                using (var cmd = connectionAdapter.DbConnection.CreateCommand())
                {
                    cmd.CommandText = string.Format(PragmaSql, tableName);
                    using (var dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            var refersToTable = dr.GetString("table");
                            var con           =
                                Result.FirstOrDefault(x => x.TableName == tableName && x.RefersToTable == refersToTable);
                            if (con == null)
                            {
                                con = new DatabaseConstraint
                                {
                                    TableName      = tableName,
                                    SchemaOwner    = "",
                                    ConstraintType = ConstraintType.ForeignKey,
                                    RefersToTable  = refersToTable,
                                    UpdateRule     = dr.GetString("on_update"),
                                    DeleteRule     = dr.GetString("on_delete"),
                                };
                                Result.Add(con);
                            }
                            con.Columns.Add(dr.GetString("from"));
                        }
                    }
                }
            }

            return(Result);
        }
예제 #31
0
파일: Natori.cs 프로젝트: grtwall/TJAStudio
 private void Init(string input)
 {
     foreach (var item in Regex.Split(input, "\r\n"))
     {
         Result.Add(new NatoriInfo(item));
     }
     foreach (var item in Result)
     {
         if (Regex.Replace(item.Text, " *//.*", "").Contains(":"))
         {
             item.Type = LineType.Header;
         }
         else if (Regex.Replace(item.Text, " *//.*", "").StartsWith("#"))
         {
             item.Type = LineType.Command;
         }
         else
         {
             item.Type = LineType.Text;
         }
     }
     foreach (var item in Result)
     {
         if (item.Type == LineType.Text)
         {
             item.Amount = Regex.Replace(item.Text, " *//.*", "").Trim().Length;
             var notesCount = 0;
             foreach (var measure in Regex.Replace(item.Text, " *//.*", "").Trim())
             {
                 if (Regex.IsMatch(measure.ToString(), "[1234]"))
                 {
                     notesCount++;
                 }
             }
             item.NotesAmount = notesCount;
         }
     }
 }
예제 #32
0
        protected override void Mapper(IDataRecord record)
        {
            //overflow protection
            var length    = record.GetNullableLong("CHARACTER_MAXIMUM_LENGTH");
            var maxLength = (length > int.MaxValue) ? int.MaxValue : (int?)length;
            var col       = new DatabaseColumn
            {
                SchemaOwner  = record.GetString("TABLE_SCHEMA"),
                TableName    = record.GetString("TABLE_NAME"),
                Name         = record.GetString("COLUMN_NAME"),
                Ordinal      = record.GetInt("ORDINAL_POSITION"),
                Nullable     = record.GetBoolean("IS_NULLABLE"),
                DefaultValue = record.GetString("COLUMN_DEFAULT"),
                DbDataType   = record.GetString("COLUMN_TYPE"),
                Length       = maxLength,
                Precision    = record.GetNullableInt("NUMERIC_PRECISION"),
                Scale        = record.GetNullableInt("NUMERIC_SCALE"),
                //DateTimePrecision = record.GetNullableInt("DATETIME_PRECISION"), //added in MySQL 5.6.4.
                Description = record.GetString("COLUMN_COMMENT"),
            };

            Result.Add(col);
        }
예제 #33
0
        public Result ProcessCall()
        {
            Expression e = ParseExpression ();

            e.Resolve (null);

            ColumnType type = e.ColumnType;
            object o = e.GetValue ();
            Result r = new Result (1);

            r.Table [0] = "";
            r.Type [0] = type;
            r.Label [0] = "";
            r.Name [0] = "";

            object[] row = new object[1];

            row [0] = o;

            r.Add (row);

            return r;
        }
예제 #34
0
        // [email protected] end changes from 1.50
        // [email protected] begin changes from 1.50
        public Result GetResult(int start, int cnt, Channel cChannel)
        {
            int maxrows=start+cnt;  //<-new, cut definitly
            // [email protected] begin changes from 1.50
            Resolve();
            CheckResolved();

            if (sUnion != null && sUnion.iResultLen != iResultLen)
            {
                throw TracingHelper.Error(TracingHelper.COLUMN_COUNT_DOES_NOT_MATCH);
            }

            int     len = eColumn.Length;
            Result  r = new Result(len);
            bool aggregated = false;
            bool grouped = false;

            for (int i = 0; i < len; i++)
            {
                Expression e = eColumn[i];

                r.Type[i] = e.ColumnType;

                if (e.IsAggregate)
                {
                    aggregated = true;
                }
            }

            object[] agg = null;

            if (aggregated)
            {
                agg = new object[len];
            }

            if (iGroupLen > 0)
            {    // has been set in Parser
                grouped = true;
            }

            bool simple_maxrows = false;

            if (maxrows != 0 && grouped == false && sUnion == null && iOrderLen == 0)
            {
                simple_maxrows = true;
            }

            int     count = 0;
            int     filter = tFilter.Length;
            bool[] first = new bool[filter];
            int     level = 0;

            while (level >= 0)
            {
                bool     found = false;

                if( filter > 0 )
                {
                    TableFilter t = tFilter[level];

                    if (!first[level])
                    {
                        found = t.FindFirst();
                        first[level] = found;
                    }
                    else
                    {
                        found = t.Next();
                        first[level] = found;
                    }

                }

                if (!found)
                {
                    level--;

                    if( !OnlyVars )
                        continue;
                }

                if (level < filter - 1)
                {
                    level++;

                    continue;
                }

                if (eCondition == null || eCondition.Test())
                {
                    object[] row = new object[len];

                    for (int i = 0; i < len; i++)
                    {
                        row[i] = eColumn[i].GetValue();

                        if( cChannel != null && eColumn[i].IsVarAssign )
                        {
                            cChannel.SetDeclareValue( eColumn[i].Arg.ColumnName, row[i] );
                        }
                    }

                    count++;

                    if (aggregated && !grouped)
                    {
                        UpdateAggregateRow(agg, row, len);
                    }
                    else
                    {
                        r.Add(row);

                        if (simple_maxrows && count >= maxrows)
                        {
                            break;
                        }
                    }
                }
            }

            if ( aggregated && !grouped )
            {
                AddAggregateRow(r, agg, len, count);
            }
            else if ( grouped )
            {
                int[] order = new int[iGroupLen];
                int[] way = new int[iGroupLen];

                for (int i = iResultLen, j = 0; j < iGroupLen; i++, j++)
                {
                    order[j] = i;
                    way[j] = 1;
                }

                r = SortResult(r, order, way);

                Record n = r.Root;
                Result x = new Result(len);

                for (int i = 0; i < len; i++)
                {
                    x.Type[i] = r.Type[i];
                }

                do
                {
                    object[] row = new object[len];

                    count = 0;

                    bool newgroup = false;

                    while (n != null && newgroup == false)
                    {
                        count++;

                        for (int i = 0; i < iGroupLen; i++)
                        {
                            if (n.Next == null)
                            {
                                newgroup = true;
                            }
                            else if (Column.Compare(n.Data[i], n.Next.Data[i], r.Type[i]) != 0)
                            {
                                // can't use .Equals because 'null' is also one group
                                newgroup = true;
                            }
                        }

                        UpdateAggregateRow(row, n.Data, len);

                        n = n.Next;
                    }

                    AddAggregateRow(x, row, len, count);

                } while (n != null);

                r = x;
            }

            if (iOrderLen != 0)
            {
                int[] order = new int[iOrderLen];
                int[] way = new int[iOrderLen];

                for (int i = iResultLen, j = 0; j < iOrderLen; i++, j++)
                {
                    order[j] = i;
                    way[j] = eColumn[i].IsDescending ? -1 : 1;
                }

                r = SortResult(r, order, way);
            }

            // the result maybe is bigger (due to group and order by)
            // but don't tell this anybody else
            r.SetColumnCount( iResultLen );

            if (bDistinct)
            {
                r = RemoveDuplicates(r);
            }

            for (int i = 0; i < iResultLen; i++)
            {
                Expression e = eColumn[i];

                r.Label[i] = e.Alias;
                r.Table[i] = e.TableName;
                r.Name[i] = e.ColumnName;
            }

            if (sUnion != null)
            {
                Result x = sUnion.GetResult(0, cChannel);

                if (UnionType == SelectType.Union)
                {
                    r.Append(x);

                    r = RemoveDuplicates(r);
                }
                else if (UnionType == SelectType.UnionAll)
                {
                    r.Append(x);
                }
                else if (UnionType == SelectType.Intersect)
                {
                    r = RemoveDuplicates(r);
                    x = RemoveDuplicates(x);
                    r = RemoveDifferent(r, x);
                }
                else if (UnionType == SelectType.Except)
                {
                    r = RemoveDuplicates(r);
                    x = RemoveDuplicates(x);
                    r = RemoveSecond(r, x);
                }
            }

            if (maxrows > 0 &&!simple_maxrows)
            {
                TrimResult(r, maxrows);
            }

            // [email protected] begin changes from 1.50
            if (start > 0)
            {	//then cut the first 'start' elements
                TrimResultFront( r, start );
            }
            // [email protected] end changes from 1.50

            return r;
        }
예제 #35
0
        private void AddRow(Result result, string sql)
        {
            string[] s = new string[1];

            s[0] = sql;

            result.Add(s);
        }
예제 #36
0
        public Result ProcessUpdate()
        {
            string token = tTokenizer.GetString ();

            cChannel.CheckReadWrite ();
            cChannel.Check (token, AccessType.Update);

            Table table = dDatabase.GetTable (token, cChannel);
            TableFilter filter = new TableFilter (table, null, false);

            tTokenizer.GetThis ("SET");

            ArrayList vColumn = new ArrayList ();
            ArrayList eColumn = new ArrayList ();
            int len = 0;

            token = null;

            do {
                len++;

                int i = table.GetColumnNumber (tTokenizer.GetString ());

                vColumn.Add (i);
                tTokenizer.GetThis ("=");

                Expression e = ParseExpression ();

                e.Resolve (filter);
                eColumn.Add (e);

                token = tTokenizer.GetString ();
            } while (token.Equals (","));

            Expression eCondition = null;

            if (token.Equals ("WHERE")) {
                eCondition = ParseExpression ();

                eCondition.Resolve (filter);
                filter.SetCondition (eCondition);
            } else {
                tTokenizer.Back ();
            }

            // do the update
            Expression[] exp = new Expression[len];

            eColumn.CopyTo (exp);

            int[] col = new int[len];
            ColumnType[] type = new ColumnType[len];

            for (int i = 0; i < len; i++) {
                col [i] = ((int)vColumn [i]);
                type [i] = table.GetType (col [i]);
            }

            int count = 0;

            if (filter.FindFirst ()) {
                Result del = new Result ();    // don't need column count and so on
                Result ins = new Result ();
                int size = table.ColumnCount;

                do {
                    if (eCondition == null || eCondition.Test ()) {
                        object[] nd = filter.oCurrentData;

                        del.Add (nd);

                        object[] ni = table.NewRow;

                        for (int i = 0; i < size; i++) {
                            ni [i] = nd [i];
                        }

                        for (int i = 0; i < len; i++) {
                            ni [col [i]] = exp [i].GetValue (type [i]);
                        }

                        ins.Add (ni);
                    }
                } while (filter.Next ());

                lock (cChannel.SyncRoot) {

                    cChannel.BeginNestedTransaction ();

                    try {
                        Record nd = del.Root;

                        while (nd != null) {
                            table.DeleteNoCheck (nd.Data, cChannel);

                            nd = nd.Next;
                        }

                        Record ni = ins.Root;

                        while (ni != null) {
                            table.InsertNoCheck (ni.Data, cChannel);

                            ni = ni.Next;
                            count++;
                        }

                        table.CheckUpdate (col, del, ins);

                        ni = ins.Root;

                        while (ni != null) {
                            ni = ni.Next;
                        }

                        cChannel.EndNestedTransaction (false);
                    } catch (Exception e) {

                        // update failed (violation of primary key / referential integrity)
                        cChannel.EndNestedTransaction (true);

                        throw e;
                    }
                }
            }

            Result r = new Result ();

            r.SetUpdateCount (count);

            return r;
        }
예제 #37
0
        public Result ProcessDelete()
        {
            tTokenizer.GetThis ("FROM");

            string token = tTokenizer.GetString ();

            cChannel.CheckReadWrite ();
            cChannel.Check (token, AccessType.Delete);

            Table table = dDatabase.GetTable (token, cChannel);
            TableFilter filter = new TableFilter (table, null, false);

            token = tTokenizer.GetString ();

            Expression eCondition = null;

            if (token.Equals ("WHERE")) {
                eCondition = ParseExpression ();

                eCondition.Resolve (filter);
                filter.SetCondition (eCondition);
            } else {
                tTokenizer.Back ();
            }

            int count = 0;

            if (filter.FindFirst ()) {
                Result del = new Result ();    // don't need column count and so on

                do {
                    if (eCondition == null || eCondition.Test ()) {
                        del.Add (filter.oCurrentData);
                    }
                } while (filter.Next ());

                Record n = del.Root;

                while (n != null) {
                    table.Delete (n.Data, cChannel);

                    count++;
                    n = n.Next;
                }
            }

            Result r = new Result ();

            r.SetUpdateCount (count);

            return r;
        }
예제 #38
0
        private void AddAggregateRow(Result result, object[] row, int len, int count)
        {
            for (int i = 0; i < len; i++)
            {
                ExpressionType t = eColumn[i].Type;

                if (t == ExpressionType.Average)
                {
                    row[i] = Column.Avg(row[i], eColumn[i].ColumnType, count);
                }
                else if (t == ExpressionType.Count)
                {
                    // this fixes the problem with count(*) on a empty table
                    if (row[i] == null)
                    {
                        row[i] = 0;
                    }
                }
            }

            result.Add(row);
        }
예제 #39
0
        private Result ProcessShow(Tokenizer tokenizer, Channel channel)
        {
            Result r = new Result(1);

            string sToken = tokenizer.GetString();

            if (sToken.Equals("TABLES"))
            {
                r.Table[0] = "SYSTEM_TABLES";
                r.Label[0] = "TABLE_NAME";
                System.Collections.ArrayList al = channel.Database.Tables;
                //r.Label[0] = "TABLE";
                r.Type[0] = ColumnType.VarChar;
                for(int x=0;x<al.Count;x++)
                {
                    Table table = (Table)al[x];
                    string[] tablename = new string [1];
                    tablename[0]=table.Name;
                    r.Add(tablename);
                }
                channel.Commit();
            }
            else if (sToken.Equals("DATABASES"))
            {
                r.Table[0] = "SYSTEM_DATABASES";
                r.Label[0] = "DATABASE";
                r.Type[0] = ColumnType.VarChar;

                System.IO.DirectoryInfo di = new
                    System.IO.DirectoryInfo(System.IO.Directory.GetCurrentDirectory());
                System.IO.FileInfo[] rgFiles = di.GetFiles("*.data");
                foreach(System.IO.FileInfo fi in rgFiles)
                {

                    string[] databaseName = new string [1];
                    databaseName[0]=fi.Name.ToUpper().Replace(".DATA","");
                    r.Add(databaseName);
                }

                channel.Commit();
            }
            else if (sToken.Equals("ALIAS"))
            {
                r = new Result(2);
                r.Label[0]="NAME";
                r.Type[0] = ColumnType.VarChar;
                r.Label[1]="LIBRARY";
                r.Type[1] = ColumnType.VarChar;

                foreach( DictionaryEntry entry in _alias )
                {
                    string[] alias = new string [2];
                    alias[0] = entry.Key.ToString();
                    alias[1] = entry.Value.ToString();
                    r.Add(alias);
                }

                channel.Commit();
            }
            else if (sToken.Equals("PARAMETERS"))
            {
                string alias = tokenizer.GetString().ToUpper();

                if( !_alias.ContainsKey( alias ) )
                    throw TracingHelper.Error(TracingHelper.UNKNOWN_FUNCTION, alias);

                string fqn = _alias[alias].ToString();

                Function f = new Function( fqn, channel );

                System.Reflection.MethodInfo mi = f.GetMethodInfo( fqn );

                r = new Result(4);
                r.Label[0]="ALIAS";
                r.Type[0] = ColumnType.VarChar;
                r.Label[1]="PARAMETER";
                r.Type[1] = ColumnType.VarChar;
                r.Label[2]="TYPE";
                r.Type[2] = ColumnType.VarChar;
                r.Label[3]="POSITION";
                r.Type[3] = ColumnType.Integer;

                System.Reflection.ParameterInfo[] parms = mi.GetParameters();

                int rt = 0;

                if( mi.ReturnType != null )
                {
                    object[] p = new object[4];
                    p[0] = alias;
                    p[1] = "RETURN_VALUE";
                    p[2] = Column.GetColumnTypeString( Function.GetDataType( mi.ReturnType ) );
                    p[3] = 0;
                    r.Add(p);
                    rt = 1;
                }

                foreach( System.Reflection.ParameterInfo pi in parms )
                {
                    object[] p = new object[4];
                    p[0] = alias;
                    p[1] = pi.Name;
                    p[2] = Column.GetColumnTypeString( Function.GetDataType( pi.ParameterType ) );
                    p[3] = (pi.Position + rt);
                    r.Add(p);
                }

                channel.Commit();
            }
            else if (sToken.Equals("COLUMNS"))
            {
                string t = tokenizer.GetString().ToUpper();
                Table theTable = null;

                foreach( Table table in channel.Database.Tables )
                {
                    if( table.Name.ToUpper() == t )
                    {
                        theTable = table;
                        break;
                    }
                }

                if( theTable == null )
                    throw TracingHelper.Error(TracingHelper.TABLE_NOT_FOUND, t);

                r = new Result(7);
                r.Label[0]="TABLE";
                r.Type[0] = ColumnType.VarChar;
                r.Label[1]="COLUMN";
                r.Type[1] = ColumnType.VarChar;
                r.Label[2]="NATIVETYPE";
                r.Type[2] = ColumnType.VarChar;
                r.Label[3]="DBTYPE";
                r.Type[3] = ColumnType.Integer;
                r.Label[4]="POSITION";
                r.Type[4] = ColumnType.Integer;
                r.Label[5]="NULLABLE";
                r.Type[5] = ColumnType.Bit;
                r.Label[6]="IDENTITY";
                r.Type[6] = ColumnType.Bit;

                for(int ix=0;ix<theTable.ColumnCount;ix++)
                {
                    Column col = theTable.GetColumn(ix);
                    object[] coldata = new object[7];
                    coldata[0] = theTable.Name;
                    coldata[1] = col.Name;
                    coldata[2] = Column.GetColumnTypeString( col.ColumnType );
                    coldata[3] = Column.GetDbType( col.ColumnType );
                    coldata[4] = ix;
                    coldata[5] = col.IsNullable;
                    coldata[6] = col.IsIdentity;
                    r.Add(coldata);
                }
                channel.Commit();
            }
            else
            {
                throw TracingHelper.Error(TracingHelper.UnexpectedToken, sToken);
            }

            return r;
        }