Пример #1
0
        private IReadOnlyNameValueList <string> LoadHeaders()
        {
            var result = new NameValueList <string>(false);

            foreach (var h in ResponseMessage.Headers)
            {
                foreach (var v in h.Value)
                {
                    result.Add(h.Key, v);
                }
            }

            if (ResponseMessage.Content?.Headers == null)
            {
                return(result);
            }

            foreach (var h in ResponseMessage.Content.Headers)
            {
                foreach (var v in h.Value)
                {
                    result.Add(h.Key, v);
                }
            }

            return(result);
        }
Пример #2
0
        public static bool Save(Transaction trans, params string[] fields)
        {
            NameValueList config = OriData;

            lock (Singleton)
            {
                Transaction _trans = trans;
                if (_trans == null)
                {
                    _trans = new Transaction(true);
                }
                bool res = true;
                foreach (var nv in OriData)
                {
                    if (fields.Length == 0 || nv.Name.In(fields))
                    {
                        object        d   = Burst.Utils.Serialize(nv.Value, SerializeType);
                        NameValueList pms = new NameValueList();
                        pms.Add("@" + KeyFieldName, nv.Name);
                        pms.Add("@" + TypeFieldName, nv.Value.GetType().AssemblyQualifiedName);
                        pms.Add("@" + ValueFieldName, d);
                        Command cmd = DbProvider.Adapter.GetReplaceCommand(TableName, nv.Name, KeyFieldName, pms, DbProvider);
                        res = cmd.ExecuteNonQuery(_trans) > -1 && res;
                    }
                }
                if (trans != null)
                {
                    return(res);
                }
                return(_trans.Commit());
            }
        }
Пример #3
0
        /// <summary>
        /// 从默认配置中初始化数据连接参数,包括连接字符串(ConnectionString)、DbProviderFactory、DbAdapter。
        /// </summary>
        /// <returns>初始化成功时,返回DbProvider,否则,返回null。</returns>
        public static DbProvider Initialize()
        {
            DbConnection _conn = null;
            DbProvider   res   = new DbProvider();

            try
            {
                res._config["DbAdapter"] = Activator.CreateInstance(Type.GetType(ConfigurationManager.AppSettings["DbAdapter"]));
                res.Adapter.InitializeOptions(res.Options);
                if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["DbProviderFactory"]) && res.Options["DefaultDbProviderFactory"] != null)
                {
                    res._config["DbProviderFactory"] = _getInstance <DbProviderFactory>(res.Options["DefaultDbProviderFactory"]);
                }
                else
                {
                    res._config["DbProviderFactory"] = Activator.CreateInstance(Type.GetType(ConfigurationManager.AppSettings["DbProviderFactory"]));
                }
                res._config["ConnectionString"] = ConfigurationManager.AppSettings["ConnectionString"];
                if (string.IsNullOrEmpty(res.ConnectionString))
                {
                    NameValueList DbParameters = new NameValueList();
                    DbParameters.Add("Host", ConfigurationManager.AppSettings["DbHost"]);
                    DbParameters.Add("Database", ConfigurationManager.AppSettings["DbDatabase"]);
                    DbParameters.Add("FilePath", ConfigurationManager.AppSettings["DbFilePath"]);
                    DbParameters.Add("Username", ConfigurationManager.AppSettings["DbUsername"]);
                    DbParameters.Add("Password", ConfigurationManager.AppSettings["DbPassword"]);
                    DbParameters.Add("Charset", ConfigurationManager.AppSettings["DbCharset"]);
                    DbParameters.Add("Version", ConfigurationManager.AppSettings["DbVersion"]);
                    DbParameters.Add("ReadOnly", ConfigurationManager.AppSettings["DbReadOnly"]);
                    res._config["ConnectionString"] = res.Adapter.BuildConnectionString(DbParameters);
                }
                _conn = res.Provider.CreateConnection();
                _conn.ConnectionString = res.ConnectionString;
                _conn.Open();
                res._config["DbSchema"] = res.Adapter.GetSchema(_conn);
                if (Current == null)
                {
                    Current = res;
                }
                return(res);
            }
            catch (Exception e)
            {
                #if DEBUG
                DbConnectException dce = new DbConnectException(e, res._config);
                Debug.WriteLine(dce);
                throw dce;
                #endif

                return(null);
            }
            finally
            {
                try
                {
                    _conn.Close();
                }
                catch { }
            }
        }
