What came before

In my previous post I discussed ways of making the settings table using Generics to have typed access to our properties. This required us to still pass in the name of our property as a string to a method.

User user = db.Users.First();if(user.Setting<bool>("IsAdministrator")){//yay, this user is an admin!}

Today we’re going to take advantage of dynamic to take it one step further.

The Goal

User user = db.Users.First();if(user.Settings.IsAdministrator){//yay, this user is an admin!}

We’re going to create a new class that inherits from DynamicObject. Doing so will allow us to utilize all the power of dynamics such as getting/setting members, calling methods, or type conversions. <a

The dynamic language runtime first checks to see if the property of our DynamicObject already exists and if it doesn’t find the property it calls TryGetMember or TrySetMember. This is what we’re going to use to return our settings property. Here is a barebones DynamicObject that uses aDictionary<string, object> to store values.

//These are essentially the same//user.Settings["IsAdministrator"]//user.Settings.IsAdministratorclassSettingsDynamicObject:DynamicObject{//used for cachingDictionary<string,object> _dictionary;publicSettingsDynamicObject(User user){
_dictionary =newDictionary<string,object>();}publicoverrideboolTrySetMember(SetMemberBinder binder,object value){
_dictionary[binder.Name]= value;returntrue;}publicoverrideboolTryGetMember(GetMemberBinder binder,outobject result){if( _dictionary.TryGetValue(binder.Name,out result)){returntrue;}}}

Adding our new database overrides

We’re now going to modify our overrides to pull values from the database if they don’t already exist in the _dictionary object and add our code to save the new values.

