5月 20

ASP.NET Web API(本文简称Web API),是基于ASP.NET平台构建RESTful应用程序的框架。可以说 Web API 就是为在.NET平台下构建RESTful应用程序而生的。

协议

public class Contact
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string PhoneNo { get; set; }
    public string EmailAddress { get; set; }
    public string Address { get; set; }
}

ContactsController  

public class ContactsController : ApiController
{
  
  
    static List<Contact> contacts;
    static int counter = 2;
  
    static ContactsController()
    {
        contacts = new List<Contact>();
        contacts.Add(new Contact
        {
            Id = "001",
            Name = "张三",
            PhoneNo = "0512-12345678",
            EmailAddress = "zhangsan@gmail.com",
            Address = "江苏省苏州市星湖街328号"
        });
        contacts.Add(new Contact
        {
            Id = "002",
            Name = "李四",
            PhoneNo = "0512-23456789",
            EmailAddress = "lisi@gmail.com",
            Address = "江苏省苏州市金鸡湖大道328号"
        });
    }
  
  
    public IEnumerable<Contact> Get(string id = null)
    {
        return from contact in contacts
               where contact.Id == id || string.IsNullOrEmpty(id)
               select contact;
    }
  
    public void Post(Contact contact)
    {
        Interlocked.Increment(ref counter);
        contact.Id = counter.ToString("D3");
        contacts.Add(contact);
    }
  
    public void Put(Contact contact)
    {
        contacts.Remove(contacts.First(c => c.Id == contact.Id));
        contacts.Add(contact);
    }
  
    public void Delete(string id)
    {
        contacts.Remove(contacts.First(c => c.Id == id));
    }
}

Global注册路由

public class Global : System.Web.HttpApplication
{
  
    protected void Application_Start(object sender, EventArgs e)
    {
        GlobalConfiguration.Configuration.Routes.MapHttpRoute(
           name: "DefaultApi",
           routeTemplate: "api/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional });
    }
}

需要引用的dll

System.Web.Http.dll 
System.Net.Formatting.Http.dll 
System.Web.Http.WebHost.dll 
System.Net.Http.dll

http://www.cnblogs.com/artech/p/web-api-sample.html

written by ocean

5月 20

ASP.NET MVC出来也有一阵子.之前也有写过 150行C#代码实现自己的MVC

打算学习一下restful,结果发现是基于MVC的.只能先学习一下了

 

 

ASP.NET MVC由以下两个核心组成部分构成:

  1. 一个名为UrlRoutingModule的自定义HttpModule,用来解析Controller与Action名称;

  2. 一个名为MvcHandler的自定义HttpHandler,用来实现对Controller的激活和Action的执行;

整个ASP.NET MVC系统的路由信息全部存放在RoteTable这个类的静态变量Routes(为一个RouteCollection类型)中,网站开始运行时,在Application_Start中对路由进行注册:

public static void RegisterRoutes(RouteCollection routes)         
{         
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");         
                    
    routes.MapRoute(         
                    
        //是路由的名称,这个名称在应用程序的路由的集合(routes对象)中是唯一的,如果重名生成时就会报错。         
        name: "Default",         
                    
        //代表的是路由的 URL表达式。         
        url: "{controller}/{action}/{id}",         
                    
        //声明了一个包含路由值的object匿名对象         
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }         
    );          
}

 IgnoreRoute()是RouteCollection路由表类的扩展方法,用于忽略指定的路由请求。这句意思是忽略对扩展名为.axd文件的请求

 

 

路由匹配规则

  {controller}对应控制器的名称,这里规定是控制器全名去掉Controller后缀的部份,CategoryController即Category

  {action}对应控制器内的Action方法的名称