Пример #4
0
        public static Command GetUpdateCommand(Where where, IEnumerable <NameValue> pms)
        {
            if (pms.Count() == 0)
            {
                return(null);
            }
            StringBuilder ss   = new StringBuilder();
            NameValueList pre  = new NameValueList(pms);
            NameValueList _pms = new NameValueList();

            foreach (var fi in AllFields)
            {
                if (pre.ContainsKey(fi.Attribute.DbFieldName))
                {
                    ss.AppendFormat("{0}=@{1},", fi.EnsuredName, fi.Attribute.DbFieldName);
                    _pms.Add(GetFieldValue(fi, InsertType.None, pre[fi.Attribute.DbFieldName]));
                }
            }
            if (ss.Length > 0)
            {
                ss.Remove(ss.Length - 1, 1);
            }
            Command cmd = DbProvider.CreateCommand(string.Format("update {0} set {1}", EnsuredTableName, ss), _pms);

            Builder.AppendWhereByEnsuredKey(cmd, where, KeyField.EnsuredName, DbProvider.Adapter);
            return(cmd);
        }
Пример #5
0
        public static Command GetInsertCommand(InsertType iops, IEnumerable <NameValue> pms)
        {
            if (pms.Count() == 0)
            {
                return(null);
            }
            StringBuilder ss = new StringBuilder(), vs = new StringBuilder();
            NameValueList pre  = new NameValueList(pms);
            NameValueList _pms = new NameValueList();

            foreach (var fi in AllFields)
            {
                if (pre.ContainsKey(fi.Attribute.DbFieldName))
                {
                    if (iops == InsertType.New && fi.Key)
                    {
                        continue;
                    }
                    ss.AppendFormat("{0},", fi.EnsuredName);
                    vs.AppendFormat("@{0},", fi.Attribute.DbFieldName);
                    _pms.Add(GetFieldValue(fi, InsertType.None, pre[fi.Attribute.DbFieldName]));
                }
            }
            if (ss.Length > 0)
            {
                ss.Remove(ss.Length - 1, 1);
                vs.Remove(vs.Length - 1, 1);
            }
            return(DbProvider.CreateCommand(string.Format("insert into {0} ({1}) values ({2})", EnsuredTableName, ss, vs), _pms));
        }
Пример #6
0
        public ActionResult DBProviders()
        {
            NameValueList providers = new NameValueList();

            try
            {
                foreach (Provider provider in System.Enum.GetValues(typeof(Provider)))
                {
                    string value = provider.ToString();
                    providers.Add(new ListItem()
                    {
                        Name = value, Value = value
                    });
                }

                return(Json(providers, JsonRequestBehavior.AllowGet));
            }
            catch (Exception e)
            {
                _logger.Error(e.ToString());
                _CustomErrorLog = new CustomErrorLog();
                _CustomError    = _CustomErrorLog.customErrorLogger(ErrorMessages.errUIDBProviders, e, _logger);
                return(Json(new { success = false, message = "[ Message Id " + _CustomError.msgId + "] - " + _CustomError.errMessage, stackTraceDescription = _CustomError.stackTraceDescription }, JsonRequestBehavior.AllowGet));
            }
        }
Пример #7
0
        public void SchemaTestMethod()
        {
            var pms = new NameValueList();

            pms.Add("");
            var schema = new DbSchema(DbProvider.Initialize(pms));
        }
