示例#1
0
        /// <summary>
        /// 返回指定类型的对象,其值等效于指定字符串对象。
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="input"> 需要转换类型的字符串对象 </param>
        /// <param name="outputType"> 换转后的类型 </param>
        /// <param name="success"> 是否成功 </param>
        protected override IDictionary <K, V> ChangeType(ConvertContext context, string input, Type outputType,
                                                         out bool success)
        {
            input = input?.Trim() ?? "";
            if (input.Length == 0)
            {
                var keyConvertor   = context.Get <K>();
                var valueConvertor = context.Get <V>();

                var builder = new DictionaryBuilder(context, outputType, keyConvertor, valueConvertor);
                // ReSharper disable once AssignmentInConditionalExpression
                return((success = builder.TryCreateInstance()) ? builder.Instance : null);
            }
            if (input?.Length > 2)
            {
                if ((input[0] == '{') && (input[input.Length - 1] == '}'))
                {
                    try
                    {
                        var result = ComponentServices.ToJsonObject(outputType, input);
                        success = true;
                        return((IDictionary <K, V>)result);
                    }
                    catch (Exception ex)
                    {
                        context.AddException(ex);
                    }
                }
            }
            success = false;
            return(null);
        }
示例#2
0
        /// <summary>
        /// 返回指定类型的对象,其值等效于指定字符串对象。
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="input"> 需要转换类型的字符串对象 </param>
        /// <param name="outputType"> 换转后的类型 </param>
        /// <param name="success"> 是否成功 </param>
        protected override IList ChangeType(ConvertContext context, string input, Type outputType, out bool success)
        {
            input = input?.Trim();
            if ((input == null) || (input.Length <= 1))
            {
                success = false;
                return(null);
            }
            if ((input[0] == '[') && (input[input.Length - 1] == ']'))
            {
                try
                {
                    var result = ComponentServices.ToJsonObject(outputType, input);
                    success = true;
                    return((IList)result);
                }
                catch (Exception ex)
                {
                    context.AddException(ex);
                    success = false;
                    return(null);
                }
            }
            var arr = input.Split(_Separator, StringSplitOptions.None);

            return(ChangeType(context, arr, outputType, out success));
        }
示例#3
0
        public ActionResult StudentsEnrolled(IEnumerable <StudentEnrollementViewModel> list)
        {
            var scoreServices     = new ScoreServices(_scoreRepository, _courseRepository, _userRepository);
            var componentServices = new ComponentServices(_componentRepository, _courseRepository);
            var userServices      = new UserServices(_userRepository);

            foreach (var s in list)
            {
                foreach (var scor in s.scores)
                {
                    Score ss = new Score()
                    {
                        Id        = scor.Id,
                        Value     = scor.Value,
                        Component = componentServices.GetById(scor.Component.Id),
                        Student   = (Student)userServices.GetUserById(scor.Student.Id)
                    };
                    if (ss.Value > ss.Component.MaximumPoints)
                    {
                        return(RedirectToAction("StudentsEnrolled", "Lecturer", new { id = ss.Component.Course.Id, error = true }));
                    }
                    else
                    {
                        scoreServices.SaveScore(ss);
                    }
                }
            }
            return(RedirectToAction("Index", "Lecturer"));
        }
示例#4
0
        public ActionResult EditComponent(ComponentViewModel comp)
        {
            var componentServices = new ComponentServices(_componentRepository, _courseRepository);
            var component         = componentServices.UpdateComponent(comp.Name, comp.Id, comp.MinimumPointsToPass, comp.MaximumPoints);

            return(RedirectToAction("Component", "Lecturer", new { id = comp.CourseId }));
        }