URL表达式都是相对的,不包括主机域名部份(比如http://www.xxx.com)。{}保存的是占位符,“/”,“.”则用来作为分隔符,什么都有没则是静态内容

URL /category/showcategory/1000  匹配 "{controller}/{action}/{id}"。

URL /product/2012/4/28.html         匹配  “/product/{year}/{month}/{day}.html”  ,诸如此类。

 

 

MVC整个网站目录和特殊文件

  • App_Data

    • 这个目录跟我们一般的ASP.NET website是一样的,用于存放数据。

  • Content

    • 这个目录是建议用来存放一下资源文件的。例如CSS、JS、图片等等。当然你不愿意的话,完全可以不放到这里来。

  • Controllers

    • 这个目录是建议将Controller类都放到这里来,方便管理。Controller类的命名必须以Controller结尾,例如一个名为Home的Controller则要命名为HomeController。

  • Models

    • 这个目录是建议用来存放你的业务实体、数据访问层代码的类的。当然,更好的做法我觉得应该是将Models独立为一个类库。

  • Views

    • 在默认情况下,所有的view文件都必须放到这个目录下来,每一个Controller对应一个子目录,而且子目录的命名必须以Controller的命名一样。例如,HomeController的view就应该放到Home子目录中。我们见到Views目录下还有一个Shared的子目录,这个子目录是用于存放一些共享的view的,例如Error.aspx和Site.Master。Controller在Views\ControllerNmae 中找不到指定的view的时候,会到Shared中去寻找。

 

啥都没有写个例子好.简单的例子

 

添加路由规则

routes.MapRoute("User", "user/{id}", new { controller = "Home", action = "User" });

~/Controllers/HomeController.cs 添加Action

public ActionResult User(int id)   
{   
    TestDemo.MVC.Models.User user = new TestDemo.MVC.Models.User() {   
     UserId=id,   
     UserName = "UserName"+id,   
    };   
    return View(user);   
}

~/Models/User.cs 添加Model

public class User   
{   
    public int UserId { get; set; }   
    public string UserName { get; set; }   
}

 ~/Views/Home/User.cshtml 添加View

@model TestDemo.MVC.Models.User   
@{  
    ViewBag.Title = "User";  
}   
<h2>User</h2>   
UserId: @Model.UserId,UserName:@Model.UserName

 访问路径

http://localhost:5949/user/3

记录路由规则加在前面

 

written by ocean

5月 19

一个好的系统肯定会有一个好的日志模块.

之前也一直使用log4net,当然每次嫌配置麻烦,做过零配置使用log4net

依然觉得麻烦,不希望引用第三方库.只能自己写一个喽

思路大概是这样的.

将日志存入到一个队列中,定时写入数据库或者文本文件以便于提升效率

使用了接口,用来实现扩展.

public interface ILog<T>   
{   
    void Log(LogLevel logLevel, T logInfo);   
           
    void Info(T logInfo);   
    void Debug(T logInfo);   
    void Error(T logInfo);   
    void Message(T logInfo);    
}

public class LogDataBase<T> : LogBase<T>, ILog<T>   
{   
    public LogDataBase(LogLevel currentLogLevel)   
    {   
        this.LogLevel = currentLogLevel;   
    }   
           
    public LogDataBase(LogLevel currentLogLevel, Action<Queue<T>> saveFunction):base()   
    {   
        this.LogLevel = currentLogLevel;   
        this.SaveFunction = saveFunction;   
    }    
}
public class LogFile<T> :LogBase<T>, ILog<T>   
{   
                
    public LogFile(LogLevel currentLogLevel)   
    {   
        this.LogLevel = currentLogLevel;   
    }   
           
    public LogFile(LogLevel currentLogLevel, Action<Queue<T>> saveFunction):base()   
    {   
        this.LogLevel = currentLogLevel;   
        this.SaveFunction = saveFunction;   
    }      
}
public class LogInfo   
{   
    public string Message { get; set; }   
    public DateTime Time { get; set; }    
    public Exception Exception { get; set; }    
}   
          
public class LogInfo<T>   
{   
          
    public string Message { get; set; }   
    public DateTime Time { get; set; }   
    public Exception Exception { get; set; }   
          
    public T Data { get; set; }   
}
public enum LogLevel   
{   
    /// <summary>   
    /// Used to always log a message regardless of loglevel   
    /// </summary>   
    Message=999,   
          
          
    /// <summary>   
    /// Debug level   
    /// </summary>   
    Debug=10,   
          
          
    /// <summary>   
    /// Info level   
    /// </summary>   
    Info=20,   
          
          
    /// <summary>   
    /// Warn level   
    /// </summary>   
    Warn=30,   
          
          
    /// <summary>   
    /// Error level   
    /// </summary>   
    Error=40,    
               
};
public abstract class LogBase<T>   
{   
    private Queue<T> queue = null;   
    private Queue<T> saveQueue = null;   
    protected LogLevel LogLevel = LogLevel.Message;   
    private object obj = new object();   
    private Thread thread = null;   
    private int BufferSecond =1000;   
    /// <summary>   
    /// 是否保存完成   
    /// </summary>   
    private bool IsSaveComplete = true;   
    /// <summary>   
    /// 是否停止   
    /// </summary>   
    private bool IsStop = false;   
          
    protected Action<Queue<T>> SaveFunction = null;    
          
    public LogBase() {   
        queue = new Queue<T>();   
        thread = new Thread(new ThreadStart(SaveLog2Store));   
        thread.Start();   
    }    
          
    private void SaveLog2Store()   
    {   
        while (true)   
        {   
          
            lock (obj)   
            {   
                if (IsSaveComplete) //上次的保存完成了   
                {   
                    saveQueue = queue;   
                    queue = new Queue<T>();   
          
                    this.IsSaveComplete = false;   
                    this.Flush();   
                    this.IsSaveComplete = true;   
          
                    if (IsStop)   
                        break;   
                }   
            }   
            Thread.Sleep(BufferSecond);   
        }   
    }   
          
    ~LogBase()   
    {   
        IsStop = true;   
    }   
          
          
    public void Log(LogLevel logLevel, T logInfo)   
    {   
        if (logLevel >= this.LogLevel) //大于设计的等级才记录   
        {   
            lock (obj)   
            {   
                this.queue.Enqueue(logInfo);   
            }   
        }   
    }   
          
          
    public void Info(T logInfo)   
    {   
        this.Log(LogLevel.Info, logInfo);   
    }   
          
    public void Debug(T logInfo)   
    {   
        this.Log(LogLevel.Debug, logInfo);   
    }   
          
    public void Error(T logInfo)   
    {   
        this.Log(LogLevel.Error, logInfo);   
    }   
          
    public void Message(T logInfo)   
    {   
        this.Log(LogLevel.Message, logInfo);   
    }   
    public void Warn(T logInfo)   
    {   
        this.Log(LogLevel.Warn, logInfo);   
    }   
          
               
    public  void Flush()   
    {   
        if (saveQueue != null && saveQueue.Count > 0)   
        {    
            SaveFunction(saveQueue);   
        }   
    }    
          
}

其实代码很简单,实现了非可靠的日志系统(不可靠在队列中数据未保存时突然掉电等意外)

 

使用的时候,需要自定义初始化方法

优点是灵活,用户完全可以自定义

缺点呢就是用户需要自己定义,增加工作量

这个有时间会改成可配置那种

public class LogFactory  
{  
   
    /// <summary>  
    /// System Log Save to File  
    /// </summary>  
    public static ILog<LogInfo> System = new LogFile<LogInfo>(LogLevel.Debug, SaveSystemLog);  
    private static void SaveSystemLog(Queue<LogInfo> queue)  
    {  
        string folderPath = @"C:\Logs\itrazv2";  
        string fileName = DateTime.Now.ToString("yyyy-MM-dd-HH") + ".log";  
        if (!Directory.Exists(folderPath))  
        {  
            Directory.CreateDirectory(folderPath);  
        }  
        string filePath = Path.Combine(folderPath, fileName);   
        if (queue != null && queue.Count > 0)  
        {  
            StringBuilder sb = new StringBuilder();  
            foreach (var item in queue)  
            {  
                sb.AppendLine(string.Format("==============【{0}】==============\r\n{1}\r\n{2}\r\n{3}\r\n{4}",  
                                item.Time.ToString("yyyy-MM-dd HH:mm:ss:fff"),  
                                item.Message,  
                                item.Exception.Message,  
                                item.Exception.Source,  
                                item.Exception.StackTrace  
            ));  
            }  
            if (sb.Length > 0)  
            {  
                File.AppendAllText(filePath, sb.ToString(),Encoding.UTF8);  
            }  
        }  
    }  
   
   
   
    /// <summary>  
    /// System Log Save to File  
    /// </summary>  
    public static ILog<OpLogInfo> Operator = new LogDataBase<OpLogInfo>(LogLevel.Debug, SaveOperatorLog);  
    private static void SaveOperatorLog(Queue<OpLogInfo> queue)  
    {  
   
        if (queue != null && queue.Count > 0)  
        {  
            StringBuilder sb = new StringBuilder();  
            foreach (var item in queue)  
            {  
                AddOpLogInfo(item);  
            }  
        }  
    }  
    private static void AddOpLogInfo(OpLogInfo opLogInfo)  
    {  
        try
        {  
            SQLHelper sqlHelper = new SQLHelper(SQLHelper.DefaultConnectionString);  
            string sql = @"INSERT INTO [OperatorLog]  
                                        (      
                                                [OperatorUserId],    
                                                [OperatorUserName],    
                                                [FunctionId],    
                                                [Data],    
                                                [CreateDate]     
                                        )  
                                        VALUES  
                                        (        
                                                @OperatorUserId,     
                                                @OperatorUserName,     
                                                @FunctionId,     
                                                @Data,     
                                                @CreateDate      
                                        );";  
            DbCommand dbCommand = sqlHelper.GetSqlStringCommand(sql);  
            sqlHelper.AddInParameter(dbCommand, "@OperatorUserId", DbType.Int32, opLogInfo.OperatorUserId);  
            sqlHelper.AddInParameter(dbCommand, "@OperatorUserName", DbType.String, opLogInfo.OperatorUserName);  
            sqlHelper.AddInParameter(dbCommand, "@FunctionId", DbType.Int32, opLogInfo.FunctionId);  
            sqlHelper.AddInParameter(dbCommand, "@Data", DbType.String, opLogInfo.Data??string.Empty);  
            sqlHelper.AddInParameter(dbCommand, "@CreateDate", DbType.DateTime, opLogInfo.CreateDate);  
            sqlHelper.ExecuteScalar(dbCommand);  
        }  
        catch (Exception ex)  
        {  
            LogFactory.System.Error(ex);  
        }  
   
    }  
}
public static class LogCustomerMethod  
{  
    public static void Error(this ILog<LogInfo> log, Exception ex)  
    {   
        LogInfo logInfo = new LogInfo();  
        logInfo.Time = DateTime.Now;  
        logInfo.Exception = ex;  
        LogFactory.System.Error(logInfo);  
    }  
   
    public static void Message(this ILog<OpLogInfo> log, int OperatorUserId,  
        string OperatorUserName,  
        int FunctionId,  
        string Data)  
    {  
        OpLogInfo opLogInfo = new OpLogInfo();  
        opLogInfo.OperatorUserId = OperatorUserId;  
        opLogInfo.OperatorUserName = OperatorUserName;  
        opLogInfo.FunctionId = FunctionId;  
        opLogInfo.Data = Data;  
        opLogInfo.CreateDate = DateTime.Now;  
        LogFactory.Operator.Message(opLogInfo);  
    }  
   
}  
   
public class OpLogInfo {  
          
    public int  OperatorUserId { get; set; }   
    public string  OperatorUserName { get; set; }   
    public int FunctionId { get; set; }   
    public string  Data { get; set; }   
    public DateTime CreateDate { get; set; }     
}

 

 调用

LogFactory.System.Error(ex);

 

网上找了一些方案

  1. 直接记录为txt/xml文件

  2. Windows Event Log

  3. 当前进程的本地队列

  4. MSMQ

  5. 独立进程中的WCF服务(进程间管道)

  6. 独立进程中的WCF服务(异步调用方式)

  7. 数据库

  8. Sql server的Service Broker

  9. MongoDB(或者类似的NoSQL数据库)

written by ocean

5月 09

1965年Vladmir Levenshtein创造了莱温斯坦算法.

该算法主要 用来表述一个 字符串到另外 一个字符串需要 移动的次数. 使用该算法我们 可以测量两个 字符串的 相似性.

ant==>aunt     LD=1   因为只需要加'u'

Samantha==>Sam    LD=5   需要移除5个字母

Flomax==>Volmax    LD=3 需要更改前3 个字母

算法 简单实现

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(LevenshteinDistance.Compute("aunt", "ant"));
        Console.WriteLine(LevenshteinDistance.Compute("Sam", "Samantha"));
        Console.WriteLine(LevenshteinDistance.Compute("flomax", "volmax"));
        Console.WriteLine(LevenshteinDistance.Compute("www.wx6.org", "ciyu.wx6.org"));
  
        Console.Read();
    }
}
  
  
  
