Esempio n. 1
0
        /// <summary>
        /// 商户获取自身Token并缓存
        /// </summary>
        /// <param name="appid">商户AppID</param>
        /// <param name="secret">商户AppSecret</param>
        /// <returns></returns>
        public static string GetToken(string appid, string secret)
        {
            //缓存KeyName: Weixin_APP_Token_{appid}
            string str_cache_key = string.Format(CacheKey.Token, appid);
            //取Cache中Token
            string str_result = CacheHelper.Get <string>(str_cache_key);

            if (string.IsNullOrWhiteSpace(str_result))
            {
                string url = string.Format(ApiUrl.GetToken, appid, secret);

                try
                {
                    str_result = new WebUtils().DoGet(url, null);
                    if (!string.IsNullOrWhiteSpace(str_result) &&
                        str_result.IndexOf("access_token", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        JObject jobj_token = JsonConvert.DeserializeObject <JObject>(str_result);
                        str_result = (string)jobj_token["access_token"];
                        if (!string.IsNullOrWhiteSpace(str_result))
                        {
                            //将access_token绝对过期缓存
                            CacheHelper.Insert(str_cache_key, str_result, Config.Token_Expires);
                        }
                    }
                }
                catch (Exception ex)
                {
                    TextLogHelper.WriterExceptionLog(ex);
                }
            }

            return(str_result);
        }
Esempio n. 2
0
        public ActionResult List()
        {
            Hashtable   param_i = base.GetParameters();
            Hashtable   param_q = null;
            ParamVessel pv      = new ParamVessel();

            pv.Add("_search_", "0", HandleType.DefaultValue);

            try
            {
                param_q = param_i.Trim(pv);
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                return(RedirectToAction(actionName: "Index", controllerName: "Error", routeValues: new { id = "500" }));
            }

            if (param_q["_search_"].ToString().Equals("1"))
            {
                return(PartialView("../PartialView/MemberList"));
            }
            else
            {
                return(View("List"));
            }
        }
Esempio n. 3
0
File: JSON.cs Progetto: 17/YunPos
 /// <summary>
 /// 将指定的 JSON 字符串转换为 T 类型的对象。
 /// </summary>
 /// <typeparam name="T">所生成对象的类型。</typeparam>
 /// <param name="input">要进行反序列化的 JSON 字符串。</param>
 /// <returns>反序列化的对象。</returns>
 public static T Deserialize <T>(string input)
 {
     try
     {
         //return Serializer.Deserialize<T>(input);
         return(JsonConvert.DeserializeObject <T>(input));
     }
     catch (ArgumentNullException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (ArgumentException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (InvalidOperationException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (Exception ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
 }
Esempio n. 4
0
        public override BaseResult Add(dynamic entity)
        {
            BaseResult result = new BaseResult()
            {
                Success = true
            };
            var model = entity as Tb_Gysfl;

            if (model == null)
            {
                result.Success = false;
                result.Message.Add("参数有误!");
                return(result);
            }
            Hashtable ht = new Hashtable();

            ht.Add("id_masteruser", model.id_masteruser);
            ht.Add("id_farther", model.id_farther);
            ht.Add("flag_delete", (int)Enums.FlagDelete.NoDelete);
            ht.Add("mc", model.mc);
            if (CheckMC(ht))
            {
                result.Success = false;
                result.Message.Add("供应商分类名称已存在!");
                return(result);
            }
            try
            {
                model.id          = Guid.NewGuid().ToString();
                model.flag_delete = (int)Enums.FlagDelete.NoDelete;
                if (string.IsNullOrEmpty(model.id_farther) || model.id_farther == "0")
                {
                    model.id_farther = "0";
                    model.path       = string.Format("/0/{0}", model.id);
                }
                else
                {
                    ht.Clear();
                    ht.Add("id_masteruser", model.id_masteruser);
                    ht.Add("id", model.id_farther);
                    var item = DAL.GetItem <Tb_Gysfl>(typeof(Tb_Gysfl), ht);
                    if (item == null)
                    {
                        result.Success = false;
                        result.Message.Add("选中的父节点已不存在!");
                        return(result);
                    }
                    model.path = item.path + "/" + model.id;
                }
                model.rq_create = model.rq_edit = DateTime.Now;
                DAL.Add <Tb_Gysfl>(model);
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                result.Success = false;
                result.Message.Add(ex.Message);
            }
            return(result);
        }
Esempio n. 5
0
        public ActionResult ShopList2()
        {
            Hashtable param_i = base.GetParameters();
            //PageNavigate pn = BusinessFactory.Tb_Shop.GetPage(param_i);
            Hashtable   param_q = null;
            ParamVessel pv      = new ParamVessel();

            pv.Add("_search_", "0", HandleType.DefaultValue);

            try
            {
                param_q = param_i.Trim(pv);
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
            }

            if (param_q["_search_"].ToString().Equals("1"))
            {
                return(PartialView("PartialView/P_ShopList"));
            }
            else
            {
                return(View("ShopList2"));
            }
        }
Esempio n. 6
0
        public static bool Set(string key, dynamic str_json)
        {
            bool success = true;

            if (null != str_json)
            {
                try
                {
                    if (isRedis)
                    {
                        string sid = _session.SessionID;        //此处代替Session功能,需要记录SessionID
                        RedisHelper.Set(string.Format("{0}_{1}", sid, key), str_json);
                    }
                    else
                    {
                        _session[key] = str_json;
                    }
                }
                catch (System.Exception ex)
                {
                    success = false;
                    TextLogHelper.WriterExceptionLog(ex);
                }
            }

            return(success);
        }
Esempio n. 7
0
        public static bool Create(Hashtable keyValues)
        {
            bool succeed = false;

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine("<settings>");

            try
            {
                foreach (DictionaryEntry keyValue in keyValues)
                {
                    sb.AppendLine(String.Format("<add key=\"{0}\" value=\"{1}\" /> ", keyValue.Key, keyValue.Value));
                }
                sb.AppendLine("</settings>");

                using (StreamWriter writre = new StreamWriter(ApplicationInfo.ConfigPath, false, Encoding.UTF8))
                {
                    writre.Write(sb.ToString());
                }

                succeed = true;
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                succeed = false;
            }

            return(succeed);
        }
Esempio n. 8
0
        public static string Get(string str_key)
        {
            string result = null;

            try
            {
                object obj = null;
                if (isRedis)
                {
                    string sid = _session.SessionID;        //此处代替Session功能,需要记录SessionID
                    if (RedisHelper.Exists(string.Format("{0}_{1}", sid, str_key)))
                    {
                        obj = RedisHelper.Get(string.Format("{0}_{1}", sid, str_key));
                    }
                }
                else
                {
                    obj = _session[str_key];
                }

                if (null != obj)
                {
                    result = obj.ToString();
                }
            }
            catch (System.Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
            }

            return(result);
        }
Esempio n. 9
0
        public static T Get <T>(string obj_key)
            where T : class, new()
        {
            T result = null;

            try
            {
                if (isRedis)
                {
                    string sid = _session.SessionID;        //此处代替Session功能,需要记录SessionID
                    if (RedisHelper.Exists(string.Format("{0}_{1}", sid, obj_key)))
                    {
                        result = RedisHelper.Get <T>(string.Format("{0}_{1}", sid, obj_key));
                    }
                }
                else
                {
                    object obj = _session[obj_key];
                    if (null != obj)
                    {
                        result = (obj as T);
                    }
                }
            }
            catch (System.Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
            }

            return(result);
        }
Esempio n. 10
0
 public void AfterThrowing(CySoftException ex)
 {
     if (ex.Result != null && ex.Result.Level == ErrorLevel.Error)
     {
         TextLogHelper.WriterExceptionLog(ex);
     }
 }
Esempio n. 11
0
        /// <summary>
        /// 应用程序出错时执行
        /// </summary>
        #region protected void Application_Error(object sender, EventArgs e)
        protected void Application_Error(object sender, EventArgs e)
        {
            Exception lastError = Server.GetLastError();

            if (lastError != null)
            {
                Exception ex = lastError.GetBaseException();
                Server.ClearError();
                //过滤浏览器请求图片所产生的错误
                if (ex is HttpException)
                {
                    string absolutePath = Request.Url.AbsolutePath.ToLower();
                    string ext          = Path.HasExtension(absolutePath) ? Path.GetExtension(absolutePath) : "";
                    if (new string[] { ".ico", ".gif", ".jpg", ".png", ".bmp", ".cur", ".map" }.Contains(ext.ToLower()))
                    {
                        return;
                    }
                }
                if (ex is CySoftException)
                {
                    SystemError(ex);
                    return;
                }
                TextLogHelper.WriterExceptionLog(ex);
                SystemError(ex);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 获取网页授权access_token、openid
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static Domain.TokenSns GetToken(string appid, string appsecret, string code)
        {
            Domain.TokenSns token_sns  = null;
            string          strIsDebug = Utility.AppConfig.GetValue("isDebug");

            if (!string.IsNullOrWhiteSpace(strIsDebug) && strIsDebug.Equals("1", StringComparison.OrdinalIgnoreCase))
            {
                //TODO: YZQ TEST Return Token & openid
                token_sns = new Utility.Weixin.Domain.TokenSns
                {
                    access_token  = "TgBi2hhQWCGph-Q4b9ah81ejRoYSp-uBBbfLb6yLHpZES9d5gELY7Ma_meWNtwm4MPoA-3acet7Q728RUJFPI3vCvwECd2KH-AIecag-gqw",
                    expires_in    = 7200,
                    refresh_token = "5XxVyBZPEG9qiHwQZdGcDiO8t55epRLzHdMVvkE1Xrbo4nDRd4LLebEbSc2M_V5MEzAPN9Rg7ovpCVmVueOK6QCUPPRBRD8u5pmzSKtn9nw",
                    openid        = "554393109",
                    scope         = "snsapi_base"
                };

                return(token_sns);
            }
            else
            {
                try
                {
                    string url = string.Format(ApiUrl.GetToken_SNS, appid, appsecret, code);
                    Utility.LogHelper.WeixinInfo(string.Format("【网页授权code获取token】, request:{0}", url));
                    string str_result = new WebUtils().DoGet(url, null);
                    Utility.LogHelper.WeixinInfo(string.Format("【网页授权code获取token】, response:{0}", str_result));

                    if (string.IsNullOrWhiteSpace(str_result) ||
                        str_result.IndexOf("errcode", StringComparison.OrdinalIgnoreCase) != -1 ||
                        str_result.IndexOf("errmsg", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                    }
                    else
                    {
                        JObject jobj_token = JsonConvert.DeserializeObject <JObject>(str_result);
                        token_sns = new Domain.TokenSns()
                        {
                            access_token  = (string)jobj_token["access_token"],
                            expires_in    = (int)jobj_token["expires_in"],
                            refresh_token = (string)jobj_token["refresh_token"],
                            openid        = (string)jobj_token["openid"],
                            scope         = (string)jobj_token["scope"],
                        };
                    }
                }
                catch (Exception ex)
                {
                    TextLogHelper.WriterExceptionLog(ex);
                }

                return(token_sns);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// 网页授权用户获取用户信息(需scope为 snsapi_userinfo)
        /// </summary>
        /// <param name="token"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static Domain.UserInfo GetUserInfo(string token, string openid)
        {
            string strIsDebug = Utility.AppConfig.GetValue("isDebug");

            if (!string.IsNullOrWhiteSpace(strIsDebug) && strIsDebug.Equals("1", StringComparison.OrdinalIgnoreCase))
            {
                //TODO: YZQ TEST Return UserInfo
                Domain.UserInfo userinfo = new Utility.Weixin.Domain.UserInfo()
                {
                    openid     = openid,
                    nickname   = "SP",
                    sex        = 1,
                    language   = "zh_CN",
                    city       = "Guangzhou",
                    province   = "Guangdong",
                    country    = "CN",
                    headimgurl = "http://wx.qlogo.cn/mmopen/Jiavz9UrH80moUmmetxLgfMOOicGvzYHq3oKia9lgXbXECIm1VoLMvHBeVibCic2zFNU7V6ulGUydPqWuOhneIKGhcU0rdj6iawvnS/0",
                    unionid    = null
                };
                userinfo.privilege.Add("chinaunicom");

                return(userinfo);
            }
            else
            {
                Domain.UserInfo user = null;

                try
                {
                    string url = string.Format(ApiUrl.GetUserInfo, token, openid);
                    Utility.LogHelper.WeixinInfo(string.Format("【获取用户基本信息】, request:{0}", url));
                    string str_result = new WebUtils().DoGet(url, null);
                    Utility.LogHelper.WeixinInfo(string.Format("【获取用户基本信息】, response:{0}", str_result));

                    if (string.IsNullOrWhiteSpace(str_result) ||
                        str_result.IndexOf("errcode", StringComparison.OrdinalIgnoreCase) != -1 ||
                        str_result.IndexOf("errmsg", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                    }
                    else
                    {
                        user = JsonConvert.DeserializeObject <Domain.UserInfo>(str_result);
                    }
                }
                catch (Exception ex)
                {
                    TextLogHelper.WriterExceptionLog(ex);
                }

                return(user);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 创建自定义菜单
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="menuJson"></param>
        /// <returns></returns>
        public static string CreateMenus(string accessToken, string menuJson)
        {
            string url        = string.Format(ApiUrl.MenuCreate, accessToken);
            string str_result = string.Empty;

            try
            {
                str_result = new WebUtils().DoPost(url, menuJson);
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
            }

            return(str_result);
        }
Esempio n. 15
0
        /// <summary>
        /// 删除自定义菜单
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string DeleteMenus(string accessToken)
        {
            string url        = string.Format(ApiUrl.MenuDelete, accessToken);
            string str_result = string.Empty;

            try
            {
                str_result = new WebUtils().DoGet(url, null);
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
            }

            return(str_result);
        }
Esempio n. 16
0
        public static bool Save(Dictionary <string, string> keyValues)
        {
            bool succeed = false;

            if (!IsExist)
            {
                succeed = Create(keyValues);
            }
            else
            {
                try
                {
                    XmlDocument doc = XmlDoc;
                    foreach (KeyValuePair <string, string> item in keyValues)
                    {
                        XmlNode node = doc.SelectSingleNode(String.Format("//settings/add[@key='{0}']", item.Key));
                        if (node == null)
                        {
                            XmlNode    root = doc.SelectSingleNode("/settings");
                            XmlElement elem = doc.CreateElement("add");

                            XmlAttribute attr = doc.CreateAttribute("key");
                            attr.Value = item.Key;
                            elem.Attributes.SetNamedItem(attr);
                            node       = root.AppendChild(elem);
                            attr       = doc.CreateAttribute("value");
                            attr.Value = item.Value;
                            elem.Attributes.SetNamedItem(attr);
                            node = root.AppendChild(elem);
                        }
                        else
                        {
                            node.Attributes["value"].Value = item.Value;
                        }
                    }
                    doc.Save(ApplicationInfo.ConfigPath);
                    succeed = true;
                }
                catch (Exception ex)
                {
                    TextLogHelper.WriterExceptionLog(ex);
                    succeed = false;
                }
            }

            return(succeed);
        }
Esempio n. 17
0
        /// <summary>
        /// 商户获取Ticket
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string GetTicket(string accessToken)
        {
            //缓存KeyName: Weixin_Jsapi_Ticket_{accessToken}
            string str_cache_key = string.Format(CacheKey.Jsapi_Ticket, accessToken);
            //取Cache中Ticket
            string str_result = CacheHelper.Get <string>(str_cache_key);

            if (string.IsNullOrWhiteSpace(str_result))
            {
                string url = string.Format(ApiUrl.GetTicket, accessToken);

                try
                {
                    str_result = new WebUtils().DoGet(url, null);
                    if (!string.IsNullOrWhiteSpace(str_result) &&
                        str_result.IndexOf("ticket", StringComparison.OrdinalIgnoreCase) != -1)
                    {
                        JObject jobj_ticket = JsonConvert.DeserializeObject <JObject>(str_result);
                        int?    errcode     = (int?)jobj_ticket["errcode"];
                        string  errmsg      = (string)jobj_ticket["errmsg"];
                        string  str_ticket  = (string)jobj_ticket["ticket"];

                        if (!errcode.HasValue ||
                            errcode != 0 ||
                            string.IsNullOrWhiteSpace(errmsg) ||
                            !errmsg.Equals("ok", StringComparison.OrdinalIgnoreCase) ||
                            string.IsNullOrWhiteSpace(str_ticket))
                        {
                            return(string.Empty);
                        }

                        str_result = str_ticket;
                        //将Ticket绝对过期缓存
                        CacheHelper.Insert(str_cache_key, str_result, Config.Ticket_Expires);
                    }
                }
                catch (Exception ex)
                {
                    TextLogHelper.WriterExceptionLog(ex);
                }
            }

            return(str_result);
        }
Esempio n. 18
0
 /// <summary>
 /// 读取pem字符串
 /// </summary>
 /// <param name="strKey"></param>
 /// <param name="signType"></param>
 /// <returns></returns>
 private static RSACryptoServiceProvider LoadCertificateString(string strKey, string signType)
 {
     byte[] data = null;
     //读取带
     //ata = Encoding.Default.GetBytes(strKey);
     data = Convert.FromBase64String(strKey);
     //data = GetPem("RSA PRIVATE KEY", data);
     try
     {
         RSACryptoServiceProvider rsa = DecodeRSAPrivateKey(data, signType);
         return(rsa);
     }
     catch (Exception ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         //    throw new AopException("EncryptContent = woshihaoren,zheshiyigeceshi,wanerde", ex);
     }
     return(null);
 }
Esempio n. 19
0
        public ActionResult Get_Left_Tree()
        {
            BaseResult br = new BaseResult();

            br.Success = true;
            dynamic tree = new List <dynamic>();

            try
            {
                Hashtable param = new Hashtable();
                param.Add("id_masteruser", id_user_master);
                param.Add("flag_delete", (int)Enums.FlagDelete.NoDelete);
                param.Add("sort", "sort_id");
                param.Add("dir", "asc");


                br = BusinessFactory.Tb_Gysfl.GetAll(param);
                if (br.Success && br.Data is List <Tb_Gysfl> )
                {
                    List <Tb_Gysfl> list = br.Data as List <Tb_Gysfl>;
                    list.Insert(0, new Tb_Gysfl()
                    {
                        id = "0", id_farther = "#", mc = "全部", bm = "0"
                    });

                    tree = (from node in list
                            select new
                    {
                        id = node.id,
                        parent = node.id_farther,
                        text = node.mc,
                        bm = node.bm
                    });
                }
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
            }
            br.Data = tree;
            return(JsonString(br));
        }
Esempio n. 20
0
        public static bool SetValue(string key, string newValue)
        {
            if (!IsExist)
            {
                return(false);
            }
            bool succeed = false;

            try
            {
                XmlDocument doc  = XmlDoc;
                XmlNode     node = doc.SelectSingleNode(String.Format("//settings/add[@key='{0}']", key));
                if (node == null)
                {
                    XmlNode    root = doc.SelectSingleNode("/settings");
                    XmlElement elem = doc.CreateElement("add");

                    XmlAttribute attr = doc.CreateAttribute("key");
                    attr.Value = key;
                    elem.Attributes.SetNamedItem(attr);
                    node       = root.AppendChild(elem);
                    attr       = doc.CreateAttribute("value");
                    attr.Value = newValue;
                    elem.Attributes.SetNamedItem(attr);
                    node = root.AppendChild(elem);
                }
                else
                {
                    node.Attributes["value"].Value = newValue;
                }
                doc.Save(ApplicationInfo.ConfigPath);
                succeed = true;
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                succeed = false;
            }

            return(succeed);
        }
Esempio n. 21
0
        /// <summary>
        /// 用私钥加密数据
        /// </summary>
        /// <param name="content"></param>
        /// <param name="publicKeyPem"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string RSAEncrypt(string content, string publicKeyPem, string charset)
        {
            try
            {
                string sPublicKeyPEM         = File.ReadAllText(publicKeyPem);
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.PersistKeyInCsp = false;
                RSACryptoServiceProviderExtension.LoadPublicKeyPEM(rsa, sPublicKeyPEM);
                if (string.IsNullOrEmpty(charset))
                {
                    charset = DEFAULT_CHARSET;
                }
                byte[] data         = Encoding.GetEncoding(charset).GetBytes(content);
                int    maxBlockSize = rsa.KeySize / 8 - 11; //加密块最大长度限制
                if (data.Length <= maxBlockSize)
                {
                    byte[] cipherbytes = rsa.Encrypt(data, false);
                    return(Convert.ToBase64String(cipherbytes));
                }
                MemoryStream plaiStream = new MemoryStream(data);
                MemoryStream crypStream = new MemoryStream();
                Byte[]       buffer     = new Byte[maxBlockSize];
                int          blockSize  = plaiStream.Read(buffer, 0, maxBlockSize);
                while (blockSize > 0)
                {
                    Byte[] toEncrypt = new Byte[blockSize];
                    Array.Copy(buffer, 0, toEncrypt, 0, blockSize);
                    Byte[] cryptograph = rsa.Encrypt(toEncrypt, false);
                    crypStream.Write(cryptograph, 0, cryptograph.Length);
                    blockSize = plaiStream.Read(buffer, 0, maxBlockSize);
                }

                return(Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None));
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                //throw new AopException("EncryptContent = " + content + ",charset = " + charset, ex);
                throw new Exception("EncryptContent = " + content + ",charset = " + charset, ex);
            }
        }
Esempio n. 22
0
File: JSON.cs Progetto: 17/YunPos
 /// <summary>
 /// 将给定对象转换为指定类型。
 /// </summary>
 /// <typeparam name="T">obj 将转换成的类型。</typeparam>
 /// <param name="obj">序列化的 JSON 字符串。</param>
 /// <returns>已转换为目标类型的对象。</returns>
 public static T ConvertToType <T>(object obj)
 {
     try
     {
         return(Serializer.ConvertToType <T>(obj));
     }
     catch (InvalidOperationException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (ArgumentException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (Exception ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
 }
Esempio n. 23
0
 /// <summary>
 /// 设置登录信息
 /// </summary>
 /// <param name="key">键</param>
 /// <param name="value">值</param>
 protected void SetLoginInfo(string key, object value)
 {
     if (!IsLogOn)
     {
         BaseResult br = new BaseResult();
         br.Success = false;
         br.Message.Add("您未登录或登录已超时,请重新登录!");
         br.Level = ErrorLevel.Drump;
         throw new CySoftException(br);
     }
     try
     {
         Hashtable loginInfo = (Hashtable)Session["MobileLoginInfo"];
         loginInfo[key]             = value;
         Session["MobileLoginInfo"] = loginInfo;
     }
     catch (Exception ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw new CySoftException("登陆信息设置失败,请联系管理员!", ErrorLevel.Error);
     }
 }
Esempio n. 24
0
        /// <summary>
        /// 支付宝响应内容验签
        /// </summary>
        /// <param name="signContent">签名内容</param>
        /// <param name="sign">签名</param>
        /// <param name="publicKeyPem">支付宝公钥文件</param>
        /// <param name="charset">编码格式</param>
        /// <param name="signType">签名算法类型</param>
        /// <returns></returns>
        public static bool RSACheckContent(string signContent, string sign, string publicKeyPem, string charset, string signType)
        {
            try
            {
                if (string.IsNullOrEmpty(charset))
                {
                    charset = DEFAULT_CHARSET;
                }


                if ("RSA2".Equals(signType))
                {
                    string sPublicKeyPEM = File.ReadAllText(publicKeyPem);

                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    rsa.PersistKeyInCsp = false;
                    RSACryptoServiceProviderExtension.LoadPublicKeyPEM(rsa, sPublicKeyPEM);

                    bool bVerifyResultOriginal = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), "SHA256", Convert.FromBase64String(sign));
                    return(bVerifyResultOriginal);
                }
                else
                {
                    string sPublicKeyPEM         = File.ReadAllText(publicKeyPem);
                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                    rsa.PersistKeyInCsp = false;
                    RSACryptoServiceProviderExtension.LoadPublicKeyPEM(rsa, sPublicKeyPEM);

                    SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                    bool bVerifyResultOriginal     = rsa.VerifyData(Encoding.GetEncoding(charset).GetBytes(signContent), sha1, Convert.FromBase64String(sign));
                    return(bVerifyResultOriginal);
                }
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                return(false);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// AES 加密
        /// </summary>
        /// <param name="encryptKey"></param>
        /// <param name="bizContent"></param>
        /// <param name="charset"></param>
        /// <returns></returns>
        public static string AesEncrypt(string encryptKey, string bizContent, string charset = null)
        {
            if (string.IsNullOrWhiteSpace(encryptKey))
            {
                encryptKey = AppConfig.GetValue("AesKey");
            }

            Byte[] keyArray       = Convert.FromBase64String(encryptKey);
            Byte[] toEncryptArray = null;

            if (string.IsNullOrWhiteSpace(charset))
            {
                toEncryptArray = Encoding.UTF8.GetBytes(bizContent);
            }
            else
            {
                toEncryptArray = Encoding.GetEncoding(charset).GetBytes(bizContent);
            }

            System.Security.Cryptography.RijndaelManaged rDel = new System.Security.Cryptography.RijndaelManaged();

            try
            {
                rDel.Key     = keyArray;
                rDel.Mode    = System.Security.Cryptography.CipherMode.CBC;
                rDel.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                rDel.IV      = AES_IV;

                System.Security.Cryptography.ICryptoTransform cTransform = rDel.CreateEncryptor(rDel.Key, rDel.IV);
                Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
                return(Convert.ToBase64String(resultArray));
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                return(null);
            }
        }
Esempio n. 26
0
        internal static BaseResult SetBaseCoding(object entity, Type type = null, string setPropertyName = "bm")
        {
            BaseResult br = new BaseResult();

            try
            {
                ICodingRule helper = null;
                //if (entity.HasProperty("fatherId"))
                //{
                //    helper = new TreeCodingRule();
                //}
                //else
                if (entity.HasProperty("dh"))
                {
                    helper          = new BillCodingRule();
                    setPropertyName = "dh";
                }
                else
                {
                    helper = new BaseCodingRule();
                }
                br = helper.SetCoding(entity, type, setPropertyName);
            }
            catch (CySoftException ex)
            {
                br = ex.Result;
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);

                br.Success = false;
                br.Message.Clear();
                br.Message.Add("生成编码失败,请联系管理员!");
                br.Level = ErrorLevel.Error;
            }
            return(br);
        }
Esempio n. 27
0
        /// <summary>
        /// 用私钥解密数据
        /// </summary>
        /// <param name="content"></param>
        /// <param name="privateKeyPem"></param>
        /// <param name="charset"></param>
        /// <param name="signType"></param>
        /// <returns></returns>
        public static string RSADecrypt(string content, string privateKeyPem, string charset, string signType)
        {
            try
            {
                RSACryptoServiceProvider rsaCsp = LoadCertificateFile(privateKeyPem, signType);
                if (string.IsNullOrEmpty(charset))
                {
                    charset = DEFAULT_CHARSET;
                }
                byte[] data         = Convert.FromBase64String(content);
                int    maxBlockSize = rsaCsp.KeySize / 8;           //解密块最大长度限制
                if (data.Length <= maxBlockSize)
                {
                    byte[] cipherbytes = rsaCsp.Decrypt(data, false);
                    return(Encoding.GetEncoding(charset).GetString(cipherbytes));
                }
                MemoryStream crypStream = new MemoryStream(data);
                MemoryStream plaiStream = new MemoryStream();
                Byte[]       buffer     = new Byte[maxBlockSize];
                int          blockSize  = crypStream.Read(buffer, 0, maxBlockSize);
                while (blockSize > 0)
                {
                    Byte[] toDecrypt = new Byte[blockSize];
                    Array.Copy(buffer, 0, toDecrypt, 0, blockSize);
                    Byte[] cryptograph = rsaCsp.Decrypt(toDecrypt, false);
                    plaiStream.Write(cryptograph, 0, cryptograph.Length);
                    blockSize = crypStream.Read(buffer, 0, maxBlockSize);
                }

                return(Encoding.GetEncoding(charset).GetString(plaiStream.ToArray()));
            }
            catch (Exception ex)
            {
                TextLogHelper.WriterExceptionLog(ex);
                //throw new AopException("DecryptContent = " + content + ",charset = " + charset, ex);
                throw new Exception("DecryptContent = " + content + ",charset = " + charset, ex);
            }
        }
Esempio n. 28
0
File: JSON.cs Progetto: 17/YunPos
 /// <summary>
 ///
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="formatting">None = 0, Indented = 1</param>
 /// <returns></returns>
 public static string Serialize(object obj, int formatting)
 {
     try
     {
         //return Serializer.Serialize(obj);
         return(JsonConvert.SerializeObject(obj, (Formatting)formatting));
     }
     catch (InvalidOperationException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (ArgumentException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (Exception ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
 }
Esempio n. 29
0
File: JSON.cs Progetto: 17/YunPos
 /// <summary>
 /// 将对象转换为 JSON 字符串。
 /// </summary>
 /// <param name="obj">要序列化的对象。</param>
 /// <returns> 序列化的 JSON 字符串。</returns>
 public static string Serialize(object obj)
 {
     try
     {
         return(Serializer.Serialize(obj));
         //return JsonConvert.SerializeObject(obj, Formatting.None);
     }
     catch (InvalidOperationException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (ArgumentException ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
     catch (Exception ex)
     {
         TextLogHelper.WriterExceptionLog(ex);
         throw ex;
     }
 }
Esempio n. 30
0
 /// <summary>
 /// 加载私钥文件
 /// </summary>
 /// <param name="filename"></param>
 /// <param name="signType"></param>
 /// <returns></returns>
 private static RSACryptoServiceProvider LoadCertificateFile(string filename, string signType)
 {
     using (System.IO.FileStream fs = System.IO.File.OpenRead(filename))
     {
         byte[] data = new byte[fs.Length];
         byte[] res  = null;
         fs.Read(data, 0, data.Length);
         if (data[0] != 0x30)
         {
             res = GetPem("RSA PRIVATE KEY", data);
         }
         try
         {
             RSACryptoServiceProvider rsa = DecodeRSAPrivateKey(res, signType);
             return(rsa);
         }
         catch (Exception ex)
         {
             TextLogHelper.WriterExceptionLog(ex);
         }
         return(null);
     }
 }