Beispiel #1
0
        private string GetObjects(IEnumerable <Column> columns, IEnumerable <string> values)
        {
            var names   = Columns.Select(c => c.Name).ToList();
            var objects = columns.Aggregate(new StringBuilder(),
                                            (sb, c) => sb.Append($"\"{c.Name}\": {GetValue(c.Type, values.ElementAt(c.Index))}{(c.Name == names.Last() ? "" : $"\n\t\t")}"));

            return(objects.ToString());
        }
Beispiel #2
0
        /// <summary>
        /// 创建实例
        /// </summary>
        /// <param name="propertyInfo">属性值类型</param>
        /// <param name="instance">将设置其属性值的对象</param>
        public static object GetValue(FieldInfo propertyInfo, object instance)
        {
            // 缓存
            var key = propertyInfo;

            if (DicFieldGetValueList.ContainsKey(key))
            {
                return(DicFieldGetValueList[key](instance));
            }

            return(GetValue(propertyInfo)(instance));
        }
Beispiel #3
0
        public GetSetGeneric(string name)
        {
            Name = name;
            MethodInfo getMethod;
            MethodInfo setMethod = null;
            var        t         = typeof(T);
            //var p = t.GetProperty(name); JSC
            var p = t.GetRuntimeProperty(name);

            if (p == null)
            {
                // FieldInfo = typeof(T).GetField(Name); JSC
                FieldInfo      = typeof(T).GetRuntimeField(Name);
                _get           = new GetValue(GetFieldValue);
                _set           = new SetValue(SetFieldValue);
                CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;
                return;
            }
            Info           = p;
            CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
            getMethod      = p.GetMethod;
            setMethod      = p.SetMethod;
            _get           = (GetValue)getMethod.CreateDelegate(typeof(GetValue));
            if (setMethod != null)
            {
                _set = (SetValue)setMethod.CreateDelegate(typeof(SetValue));
            }
        }
 public object Any(GetValue request)
 {
     return(new GetValueResponse
     {
         Value = Redis.GetValue(request.Key)
     });
 }
 /// <summary>
 /// Returns the formated string to pass to the speech engine
 /// </summary>
 /// <returns></returns>
 public string SayText()
 {
     return
         (Text.Replace("{warning}", Warning.ToString("0.##"))
          .Replace("{value}", GetValue.ToString("0.##"))
          .Replace("{name}", Item.Name));
 }
            internal IEnumerable <string> Values(XElement row, GetValue getValue = null)
            {
                if (row != null)
                {
                    int col = 0;
                    foreach (var cell in row.Elements(xmlnsC))
                    {
                        var nextColumn = CellAddress.ColumnOffset(cell);
                        while (nextColumn > col)
                        {
                            yield return(null);

                            col += 1;
                        }
                        if (getValue == null)
                        {
                            yield return(Value(cell));
                        }
                        else
                        {
                            yield return(getValue(cell, col));
                        }
                        col += 1;
                    }
                }
            }
Beispiel #7
0
    public void LoadData(int Aid)
    {
        DataBase db  = new DataBase();
        string   sql = "";

        sql = "Select * from AddressList where id= " + Aid;
        DataRow dr = db.GetDataRow(sql);

        if (dr != null)
        {
            this._ID             = GetValue.ValidataDataRow_I(dr, "id");
            this._userID         = GetValue.ValidateDataRow_S(dr, "userId");
            this._frdQQ          = GetValue.ValidateDataRow_S(dr, "frdQQ");
            this._frdPhone       = GetValue.ValidateDataRow_S(dr, "frdPhone");
            this._frdName        = GetValue.ValidateDataRow_S(dr, "frdName");
            this._frdMobilePhone = GetValue.ValidateDataRow_S(dr, "frdMobilePhone");
            this._frdImageUrl    = GetValue.ValidateDataRow_S(dr, "frdImageUrl");
            this._frdEmail       = GetValue.ValidateDataRow_S(dr, "frdEmail");
            this._frdAddress     = GetValue.ValidateDataRow_S(dr, "frdAddress");
            this.CreateDate      = GetValue.ValidateDataRow_T(dr, "CreateDate");
            this._general        = GetValue.ValidateDataRow_S(dr, "General");

            this._exist = true;
        }
        else
        {
            this._exist = false;
        }
    }
Beispiel #8
0
 public TDPoint(object obj, PropertyInfo info)
 {
     _get = Delegate.CreateDelegate(typeof(GetValue), obj, info.GetGetMethod()) as GetValue;
     _set = Delegate.CreateDelegate(typeof(SetValue), obj, info.GetSetMethod()) as SetValue;
     x    = new TDInt(GetX, SetX);
     y    = new TDInt(GetY, SetY);
 }