/// <summary>
/// Contains approximate string matching
/// </summary>
static class LevenshteinDistance
{
    /// <summary>
    /// Compute the distance between two strings.
    /// </summary>
    public static int Compute(string s, string t)
    {
        int n = s.Length;
        int m = t.Length;
        int[,] d = new int[n + 1, m + 1];
  
        // Step 1
        if (n == 0)
        {
            return m;
        }
  
        if (m == 0)
        {
            return n;
        }
  
        // Step 2
        for (int i = 0; i <= n; d[i, 0] = i++)
        {
        }
  
        for (int j = 0; j <= m; d[0, j] = j++)
        {
        }
  
        // Step 3
        for (int i = 1; i <= n; i++)
        {
            //Step 4
            for (int j = 1; j <= m; j++)
            {
                // Step 5
                int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;
  
                // Step 6
                d[i, j] = Math.Min(
                    Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                    d[i - 1, j - 1] + cost);
            }
        }
        // Step 7
        return d[n, m];
    }
}

该算法 有很大的意义, 去除重复 文本

written by ocean

5月 08

要做一个AD服务器相关的项目,先做一点只是储备吧

LDAP(轻量级目录访问协议,Lightweight Directory Access Protocol)是实现提供被称为目录服务的信息服务。目录服务是一种特殊的数据库系统,其专门针对读取,浏览和搜索操作进行了特定的优化。目录一般用来包含描述性的,基于属性的信息并支持精细复杂的过滤能力。目录一般不支持通用数据库针对大量更新操作操作需要的复杂的事务管理或回卷策略。而目录服务的更新则一般都非常简单。这种目录可以存储包括个人信息、web链结、jpeg图像等各种信息。为了访问存储在目录中的信息,就需要使用运行在TCP/IP 之上的访问协议—LDAP。

  LDAP目录中的信息是是按照树型结构组织,具体信息存储在条目(entry)的数据结构中。条目相当于关系数据库中表的记录;条目是具有区别名DN (Distinguished Name)的属性(Attribute),DN是用来引用条目的,DN相当于关系数据库表中的关键字(Primary Key)。属性由类型(Type)和一个或多个值(Values)组成,相当于关系数据库中的字段(Field)由字段名和数据类型组成,只是为了方便检索的需要,LDAP中的Type可以有多个Value,而不是关系数据库中为降低数据的冗余性要求实现的各个域必须是不相关的。LDAP中条目的组织一般按照地理位置和组织关系进行组织,非常的直观。LDAP把数据存放在文件中,为提高效率可以使用基于索引的文件数据库,而不是关系数据库。类型的一个例子就是mail,其值将是一个电子邮件地址。

    LDAP的信息是以树型结构存储的,在树根一般定义国家(c=CN)或域名(dc=com),在其下则往往定义一个或多个组织 (organization)(o=Acme)或组织单元(organizational units) (ou=People)。一个组织单元可能包含诸如所有雇员、大楼内的所有打印机等信息。此外,LDAP支持对条目能够和必须支持哪些属性进行控制,这是有一个特殊的称为对象类别(objectClass)的属性来实现的。该属性的值决定了该条目必须遵循的一些规则,其规定了该条目能够及至少应该包含哪些属性。例如:inetorgPerson对象类需要支持sn(surname)和cn(common name)属性,但也可以包含可选的如邮件,电话号码等属性。

