一:事件委托的使用,已分页控件为例。
1:定义一个参数类PagesChangingEventArgs继承EventArgs,里面定义自己需要的参数。
2:定义一个委托 public delegate void PageChangingHandler(object sender, PagesChangingEventArgs e)。
3:使用这个委托定义一个事件 public event PageChangingHandler PageChanging;。
这个事件作用就是在分页控件的后台代码中可以调用“使用该分页控件的页面.aspx”后台代码中的一个方法“Page_OnChanging“
4:在web.config中配置这个自定义控件
<system.web>
<pages>
<controls>
<add tagPrefix="Inc" tagName="header" src="/common/inc/header.ascx"/>
</controls>
</pages>
</system.web>
5:在页面中使用这个分页控件
<Inc:Pagers ID="Pagers" runat="server" PageSize="10" OnPageChanging="Page_OnChanging" />。
然后在Page_OnChanging中可以使用自己定义的参数类PagesChangingEventArgs里面的字段。
二:自己写的上传控件,但是有bug,读取的是服务器上面的路径,不是客户端的路径,但是思路我感觉不错。
1:使用<asp:FileUpload ID="btnFile" runat="server" />控件打开选择对话框。
2:使用js异步把选择的路径提交到服务器。
function UpLoadFile() {
if ($("#txtFoo2").val() == "") {
alert("请选择上传的图片!");
return;
}
$.post("/Base/FileOperation.ashx?do=SaveImage", { "path": $("#txtFoo2").val() }, function (data) {
if (data.Flag) {
$("#<%=hidden_currentImage.ClientID %>").val(data.Content);
$("#" + '<%=img_user.ClientID %>').attr("src", data.Content);
} else {
alert("失败:" + data.Content);
}
}, "json");
3:在服务器上面读取图片并保存,这里把一些固定的数据不要写成固定值,而是写在配置文件当中。再就是抛出自己的异常,然后在捕获异常。这两点是值的学习的。
try
{
string _extent = path.Split('.')[path.Split('.').Length - 1];
List<string> _imageTypeList = ConfigurationManager.AppSettings["ImageType"].Split(',').ToList();
if (_imageTypeList.Contains(_extent.ToLower()))
{
string _imageName = Guid.NewGuid().ToString() + "." + _extent;
string _path = context.Server.MapPath(ConfigurationManager.AppSettings["tempuserface"]);
string _saveFile = string.Format("{0}{1}", _path, _imageName);
FileHelp.SaveFile(path, _saveFile);
ResponseResult.Flag = true;
ResponseResult.Content = ConfigurationManager.AppSettings["tempuserface"] + _imageName;
}
else
{
throw new Exception(string.Format("{0}不是合法格式", _extent));
}
}
catch (Exception ex)
{
ResponseResult.Flag = false;
ResponseResult.Content = "上传图片失败,原因:" + ex.Message;
}
4:定义一个类使用数据流保存图片。这里的路径就读取的不对了,所以就不能吧保存图片了。
public static bool SaveFile(string filePath, string saveFilePath)
{
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open))
{
using (FileStream fs2 = new FileStream(saveFilePath, FileMode.Create))
{
byte[] data = new byte[1024];
BufferedStream bs = new BufferedStream(fs);
BufferedStream bs2 = new BufferedStream(fs2);
while (fs.Read(data, 0, data.Length) > 0)
{
fs2.Write(data, 0, data.Length);
fs2.Flush();
}
}
}
return true;
}
catch (Exception ex)
{
throw ex;
}
}
5:在web.config中配置这个自定义控件
6:在页面中直接使用。
三:一个新的字典集合。可以得到键和值。
KeyValuePair<int, bool> index = (KeyValuePair<int, bool>)e.Item.DataItem;
index.Key键的值
index.Value值
可以直接使用
四:创建实体的时候,没必要定义多个构造函数,可以通过简单的创建对象的方式来解决这个问题。
OChart _ochart = new OChart()
{
CreateDateTime = DateTime.Now,
CreateUserId = CurrentAccount.AccountId,
DealerId = dealer.DealerId,
IsActive = 1,
IsCustom = 0,
Status = 1
};
如果一些值不是直接得到的,可以先定义一个变量,然后在{属性=变量值}。
或者是定义完以后单独赋值,例如创建完成以后,再_ochart.属性=值。
五:动态类型
dynamic _dealerHistory = new ExpandoObject();属性和方法自己动态添加的
添加属性
_dealerHistory.属性一=值。然后_dealerHistory就有属性一这个属性了
添加方法
_dealerHistory.Increment = (Action)(() => { _dealerHistory.number++; });
添加事件
_dealerHistory.sampleEvent += new EventHandler(SampleHandler);
六:匿名方法lambda表达式 DasAccountInfoService.FindAll(_query).ForEach(p =>{方法体})的使用。
七:反射的使用
Type _type = typeof(DealerInfo);
List<PropertyInfo> _propertyList = _type.GetProperties().ToList();
PropertyInfo _temp = _propertyList.Find(k => { return k.Name == "字段名"; });
得到一个对象属性的值
_temp.GetValue(_dealerHistory, null).ToString()
设置一个对象属性的值
_temp.SetValue(_dealerHistory, Convert.ChangeType(_value, _property.PropertyType), null)
动态加载一个类
Type _assembly = Assembly.LoadFrom(".dll路径").GetType(string.Format("{0}.{1}", .dll的命名空间,"类名"));
object _invokeResult = _assembly.InvokeMember(方法名, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args);
八:枚举的使用,得到枚举的自定义说明
1:创建一个自定义的属性类
public class EnumDescriptionAttribute : Attribute
{
public string Description;
}
2:利用自定义属性,定义一个枚举,加上自定义属性的值,注意这里使用的是EnumDescription不是EnumDescriptionAttribute 。
public enum OChartStatusEnmu
{
[EnumDescription(Description = "草稿")]
Draft = 0,
[EnumDescription(Description = "正常")]
Enabled = 1
}
3:写一个方法得到枚举值上面的文字描述
public static class EnumDescription
{
public static string GetDescription<T>(T enumField)
{
return ((EnumDescriptionAttribute)typeof(T).GetField(enumField.ToString()).GetCustomAttributes(false)[0]).Description;
}
}
4:调用这个方法得到文字描述
EnumDescription.GetDescription<OChartStatusEnmu>((OChartStatusEnmu)_dasAccountInfo.Status)
不调用方法,根据数据库中保存的字段id,得到文字。
<%#((EnumDescriptionAttribute)typeof(ApproveEnum).GetField(Enum.GetName(typeof(ApproveEnum), Eval("ApproveStatus"))).GetCustomAttributes(false)[0]).Description%>
九,枚举使用,得到枚举值的数据库中对应的字段值
1:自定义一个属性
public class EnumDescriptionFromDBAttribute : Attribute
{
public string DescriptionField;
public string EntityServiceType;
}
2:定义一个类,使用一个方法得到该值对应数据库中的值
public class EnumDescriptionValueFromDB
{
static string _serviceAssembly = ConfigurationManager.AppSettings["ServiceAssembly"];
static string _serviceNameSpace = ConfigurationManager.AppSettings["ServiceNameSpace"];
public static string GetDescription(EnumDescriptionFromDBAttribute attribute, string methodName, object[] args)
{
Type _assembly = Assembly.LoadFrom(_serviceAssembly).GetType(string.Format("{0}.{1}", _serviceNameSpace, attribute.EntityServiceType));
object _invokeResult = _assembly.InvokeMember(methodName, BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.Static, null, null, args);
if (_invokeResult != null)
{
Type _type = _invokeResult.GetType();
PropertyInfo _property = _type.GetProperty(attribute.DescriptionField);
if (_property != null)
{
object value = _property.GetValue(_invokeResult, null);
return value == null ? null : value.ToString();
}
}
return null;
}
3:在实体类的属性值上面加上自定义的属性
[EnumDescriptionFromDBAttribute(DescriptionField = "EducationName", EntityServiceType = "EducationService")]
public int Education
{
get { return _education; }
set { _education = value; }
}
4:调用方法得到数据库中对应的字段
UserrInfoCompare _item = new UserrInfoCompare();
PropertyInfo _property = typeof(UserInfo).GetProperty(p);
_item.Name = ((EnumDescriptionAttribute)_property.GetCustomAttributes(typeof(EnumDescriptionAttribute), true)[0]).Description;
_item.OldContent = _property.GetValue(_oldContent, null).ToString();
if (_property.GetCustomAttributes(typeof(EnumDescriptionFromDBAttribute), true).Length != 0)
{
EnumDescriptionFromDBAttribute _attr = ((EnumDescriptionFromDBAttribute)_property.GetCustomAttributes(typeof(EnumDescriptionFromDBAttribute), true)[0]);
int _enum = 0;
if (int.TryParse(_property.GetValue(_oldContent, null).ToString(), out _enum))
{
_item.OldContent = EnumDescriptionValueFromDB.GetDescription(_attr, "FindById", new object[] { _enum });
}
if (int.TryParse(_property.GetValue(_ModifyContent, null).ToString(), out _enum))
{
_item.ModifyContent = EnumDescriptionValueFromDB.GetDescription(_attr, "FindById", new object[] { _enum });
}
}