Beispiel #9
0
 public static List <EventActionData> GetActionBlockFromNode(Node node)
 {
     if (node is NodeSetValue)
     {
         var source = node as NodeSetValue;
         var action = new SetValue();
         action.setType = source.setType;
         action.target  = new MemberData(source.target);
         action.value   = new MemberData(source.value);
         return(new List <EventActionData>()
         {
             action
         });
     }
     else if (node is MultipurposeNode)
     {
         var source = node as MultipurposeNode;
         if (source.IsFlowNode())
         {
             var action = new GetValue();
             action.target = new MultipurposeMember(source.target);
             return(new List <EventActionData>()
             {
                 action
             });
         }
     }
     return(new List <EventActionData>());
 }
        private void DBDetect()
        {
            GetValue gv = ValueChange;

            //check database and login
            this.Invoke(gv, 10);
            if (CheckDB() <= 0)
            {
                this.Invoke(gv, 30);
                Thread.Sleep(200);
                sb.Clear();
                sb.Append("false");
                this.Invoke(gv, 100);
                return;
            }
            this.Invoke(gv, 30);
            Thread.Sleep(200);
            if (CheckLogin() <= 0)
            {
                this.Invoke(gv, 50);
                Thread.Sleep(200);
                sb.Clear();
                sb.Append("false");
                this.Invoke(gv, 100);

                return;
            }
            sb.Clear();
            sb.Append("true");
            this.Invoke(gv, 80);
            Thread.Sleep(200);

            this.Invoke(gv, 100);
        }
        public virtual bool Match(Context env, Concept check, GetValue propfunc, params object[] args)
        {
            // Apply propfunc now, and save for later
            object value   = propfunc(check, args);
            bool   matched = false;

            if (value is Concept)
            {
                matched = IsMatch((Concept)value);
            }
            else if (value is IParsedPhrase)
            {
                matched = IsMatch((IParsedPhrase)value);
            }

            if (matched)
            {
                object propogate = new ThreeTuple <GetValue, object, object[]>(propfunc, check, args);

                Propogate(env, propogate, 1.0);
                return(true);
            }

            return(false);
        }
Beispiel #12
0
    static void Main(string[] args)
    {
        IGetValue <string> GetString = new GetValue <string>("Hello");
        IGetValue <int>    GetInt    = new GetValue <int>(21);

        if (GetString is IGetValue)
        {
            Console.WriteLine("GetValue<string> is an IGetValue");
        }
        else
        {
            Console.WriteLine("GetValue<string> is not an IGetValue");
        }

        if (GetInt is IGetValue)
        {
            Console.WriteLine("GetValue<int> is an IGetValue");
        }
        else
        {
            Console.WriteLine("GetValue<int> is not an IGetValue");
        }

        Console.ReadKey();
    }
Beispiel #13
0
 public List <Customers> Get_List_Customers(GetValue getValue)
 {
     using (var _db = new GmpContext(getValue.ConStr))
     {
         return(_db.Customers.Where(x => x.Deleted == false /*&& x.CompanyRecId == getValue.CompanyId */ && x.IsArsiv == false).ToList());
     }
 }
Beispiel #14
0
        static void Main(string[] args)
        {
            TaskManager taskManager = new TaskManager();
            List <Task> tasksList   = new List <Task>();

            tasksList = taskManager.AddNewTasks(tasksList);

            Display(tasksList);
            tasksList = taskManager.SortListTasks(tasksList);
            Console.WriteLine("Sort List by Priority & Difficulty:");
            Display(tasksList);
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

            //1 - how much time is needed to complete all tasks
            taskManager.AllTime(tasksList);

            //2 - list of tasks of a given priority
            taskManager.DisplayConsoleMessage <Priority>($"Enter {typeof(Priority).Name.ToLower()} for build list (");

            Task validation = new Task();

            validation.Priority = GetValue.ValidationValue <Priority>();

            new FilterTaskByPriority(validation.Priority, tasksList);

            //3 - what tasks can be done in N days based on priority
            taskManager.TasksCanBeDone(tasksList);

            //4 - print
            new PrintTaskPage();
            Console.ReadKey();
        }
Beispiel #15
0
        /// <summary>
        /// Provide as much information about the input stream as we can,  size
        /// and position
        /// </summary>
        /// <param name="reader">reader we are analysing</param>
        public StreamInfoProvider(TextReader reader)
        {
            if (reader is StreamReader)
            {
                var stream = ((StreamReader)reader).BaseStream;
                if (stream.CanSeek)
                {
                    mLength = stream.Length;
                }
                // Uses the buffer position
                mPositionCalculator = () => stream.Position;
            }
            else if (reader is InternalStreamReader)
            {
                var reader2 = ((InternalStreamReader)reader);
                var stream  = reader2.BaseStream;

                if (stream.CanSeek)
                {
                    mLength = stream.Length;
                }
                // Real Position
                mPositionCalculator = () => reader2.Position;
            }
            else if (reader is InternalStringReader)
            {
                var stream = (InternalStringReader)reader;
                mLength             = stream.Length;
                mPositionCalculator = () => stream.Position;
            }
        }
Beispiel #16
0
 public Customer()
 {
     FirstName  = GetValue.ReadValueFromConsole("Enter First Name: ");
     LastName   = GetValue.ReadValueFromConsole("Enter Last Name: ");
     CustomerID = Guid.NewGuid();
     Phone      = GetValue.ReadValueFromConsole($"Enter phone: ", isPhone: true);
 }
Beispiel #17
0
        public static Instruction Create(string method, int argCount, MethodInfo mi)
        {
            switch (method)
            {
            case "get_HasValue": return(s_hasValue ?? (s_hasValue = new HasValue()));

            case "get_Value": return(s_value ?? (s_value = new GetValue()));

            case "Equals": return(s_equals ?? (s_equals = new EqualsClass()));

            case "GetHashCode": return(s_getHashCode ?? (s_getHashCode = new GetHashCodeClass()));

            case "GetValueOrDefault":
                if (argCount == 0)
                {
                    return(new GetValueOrDefault(mi));
                }
                else
                {
                    return(s_getValueOrDefault1 ?? (s_getValueOrDefault1 = new GetValueOrDefault1()));
                }

            case "ToString": return(s_toString ?? (s_toString = new ToStringClass()));

            default:
                // System.Nullable doesn't have other instance methods
                throw ContractUtils.Unreachable;
            }
        }
        /// <summary>
        /// Provide as much information about the input stream as we can,  size
        /// and position
        /// </summary>
        /// <param name="reader">reader we are analysing</param>
        public StreamInfoProvider(TextReader reader)
        {
            if (reader is StreamReader)
            {
                var stream = ((StreamReader)reader).BaseStream;
                mLength = stream.Length;
                // Uses the buffer position
                mPositionCalculator = () => stream.Position;
            }
            else if (reader is InternalStreamReader)
            {
                var reader2 = ((InternalStreamReader)reader);
                var stream = reader2.BaseStream;

                mLength = stream.Length;
                // Real Position
                mPositionCalculator = () => reader2.Position;
            }
            else if (reader is InternalStringReader)
            {
                var stream = (InternalStringReader)reader;
                mLength = stream.Length;
                mPositionCalculator = () => stream.Position;
            }
        }