LDAP简称对应

o– organization(组织-公司)

ou – organization unit(组织单元-部门)

c – countryName(国家)

dc – domainComponent(域名)

sn – suer name(真实名称)

cn – common name(常用名称)

/// <summary>
/// 验证登录
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
public static bool Login(string userName, string password)
{
    using (DirectoryEntry deUser = new DirectoryEntry(string.Format("LDAP://{0}", DOMAIN), userName, password, AuthenticationTypes.Secure))
    {
        try
        {
            // The NativeObject call on the DirectoryEntry object entry is an attempt to bind to the object in the directory.
            // Since this call forces authentication, you will get an error if the user does not exist.
            // If the user is a valid user in the domain, the call will succeed.
            Object native = deUser.NativeObject;  
            return true;
        }
        catch
        {
            return false;
        }
    }
}

/// <summary>
/// 获取某用户的所有组
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
public static string[] GetAllGroupsByUser(string username)
{
   var entry = new DirectoryEntry(string.Format("LDAP://{0}", DOMAIN), USERNAME, PASSWORD); 
    DirectorySearcher ds = new DirectorySearcher(entry);
    ds.Filter = "(&(sAMAccountName=" + username + "))";
    ds.PropertiesToLoad.Add("memberof");
    SearchResult r = ds.FindOne();
    if (r.Properties["memberof"] == null)
    {
        return (null);
    }
    string[] results = new string[r.Properties["memberof"].Count + 1];
    for (int i = 0; i < r.Properties["memberof"].Count; i++)
    {
        string theGroupPath = r.Properties["memberof"][i].ToString();
        results[i] = theGroupPath.Substring(3, theGroupPath.IndexOf(",") - 3);
    } 
    return (results);
}