示例#5
0
        /// <summary>
        /// 返回指定类型的对象,其值等效于指定字符串对象。
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="input"> 需要转换类型的字符串对象 </param>
        /// <param name="outputType"> 换转后的类型 </param>
        /// <param name="success"> 是否成功 </param>
        protected override ICollection <T> ChangeType(ConvertContext context, string input, Type outputType,
                                                      out bool success)
        {
            input = input.Trim();
            if (input.Length == 0)
            {
                var builder = new ListBuilder(context, outputType);
                // ReSharper disable once AssignmentInConditionalExpression
                return((success = builder.TryCreateInstance()) ? builder.Instance : null);
            }
            if ((input[0] == '[') && (input[input.Length - 1] == ']'))
            {
                try
                {
                    var result = ComponentServices.ToJsonObject(outputType, input);
                    success = true;
                    return((ICollection <T>)result);
                }
                catch (Exception ex)
                {
                    context.AddException(ex);
                    success = false;
                    return(null);
                }
            }
            var arr = input.Split(_Separator, StringSplitOptions.None);

            return(ChangeType(context, arr, outputType, out success));
        }
示例#6
0
        /// <summary>
        /// 将正文格式化为字节流
        /// </summary>
        /// <param name="format"> 包含格式规范的格式字符串 </param>
        /// <param name="body"> 请求或响应正文 </param>
        /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param>
        /// <returns> </returns>
        public override byte[] Serialize(string format, IEnumerable <KeyValuePair <string, object> > body, IFormatProvider formatProvider)
        {
            string json;

            if (body == null)
            {
                json = "null";
            }
            else if (body.FirstOrDefault().Key == null && body.Count() == 1)
            {
                json = ComponentServices.ToJsonString(body.FirstOrDefault().Value);
            }
            else if (body.GetType().GetInterfaces().Any(t => t == typeof(IDictionary) || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IDictionary <,>))))
            {
                json = ComponentServices.ToJsonString(body);
            }
            else
            {
                json = ComponentServices.ToJsonString(new DictionaryWrapper(body));
            }

            var charset = GetEncoding(formatProvider) ?? Encoding.UTF8;

            return(charset.GetBytes(json));
        }
示例#7
0
        /// <summary>
        /// 将字节流转换为键值对枚举
        /// </summary>
        /// <param name="bytes"> </param>
        /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param>
        /// <returns> </returns>
        public override IEnumerable <KeyValuePair <string, object> > Deserialize(byte[] bytes, IFormatProvider formatProvider)
        {
            var charset = GetEncoding(formatProvider) ?? Encoding.UTF8;
            var json    = charset.GetString(bytes);

            return((Dictionary <string, object>)ComponentServices.ToJsonObject(typeof(Dictionary <string, object>), json));
        }
示例#8
0
        /// <summary>
        /// 将字节流转换为指定对象
        /// </summary>
        /// <param name="bytes"> </param>
        /// <param name="formatProvider"> 它提供有关当前实例的格式信息 </param>
        /// <returns> </returns>
        public override T Deserialize <T>(byte[] bytes, IFormatProvider formatProvider)
        {
            var charset = GetEncoding(formatProvider) ?? Encoding.UTF8;
            var json    = charset.GetString(bytes);

            return((T)ComponentServices.ToJsonObject(typeof(T), json));
        }
示例#9
0
 /// <summary>
 /// 返回指定类型的对象,其值等效于指定字符串对象。
 /// </summary>
 /// <param name="context"> </param>
 /// <param name="input"> 需要转换类型的字符串对象 </param>
 /// <param name="outputType"> 换转后的类型 </param>
 /// <param name="success"> 是否成功 </param>
 protected override IDictionary ChangeType(ConvertContext context, string input, Type outputType,
                                           out bool success)
 {
     if (string.IsNullOrWhiteSpace(input))
     {
         success = false;
         return(null);
     }
     input = input.Trim();
     if ((input[0] == '{') && (input[input.Length - 1] == '}'))
     {
         try
         {
             var result = ComponentServices.ToJsonObject(outputType, input);
             success = true;
             return((IDictionary)result);
         }
         catch (Exception ex)
         {
             context.AddException(ex);
         }
     }
     success = false;
     return(null);
 }
示例#10
0
 /// <summary>
 /// 初始化 <see cref="PropertyHandler"/>
 /// </summary>
 /// <param name="property">属性</param>
 public PropertyHandler(PropertyInfo property)
 {
     Property     = property;
     PropertyType = property.PropertyType;
     Name         = property.Name;
     Get          = ComponentServices.GetGeter(property);
     Set          = ComponentServices.GetSeter(property);
 }