Beispiel #19
0
        public ActionResult Older()
        {
            if (Session["Name"] == null)
            {
                return(Redirect("/Users/Login"));
            }
            int groupid = Convert.ToInt16(Session["GroupId"]);

            if (!GetValue.PerThree(groupid))
            {
                return(Redirect("/Backstage/Ero"));
            }
            string search  = Request["Search"];
            var    tagList = from ta in context.Tags
                             select ta;
            // jycsb什么他妈玩意儿,这里直接用LINQ只选出6条不就结了吗
            var clickList = from c in context.Postses
                            orderby c.Click descending
                            select c;
            // jycsb什么他妈玩意儿,这里直接用LINQ只选出6条不就结了吗
            var bydatePosts = from b in context.Postses
                              orderby b.CreateDate descending
                              select b;
            var polist = from po in context.Postses
                         where (po.Title.Contains(search)) || (po.Outline.Contains(search)) || (po.Content.Contains(search))
                         select po;

            ViewData["search"] = search;
            ViewBag.tag        = tagList.Select(p => p.Name).Distinct().Take(20).ToList();
            ViewBag.sellist    = clickList.Take(6).ToList();
            ViewBag.newsposts  = bydatePosts.Take(6).ToList();
            ViewBag.polist     = polist.ToList();
            return(View());
        }
Beispiel #20
0
        public ActionResult Single(Reply n, int id)
        {
            if (Session["Name"] == null)
            {
                return(Redirect("/Users/Login"));
            }
            int groupid = Convert.ToInt16(Session["GroupId"]);

            if (!GetValue.PerTwo(groupid))
            {
                return(Redirect("/Backstage/Ero"));
            }

            var reply = new Reply
            {
                Name         = n.Name,
                Email        = n.Email,
                ReplyContent = n.ReplyContent,
                CreateDate   = DateTime.Now,
                SecondReply  = n.SecondReply == 0 ? 0 : n.SecondReply,
                PostsId      = id
            };

            context.Replies.Add(reply);
            context.SaveChanges();
            return(Redirect("/Home/Single/" + id));
        }
Beispiel #21
0
 public Customers Get_Customers(GetValue getValue)
 {
     using (var _db = new GmpContext(getValue.ConStr))
     {
         return(_db.Customers.FirstOrDefault(x => x.RecId == getValue.Id));
     }
 }
        public GetSetGeneric(string name)
        {
            Name = name;
            var t = typeof(T);
            var p = t.GetProperty(name);

            if (p == null)
            {
                FieldInfo      = typeof(T).GetField(Name);
                _get           = new GetValue(GetFieldValue);
                _set           = new SetValue(SetFieldValue);
                CollectionType = FieldInfo.FieldType.GetInterface("IEnumerable", true) != null;
                return;
            }
            Info           = p;
            CollectionType = Info.PropertyType.GetInterface("IEnumerable", true) != null;
            var getMethod = p.GetGetMethod();
            var setMethod = p.GetSetMethod();

            _get = (GetValue)Delegate.CreateDelegate(typeof(GetValue), getMethod);
            if (setMethod != null)
            {
                _set = (SetValue)Delegate.CreateDelegate(typeof(SetValue), setMethod);
            }
        }
Beispiel #23
0
        private void ProcessingSubMenu(int userСhoice, ColorGarland _colorGarland)
        {
            int lengthGarland = _colorGarland._garland.Length;

            switch (userСhoice)
            {
            case 1:
                //1. Set color to lamp in Colored Garland
                Console.Write("Please enter index of lamp in Colored Garlend: ");
                int indexLamp = GetValue.ReadValueConsoleToMenu(lengthGarland);
                indexLamp -= 1;
                Console.Write("\nPlease enter color: ");
                string newColor = GetValue.ReadValueConsoleColor();
                PrintTaskPage.StringToPrint       = null;//clear Print buffer
                _colorGarland._garland[indexLamp] = new ColorLamp(indexLamp, newColor);
                _colorGarland.ShowStatusGarland();
                break;

            case 2:
                //2. Get color of lamp in Colored Garland
                Console.Write("Please enter index of lamp in Colored Garlend: ");
                int indexLampGetColor = GetValue.ReadValueConsoleToMenu(lengthGarland);
                indexLampGetColor -= 1;
                string getColor = _colorGarland._garland[indexLampGetColor].ColorsLamp;
                Console.Write($"\nColor of lamp with index number {indexLampGetColor+1} is {getColor}\n");
                break;

            default:
            case 3:
                //3. Exit
                Environment.Exit(0);
                break;
            }
        }
Beispiel #24
0
        public ActionResult Index()
        {
            if (Session["Name"] == null)
            {
                return(Redirect("/Users/Login"));
            }

            int groupid = Convert.ToInt16(Session["GroupId"]);

            if (!GetValue.PerThree(groupid))
            {
                return(Redirect("/Backstage/Ero"));
            }
            int id        = Convert.ToInt16(Session["UserId"]);
            var PostsList = from po in context.Postses
                            where po.UserId == id
                            select po;

            if (GetValue.PerFour(groupid))
            {
                PostsList = from po in context.Postses
                            select po;
            }

            ViewBag.groupid = groupid;
            return(View(PostsList));
        }
