随笔 - 4  文章 - 2 评论 - 3 trackbacks - 0
<2012年2月>
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910

昵称:_Sin
园龄:4年1个月
粉丝:0
关注:1

搜索

 
 

常用链接

我的标签

随笔档案

最新评论

做unity3d 的时候 要用JSON传数据,国外一个开源网站上找到的  http://www.opensource.org/licenses/lgpl-2.1.php

对自带类增加了个字符串属性  ,Mark 一下, 以后可能会用到

 

 

对JSon进行解析 

string encodedString = "[{\"strName\":\"0.5\",\"strScore\":300,\"strRank\":1},{\"strName\":\"sin\",\"strScore\":250,\"strRank\":2}]";

 int tempIndex = 0;
        List<Rank> ranklist = DeserializeJson(encodedString);        
        foreach (Rank myr in ranklist)
        {
            tempIndex++;
            print(myr.strName + myr.strRank + myr.strScore);
            GameObject tempgo = (GameObject)Instantiate(RowTempgo);
            tempgo.transform.parent = RankPanelgo.transform;
            tempgo.transform.localPosition = new Vector3(0, -20f - 8 * tempIndex, 0);
            tempgo.transform.localScale = new Vector3(1, 1, 1);
            SpriteText stname = tempgo.transform.FindChild("Name").GetComponent<SpriteText>();
            stname.Text = myr.strName;
            SpriteText strank = tempgo.transform.FindChild("Rank").GetComponent<SpriteText>();
            strank.Text = myr.strRank;
            SpriteText stscore = tempgo.transform.FindChild("Score").GetComponent<SpriteText>();
            stscore.Text = myr.strScore;
        }

    /// <summary>

    /// 此方法 目前只支持 两级, ,,三级或者多级需要 再写
    /// </summary>
    /// <param name="json"></param>
    /// <returns></returns>
    public List<Rank> DeserializeJson(string json)
    {
        List<Rank> tlist = new List<Rank>();
        JSONObject myjson = new JSONObject(json);
        //Debug.LogError("myjson.list.Count:" + myjson.list.Count.ToString());
        for (int i = 0; i < myjson.list.Count; i++)
        {
            JSONObject tempmyjson = (JSONObject)myjson.list[i];
            Dictionary<string, string> tempDict = tempmyjson.ToDictionary();
            Rank myrank = new Rank("", "", "");
            foreach (KeyValuePair<string, string> a in tempDict)
            {
                if (a.Key == "strName")
                {
                    myrank.strName = a.Value;
                }
                if (a.Key == "strScore")
                {
                    myrank.strScore = a.Value;
                }
                if (a.Key == "strRank")
                {
                    myrank.strRank = a.Value;
                }
            }
            tlist.Add(myrank);
        }
        return tlist;
    }
}
public class Rank
{
    public Rank(string name, string score, string rank)
    {
        strName = name;
        strScore = score;
        strRank = rank;
    }
    public string strName;
    public string strScore;
    public string strRank;
}

 ============================================下面是源码类==============================================

#define READABLE
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/*
 * http://www.opensource.org/licenses/lgpl-2.1.php
 * JSONObject class     only support simple data...
 * for use with Unity
 * Copyright Matt Schoen 2010
 */
public class Nullable
{
    //Extend this class if you want to use the syntax
    //  if(myObject)
    //to check if it is not null
    public static implicit operator bool(Nullable o)
    {
        return (object)o != null;
    }
}
public class JSONObject : Nullable {
const int MAX_DEPTH = 1000;
public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL }
public JSONObject parent;
public Type type = Type.NULL;
public ArrayList list = new ArrayList();
public ArrayList keys = new ArrayList();
public string str;
public double n;
public bool b;
public static JSONObject nullJO { get { return new JSONObject(JSONObject.Type.NULL); } }
public static JSONObject obj { get { return new JSONObject(JSONObject.Type.OBJECT); } }
public static JSONObject arr { get { return new JSONObject(JSONObject.Type.ARRAY); } }
public JSONObject(JSONObject.Type t) {
type = t;
switch(t) {
case Type.ARRAY:
list = new ArrayList();
break;
case Type.OBJECT:
list = new ArrayList();
keys = new ArrayList();
break;
}
}
public JSONObject(bool b) {
type = Type.BOOL;
this.b = b;
}
public JSONObject(float f) {
type = Type.NUMBER;
this.n = f;
}
public JSONObject(Dictionary<string, string> dic) {
type = Type.OBJECT;
foreach(KeyValuePair<string, string> kvp in dic){
keys.Add(kvp.Key);
list.Add(kvp.Value);
}
}
    public string strJson = "";