Пример #8
0
        /// <summary>
        /// Appends a query parameter. If value is a collection type (array, IEnumerable, etc.), multiple parameters are added, i.e. x=1&amp;x=2.
        /// To overwrite existing parameters of the same name, use AddOrReplace instead.
        /// </summary>
        /// <param name="name">Name of the parameter.</param>
        /// <param name="value">Value of the parameter. If it's a collection, multiple parameters of the same name are added.</param>
        /// <param name="isEncoded">If true, assume value(s) already URL-encoded.</param>
        /// <param name="nullValueHandling">Describes how to handle null values.</param>
        public void Add(string name, object value, bool isEncoded = false, NullValueHandling nullValueHandling = NullValueHandling.Remove)
        {
            if (value == null && nullValueHandling == NullValueHandling.Remove)
            {
                _values.Remove(name);
                return;
            }

            foreach (var val in SplitCollection(value))
            {
                if (val == null && nullValueHandling != NullValueHandling.NameOnly)
                {
                    continue;
                }
                _values.Add(name, new QueryParamValue(val, isEncoded));
            }
        }
Пример #9
0
        public static void Set(string name, Object data)
        {
            NameValueList config = OriData;

            lock (Singleton)
            {
                config.Add(name, data);
            }
        }
Пример #10
0
        public static void Reload(Transaction trans, params string[] fields)
        {
            lock (Singleton)
            {
                if (_buf == null)
                {
                    _buf = new NameValueList();
                }

                Command cmd = new Command(string.Format("select * from {0}", EnsuredTableName));
                if (fields.Length > 0)
                {
                    Builder.AppendWhere(
                        cmd,
                        new Compare(KeyFieldName, fields as object[]).ToWhere(),
                        KeyFieldName, DbProvider.Adapter
                        );
                }
                else
                {
                    _buf.Clear();
                }

                NameValueList _old_buf = _buf;
                _buf = new NameValueList();
                (Singleton as DbConfiguration <T>).Initialize();
                foreach (var i in _buf)
                {
                    if (!_old_buf.ContainsKey(i.Name))
                    {
                        _old_buf.Add(i);
                    }
                }
                _buf = _old_buf;

                NameValueList[] res = cmd.Execute(trans);
                foreach (var nv in res)
                {
                    try
                    {
                        _buf.Add(
                            nv.Get <string>(KeyFieldName),
                            Burst.Utils.DeserializeAs(
                                nv.Get <object>(ValueFieldName),
                                Type.GetType(nv.Get <string>(TypeFieldName)),
                                SerializeType
                                )
                            );
                    }
                    catch { }
                }
            }
        }
Пример #11
0
        public NameValueList SaveFields()
        {
            var nvList = new NameValueList();

            // Find all fields that are persistable, and record those of them that have non-null values
            for (int idx = this.RepeaterIndex + 1; idx < this.EndingIndex; idx++)
            {
                var field = this.Form.Fields[idx];
                if (field is SBSPersistableFormField && field.Value != null)
                {
                    nvList.Add(new NameValuePair(field.Name, field.Value));
                }
            }

            return(nvList);
        }
Пример #12
0
        /// <summary>
        /// Adds or updates name-value pairs in this request's Cookie header, based on property names/values
        /// of the provided object, or keys/values if object is a dictionary.
        /// To automatically maintain a cookie "session", consider using a CookieJar or CookieSession instead.
        /// </summary>
        /// <param name="request">The IFlurlRequest.</param>
        /// <param name="values">Names/values of HTTP cookies to set. Typically an anonymous object or IDictionary.</param>
        /// <returns>This IFlurlClient.</returns>
        public static IFlurlRequest WithCookies(this IFlurlRequest request, object values)
        {
            var cookies = new NameValueList <string>(request.Cookies);

            // although rare, we need to accommodate the possibility of multiple cookies with the same name
            foreach (var group in values.ToKeyValuePairs().GroupBy(x => x.Key))
            {
                // add or replace the first one (by name)
                cookies.AddOrReplace(group.Key, group.First().Value.ToInvariantString());
                // append the rest
                foreach (var kv in group.Skip(1))
                {
                    cookies.Add(kv.Key, kv.Value.ToInvariantString());
                }
            }
            return(request.WithHeader("Cookie", CookieCutter.ToRequestHeader(cookies)));
        }