Beispiel #25
0
        static void Main(string[] args)
        {
            //Console.WriteLine("het nummer is {0}", AddNumber(3));
            NumberChanger nc = new NumberChanger(AddNumber);

            Console.WriteLine("het nummer is {0}", nc(5));
            Console.WriteLine("het nummer is {0}", nc.Invoke(3));
            NumberChanger ncMult = new NumberChanger(Multinumber);

            Console.WriteLine("Het nummer is {0}", ncMult(2));
            NumberChanger ncDev = new NumberChanger(DevideNumber);

            Console.WriteLine("Het nummer is {0}", ncDev(2));
            NumberChanger ncSub = new NumberChanger(subtractNumber);

            Console.WriteLine("Het nummer is {0}", ncSub(3));

            TextChanger tc = new TextChanger(AddText);

            Console.WriteLine("De tekst is {0}", tc(" en ik wil een kopje koffie"));

            //instantiate the delegate
            //TextChanger word = DelegateMethod;
            //call the delegate
            //word("helloow");
            GetWord  word  = WordValue;
            GetValue value = NumberValue;

            value(5);
            value(ncSub(5));
            //value(nc(1));
            value(ncMult(5));
            word(message);
        }
Beispiel #26
0
        public ActionResult Edit(int id)
        {
            int groupid = Convert.ToInt16(Session["GroupId"]);

            if (!GetValue.PerThree(groupid))
            {
                return(Redirect("/Backstage/Ero"));
            }
            int userid = Convert.ToInt16(Session["UserId"]);
            var list   = (from po in context.Postses
                          where po.PostsId == id && po.UserId == userid
                          select po).FirstOrDefault();

            if (GetValue.PerFour(groupid))
            {
                list = (from po in context.Postses
                        where po.PostsId == id
                        select po).First();
            }

            if (list == null)
            {
                return(Content("滚!"));
            }


            var tagList = from ta in context.Tags
                          select ta;

            ViewBag.tag = tagList.Select(p => p.Name).Distinct().Take(20).ToList();
            return(View(list));
        }