public JSONObject() { }
public JSONObject(string str) { //create a new JSONObject from a string (this will also create any children, and parse the whole string)
//Debug.Log(str);
        strJson = str;
if(str != null) {
#if(READABLE)
str = str.Replace("\\n", "");
str = str.Replace("\\t", "");
str = str.Replace("\\r", "");
str = str.Replace("\t", "");
str = str.Replace("\n", "");
str = str.Replace("\\", "");
#endif
if(str.Length > 0) {
if(string.Compare(str, "true", true) == 0) {
type = Type.BOOL;
b = true;
} else if(string.Compare(str, "false", true) == 0) {
type = Type.BOOL;
b = false;
} else if(str == "null") {
type = Type.NULL;
} else if(str[0] == '"') {
type = Type.STRING;
this.str = str.Substring(1, str.Length - 2);
} else {
try {
n = System.Convert.ToDouble(str);
type = Type.NUMBER;
} catch(System.FormatException) {
int token_tmp = 0;
/*
* Checking for the following formatting (www.json.org)
* object - {"field1":value,"field2":value}
* array - [value,value,value]
* value - string - "string"
* - number - 0.0
* - bool - true -or- false
* - null - null
*/
switch(str[0]) {
case '{':
type = Type.OBJECT;
keys = new ArrayList();
list = new ArrayList();
break;
case '[':
type = JSONObject.Type.ARRAY;
list = new ArrayList();
break;
default:
type = Type.NULL;
Debug.LogWarning("improper JSON formatting:" + str);
return;
}
int depth = 0;
bool openquote = false;
bool inProp = false;
for(int i = 1; i < str.Length; i++) {
if(str[i] == '\\') {
i++;
continue;
}
if(str[i] == '"')
openquote = !openquote;
if(str[i] == '[' || str[i] == '{')
depth++;
if(depth == 0 && !openquote) {
if(str[i] == ':' && !inProp) {
inProp = true;
try {
keys.Add(str.Substring(token_tmp + 2, i - token_tmp - 3));
} catch { Debug.Log(i + " - " + str.Length + " - " + str); }
token_tmp = i;
}
if(str[i] == ',') {
inProp = false;
list.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1)));
token_tmp = i;
}
if(str[i] == ']' || str[i] == '}')
list.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1)));
}
if(str[i] == ']' || str[i] == '}')
depth--;
}
}
}
}
} else {
type = Type.NULL; //If the string is missing, this is a null
}
}
public void AddField(bool val) { Add(new JSONObject(val)); }
public void AddField(float val) { Add(new JSONObject(val)); }
public void AddField(int val) { Add(new JSONObject(val)); }
public void Add(JSONObject obj) {
if(obj) { //Don't do anything if the object is null
if(type != JSONObject.Type.ARRAY) {
type = JSONObject.Type.ARRAY; //Congratulations, son, you're an ARRAY now
Debug.LogWarning("tried to add an object to a non-array JSONObject.  We'll do it for you, but you might be doing something wrong.");
}
list.Add(obj);
}
}
public void AddField(string name, bool val) { AddField(name, new JSONObject(val)); }
public void AddField(string name, float val) { AddField(name, new JSONObject(val)); }
public void AddField(string name, int val) { AddField(name, new JSONObject(val)); }
public void AddField(string name, string val) {
AddField(name, new JSONObject { type = JSONObject.Type.STRING, str = val });
}
public void AddField(string name, JSONObject obj) {
if(obj){ //Don't do anything if the object is null
if(type != JSONObject.Type.OBJECT){
type = JSONObject.Type.OBJECT; //Congratulations, son, you're an OBJECT now
Debug.LogWarning("tried to add a field to a non-object JSONObject.  We'll do it for you, but you might be doing something wrong.");
}
keys.Add(name);
list.Add(obj);
}
}
public void SetField(string name, JSONObject obj) {
if(HasField(name)) {
list.Remove(this[name]);
keys.Remove(name);
}
AddField(name, obj);
}
public JSONObject GetField(string name) {
if(type == JSONObject.Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if((string)keys[i] == name)
return (JSONObject)list[i];
return null;
}
public bool HasField(string name) {
if(type == JSONObject.Type.OBJECT)
for(int i = 0; i < keys.Count; i++)
if((string)keys[i] == name)
return true;
return false;
}
public void Clear() {
type = JSONObject.Type.NULL;
list.Clear();
keys.Clear();
str = "";
n = 0;
b = false;
}
public JSONObject Copy() {
return new JSONObject(print());
}
/*
* The Merge function is experimental. Use at your own risk.
*/
public void Merge(JSONObject obj) {
MergeRecur(this, obj);
}
static void MergeRecur(JSONObject left, JSONObject right) {
if(right.type == JSONObject.Type.OBJECT) {
for(int i = 0; i < right.list.Count; i++) {
if(right.keys[i] != null) {
string key = (string)right.keys[i];
JSONObject val = (JSONObject)right.list[i];
if(val.type == JSONObject.Type.ARRAY || val.type == JSONObject.Type.OBJECT) {
if(left.HasField(key))
MergeRecur(left[key], val);
else
left.AddField(key, val);
} else {
if(left.HasField(key))
left.SetField(key, val);
else
left.AddField(key, val);
}
}
}
}// else left.list.Add(right.list);
}
public string print() {
return print(0);
}
public string print(int depth) { //Convert the JSONObject into a stiring
if(depth++ > MAX_DEPTH) {
Debug.Log("reached max depth!");
return "";
}
string str = "";
switch(type) {
case Type.STRING:
str = "\"" + this.str + "\"";
break;
case Type.NUMBER:
str += n;
break;
case JSONObject.Type.OBJECT:
if(list.Count > 0) {
str = "{";
#if(READABLE) //for a bit more readability, comment the define above to save space
str += "\n";
depth++;
#endif
for(int i = 0; i < list.Count; i++) {
string key = (string)keys[i];
JSONObject obj = (JSONObject)list[i];
if(obj) {
#if(READABLE)
for(int j = 0; j < depth; j++)
str += "\t"; //for a bit more readability
#endif
str += "\"" + key + "\":";
str += obj.print(depth) + ",";
#if(READABLE)
str += "\n";
#endif
}
}
#if(READABLE)
str = str.Substring(0, str.Length - 1);
#endif
str = str.Substring(0, str.Length - 1);
str += "}";
} else str += "null";
break;
case JSONObject.Type.ARRAY:
if(list.Count > 0) {
str = "[";
#if(READABLE)
str += "\n"; //for a bit more readability
depth++;
#endif
foreach(JSONObject obj in list) {
if(obj) {
#if(READABLE)
for(int j = 0; j < depth; j++)
str += "\t"; //for a bit more readability
#endif
str += obj.print(depth) + ",";
#if(READABLE)
str += "\n"; //for a bit more readability
#endif
}
}
#if(READABLE)
str = str.Substring(0, str.Length - 1);
#endif
str = str.Substring(0, str.Length - 1);
str += "]";
}
break;
case Type.BOOL:
if(b)
str += "true";
else
str += "false";
break;
case Type.NULL:
str = "null";
break;
}
return str;
}
public JSONObject this[int index] {
get { return (JSONObject)list[index]; }
}
public JSONObject this[string index] {
get { return GetField(index); }
}
public override string ToString() {
return print();
}
public Dictionary<string, string> ToDictionary() {
if(type == Type.OBJECT) {
Dictionary<string, string> result = new Dictionary<string, string>();
for(int i = 0; i < list.Count; i++) {
JSONObject val = (JSONObject)list[i];
switch(val.type){
case Type.STRING: result.Add((string)keys[i], val.str); break;
case Type.NUMBER: result.Add((string)keys[i], val.n + ""); break;
case Type.BOOL: result.Add((string)keys[i], val.b + ""); break;
default: Debug.LogWarning("Omitting object: " + (string)keys[i] + " in dictionary conversion"); break;
}
}
return result;
} else Debug.LogWarning("Tried to turn non-Object JSONObject into a dictionary");
return null;
}
    
}

 