Пример #13
0
        protected virtual NameValueList AsNameValueList(InsertType iops)
        {
            NameValueList res = new NameValueList();

            for (int i = 0; i < AllFields.Length; i++)
            {
                var fi = AllFields[i];
                if (iops == InsertType.New && fi.Key)
                {
                    continue;
                }
                NameValue cnv = GetFieldValue(fi, iops, GetValue(fi.Attribute.DbFieldName));
                if (cnv != null)
                {
                    res.Add(cnv);
                }
            }
            return(res);
        }
Пример #14
0
        /// <summary>
        /// 根据<see cref="SqlSearchKeyAttribute"/>将数据库相应行中<see cref="SqlBindingAttribute"/>绑定的属性更新。
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="binding"></param>
        public static void Update(this ISqlObject obj, string binding)
        {
            //获取成员列表。
            NameValueList vs = new NameValueList();

            foreach (var property in obj.GetType().GetProperties())
            {
                if (property.CanWrite && property.CanRead && property.TryGetSqlElementName(out string name) && property.SqlBindingExists(binding))
                {
                    //加密。
                    vs.Add(name, GetSqlValue(property.GetValue(obj), property.IsSqlEncrypt()));
                }
            }
            //生成命令语句。
            string cmd = $"update {obj.Table} set " +
                         string.Join(',', vs.Map((m) => $"{m.Name}={m.Value}")) + " " +
                         obj.GetWhereExpression();

            obj.SqlProvider.Execute(cmd);
        }
Пример #15
0
        /// <summary>
        /// 添加到数据库。
        /// </summary>
        /// <param name="obj"></param>
        public static void Add(this ISqlObject obj)
        {
            //获取成员列表。
            NameValueList vs = new NameValueList();

            foreach (var property in obj.GetType().GetProperties())
            {
                if (property.CanWrite && property.CanRead && property.TryGetSqlElementName(out string name, out bool isreadonly))
                {
                    if (property.GetValue(obj) != null && !isreadonly)
                    {
                        //加密。
                        vs.Add(name, GetSqlValue(property.GetValue(obj), property.IsSqlEncrypt()));
                    }
                }
            }
            //生成命令语句。
            //string cmd = $"insert into {obj.Table} set  {(string.Join(',', vs.Map((m) => $"{m.Name}={m.Value}")))}";

            string cmd = $"insert into {obj.Table} ({ToolUtil.JoinString(',', vs.Names)}) values ({ToolUtil.JoinString(',', vs.Values)})";

            obj.SqlProvider.Execute(cmd);
        }
Пример #16
0
        private void _forest_ForestGrowComplete(object sender, EventArgs e)
        {
            Progress            = 100;
            IsBtnGenerateEnable = true;
            IsBtnResolveEnable  = true;

            App.Current.Dispatcher.Invoke(() => { NameValueList.Clear(); });
            IItemNumerical item  = _forest.CreateItem();
            var            names = _forest.GetFeatureNames();

            foreach (var name in names)
            {
                if (name == ResolutionFeatureName)
                {
                    continue;
                }
                App.Current.Dispatcher.Invoke(() =>
                {
                    NameValueList.Add(new NameValue {
                        Name = name, Value = 0
                    });
                });
            }
        }