Beispiel #27
0
 private Data.App.LoginUser GetUsers(GetValue _GetValue)
 {
     _user          = bl.AppService.GetLoginUser(_GetValue);
     __dl_Users_Gmp = _user;
     __dl_Users     = _user;
     return(_user);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateFieldGetAccessor"/> class
        /// for field get access via DynamicMethod.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="fieldName">Name of the field.</param>
        public DelegateFieldGetAccessor(Type targetObjectType, string fieldName)
        {
            // this.targetType = targetObjectType;
            _fieldName = fieldName;

            FieldInfo fieldInfo = targetObjectType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            // Make sure the field exists
            if (fieldInfo == null)
            {
                throw new NotSupportedException(
                          string.Format("Field \"{0}\" does not exist for type "
                                        + "{1}.", fieldName, targetObjectType));
            }
            _fieldType   = fieldInfo.FieldType;
            nullInternal = GetNullInternal(_fieldType);

            DynamicMethod dynamicMethodGet = new DynamicMethod("GetImplementation", typeof(object), new Type[] { typeof(object) }, GetType().Module, false);
            ILGenerator   ilgen            = dynamicMethodGet.GetILGenerator();

            // Emit the IL for get access.

            // We need a reference to the current instance (stored in local argument index 0)
            // so Ldfld can load from the correct instance (this one).
            ilgen.Emit(OpCodes.Ldarg_0);
            ilgen.Emit(OpCodes.Ldfld, fieldInfo);
            if (_fieldType.IsValueType)
            {
                // Now, we execute the box opcode, which pops the value of field 'x',
                // returning a reference to the filed value boxed as an object.
                ilgen.Emit(OpCodes.Box, fieldInfo.FieldType);
            }
            ilgen.Emit(OpCodes.Ret);
            _get = (GetValue)dynamicMethodGet.CreateDelegate(typeof(GetValue));
        }
Beispiel #29
0
        private void MouseMoveOverline(
            MouseEventArgs e,
            bool final,
            int initialValue,
            GetValue getValue,
            SetValue setValue,
            EventHandler changed)
        {
            using (Graphics graphics = CreateGraphics())
            {
                if (e.X < 0)
                {
                    MouseScrollLeft();
                }
                else if (e.X >= ClientSize.Width)
                {
                    MouseScrollRight();
                }

                SetScrollOffsetsForRendering(graphics);
                int oldValue = getValue();
                int newValue = (e.Y >= 0) && (e.Y < ClientSize.Height) ? ClientXToFrame(e.X) : initialValue;
                setValue(newValue);
                RedrawSamplePartial(FrameToClientX(oldValue), 1);
                RedrawSamplePartial(FrameToClientX(newValue), 1);
                Redraw(graphics, false /*drawSample*/); // update overline header
                if (changed != null)
                {
                    changed.Invoke(this, EventArgs.Empty);
                }
            }
        }
        public static string AggregateWhere <T>(List <T> Array, string IfMethod, string ValueMethod, char?split)
#endif
        {
            Type type = typeof(T);

            System.Reflection.PropertyInfo propertyValue = type.GetProperty(ValueMethod);
            System.Reflection.PropertyInfo propertyIf    = type.GetProperty(IfMethod);
            System.Reflection.MethodInfo   methodValue   = propertyValue.GetGetMethod();
            System.Reflection.MethodInfo   methodIf      = propertyIf.GetGetMethod();
            string stmp = string.Empty;

            foreach (T item in Array)
            {
                GetValue <string> getValue   = (GetValue <string>)Delegate.CreateDelegate(typeof(GetValue <string>), item, methodValue);
                GetValue <bool>   getBoolean = (GetValue <bool>)Delegate.CreateDelegate(typeof(GetValue <bool>), item, methodIf);

                if (getBoolean())
                {
                    if (split.HasValue && stmp.Length > 0)
                    {
                        stmp += split.Value;
                    }

                    stmp += getValue();
                }
            }
            return(stmp);
        }
Beispiel #31
0
        public Case(Notifier <T> notifier, string operation, T _targetValue, string subProp = null, bool wildcard = false)
        {
            bitOperator    = BitOperator.AND;
            this.operation = operation;
            //targetIsFunction = Reflect.isFunction(_targetValue);
            //if (targetIsFunction) _targetFunction = _targetValue;
            //else this._targetValue = _targetValue;
            this._targetValue = _targetValue;

            this.notifier = notifier;
            this.subProp  = subProp;

            if (operation == Operation.EQUAL)
            {
                if (wildcard)
                {
                    getValue = wildcardEqualTo;
                }
                else
                {
                    getValue = equalTo;
                }
            }
            else if (operation == Operation.NOT_EQUAL)
            {
                getValue = notEqualTo;
            }
            else if (operation == Operation.LESS_THAN_OR_EQUAL)
            {
                getValue = lessThanOrEqualTo;
            }
            else if (operation == Operation.LESS_THAN)
            {
                getValue = lessThan;
            }
            else if (operation == Operation.GREATER_THAN_OR_EQUAL)
            {
                getValue = greaterThanOrEqualTo;
            }
            else if (operation == Operation.GREATER_THAN)
            {
                getValue = greaterThan;
            }

            //super();
            notifier.Add((value) =>
            {
                //Console.WriteLine("value = " + value);
                check();
            });
            check();

            /*
             * notifier.add(() -> {
             *  check();
             * }, 1000);
             * check();
             */
        }
 /// <summary>
 /// Provide as much information about the output stream as we can,
 /// size and position
 /// </summary>
 /// <param name="writer">writer we are analysing</param>
 public StreamInfoProvider(TextWriter writer)
 {
     if (writer is StreamWriter)
     {
         var stream = ((StreamWriter)writer).BaseStream;
         mLength = stream.Length;
         mPositionCalculator = () => stream.Position;
     }
 }
        /// <summary>
        /// Provide as much information about the output stream as we can,
        /// size and position
        /// </summary>
        /// <param name="writer">writer we are analysing</param>
        public StreamInfoProvider(TextWriter writer)
        {
            var streamWriter = writer as StreamWriter;
            if (streamWriter == null)
                return;

            var stream = streamWriter.BaseStream;
            mLength = stream.Length;
            mPositionCalculator = () => stream.Position;
        }
 public StreamInfoProvider(TextReader reader)
 {
     if (reader is StreamReader)
     {
         var stream = ((StreamReader)reader).BaseStream;
         mLengthCalculator = () => stream.Length;
         mPositionCalculator = () => stream.Position;
     }
     else if (reader is InternalStringReader)
     {
         var stream = (InternalStringReader)reader;
         mLengthCalculator = () => stream.Length;
         mPositionCalculator = () => stream.Position;
     }
 }
        public virtual bool Match(Context env, Concept check, GetValue propfunc, params object[] args)
        {
            // Apply propfunc now, and save for later
            object value = propfunc(check, args);
            bool matched = false;
            if (value is Concept)
                matched = IsMatch((Concept) value);
            else if (value is IParsedPhrase)
                matched = IsMatch((IParsedPhrase) value);

            if (matched)
            {
                object propogate = new ThreeTuple<GetValue, object, object[]>(propfunc, check, args);

                Propogate(env, propogate, 1.0);
                return true;
            }

            return false;
        }
Beispiel #36
0
 //public override string[] GetStaticallyTypedPropertyNames()
 //{
 //    return new string[]{"Name", "Prop3", "DecimalCheck"};
 //}
 //public override void SetValue(string property, object value)
 //{
 //    switch (property)
 //    {
 //        case "Prop3":
 //            this.Prop3 = value is int ? (int)value : value != null ? Convert.ToInt32(value) : 0; break;
 //        case "Name":
 //            this.Name = value is string ? (string)value : value != null ? value.ToString() : String.Empty; break;
 //        case "DecimalCheck":
 //            this.DecimalCheck = value is decimal ? (decimal)value : value != null ? Convert.ToDecimal(value) : 0;break;
 //        default:
 //            break;
 //    }
 //}
 //if dynamic then you may need to handle those first
 //will need to know what are the regular properties
 public object this[string property]
 {
     get
     {
         if (Test.GetMethod == null)
         {
             Test.GetMethod = Compiler.GetHelper.Value<Test>();
         }
         if(Test.GetMethod !=null)
         {
             return GetMethod(this, property);
         }
         return null;
     }
     set
     {
         if (Test.SetMethod == null)
         {
             Test.SetMethod = Compiler.SetHelper.Value<Test>(this.GetType());
         }
         if (Test.SetMethod != null)
         {
             Test.SetMethod(this, property, value);
         }
         //var properties = this.GetStaticallyTypedPropertyNames();
         //if (properties != null && properties.FirstOrDefault(p => p == property) != null)
         //{
         //    this.SetValue(property, value);
         //}
         //else
         //{
         //    dictionary[property] = value;
         //}
     }
 }
Beispiel #37
0
 public Token(string name, PrepareValue prepare, GetValue getvalue)
 {
     _name = name;
     _prepare = prepare;
     _getvalue = getvalue;
 }
Beispiel #38
0
 public TokensSet Add(string name, GetValue value)
 {
     _tokens.Add(name, new Token(name, value));
     return this;
 }
Beispiel #39
0
 public Token(string name, GetValue value)
     : this(name, null, value)
 {
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="DelegatePropertyGetAccessor"/> class
        /// for get property access via DynamicMethod.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="propertyName">Name of the property.</param>
        public DelegatePropertyGetAccessor(Type targetObjectType, string propertyName)
        {
            targetType = targetObjectType;
            this.propertyName = propertyName;

            PropertyInfo propertyInfo = GetPropertyInfo(targetObjectType);

            if (propertyInfo == null)
            {
                propertyInfo = targetType.GetProperty(propertyName);
            }

            // Make sure the property exists
            if(propertyInfo == null)
            {
                throw new NotSupportedException(
                    string.Format("Property \"{0}\" does not exist for type "
                    + "{1}.", propertyName, targetType));
            }
            else
            {
                _propertyType = propertyInfo.PropertyType;
                _canRead = propertyInfo.CanRead;

                this.nullInternal = this.GetNullInternal(_propertyType);

                if (propertyInfo.CanRead)
                {
                    DynamicMethod dynamicMethod = new DynamicMethod("GetImplementation", typeof(object), new Type[] { typeof(object) }, this.GetType().Module, true);
                    ILGenerator ilgen = dynamicMethod.GetILGenerator();

                    // Emit the IL for get access.
                    MethodInfo targetGetMethod = propertyInfo.GetGetMethod();

                    ilgen.DeclareLocal(typeof(object));
                    ilgen.Emit(OpCodes.Ldarg_0);	//Load the first argument,(target object)
                    ilgen.Emit(OpCodes.Castclass, targetObjectType);	//Cast to the source type
                    ilgen.EmitCall(OpCodes.Callvirt, targetGetMethod, null); //Get the property value
                    if (targetGetMethod.ReturnType.IsValueType)
                    {
                        ilgen.Emit(OpCodes.Box, targetGetMethod.ReturnType); //Box if necessary
                    }
                    ilgen.Emit(OpCodes.Stloc_0); //Store it
                    ilgen.Emit(OpCodes.Ldloc_0);
                    ilgen.Emit(OpCodes.Ret);

                    _get = (GetValue)dynamicMethod.CreateDelegate(typeof(GetValue));
                }
            }
        }
 public void _BuildTree(XtraForm danhMucForm,string btnCaption, GetValue function, string columnField, string TableName, int[] RootID, string IDField, string IDParentField, string[] VisibleFields, string[] Captions, string getField)
 {
     this._initTree(IDField, IDParentField, VisibleFields, Captions);
     this.danhMucForm = danhMucForm;
     this.IDField = IDField;
     this.tableName = TableName;
     fieldGet = getField;
     this.btnExtend.Text = btnCaption;
     this.btnExtend.Width = btnExtend.CalcBestSize().Width;
     this.btnExtend.Visible = true;
     this.formValue = function;
     this.RootID = RootID;
     this.columnField = columnField;
     DataTable dt = LoadTable(TableName, RootID);
     treeList1.DataSource = dt;
 }
Beispiel #42
0
 public object this[string property]
 {
     get
     {
         if (SqlObject.GetMethod == null)
         {
             SqlObject.GetMethod = Compiler.GetHelper.Value(this.GetType());
         }
         if (SqlObject.GetMethod != null)
         {
             return GetMethod(this, property);
         }
         return null;
     }
     set
     {
         if (SqlObject.SetMethod == null)
         {
             SqlObject.SetMethod = Compiler.SetHelper.Value<SqlObject>(this.GetType());
         }
         if (SqlObject.SetMethod != null)
         {
             SqlObject.SetMethod(this, property, value);
         }
     }
 }
 public void _init(XtraForm frmDanhMuc,string btnCaption, GetValue function, string tableName, string valueField, string[] visibleField, string[] caption, string getField)
 {
     this.tableName = tableName;
     this.danhMucForm = frmDanhMuc;
     this.getField = getField;
     this.valueField = valueField;
     this.btnExtend.Text = btnCaption;
     this.btnExtend.Width = this.btnExtend.CalcBestSize().Width;
     this.btnExtend.Visible = true;
     this.formValue = function;
     _initGridView(valueField, visibleField, caption);
     this.gridControl1.DataSource = _loadData();
     if (popupContainerEdit != null)//Su dung tren form
         popupContainerEdit.Properties.NullText = GlobalConst.NULL_TEXT;
 }
        /// <summary>
        /// Replaces named template items in a specified string 
        /// with the string representation of a corresponding named object 
        /// provided by the passed function. 
        /// A specified parameter supplies culture-specific formatting information.
        /// </summary>
        /// <param name="provider">An object that supplies culture-specific formatting information.</param>
        /// <param name="template">A template string (see Remarks).</param>
        /// <param name="getValue">An function that supplies named objects to format.</param>
        /// <returns>A copy of template in which the template items have been replaced 
        /// by the string representation of the corresponding objects supplied by getValue.</returns>
        /// <exception cref="ArgumentNullException">template or the getValue callback is null.</exception>
        /// <exception cref="FormatException">template is invalid, 
        /// or one of the named template items cannot be provided
        /// (getValue returns false when that item is requested).</exception>
        /// <remarks>
        /// <para>
        /// Note that argument names may or may not be case-sensitive depending on the
        /// comparer used by the dictionary. To get case-insensitive behaviour, use
        /// a dictionary that has a case-insensitive comparer.
        /// </para>
        /// <para>
        /// For implementations where a user-supplied template is used to format 
        /// arguments provided by the system it is recommended that arguments
        /// are case-insensitive.
        /// </para>
        /// </remarks>
        public static string Format(IFormatProvider provider, string template, GetValue getValue)
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }
            if (getValue == null)
            {
                throw new ArgumentNullException("getValue");
            }

            char[] chArray = template.ToCharArray(0, template.Length);
            int index = 0;
            int length = chArray.Length;
            char ch = '\0';

            ICustomFormatter formatter = null;
            if (provider != null)
            {
                formatter = (ICustomFormatter)provider.GetFormat(typeof(ICustomFormatter));
            }

            StringBuilder builder = new StringBuilder();
            while (index < length)
            {
                ch = chArray[index];
                index++;
                if (ch == '}')
                {
                    if ((index < length) && (chArray[index] == '}'))
                    {
                        // Literal close curly brace
                        builder.Append('}');
                        index++;
                    }
                    else
                    {
                        throw new FormatException(Resource.StringTemplate_InvalidString);
                    }
                }
                else if (ch == '{')
                {
                    if ((index < length) && (chArray[index] == '{'))
                    {
                        // Literal open curly brace
                        builder.Append('{');
                        index++;
                    }
                    else
                    {
                        // Template item:
                        if (index == length)
                        {
                            throw new FormatException(Resource.StringTemplate_InvalidString);
                        }

                        // Argument name
                        int nameStart = index;
                        ch = chArray[index];
                        index++;
                        if (!( ch == '_'
                            || ((ch >= 'a') && (ch <= 'z'))
                            || ((ch >= 'A') && (ch <= 'Z'))))
                        {
                            throw new FormatException(Resource.StringTemplate_InvalidString);
                        }
                        while ((index < length) &&
                                ( ch == '.' || ch == '-' || ch == '_'
                                || ((ch >= '0') && (ch <= '9'))
                                || ((ch >= 'a') && (ch <= 'z'))
                                || ((ch >= 'A') && (ch <= 'Z'))))
                        {
                            ch = chArray[index];
                            index++;
                        }
                        int nameEnd = index - 1;
                        if( nameEnd == nameStart )
                        {
                            throw new FormatException(Resource.StringTemplate_InvalidString);
                        }
                        string argumentName = new string(chArray, nameStart, nameEnd - nameStart);
                        object arg;
                        if (!getValue(argumentName, out arg))
                        {
                            throw new FormatException(Resource.StringTemplate_ArgumentNotFound);
                        }

                        // Skip blanks
                        while ((index < length) && (ch == ' '))
                        {
                            ch = chArray[index];
                            index++;
                        }

                        // Argument alignment
                        int width = 0;
                        bool leftAlign = false;
                        if( ch == ',' )
                        {
                            if (index == length)
                            {
                                throw new FormatException(Resource.StringTemplate_InvalidString);
                            }
                            ch = chArray[index];
                            index++;
                            while ((index < length) && (ch == ' '))
                            {
                                ch = chArray[index];
                                index++;
                            }
                            if (index == length)
                            {
                                throw new FormatException(Resource.StringTemplate_InvalidString);
                            }
                            if (ch == '-')
                            {
                                leftAlign = true;
                                if (index == length)
                                {
                                    throw new FormatException(Resource.StringTemplate_InvalidString);
                                }
                                ch = chArray[index];
                                index++;
                            }
                            if ((ch < '0') || (ch > '9'))
                            {
                                throw new FormatException(Resource.StringTemplate_InvalidString);
                            }
                            while ((index < length) && (ch >= '0') && (ch <= '9'))
                            {
                                // TODO: What if number too large for Int32, i.e. throw exception
                                width = width * 10 + (ch - 0x30);
                                ch = chArray[index];
                                index++;
                            }
                        }

                        // Skip blanks
                        while ((index < length) && (ch == ' '))
                        {
                            ch = chArray[index];
                            index++;
                        }

                        // Format string
                        string formatString = null;
                        if( ch == ':' )
                        {
                            if (index == length)
                            {
                                throw new FormatException(Resource.StringTemplate_InvalidString);
                            }
                            int formatStart = index;
                            ch = chArray[index];
                            index++;
                            while ((index < length) && (ch != '{') && (ch != '}'))
                            {
                                ch = chArray[index];
                                index++;
                            }
                            int formatEnd = index - 1;
                            if( formatEnd >= formatStart )
                            {
                                formatString = new string(chArray, formatStart, formatEnd - formatStart);
                            }
                        }

                        // Insert formatted argument
                        if (ch != '}')
                        {
                            throw new FormatException(Resource.StringTemplate_InvalidString);
                        }
                        string argumentValue = null;
                        if (formatter != null)
                        {
                            argumentValue = formatter.Format(formatString, arg, provider);
                        }
                        if (argumentValue == null)
                        {
                            if (arg is IFormattable)
                            {
                                argumentValue = ((IFormattable)arg).ToString(formatString, provider);
                            }
                            else if (arg != null)
                            {
                                argumentValue = arg.ToString();
                            }
                        }
                        if (argumentValue == null)
                        {
                            argumentValue = string.Empty;
                        }
                        int paddingCount = width - argumentValue.Length;
                        if (!leftAlign && (paddingCount > 0))
                        {
                            builder.Append(' ', paddingCount);
                        }
                        builder.Append(argumentValue);
                        if (leftAlign && (paddingCount > 0))
                        {
                            builder.Append(' ', paddingCount);
                        }
                    }
                }
                else
                {
                    // Literal -- scan up until next curly brace
                    int literalStart = index - 1;
                    while( index < length )
                    {
                        ch = chArray[index];
                        if( ch == '{' || ch == '}' )
                        {
                            break;
                        }
                        index++;
                    }
                    builder.Append(chArray, literalStart, index - literalStart);
                }
            }
            return builder.ToString();
        }
 /// <summary>
 /// Replaces named template items in a specified string 
 /// with the string representation of a corresponding named object 
 /// provided by the passed function. 
 /// A specified parameter supplies culture-specific formatting information.
 /// </summary>
 /// <param name="template">A template string (see Remarks).</param>
 /// <param name="getValue">An function that supplies named objects to format.</param>
 /// <returns>A copy of template in which the template items have been replaced 
 /// by the string representation of the corresponding objects supplied by getValue.</returns>
 /// <exception cref="ArgumentNullException">template or the getValue callback is null.</exception>
 /// <exception cref="FormatException">template is invalid, 
 /// or one of the named template items cannot be provided
 /// (getValue returns false when that item is requested).</exception>
 /// <remarks>
 /// <para>
 /// Note that argument names may or may not be case-sensitive depending on the
 /// comparer used by the dictionary. To get case-insensitive behaviour, use
 /// a dictionary that has a case-insensitive comparer.
 /// </para>
 /// <para>
 /// For implementations where a user-supplied template is used to format 
 /// arguments provided by the system it is recommended that arguments
 /// are case-insensitive.
 /// </para>
 /// </remarks>
 public static string Format(string template, GetValue getValue)
 {
     return Format(null, template, getValue);
 }