posted @ 2011-12-31 16:30 _Sin 阅读(43) 评论(0) 编辑

项目需要要有C#访问Mysql数据库,MySQL.Data.dll 这个库不知道什么原因,读以前的数据库时,字符类型是乱码。

没办法只能用 MySQLDriverCS-n-EasyQueryTools-4.0.0-DotNet2.0

中文参考手册http://www.yesky.com/imagesnew/software/mysql/manual_Reference.html

安装用了后发现问题,不支持Uint,当数据库中值在4294967295/2~4294967295就会报错。

项目不是很急,查源码。

发现CPrototypes.cs里MysqltoNetType

else if (type == (uint)enum_field_types_5.FIELD_TYPE_INT24 ||
     type == (uint)enum_field_types_5.FIELD_TYPE_LONG)
    {
             return System.Type.GetType("System.Int32");
    }

统一返回的Int32,需要添加一个分支

发现没得标识说明,查资料后发现Flags可以用,于是修改C#源码的类结构

/// <summary>
 ///  Interface extended by different MySQL_FIELD versions.
 /// </summary>
 public interface IMYSQL_FIELD
 {
        /// <summary>
        /// Div flagsdefine('NOT_NULL_FLAG',         1);
        /// define('PRI_KEY_FLAG',          2);
        /// define('UNIQUE_KEY_FLAG',       4);
        /// define('MULTIPLE_KEY_FLAG',     8);
        /// define('BLOB_FLAG',            16);
        /// define('UNSIGNED_FLAG',        32);
        /// define('ZEROFILL_FLAG',        64);
        /// define('BINARY_FLAG',         128);
        /// define('ENUM_FLAG',           256);
        /// define('AUTO_INCREMENT_FLAG', 512);
        /// define('TIMESTAMP_FLAG',     1024);
        /// define('SET_FLAG',           2048);
        /// define('NUM_FLAG',          32768);
        /// define('PART_KEY_FLAG',     16384);
        /// define('UNIQUE_FLAG',       65536);
        /// </summary>
        uint Flags{get;}
  /// <summary>
  /// Name of column
  /// </summary>
  string Name{get;}
  /// <summary>
  /// Type of field
  /// </summary>
  uint Type{get;set;}
  /// <summary>
  /// Max width for selected set
  /// </summary>
  long Max_Length {get;set;}
  /// <summary>
  /// Width of column (create length)
  /// </summary>
  uint Length{get;}
 }