publicoverrideboolTrySetMember(SetMemberBinder binder,object value){SetDatabaseValue(binder.Name, value);
_dictionary[binder.Name]= value;returntrue;}publicoverrideboolTryGetMember(GetMemberBinder binder,outobject result){//check to see if the property already existsif( _dictionary.ContainsKey(binder.Name)&& _dictionary.TryGetValue(binder.Name,out result)){returntrue;}else{var setting =this.user
.UserSettings.SingleOrDefault(s => s.Name== binder.Name);if(setting ==null){
result =null;}else{
result =newBinaryFormatter().Deserialize(newSystem.IO.MemoryStream(setting.Value));
_dictionary[binder.Name]= result;}returntrue;}}privatevoidSetDatabaseValue(string name,object value){var setting =this.user.UserSettings.SingleOrDefault(s => s.Name== name);System.IO.MemoryStream ms =newSystem.IO.MemoryStream();newBinaryFormatter().Serialize(ms, value);if(setting ==null){
setting =newUserSetting(){Name= name,Type= value.GetType().ToString(),
setting.Value= ms.ToArray();this.user.UserSettings.Add(setting);}else{if(value !=null&& setting.Type!= value.GetType().FullName)thrownewInvalidCastException(string.Format("Unable to cast: {0} to {1}",
value.GetType().FullName, setting.Type));
setting.Value= ms.ToArray();}}

Modifying our existing user object

Now we have a new DynamicObject class that we can use to populate our settings but we’ll need to modify our existing User class to utilize the new Settings. One of the downsides is that we’ll have two exposed properties instead of one but I think it’s negligable.

publicclassUser{publicInt32UserID{get;set;}publicstringLoginID{get;set;}publicstringName{get;set;}publicstringPage{get;set;}publicstringPassword{get;set;}publicvirtualICollection<UserSetting>UserSettings{get;set;}publicvirtualdynamicSettings{get;set;}publicUser(){//We need to initialize the Settings to our new DynamicObjectSettings=newSettingsDynamicObject(this);}}

And there you have it. We now have a dynamic enabled settings property that makes our code slightly easier to read. I hope this helps you on your way to understanding c# 4.0’s new dynamic namespace.

– Ben

Update:

Fixed Constructor – thanks yesthatmcgurk

http://buildstarted.com/2010/08/23/fun-with-dynamicobject-dynamic-and-the-settings-table/

Fun with dynamicobject dynamic and the settings table的更多相关文章

  1. Creating a settings table that can handle almost any type of value

    Update: Updated article here. Today I wanted to be able to have a table store any type of value as a ...

  2. 【原创】大叔问题定位分享(22)hive同时执行多个insert overwrite table只有1个可以执行

    hive 2.1 一 问题 最近有一个场景,要向一个表的多个分区写数据,为了缩短执行时间,采用并发的方式,多个sql同时执行,分别写不同的分区,同时开启动态分区: set hive.exec.dyna ...

  3. CSharp 案例:用 Dynamic 来解决 DataTable 数值累加问题

    需求说明 给定一个 DataTable,如果从中取出数值类型列的值并对其累加? 限制:不知该列是何种数值类型. 解决方案 1.将表转换为 IEnumerable<dynamic>,而后获取 ...

  4. [转]Dynamic SQL & Stored Procedure Usage in T-SQL

    转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...

  5. DataTable转List<dynamic>

    DataTable转List<dynamic> 最近做的一个项目,MVC+Ado.net.没有ORM很不习惯.找到一个办法,DataTable转List<dynamic>,这样 ...

  6. Dynamic view

    Views are a useful feature of SQL databases, letting us create virtual tables based on SQL select st ...

  7. Working with the Dynamic Type in C#

    Working with the Dynamic Type in C# https://www.red-gate.com/simple-talk/dotnet/c-programming/workin ...

  8. Dynamic Type

    啥是 Dynamic Type 动态字体,即视力不好的用户,调整了默认字体的大小,开发者应该根据这个设置,动态改变界面的字体等,保证用户能看得清楚. 这个还是蛮重要的,视力不好的人越来越多. 用户在哪 ...

  9. Deploying JRE (Native Plug-in) for Windows Clients in Oracle E-Business Suite Release 12 (文档 ID 393931.1)

    In This Document Section 1: Overview Section 2: Pre-Upgrade Steps Section 3: Upgrade and Configurati ...

随机推荐

  1. HTML&CSS基础学习笔记1.20-DIV标签2

    <span>标签 标签div把文档分割为独立的.不同的部分,而在HTML中,<span>标签则被用来组合文档中的行内元素. 看个实例: <!DOCTYPE html> ...

  2. C语言初学 比较五个整数并输出最大值和最小值2

    #include <stdio.h> int main() { int i,a[5]; int max = 0,min = 0; printf("输入5个整数(空格隔开) :\n ...

  3. QuickTime 专业版 pro 注册码

    打开QuickTime Player下拉编辑菜单--选偏好设置--注册 Name: Dawn M Fredette Key: 4UJ2-5NLF-HFFA-9JW3-X2KV 重新启动 QuickTi ...

  4. 酷狗、QQ、天天动听——手机音乐播放器竞品对比

    如果说什么艺术与人们生活最贴近,那应该属音乐了,因此当代人不离身的手机里必然会有自己喜欢的音乐播放器APP存在. 在当今无论PC端还是手机端音乐播放器都越来越同质化,我们应该选择哪款手机音乐播放器?它 ...

  5. 这样就算会了PHP么?-8

    关于PHP的一些时间函数,这个小节完之后,就可以进入PHP比较高级的内容啦... <?php date_default_timezone_set("Asia/Shanghai" ...

  6. logstash 发送慢页面到zabbix告警

    input { file { type => "zj_frontend_access" path => ["/data01/applog_backup/zjz ...

  7. SQL语言的组成

    在正式学习SQL语言之前,首先让我们对SQL语言有一个基本认识,介绍一下SQL语言的 组成: 1.一个SQL数据库是表(Table)的集合,它由一个或多个SQL模式定义. 2.一个SQL表由行集构成, ...

  8. poj2429:因数分解+搜索

    题意:给定gcd(a,b)和lcm(a,b) 求使得a+b最小的 a,b 思路:结合算数基本定理中 gcd lcm的质因子表示形式 把lcm(a,b)质因数分解 以后 通过dfs找到 a+b最小的a ...

  9. Codeforce 216 div2

    D 只要搞清楚一个性质:确定了当前最大和次大的位置,局面就唯一确定了; 根据这个性质设计dp,统计到达该局面的方法数即可. E 询问的要求是: 求有多少个区间至少覆盖了询问的点集中的一个; 转化成逆命 ...

  10. Linux一个简单的读写文件

    (1)linux中的文件描述符fd的合法范围是或者一个正正数,不可能是一个负数. (2)open返回的fd程序必须记录好,以后向这个文件的所有操作都要靠这个fd去对应这个文件,最后关闭文件时也需要fd ...