Beispiel #46
0
        public unsafe void RebuildSpheres( GetValue _Delegate )
        {
            BitmapData	LockedBitmap = m_Render.LockBits( new Rectangle( 0, 0, WIDTH, HEIGHT ), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb );

            for ( int Y=0; Y < HEIGHT; Y++ )
            {
                float	fDy = 1.0f - Y / (.5f * HEIGHT);

                byte*	pScanline = (byte*) LockedBitmap.Scan0 + Y * LockedBitmap.Stride;

                for ( int X=0; X < WIDTH; X++ )
                {
                    if ( X < .5f * WIDTH )
                    {	// Front sphere
                        float	fDx = (X - .25f * WIDTH) / (.25f * WIDTH);
                        float	fSDistance = fDx * fDx + fDy * fDy;
                        if ( fSDistance > 1.0f )
                        {	// Put a black pixel
                            pScanline[3*X+0] = 32;
                            pScanline[3*X+1] = 32;
                            pScanline[3*X+2] = 32;
                            continue;
                        }

                        float	fDz = (float) Math.Sqrt( 1.0f - fSDistance );

                        float	fValue = _Delegate( fDx, fDy, fDz );
                        if ( fValue > 0.0f )
                        {
                            pScanline[3*X+0] = 0;
                            pScanline[3*X+1] = (byte) (255.0f * Math.Min( 1.0f, fValue ));		// Green lobe for positive values
                            pScanline[3*X+2] = 0;
                        }
                        else
                        {
                            pScanline[3*X+0] = 0;
                            pScanline[3*X+1] = 0;
                            pScanline[3*X+2] = (byte) (255.0f * Math.Min( 1.0f, -fValue ));		// Red lobe for negative values
                        }
                    }
                    else
                    {	// Back sphere
                        float	fDx = (X - .75f * WIDTH) / (.25f * WIDTH);
                        float	fSDistance = fDx * fDx + fDy * fDy;
                        if ( fSDistance > 1.0f )
                        {	// Put a black pixel
                            pScanline[3*X+0] = 32;
                            pScanline[3*X+1] = 32;
                            pScanline[3*X+2] = 32;
                            continue;
                        }

                        float	fDz = -(float) Math.Sqrt( 1.0f - fSDistance );

                        float	fValue = _Delegate( fDx, fDy, fDz );
                        if ( fValue > 0.0f )
                        {
                            pScanline[3*X+0] = 0;
                            pScanline[3*X+1] = (byte) (255.0f * Math.Min( 1.0f, fValue ));		// Green lobe for positive values
                            pScanline[3*X+2] = 0;
                        }
                        else
                        {
                            pScanline[3*X+0] = 0;
                            pScanline[3*X+1] = 0;
                            pScanline[3*X+2] = (byte) (255.0f * Math.Min( 1.0f, -fValue ));		// Red lobe for negative values
                        }
                    }
                }
            }

            m_Render.UnlockBits( LockedBitmap );
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="T:DelegateFieldGetAccessor"/> class
        /// for field get access via DynamicMethod.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="fieldName">Name of the field.</param>
        public DelegateFieldGetAccessor(Type targetObjectType, string fieldName)
        {
            // this.targetType = targetObjectType;
            _fieldName = fieldName;

            FieldInfo fieldInfo = targetObjectType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            // Make sure the field exists
            if (fieldInfo == null)
            {
                throw new NotSupportedException(
                    string.Format("Field \"{0}\" does not exist for type "
                    + "{1}.", fieldName, targetObjectType));
            }
            else
            {
                _fieldType = fieldInfo.FieldType;
                this.nullInternal = this.GetNullInternal(_fieldType);

                DynamicMethod dynamicMethodGet = new DynamicMethod("GetImplementation", typeof(object), new Type[] { typeof(object) }, this.GetType().Module, false);
                ILGenerator ilgen = dynamicMethodGet.GetILGenerator();

                // Emit the IL for get access.

                // We need a reference to the current instance (stored in local argument index 0)
                // so Ldfld can load from the correct instance (this one).
                ilgen.Emit(OpCodes.Ldarg_0);
                ilgen.Emit(OpCodes.Ldfld, fieldInfo);
                if (_fieldType.IsValueType)
                {
                    // Now, we execute the box opcode, which pops the value of field 'x',
                    // returning a reference to the filed value boxed as an object.
                    ilgen.Emit(OpCodes.Box, fieldInfo.FieldType);
                }
                ilgen.Emit(OpCodes.Ret);
                _get = (GetValue)dynamicMethodGet.CreateDelegate(typeof(GetValue));
            }
        }
Beispiel #48
0
 static string BuildSomething(int number, GetValue valueGetter)
 {
     return "we are building something: " + valueGetter(number);
 }