示例#11
0
 /// <summary>
 /// 初始化属性操作器
 /// </summary>
 /// <param name="property"> 需要操作的属性 </param>
 /// <exception cref="Exception">
 /// IOC插件异常 <seealso cref="ComponentServices.GetGeter" /> 或
 /// <seealso cref="ComponentServices.GetSeter" /> 出现错误.
 /// </exception>
 public PropertyHandler(PropertyInfo property)
 {
     Name         = property.Name;
     PropertyType = property.PropertyType;
     Debug.Assert(ComponentServices.GetGeter != null, "ComponentServices.GetGeter != null");
     Debug.Assert(ComponentServices.GetSeter != null, "ComponentServices.GetSeter != null");
     _getter = ComponentServices.GetGeter(property);
     _setter = ComponentServices.GetSeter(property);
 }
示例#12
0
        /// <summary>
        /// 返回指定类型的对象,其值等效于指定字符串对象。
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="input"> 需要转换类型的字符串对象 </param>
        /// <param name="outputType"> 换转后的类型 </param>
        /// <param name="success"> 是否成功 </param>
        protected override object ChangeType(ConvertContext context, string input, Type outputType, out bool success)
        {
            if (input?.Length > 2)
            {
                switch (input[0])
                {
                case '"':
                    if (input[input.Length - 1] != '"')
                    {
                        return(base.ChangeType(context, input, outputType, out success));
                    }
                    break;

                case '\'':
                    if (input[input.Length - 1] != '\'')
                    {
                        return(base.ChangeType(context, input, outputType, out success));
                    }
                    break;

                case '{':
                    if (input[input.Length - 1] != '}')
                    {
                        return(base.ChangeType(context, input, outputType, out success));
                    }
                    break;

                case '[':
                    if (input[input.Length - 1] != ']')
                    {
                        return(base.ChangeType(context, input, outputType, out success));
                    }
                    break;

                default:
                    return(base.ChangeType(context, input, outputType, out success));
                }
                try
                {
                    success = true;
                    return(ComponentServices.ToJsonObject(outputType, input));
                }
                catch (Exception ex)
                {
                    context.AddException(ex);
                }
            }
            return(base.ChangeType(context, input, outputType, out success));
        }