实现了功能,麻烦二:一,非托管到托管的处理,不清楚内存结构。二,C写的结构不清楚查了很才查得Enmu值。

一共修改的两上上传记录一下,

最后又发现一个问题,MySQL中的VARBINARY被转换在string,处理有问题。还没发现解决方法

2011年3月1日

posted @ 2011-03-01 11:23 _Sin 阅读(152) 评论(0) 编辑

原文 http://www.cnblogs.com/xingd/archive/2009/06/23/1061800.html

程序包下载Word.rar

修改后

 public class DirtyWordOper
    {
        private static Dictionary<string, object> hash = new Dictionary<string, object>();
        private static BitArray firstCharCheck = new BitArray(char.MaxValue);//把脏词的第一个字符记录下来
        private static BitArray allCharCheck = new BitArray(char.MaxValue);//把每一个个脏词的所有字符都记录下来
        private static int maxLength = 0;//
        private static bool onlyOne = true;

        #region
        /// <summary>
        /// 返回替换后的字符串 字符串的长度不变
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string Replace(string text)
        {
            if (onlyOne)
            {
                Init();//初始化数据 执行一次就不会执行了
                onlyOne = false;
            }
            if (!isDirtyword(text))
            {
                return text;
            }
            //获取替换操作表
            List<DetailRepModel> drlist = GetList(text);
            //执行替换操作
            return Replace2(text, drlist);
        }

        /// <summary>
        /// 初始化用  只执行一次
        /// </summary>
        /// <param name="text"></param>
        private static void Init()
        {
            string[] badwords = DirtyWordData.DirtyKeyword.Split('|');
            foreach (string bw in badwords)
            {
                string[] strarrtemp = bw.Split('&');
                string word = strarrtemp[0];
                word = word.Trim();//去掉数据中的空格及格式 符号
                word = word.Replace("/r", "");
                word = word.Replace("/n", "");
                if (word == "")
                {
                    break;
                }
                if (!hash.ContainsKey(word))
                {
                    hash.Add(word, null);
                    maxLength = Math.Max(maxLength, word.Length);
                    firstCharCheck[word[0]] = true;

                    foreach (char c in word)
                    {
                        allCharCheck[c] = true;
                    }
                }
            }
        }
        /// <summary>
        /// 是否包含 了 脏 词
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private static bool isDirtyword(string text)
        {
            int index = 0;
            //int offset = 0;
            while (index < text.Length)
            {
                //如果第一个字符都不符合
                if (!firstCharCheck[text[index]])
                {// 直接找到与脏词第一字符相同为止
                    while (index < text.Length - 1 && !firstCharCheck[text[++index]]) ;
                }
                for (int j = 1; j <= Math.Min(maxLength, text.Length - index); j++)
                {
                    if (!allCharCheck[text[index + j - 1]])
                    {
                        break;
                    }
                    string sub = text.Substring(index, j);
                    //判定脏字字典中是否包括了脏词
                    if (hash.ContainsKey(sub))
                    {
                        return true;//是
                    }
                }
                index++;
            }
            return false;//否
        }

        /// <summary>
        /// 返回操作列表
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private static List<DetailRepModel> GetList(string text)
        {
            List<DetailRepModel> DetailList = new List<DetailRepModel>();
            int index = 0;
            while (index < text.Length)
            {
                if (!firstCharCheck[text[index]])
                {
                    while (index < text.Length - 1 && !firstCharCheck[text[++index]]) ;
                }
                DetailRepModel tempDetail = null;
                for (int j = 1; j <= Math.Min(maxLength, text.Length - index); j++)
                {
                    if (!allCharCheck[text[index + j - 1]])
                    {
                        if (tempDetail != null)
                        {//优先先字符串替换
                            index = index + tempDetail.number - 1;//索引要返回上一位,所以要减1
                            DetailList.Add(tempDetail);
                        }
                        break;
                    }
                    string sub = text.Substring(index, j);
                    if (hash.ContainsKey(sub))
                    {
                        tempDetail = new DetailRepModel();
                        tempDetail.index = index;
                        tempDetail.number = sub.Length;
                        tempDetail.content = sub;
                        //break;//进行下一次 不然要出现, abc 其中ab 与a都关键字要生成两个操作                      
                    }
                    if (tempDetail != null)
                    {
                        if (j + 1 > Math.Min(maxLength, text.Length - index))
                        {//优先先字符串替换
                            DetailList.Add(tempDetail);
                            index = index + tempDetail.number - 1;//索引要返回上一位,所以要减1
                        }
                    }
                }
                index++;
            }
            return DetailList;
        }
        /// <summary>
        /// 传入 字串和 脏字替换操作表,
        /// </summary>
        /// <param name="text"></param>
        /// <param name="drlist"></param>
        /// <returns> 输出替换后的字串</returns>
        private static string Replace2(string text, List<DetailRepModel> drlist)
        {


            if (drlist == null || drlist.Count == 0 || text == "")
            {
                return text;
            }
            foreach (DetailRepModel dr in drlist)
            {
                if (dr != null)
                {
                    string strtemp = text.Substring(dr.index, dr.number);
                    object ob = DirtyWordData.DirtyHT[(object)strtemp];
                    if (ob == null)
                    {
                        //记录错误
                        break;
                    }
                    // 这样替换 有错误 ,
                    text = text.Substring(0, dr.index) + ob.ToString() + text.Substring(dr.index + dr.number);
                    //text = text.Replace(strtemp, ob.ToString());
                }
            }
            return text;
        }
        #endregion
    }

 