/// <summary>
/// 获取某组的所有用户
/// </summary>
/// <param name="groupname"></param>
/// <returns></returns>
public static string[] GetUsersByGroup(string groupname)
{
    var entry = new DirectoryEntry(string.Format("LDAP://{0}", DOMAIN), USERNAME, PASSWORD);
    DirectorySearcher ds = new DirectorySearcher(entry);
    ds.Filter = "(&(objectClass=group)(cn=" + groupname + "))";
    ds.PropertiesToLoad.Add("member");
    SearchResult r = ds.FindOne();
     
    if (r.Properties["member"] == null)
    {
        return (null);
    }
     
    string[] results = new string[r.Properties["member"].Count];
    for (int i = 0; i < r.Properties["member"].Count; i++)
    {
        string theGroupPath = r.Properties["member"][i].ToString();
        results[i] = theGroupPath.Substring(3, theGroupPath.IndexOf(",") - 3);
    }
    return (results);
}

    public class ADUserInfo
    {
 
        public string CN { get; set; }
        public string SN { get; set; }
        public string ObjectsId { get; set; }
        public string ObjectGuid { get; set; }
        public string DisplayName { get; set; }
        public string ADSPath { get; set; }
 
        //public string CostCenter { get; set; }
        //public string Country { get; set; }
        //public string City { get; set; }
        //public string Name { get; set; }
        //public string Alias { get; set; }
        //public string OfficeAddress { get; set; }
        //public string ZipCode { get; set; }
        //public string Title { get; set; }
        //public string Company { get; set; }
        //public string Department { get; set; }
        //public string Phone { get; set; }
        //public string Email { get; set; }
        //public string EmployeeNumber { get; set; }
    }
      
      
        /// <summary>
        /// 单个用户登陆后,得到所需的信息
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        private static ADUserInfo GetUserInfoFromADServer(string username)
        {
            DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", DOMAIN), USERNAME, PASSWORD);
            DirectorySearcher ds = new DirectorySearcher(entry);
            ds.Filter = "(&(sAMAccountName=" + username + "))";
            SearchResult result = ds.FindOne();
  
            if (null != result)
            {
                ADUserInfo aduserInfo = new ADUserInfo();
                if (result.Properties.Contains("objectguid")) aduserInfo.ObjectGuid = BitConverter.ToString((byte[])result.Properties["objectguid"][0]);
                if (result.Properties.Contains("displayname")) aduserInfo.DisplayName = result.Properties["displayname"][0].ToString();
                if (result.Properties.Contains("cn")) aduserInfo.CN = result.Properties["cn"][0].ToString();
                if (result.Properties.Contains("sn")) aduserInfo.SN = result.Properties["sn"][0].ToString();
                if (result.Properties.Contains("adspath")) aduserInfo.ADSPath = result.Properties["adspath"][0].ToString();
                return aduserInfo;
            }
            return null;
        }