示例#13
0
        public ActionResult EditComponent(int id)
        {
            if (Session["userId"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var componentServices = new ComponentServices(_componentRepository, _courseRepository);
            var component         = componentServices.GetById(id);

            ViewBag.Title = component.Name + " " + component.Course.Name;
            ViewBag.Email = Session["email"];

            return(View(new ComponentViewModel(component)));
        }
示例#14
0
        public ActionResult DeleteComponentConfirmed(int id)
        {
            if (Session["userId"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            var componentServices = new ComponentServices(_componentRepository, _courseRepository);

            if (!componentServices.DeleteComponent(id))
            {
                return(RedirectToAction("DeleteComponent", "Lecturer", new { id = id, error = true }));
            }
            return(RedirectToAction("Index", "Lecturer"));
        }
示例#15
0
        private void InitGetSet(out Type type, out Func <object, object> get, out Action <object, object> set)
        {
            type = (Member as PropertyInfo)?.PropertyType ?? (Member as FieldInfo)?.FieldType;
            if (ComponentServices.GetGeter != null)
            {
                get = ComponentServices.GetGeter(Member);
            }
            else
            {
                switch (Member.MemberType)
                {
                case MemberTypes.Property:
                    get = ((PropertyInfo)Member).GetValue;
                    break;

                case MemberTypes.Field:
                    get = ((FieldInfo)Member).GetValue;
                    break;

                default:
                    get = null;
                    break;
                }
            }

            if (ComponentServices.GetSeter != null)
            {
                set = ComponentServices.GetSeter(Member);
            }
            else
            {
                switch (Member.MemberType)
                {
                case MemberTypes.Property:
                    set = ((PropertyInfo)Member).SetValue;
                    break;

                case MemberTypes.Field:
                    set = ((FieldInfo)Member).SetValue;
                    break;

                default:
                    set = null;
                    break;
                }
            }
        }
示例#16
0
        public ActionResult DeleteComponent(int id, bool?error)
        {
            if (Session["userId"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }
            if (error == true)
            {
                ModelState.AddModelError("error", "Ne možete pobrisati komponentu koja ima upisane bodove studentima!");
            }
            var componentServices = new ComponentServices(_componentRepository, _courseRepository);
            var component         = componentServices.GetById(id);

            ViewBag.Title = component.Name + " " + component.Course.Name;
            ViewBag.Email = Session["email"];

            return(View(new ComponentViewModel(component)));
        }
示例#17
0
        /// <summary>
        /// 追加 Json 对象到 Http 参数
        /// </summary>
        /// <param name="param"> 参数将被追加到的参数集合 </param>
        /// <param name="json"> 需要解析的 Json 字符串 </param>
        public static void AddJson(this HttpParamsBase <object> param, string json)
        {
            if (param == null)
            {
                throw new ArgumentNullException(nameof(param));
            }
            if (string.IsNullOrWhiteSpace(json))
            {
                return;
            }

            var dict = (Dictionary <string, object>)ComponentServices.ToJsonObject(typeof(Dictionary <string, object>), json);

            foreach (var item in dict)
            {
                param[item.Key] = item.Value;
            }
        }
示例#18
0
        /// <summary>
        /// 追加 Json 对象到 Http 参数
        /// </summary>
        /// <param name="param"> 参数将被追加到的参数集合 </param>
        /// <param name="json"> 需要解析的 Json 字符串 </param>
        public static void AddJson(this HttpParamsBase <string> param, string json)
        {
            if (param == null)
            {
                throw new ArgumentNullException(nameof(param));
            }
            if (string.IsNullOrWhiteSpace(json))
            {
                return;
            }

            var nv = (NameValueCollection)ComponentServices.ToJsonObject(typeof(NameValueCollection), json);

            for (int i = 0, length = nv.Count; i < length; i++)
            {
                var key = nv.GetKey(i);
                var val = nv[i];
                param[key] = val;
            }
        }
示例#19
0
 /// <summary>
 /// 返回指定类型的对象,其值等效于指定字符串对象。
 /// </summary>
 /// <param name="context"> </param>
 /// <param name="input"> 需要转换类型的字符串对象 </param>
 /// <param name="outputType"> 换转后的类型 </param>
 /// <param name="success"> 是否成功 </param>
 protected override NameValueCollection ChangeType(ConvertContext context, string input, Type outputType,
                                                   out bool success)
 {
     input = input?.Trim();
     if ((input?.Length > 1) && (input[0] == '{') && (input[input.Length - 1] == '}'))
     {
         try
         {
             var result = ComponentServices.ToJsonObject(outputType, input);
             success = true;
             return((NameValueCollection)result);
         }
         catch (Exception ex)
         {
             context.AddException(ex);
         }
     }
     success = false;
     return(null);
 }
示例#20
0
        /// <summary>
        /// 返回指定类型的对象,其值等效于指定字符串对象。
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="input"> 需要转换类型的字符串对象 </param>
        /// <param name="outputType"> 换转后的类型 </param>
        /// <param name="success"> 是否成功 </param>
        protected override T[] ChangeType(ConvertContext context, string input, Type outputType, out bool success)
        {
            input = input?.Trim() ?? "";
            if (input.Length == 0)
            {
                success = true;
                return((T[])Array.CreateInstance(outputType.GetElementType(), 0));
            }
            if ((input[0] == '[') && (input[input.Length - 1] == ']')) //判断如果是json字符串,使用json方式转换
            {
                try
                {
                    var result = ComponentServices.ToJsonObject(outputType, input);
                    success = true;
                    return((T[])result);
                }
                catch (Exception ex)
                {
                    context.AddException(ex);
                    success = false;
                    return(null);
                }
            }

            var convertor = context.Get <T>();
            var items     = input.Split(_Separator, StringSplitOptions.None);
            var array     = Array.CreateInstance(convertor.OutputType, items.Length);

            for (var i = 0; i < items.Length; i++)
            {
                var value = convertor.ChangeType(context, items[i], convertor.OutputType, out success);
                if (success == false)
                {
                    context.AddException($"{value?.ToString() ?? "<null>"} 写入数组失败!");
                    return(null);
                }
                array.SetValue(value, i);
            }
            success = true;
            return((T[])array);
        }
示例#21
0
 private static void SetValue(object instance, PropertyInfo p, params string[] names)
 {
     for (int i = 0, length = names.Length; i < length; i++)
     {
         var node = AppSettings[names[i]];
         if (!node.HasValue)
         {
             continue;
         }
         try
         {
             var value = ComponentServices.Converter.Convert(node.Value, p.PropertyType);
             ComponentServices.GetSeter(p)(instance, value);
         }
         catch (Exception ex)
         {
             Debug.Assert(true, ex.Message);
             // ignored
         }
         return;
     }
 }
示例#22
0
        public ActionResult ComponentStatistics(int id)
        {
            if (Session["userId"] == null)
            {
                return(RedirectToAction("Index", "Home"));
            }

            ViewBag.Email = Session["email"];
            ViewBag.Title = "Statistics";

            var courseService    = new CourseServices(_courseRepository, _userRepository, _componentRepository);
            var componentService = new ComponentServices(_componentRepository, _courseRepository);
            var scoreService     = new ScoreServices(_scoreRepository, _courseRepository, _userRepository);

            var course = courseService.GetCourseById(id);

            IList <Component> comp = new List <Component>();

            foreach (var c in course.Components)
            {
                comp.Add(c);
            }
            IList <ComponentStatisticsViewModel> results = new List <ComponentStatisticsViewModel>();

            foreach (var c in comp)
            {
                var   scores = scoreService.GetByComponent(c.Id);
                float sum    = 0;
                float maxSum = 0;
                foreach (var s in scores)
                {
                    sum    += s.Value;
                    maxSum += c.MaximumPoints;
                }
                results.Add(new ComponentStatisticsViewModel(c.Name, (float)sum / maxSum, c.MaximumPoints, c.Course.Id));
            }
            return(View(results));
        }
示例#23
0
        /// <summary>
        /// 返回指定类型的对象,其值等效于指定对象。
        /// </summary>
        /// <param name="context"> </param>
        /// <param name="input"> 需要转换类型的对象 </param>
        /// <param name="outputType"> 换转后的类型 </param>
        /// <param name="success"> 是否成功 </param>
        protected override string ChangeType(ConvertContext context, object input, Type outputType, out bool success)
        {
            success = true;
            if (input is DataRow || input is DataRowView)
            {
                return(ComponentServices.ToJsonString(input));
            }

            var reader = input as IDataReader;

            if (reader != null)
            {
                if (reader.IsClosed)
                {
                    success = false;
                    context.AddException("DataReader已经关闭");
                    return(null);
                }
                switch (reader.FieldCount)
                {
                case 0:
                    return(null);

                case 1:
                    return(BaseChangeType(context, reader.GetValue(0), outputType, out success));

                default:
                    return(ComponentServices.ToJsonString(input));
                }
            }

            if (input.IsNull())
            {
                return(null);
            }

            if (input is bool)
            {
                return((bool)input ? "true" : "false");
            }

            var convertible = input as IConvertible;

            if (convertible != null)
            {
                return(convertible.ToString(null));
            }

            var formattable = input as IFormattable;

            if (formattable != null)
            {
                return(formattable.ToString(null, null));
            }

            var type = input as Type;

            if (type != null)
            {
                return(CType.GetFriendlyName(type));
            }

            var bs = input as byte[];

            if (bs != null)
            {
                return(Encoding.UTF8.GetString(bs));
            }

            var ps = input.GetType().GetProperties();

            if (ps.Length > 0)
            {
                return(ComponentServices.ToJsonString(input));
            }

            return(input.ToString());
        }
示例#24
0
 public JsonFormBody(string json)
 {
     _data = ComponentServices.ToJsonObject(null, json);
     _json = json;
 }
示例#25
0
 public override string ToString()
 {
     return(ComponentServices.ToJsonString(this));
 }