效果还行, 不过我们老大给我说了个方法更NB,说比这种要快50倍;只是写起来有点麻烦

 

 public interface IReplaceDW
    {
        string Replace(string s);
    }
    public class ReplaceDW
    {
        public static void AddToWords(DirtyChar parent, string s, string t)
        {
            DirtyChar dc = parent.Children.Find(o => o.Orienginal == s[0]);
            if (dc == null)
            {
                dc = new DirtyChar() { Orienginal = s[0], Children = new List<DirtyChar>(), Target = "" };
                parent.Children.Add(dc);
            }
            if (s.Length > 1)
            {//
                AddToWords(dc, s.Substring(1), t);
            }
            else
            {
                dc.Target = t;
            }
        }

        public static string BuildChildren(DirtyChar dc, int deepLevel)
        {
            StringBuilder sb = new StringBuilder();
            string spaces = new string(' ', deepLevel + 4);

            if (dc.Children.Count > 0)
            {
                sb.Append(@"
" + spaces + @"if (i + 1 == len){");
                sb.Append(@"
" + spaces + @"    sb.Append(""" + dc.Target + @""");
                ");
                sb.Append(@"
" + spaces + @"    i++;
" + spaces + @"    break;}");
                sb.Append(@"
" + spaces + @" switch (s[i + " + deepLevel.ToString() + @"])
" + spaces + @" {
");
                foreach (DirtyChar c in dc.Children)
                {
                    sb.Append(@"
" + spaces + @"  case '" + c.Orienginal + @"':
");
                    sb.Append(BuildChildren(c, deepLevel + 1));
                    sb.Append(@"
" + spaces + @"   break;");
                }
              
              
                sb.Append(@"
" + spaces + @" default:
" + spaces + @"    sb.Append(""" + dc.Target + @""");
" + spaces + @"    i++;
" + spaces + @"    break;
" + spaces + @" }
");
            }
            else
            {
                sb.Append(@"
" + spaces + @"  sb.Append(""" + dc.Target + @""");
");
                if (deepLevel == 1)
                {
                    sb.Append(@"
" + spaces + @"  i++;
");
                }
                else
                {
                    sb.Append(@"
" + spaces + @"  i += " + (deepLevel).ToString() + @";
");
                }
            }
            return sb.ToString();
        }


        private IReplaceDW _r = null;
        private static bool isfirst = true;
        public string Replace(string s)
        {
            return _r.Replace(s);
        }
        private static List<KeyValuePair<string, string>> tmp = new List<KeyValuePair<string, string>>();
        public ReplaceDW()
        {
            if (isfirst)
            {              
                List<KeyValuePair<string, string>> dict = new List<KeyValuePair<string, string>>();
                foreach (DictionaryEntry d in KeyWord.DirtyWordData.DirtyHT)
                {
                    dict.Add(new KeyValuePair<string, string>(d.Key.ToString(), d.Value.ToString()));
                }
                // 整理进 list
                //List<KeyValuePair<string, string>> tmp = new List<KeyValuePair<string, string>>();
                foreach (KeyValuePair<string, string> kv in dict)
                {
                    tmp.Add(kv);
                }
                // 倒排
                tmp.Sort((a, b) => { return b.Key.CompareTo(a.Key); });
                isfirst = false;
            }
            var compiler = new CSharpCodeProvider();
            var options = new CompilerParameters();

            // set compile options  
            options.CompilerOptions = "/o";
            options.GenerateExecutable = false;
            options.GenerateInMemory = true;
            options.ReferencedAssemblies.Add("System.dll");
            options.ReferencedAssemblies.Add(this.GetType().Assembly.Location);

            // set the source code to compile  
            DirtyChar words = new DirtyChar() { Children = new List<DirtyChar>() };
            //DirtyChar words2 = new DirtyChar();
            //words2.Children = new List<DirtyChar>();
            foreach (KeyValuePair<string, string> kv in tmp)
            {//构建字典表
                AddToWords(words, kv.Key, kv.Value);
            }


            StringBuilder sb = new StringBuilder();
            sb.Append(@"
using System;  
namespace KeyWord
{
public class ReplaceDW_ : IReplaceDW
{  
    public string Replace( string s )
 {  
  int len = s.Length, i = 0;
        System.Text.StringBuilder sb = new System.Text.StringBuilder(len);
");
            sb.Append(@"
  while (i < len)
  {
   switch (s[i])
   {
");
            foreach (DirtyChar c in words.Children)
            {
                sb.Append(@"
    case '" + c.Orienginal + @"':
");
                sb.Append(BuildChildren(c, 1));
                sb.Append(@"
     break;");
            }
            sb.Append(@"
    default:
     sb.Append(s[i++]);
     break;
   }
  }
");
            sb.Append(@"
  return sb.ToString();

    }  
}
}");
            // compile the code, on-the-fly  
            var result = compiler.CompileAssemblyFromSource(options, sb.ToString());
           
            foreach (var error in result.Errors)
            {
                // print errors  
                ;
            }

            // if compilation sucessed  
            if ((!result.Errors.HasErrors) && (result.CompiledAssembly != null))
            {
                var type = result.CompiledAssembly.GetType("KeyWord.ReplaceDW_");
                try
                {
                    if (type != null)
                    {
                        this._r = Activator.CreateInstance(type) as IReplaceDW;
                    }
                    this.Replace("x"); //预热
                    this.Replace("x"); //预热
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
    }

 

posted @ 2010-11-25 17:33 _Sin 阅读(240) 评论(3) 编辑
web开发时,有的系统要求同一个用户在同一时间只能登录一次,也就是如果一个用户已经登录了,在退出之前如果再次登录的话需要报错。

  常见的处理方法是,在用户登录时,判断此用户是否已经在Application中存在,如果存在就报错,不存在的话就加到Application中(Application是所有Session共有的,整个web应用程序唯一的一个对象):

  string strUserId = txtUser.Text;
  ArrayList list = Application.Get("GLOBAL_USER_LIST") as ArrayList;
  if (list == null)
  {
  list = new ArrayList();
  }
  for (int i = 0; i < list.Count; i++)
  {
  if (strUserId == (list[i] as string))
  {
  //已经登录了,提示错误信息
  lblError.Text = "此用户已经登录";
  return;
  }
  }
  list.Add(strUserId);
  Application.Add("GLOBAL_USER_LIST", list);

  当然这里使用Cache等保存也可以。

  接下来就是要在用户退出的时候将此用户从Application中去除,我们可以在Global.asax的Session_End事件中处理:

  void Session_End(object sender, EventArgs e)
  {
  // 在会话结束时运行的代码。
  // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
  // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer
  // 或 SQLServer,则不会引发该事件。
  string strUserId = Session["SESSION_USER"] as string;
  ArrayList list = Application.Get("GLOBAL_USER_LIST") as ArrayList;
  if (strUserId != null && list != null)

 


  {
  list.Remove(strUserId);
  Application.Add("GLOBAL_USER_LIST", list);
  }
  }

  这些都没有问题,有问题的就是当用户直接点浏览器右上角的关闭按钮时就有问题了。因为直接关闭的话,并不会立即触发Session过期事件,也就是关闭浏览器后再来登录就登不进去了。

  这里有两种处理方式:

  1、使用Javascript方式

  在每一个页面中加入一段javascript代码:

  function window.onbeforeunload()
  {
  if (event.clientX>document.body.clientWidth && event.clientY<0||event.altKey){
  window.open("logout.aspx");
  }
  }

  由于onbeforeunload方法在浏览器关闭、刷新、页面调转等情况下都会被执行,所以需要判断是点击了关闭按钮或是按下Alt+F4时才执行真正的关闭操作。

  然后在logout.aspx的Page_Load中写和Session_End相同的方法,同时在logout.aspx中加入事件:onload="javascript:window.close()"

  但是这样还是有问题,javascript在不同的浏览器中可能有不同的行为,还有就是当通过文件->关闭时没有判断到。

  2、使用xmlhttp方法(这种方法测试下来没有问题)

  在每个页面中加入如下的javascript(这些javascript也可以写在共通里,每个页面引入就可以了)

  var x=0;
  function myRefresh()
  {
  var httpRequest = new ActiveXObject("microsoft.xmlhttp");
  httpRequest.open("GET", "test.aspx", false);
  httpRequest.send(null);
  x++;
  if(x<60) //60次,也就是Session真正的过期时间是30分钟
  {
  setTimeout("myRefresh()",30*1000); //30秒
  }
  }
  myRefresh();

  在web.config中设置

<sessionState mode="InProc" timeout="1"></sessionState>

  test.aspx页面就是一个空页面,只不过需要在Page_Load中加入:

  Response.Expires = -1;

  保证不使用缓存,每次都能调用到这个页面。

  原理就是:设置Session的过期时间是一分钟,然后在每个页面上定时每30秒连接一次测试页面,保持Session有效,总共连60次,也就是30分钟。如果30分钟后用户还没有操作,Session就会过期。当然,如果用户直接关闭浏览器,那么一分钟后Session也会过期。这样就可以满足要求了。

posted @ 2008-06-09 19:41 _Sin 阅读(44) 评论(0) 编辑