public class ADPropertyClass
  {
      public ADPropertyClass() { }
      public ADPropertyClass(string costCneter1, string country, string city, string name, string alias, string officeAddress, string state, string zipCode, string title, string company, string department, string office, string phone, string email, string employeeNumber)
      {
          this.costCenter = costCneter1;
          this.country = country;
          this.city = city;
          this.name = name;
          this.alias = alias;
          this.office = office;
          this.officeAddress = officeAddress;
          this.state = state;
          this.zipCode = zipCode;
          this.title = title;
          this.company = company;
          this.department = department;
          this.phone = phone;
          this.email = email;
          this.employeeNumber = employeeNumber;
      }
      private string costCenter;
      public string CostCenter { get { return costCenter; } set { costCenter = value; } }
      private string country;
      public string Country { get { return country; } set { country = value; } }
      private string city;
      public string City { get { return city; } set { city = value; } }
      private string name;
      public string Name { get { return name; } set { name = value; } }
      private string alias;
      public string Alias { get { return alias; } set { alias = value; } }
      private string officeAddress;
      public string OfficeAddress { get { return officeAddress; } set { officeAddress = value; } }
      private string state;
      public string State { get { return state; } set { state = value; } }
      private string zipCode;
      public string ZipCode { get { return zipCode; } set { zipCode = value; } }
      private string title;
      public string Title { get { return title; } set { title = value; } }
      private string company;
      public string Company { get { return company; } set { company = value; } }
      private string department;
      public string Department { get { return department; } set { department = value; } }
      private string office;
      public string Office { get { return office; } set { office = value; } }
      private string phone;
      public string Phone { get { return phone; } set { phone = value; } }
      private string email;
      public string Email { get { return email; } set { email = value; } }
      private string employeeNumber;
      public string EmployeeNumber { get { return employeeNumber; } set { employeeNumber = value; } }
  }