Пример #17
0
        public NameValueList[] Execute(Transaction trans)
        {
            DbConnection conn = null;
            DbDataReader r = null;
            bool err = false;
            try
            {
                DbCommand cmd;
                if (trans != null)
                    cmd = this.AsCommonCommand(trans.CurrentConnection.OriConnection, trans.CurrentTransaction);
                else
                {
                    conn = DbProvider.Current.CreateConnection();
                    conn.Open();
                    cmd = this.AsCommonCommand(conn, null);
                }
                r = cmd.ExecuteReader();
                List<NameValueList> res = new List<NameValueList>();
                List<string> keys = new List<string>();
                while (r.Read())
                {
                    NameValueList data = new NameValueList();
                    for (int i = 0; i < r.FieldCount; i++)
                    {
                        if (res.Count == 0)
                            keys.Add(r.GetName(i));
                        data.Add(keys[i], r.GetValue(i));
                    }
                    res.Add(data);
                }
                r.Close();
                return res.ToArray();
            }
            catch (Exception e)
            {
                err = true;
                if (trans != null)
                    trans.success = false;
                
                #if DEBUG
                    CommandException ce = new CommandException("Execute", this, e);
                    Debug.WriteLine(ce);
                    throw ce;
                #endif

                return new NameValueList[] { };
            }
            finally
            {
                try
                {
                    r.Close();
                }
                catch (Exception e)
                {
                    if (trans != null)
                        trans.success = false;

                    #if DEBUG
                        if (!err)
                        {
                            CommandException ce = new CommandException("Execute", this, e);
                            Debug.WriteLine(ce);
                            throw ce;
                        }
                    #endif
                }
                try
                {
                    if (trans == null)
                        conn.Close();
                }
                catch (Exception e)
                {
                    if (trans != null)
                        trans.success = false;

                    #if DEBUG
                        if (!err)
                        {
                            CommandException ce = new CommandException("Execute", this, e);
                            Debug.WriteLine(ce);
                            throw ce;
                        }
                    #endif
                }
            }
        }
Пример #18
0
 public void AddParameter(string key, Object value)
 {
     _pms.Add(key, value);
 }
Пример #19
0
 public void SchemaTestMethod()
 {
     var pms = new NameValueList();
     pms.Add("");
     var schema = new DbSchema(DbProvider.Initialize(pms));
 }
Пример #20
0
        public NameValueList[] Execute(Transaction trans)
        {
            DbConnection conn = null;
            DbDataReader r    = null;
            bool         err  = false;

            try
            {
                DbCommand cmd;
                if (trans != null)
                {
                    cmd = this.AsCommonCommand(trans.CurrentConnection.OriConnection, trans.CurrentTransaction);
                }
                else
                {
                    conn = DbProvider.Current.CreateConnection();
                    conn.Open();
                    cmd = this.AsCommonCommand(conn, null);
                }
                r = cmd.ExecuteReader();
                List <NameValueList> res  = new List <NameValueList>();
                List <string>        keys = new List <string>();
                while (r.Read())
                {
                    NameValueList data = new NameValueList();
                    for (int i = 0; i < r.FieldCount; i++)
                    {
                        if (res.Count == 0)
                        {
                            keys.Add(r.GetName(i));
                        }
                        data.Add(keys[i], r.GetValue(i));
                    }
                    res.Add(data);
                }
                r.Close();
                return(res.ToArray());
            }
            catch (Exception e)
            {
                err = true;
                if (trans != null)
                {
                    trans.success = false;
                }

                #if DEBUG
                CommandException ce = new CommandException("Execute", this, e);
                Debug.WriteLine(ce);
                throw ce;
                #endif

                return(new NameValueList[] { });
            }
            finally
            {
                try
                {
                    r.Close();
                }
                catch (Exception e)
                {
                    if (trans != null)
                    {
                        trans.success = false;
                    }

                    #if DEBUG
                    if (!err)
                    {
                        CommandException ce = new CommandException("Execute", this, e);
                        Debug.WriteLine(ce);
                        throw ce;
                    }
                    #endif
                }
                try
                {
                    if (trans == null)
                    {
                        conn.Close();
                    }
                }
                catch (Exception e)
                {
                    if (trans != null)
                    {
                        trans.success = false;
                    }

                    #if DEBUG
                    if (!err)
                    {
                        CommandException ce = new CommandException("Execute", this, e);
                        Debug.WriteLine(ce);
                        throw ce;
                    }
                    #endif
                }
            }
        }