written by ocean

5月 07

之前有简单用过EF5.0

升级6.0之后发现有的API不能用了,记录一下

Add

using (var db = new DB_TestEntities())
{
    Pow_User user = new Pow_User();
    user.UserId = 5;
    user.UserName = "ocean";
    user.UserTypeId = 1;
    user.UpdatedDate = DateTime.Now;
    user.Password = "password";
    user.PasswordSalt = "blog.wx6.org";
    user.CreatedDate = DateTime.Now;
    db.Pow_User.Add(user);
    db.SaveChanges();
}

其中userid 是自增主键, 测试下来发现不管 是否指定,都是按照自增顺序 来的

Select

using (var db = new DB_TestEntities())
{
    var user = db.Pow_User.Find(2);
}
List<Pow_User> list = null;
using (var db = new DB_TestEntities())
{
    list = (from s in db.Pow_User
            where s.UserId > 0
            select s).ToList<Pow_User>();
}

Update

using (var db = new DB_TestEntities())
{
    var user = db.Pow_User.Find(2);
    user.UserName = "ocean test";
    db.Entry(user).State = EntityState.Modified;
    db.SaveChanges();
}

Delete

using (var db = new DB_TestEntities())
{ 
    var user = db.Pow_User.Find(3);
    db.Pow_User.Remove(user);
    db.SaveChanges();
}

Delete可以看出来是先获取 再删除,还有 一种 提高性能的方式

using (var db = new DB_TestEntities())
{
    Pow_User user = new Pow_User() { UserId = 2 };
    db.Entry(user).State = EntityState.Deleted;
    db.SaveChanges();
}

分分钟做了个仓储模式的基类(有待考证是否正确)

未做测试未做鉴定,仅仅编译通过

public interface IRepository<T> where T : class
{
    IList<T> FindAll(Func<T, bool> func, int pageIndex = 1, int pageSize = 2147483647);
    T Find(params object[] keyValues);
    void Add(T entity);
    void Delete(T entity);
    void Update(T entity);
}
public class Repository<T> : IRepository<T> where T : class
{
    public DbContext db;
    public Repository(DbContext db)
    {
        this.db = db;
    }
 
    public Repository()
    {
        this.db = new DB_WX6Entities();
    }
 
    public IList<T> FindAll(Func<T, bool> func, int pageIndex = 1, int pageSize = 2147483647)
    {
        List<T> list = null;
        using (var db = new DB_WX6Entities())
        {
            if (func != null)
                list = (from s in db.Set<T>()
                        where func(s)
                        select s).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList<T>();
            else
                list = (from s in db.Set<T>()
                        select s).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList<T>();
 
        }
        return list;
    }
 
    public T Find(params object[] keyValues)
    {
        return db.Set<T>().Find(keyValues);
    }
 
    public void Add(T entity)
    {
        db.Entry(entity).State = EntityState.Added;
        db.SaveChanges();
    }
    public void Delete(T entity)
    {
        db.Entry(entity).State = EntityState.Deleted;
        db.SaveChanges();
    }
    public void Update(T entity)
    {
        db.Entry(entity).State = EntityState.Modified;
        db.SaveChanges();
    }
}

written by ocean

5月 06

安装python2.7

https://www.python.org/downloads/

将安装地址放进环境变量

C:\Python27;C:\Python27\Scripts

另外如果希望直接运行 *.py,只需再修改另一个环境变量PATHEXT:

.PY;.PYM

安装 Django

先去 Django 官网(https://www.djangoproject.com/) 上下载包

执行

python setup.py install

报错

ImportError: No module named setuptools

缺少setuptools

下载  https://pypi.python.org/pypi/setuptools

安装出错

解决办法是:

编辑Python安装目录下的mimetypes.py文件,在文件中对应位置增加红色部分内容

import os

import sys

#the following two line solve the "python ez_setup.py" install error

reload(sys)

sys.setdefaultencoding('gb18030')

#end

import posixpath

import urllib,

保存后,重新执行ez_setup.py,既可顺利完成安装。

检验安装是否成功

>>> import django 
>>> print django.get_version()

创建项目

django-admin startproject BAE

接下来,验证下我们的项目是否正常,进到 PythonProject 目录下,输入下边命令:

python manage.py runserver

在浏览器中输入 127.0.0.1:8000 后,出现了我们第一个基于 Django 框架的 Python 的项目

written by ocean

5月 05

需要下载

pyodbc

https://code.google.com/p/pyodbc/downloads

Connection

DSN = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ=D:\\PythonSC\\Test\\blog.wx6.org.mdb';
cnxn = pyodbc.connect(DSN);
cursor = cnxn.cursor()

Create

cursor.execute("Insert INTO [tb_article] ([Category],[Title],[Content],[AddDate]) VALUES (?,?,?,?)",
               "category",
               "title",
               "content",
               datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
cnxn.commit()

Delete

cursor.execute("delete from tb_article where id=?", 100)
print cursor.rowcount, 'rows deleted'
cnxn.commit()

Update

cursor.execute("update tb_article set title=? where id=?",'updateTitle', 101)
print cursor.rowcount, 'rows updated'
cnxn.commit()

Select

cursor.execute("select title from tb_article where id=?",100)
while 1:
    row = cursor.fetchone()
    if not row:
        break
    print 'title:', row.title

written by ocean