예제 #1
0
        /// <inheritdoc />
        protected override void ParsePath(StringBuilder actualUrl, int index)
        {
            int lastDelimiter = index;
            int lastSegment = index;
            index++;
            for (; index < actualUrl.Length; index++)
            {
                switch (actualUrl[index])
                {
                    case '/':
                        index = ParseSegment(actualUrl, index, ref lastSegment);
                        break;
                    case '%':
                        index = DecodeEscape(actualUrl, index);
                        break;
                    case ';':
                        index = ParseSegment(actualUrl, index, ref lastSegment);
                        Path = actualUrl.ToString(lastDelimiter, index - lastDelimiter);
                        _parameters = new ParametersCollection(";", "=");
                        ParseParameters(actualUrl, index);
                        if (_parameters.Count == 0)
                        {
                            _parameters = null;
                        }

                        return;
                }
            }

            index = ParseSegment(actualUrl, index, ref lastSegment);
            Path = actualUrl.ToString(lastDelimiter, index - lastDelimiter);
        }
예제 #2
0
파일: HttpUrl.cs 프로젝트: alien-mcl/URSA
        internal HttpUrl(
            bool isAbsolute,
            string url,
            string scheme,
            string host,
            ushort port,
            string path,
            ParametersCollection query,
            string fragment,
            params string[] segments) : base(url, scheme, null, null, host, (port == 0 ? (scheme == HttpUrlParser.Https ? HttpUrlParser.HttpsPort : HttpUrlParser.HttpPort) : port))
        {
            port = (port == 0 ? (scheme == HttpUrlParser.Https ? HttpUrlParser.HttpsPort : HttpUrlParser.HttpPort) : port);
            _isAbsolute = isAbsolute;
            _path = (!String.IsNullOrEmpty(path) ? path : "/");
            _fragment = fragment;
            _segments = segments ?? new string[0];
            _query = query;
            string safePath = (_segments.Length == 0 ? String.Empty : String.Join("/", _segments.Select(segment => UrlParser.ToSafeString(segment, HttpUrlParser.PathAllowedChars))));
            if (isAbsolute)
            {
                _location = ToAbsoluteString(scheme, host, port, _path.TrimStart('/'), _query, _fragment).Substring(scheme.Length + 1);
                _asString = ToAbsoluteString(scheme, host, port, safePath, _query, _fragment);
            }
            else
            {
                _location = _asString = ToRelativeString("/" + safePath, _query, _fragment);
            }

            _hashCode = _asString.GetHashCode();
        }
예제 #3
0
        /// <inheritdoc />
        protected override void ParsePath(StringBuilder actualUrl, int index)
        {
            int lastDelimiter = index;
            int lastSegment = index;
            index++;
            for (; index < actualUrl.Length; index++)
            {
                switch (actualUrl[index])
                {
                    case '/':
                        index = ParseSegment(actualUrl, index, ref lastSegment);
                        break;
                    case '%':
                        index = DecodeEscape(actualUrl, index);
                        break;
                    case '#':
                        index = ParseSegment(actualUrl, index, ref lastSegment);
                        Path = actualUrl.ToString(lastDelimiter, index - lastDelimiter);
                        ParseFragment(actualUrl, index);
                        return;
                    case '?':
                        index = ParseSegment(actualUrl, index, ref lastSegment);
                        Path = actualUrl.ToString(lastDelimiter, index - lastDelimiter);
                        _query = new ParametersCollection("&", "=");
                        ParseQuery(actualUrl, index);
                        return;
                }
            }

            index = ParseSegment(actualUrl, index, ref lastSegment);
            Path = actualUrl.ToString(lastDelimiter, index - lastDelimiter);
        }
예제 #4
0
	    unsafe public static CuttingScheme ConvertLayout(_Layout * layout, ParametersCollection parameters, Sheet sheet)
	    {
		    CuttingScheme result = new CuttingScheme();
            result.Sheet = sheet;
            result.Parameters = parameters;
		    CuttingResultBuilder builder = new CuttingResultBuilder();
		    builder.LoadSections(layout, result);
		    return result;
	    }
예제 #5
0
 public ParametersBase(string source)
 {
   if (String.IsNullOrEmpty(source)) return;
   _Source = source;
   int typeTail = source.IndexOf(";");
   if (typeTail == -1)
   {
     _Type = source;
     return;
   }
   _Type = source.Substring(0, typeTail);
   string p = source.Substring(typeTail + 1, source.Length - typeTail - 1);
   _Parameters = new ParametersCollection();
   Regex myReg = new Regex(@"(?<key>.+?)=((""(?<value>.+?)"")|((?<value>[^\;]+)))[\;]{0,1}", RegexOptions.Singleline);
   MatchCollection mc = myReg.Matches(p);
   foreach (Match m in mc)
   {
     if (!_Parameters.ContainsKey(m.Groups["key"].Value))
     {
       _Parameters.Add(m.Groups["key"].Value.Trim(), m.Groups["value"].Value);
     }
   }
 }
예제 #6
0
파일: dbFacade.cs 프로젝트: Digiman/ASTPP
 /// <summary>
 /// Перезаписывает данные в выбранной таблице.
 /// </summary>
 /// <param name="tablename">Имя таблицы</param>
 /// <param name="collection">Коллекция полей и значений</param>
 /// <param name="where">Строка условия</param>
 /// <returns>Код ошибки. Если 0, ошибки нет</returns>
 public int Update(string tablename, ParametersCollection collection, string where)
 {
     return Update(tablename, collection, new[] { where }, "");
 }
예제 #7
0
파일: dbFacade.cs 프로젝트: Digiman/ASTPP
 /// <summary>
 /// Вставляет данные в таблицу.
 /// </summary>
 /// <param name="tablename">Имя таблицы</param>
 /// <param name="parameters">Коллекция параметров</param>
 /// <returns>ID последней вставленной строки</returns>
 public int Insert(string tablename, ParametersCollection parameters)
 {
     int lastId = 0;
     ConnectionState previousConnectionState = ConnectionState.Closed;
     try
     {
         previousConnectionState = connect.State;
         if (connect.State == ConnectionState.Closed)
         {
             connect.Open();
         }
         command = new SQLiteCommand(connect);
         bool ifFirst = true;
         StringBuilder queryColumns = new StringBuilder("("); //список полей, в которые вставляются новые значения
         StringBuilder queryValues = new StringBuilder("(");  //список значений для этих полей
         foreach (Parameter iparam in parameters)
         {
             //добавляем новый параметр
             command.Parameters.Add("@" + iparam.ColumnName, iparam.DbType).Value = Convert.IsDBNull(iparam.Value) ? Convert.DBNull : iparam.Value;
             //собираем колонки и значения в одну строку
             if (ifFirst)
             {
                 queryColumns.Append(iparam.ColumnName);
                 queryValues.Append("@" + iparam.ColumnName);
                 ifFirst = false;
             }
             else
             {
                 queryColumns.Append("," + iparam.ColumnName);
                 queryValues.Append(",@" + iparam.ColumnName);
             }
         }
         queryColumns.Append(")");
         queryValues.Append(")");
         //создаем новый запрос
         string sql = string.Format("INSERT INTO {0} {1} VALUES {2}", tablename, queryColumns, queryValues);
         command.CommandText = sql;
         command.ExecuteNonQuery();
         //получение последнего ID
         sql = "SELECT last_insert_rowid();";
         command = new SQLiteCommand(sql, connect);
         lastId = int.Parse(command.ExecuteScalar().ToString());
     }
     catch (Exception error)
     {
         //System.Windows.Forms.MessageBox.Show(error.Message, "Ошибка при вставке нового значения", MessageBoxButtons.OK, MessageBoxIcon.Error);
         Console.WriteLine("ERROR: " + error.Message);
         return 0;
     }
     finally
     {
         if (previousConnectionState == ConnectionState.Closed)
         {
             connect.Close();
         }
     }
     return lastId;
 }
예제 #8
0
 public void Teardown()
 {
     _parameters = null;
 }
예제 #9
0
 /// <summary>
 /// Restores the state.
 /// </summary>
 /// <param name="state">The state.</param>
 void ISupportNavigationState.RestoreState(ParametersCollection state)
 {
     this.OnRestoreState(state);
 }
예제 #10
0
 public AgeSpecificPush(ParametersCollection parameters)
     : base(parameters)
 {
 }
예제 #11
0
 protected Push(ParametersCollection parameters)
 {
     Parameters = parameters;
 }
예제 #12
0
 protected internal ActionResult Navigate(INavigationHandler navigationHandler, string url, ParametersCollection parameters)
 {
     throw new NotImplementedException();
 }
예제 #13
0
 protected internal ActionResult Navigate(string url, ParametersCollection parameters)
 {
     return(this.Navigate(null, url, parameters));
 }
예제 #14
0
        private void MainFind_DisplayData()
        {
            try
            {
                CoFAS_DevExpressManager.SetCursor(this, Cursors.WaitCursor);

                Stream responseStream = null;

                responseStream = CORE.Function.CoFAS_FTPManager.FTPFileBinding(strFTP_PATH, strFILE_NAME, _pFTP_ID, _pFTP_PW);

                spreadsheetControl1.LoadDocument(responseStream);

                wb = spreadsheetControl1.Document;

                if (wb.MailMergeDataSource == null)
                {
                    return;
                }

                /*
                 * switch (DBManager.PrimaryDBManagerType)
                 * {
                 *  case DBManagerType.MySql:
                 *      wb.MailMergeDataSource = new DevExpress.DataAccess.Sql.SqlDataSource(new MySqlConnectionParameters(DBManager.InitDatabaseServer, DBManager.InitDatabaseName, DBManager.InitDatabaseID, DBManager.InitDatabasePass, 3306));
                 *      break;
                 *  case DBManagerType.SQLServer:
                 *      wb.MailMergeDataSource = new MsSqlConnectionParameters();
                 *      break;
                 * }
                 */


                Object dsTemp             = wb.MailMergeDataSource;
                ParametersCollection para = wb.MailMergeParameters;



                para["v_option1"].Value = ARRAY_CODE[1].ToString(); // KEY값
                para["v_option2"].Value = ARRAY_CODE[2].ToString(); // 사용여부
                para["v_option3"].Value = USER_CODE;                // 사용자
                para["v_option4"].Value = ARRAY_CODE[3].ToString(); // 페이징 행수 기준
                para["v_option5"].Value = ARRAY_CODE[4].ToString(); // 시작번호


                IList <IWorkbook> result = wb.GenerateMailMergeDocuments();
                using (MemoryStream resultStream = new MemoryStream())
                {
                    result[0].SaveDocument(resultStream, DocumentFormat.OpenXml);
                    wb.LoadDocument(resultStream);
                }
            }
            catch (ExceptionManager pExceptionManager)
            {
                CoFAS_DevExpressManager.ShowErrorMessage(string.Format("{0}\n{1}", pExceptionManager.Exception.Message.ToString(), pExceptionManager.TargetSite.ToString()));
            }
            catch (Exception ex)
            {
                CoFAS_DevExpressManager.ShowErrorMessage("Exception :" + ex.ToString());
            }
            finally
            {
                CoFAS_DevExpressManager.SetCursor(this, Cursors.Default);
            }
        }
예제 #15
0
        /// <summary>
        /// Returns true if parameters of two compared methods are CLS-Compliant.
        /// It tests differing only in ref or out, or in array rank.
        /// </summary>
        public static Result AreOverloadedMethodParamsClsCompliant(ParametersCollection pa, ParametersCollection pb)
        {
            var typesA = pa.Types;
            var typesB = pb.Types;

            if (typesA == null || typesB == null)
            {
                return(Result.Ok);
            }

            if (typesA.Length != typesB.Length)
            {
                return(Result.Ok);
            }

            var result = Result.Ok;

            for (var i = 0; i < typesB.Length; ++i)
            {
                var aType = typesA[i];
                var bType = typesB[i];

                if (aType.IsArray && bType.IsArray)
                {
                    var elementTypeA = aType.GetElementType();
                    var elementTypeB = bType.GetElementType();

                    if (aType.GetArrayRank() != bType.GetArrayRank() && elementTypeA == elementTypeB)
                    {
                        result = Result.RefOutArrayError;
                        continue;
                    }

                    if (elementTypeA.IsArray || elementTypeB.IsArray)
                    {
                        result = Result.ArrayArrayError;
                        continue;
                    }
                }

                if (aType != bType)
                {
                    return(Result.Ok);
                }

                const Parameter.Modifier outRefMod = (Parameter.Modifier.OutMask | Parameter.Modifier.RefMask);

                if ((pa.FixedParameters[i].ModifierFlags & outRefMod) != (pb.FixedParameters[i].ModifierFlags & outRefMod))
                {
                    result = Result.RefOutArrayError;
                }
            }
            return(result);
        }
        public bool Update(string tablename, ParametersCollection collection, object[] whereparams, string whereseparator)
        {
            ConnectionState previousConnectionState = ConnectionState.Closed;
            bool result = false;
            try
            {
                //проверяем переданные аргументы
                if (whereparams.Length == 0) throw (new SqlLiteWarningException("Ошибка! Не указано ни одно условие"));
                if (whereparams.Length > 0 && whereseparator.Trim().Length == 0) throw (new SqlLiteWarningException("При использовании нескольких условий, требуется указать разделитель OR или AND"));

                previousConnectionState = SqlCon.State;
                if (SqlCon.State == ConnectionState.Closed)
                {
                    SqlCon.Open();
                }

                int i = 0;
                //готовим переменную для сбора полей и их значений
                string sql_params = string.Empty;
                bool ifFirst = true;
                SQLiteCommand command = new SQLiteCommand(SqlCon);
                //в цикле создаем строку запроса
                foreach (Parameter param in collection)
                {
                    if (ifFirst)
                    {
                        sql_params = param.ColumnName + " = @param" + i;
                        ifFirst = false;
                    }
                    else
                    {
                        sql_params += "," + param.ColumnName + " = @param" + i;
                    }
                    //и добавляем параметры с таким же названием
                    command.Parameters.Add("@param" + i, param.DbType).Value = param.Value;
                    i++;
                }

                //условия для запроса
                string sql_where = string.Empty;
                ifFirst = true;
                //собираем строку с условиями
                foreach (object item in whereparams)
                {
                    if (ifFirst)
                    {
                        sql_where = item.ToString();
                        ifFirst = false;
                    }
                    else
                    {
                        sql_where += " " + whereseparator + " " + item;
                    }
                }
                sql_where = "WHERE " + sql_where;
                //собираем запрос воедино
                command.CommandText = string.Format("UPDATE {0} SET {1} {2}", tablename, sql_params, sql_where);
                //выполняем запрос
                command.ExecuteNonQuery();
            }
            catch (SqlLiteWarningException message)
            {
                LoggingModule.Instance.WriteMessage(LoggingModule.Severity.Error, message.Message);
                result = false;
            }
            catch (Exception error)
            {
                LoggingModule.Instance.WriteMessage(LoggingModule.Severity.Error, error.Message);
                result = false;
            }
            return result;
        }
예제 #17
0
파일: HttpUrl.cs 프로젝트: alien-mcl/URSA
        private static string ToAbsoluteString(string scheme, string host, ushort port, string path = null, ParametersCollection query = null, string fragment = null)
        {
            string portString = (((scheme == HttpUrlParser.Https) && (port == HttpUrlParser.HttpsPort)) || (port == HttpUrlParser.HttpPort) ? String.Empty : ":" + port);
            if (path == null)
            {
                return String.Format("{0}://{1}{2}/", scheme, host, portString);
            }

            return String.Format(
                "{0}://{1}{2}/{3}{4}{5}",
                scheme,
                host,
                portString,
                path,
                (query != null ? String.Format("?{0}", query.ToString(HttpUrlParser.PathAllowedChars)) : String.Empty),
                (fragment != null ? String.Format("#{0}", UrlParser.ToSafeString(fragment, HttpUrlParser.PathAllowedChars)) : String.Empty));
        }
예제 #18
0
 public GenderPush(ParametersCollection parameters)
     : base(parameters)
 {
 }
예제 #19
0
        public void Convert(ICollection<CuttingScheme> output, StreamReader tr)
        {
            // сканирование dxf, загрузка линий и текстов
            int typeCode;
            string data;
            while (true)
            {
                typeCode = int.Parse(tr.ReadLine());
                data = tr.ReadLine();
                if (typeCode == 0 && data == "SECTION")
                {
                    typeCode = int.Parse(tr.ReadLine());
                    data = tr.ReadLine();
                    if (typeCode == 2 && data == "ENTITIES")
                    {
                        break;
                    }
                }
            }

            List<Line> lines = new List<Line>();
            _texts = new LinkedList<Text>();

            while (!tr.EndOfStream)
            {
                typeCode = int.Parse(tr.ReadLine());
                data = tr.ReadLine();
                if (typeCode == 0 && data == "LINE")
                {
                    Line line = new Line();
                    line.Read(tr);
                    lines.Add(line);
                }
                else if (typeCode == 0 && data == "TEXT")
                {
                    Text text = new Text();
                    text.Read(tr);
                    _texts.AddLast(text);
                }
            }

            // составляем список резов, выбирая линии со стилем HIDDEN
            LinkedList<Line> buffer = new LinkedList<Line>(lines);
            _cuts = new LinkedList<Line>();
            BazUtils.TakeFrom(buffer, _cuts, BazUtils.CutsPredicate);

            // составляем список прямоугольноков, собирая их из линий
            List<Line> otherLines = new List<Line>();
            LinkedList<Rectangle> rects = new LinkedList<Rectangle>();
            while (buffer.Count > 0)
            {
                Line line1 = buffer.First.Value;
                buffer.RemoveFirst();
                Line line2 = BazUtils.FindContLine(line1, buffer);
                if (line2 == null)
                {
                    otherLines.Add(line1);
                    continue;
                }
                buffer.Remove(line2);
                Line line3 = BazUtils.FindContLine(line2, buffer);
                if (line3 == null)
                {
                    otherLines.Add(line1);
                    otherLines.Add(line2);
                    continue;
                }
                buffer.Remove(line3);
                Line line4 = BazUtils.FindContLine(line2, buffer);
                if (line4 != null)
                {
                    otherLines.Add(line1);
                    otherLines.Add(line2);
                    otherLines.Add(line3);
                    continue;
                }
                buffer.Remove(line4);

                Rectangle rect = new Rectangle();
                rect.LeftBottom.X = Math.Min(line1.P1.X, line2.P2.X);
                rect.LeftBottom.Y = Math.Min(line1.P1.Y, line2.P2.Y);
                rect.RightTop.X = Math.Max(line1.P1.X, line2.P2.X);
                rect.RightTop.Y = Math.Max(line1.P1.Y, line2.P2.Y);
                rects.AddLast(rect);
            }

            BazUtils.BubbleSort<Rectangle>(rects, Rectangle.SquareDescending);
            while (rects.Count > 0)
            {
                // находим прямоугольники листа и его обрезанной части
                Rectangle sheetRect = rects.First.Value;
                rects.RemoveFirst();
                List<Rectangle> internals = new List<Rectangle>();
                BazUtils.TakeFrom<Rectangle>(rects, internals, sheetRect.IsContains);
                if (internals.Count == 0)
                {
                    break;
                }
                Rectangle cutoffRect = internals[0];

                // определяем ширину реза и направление первого реза
                CutMatcher matcher = new CutMatcher();
                CuttingDirection firstCut;
                matcher.Bounds = cutoffRect;
                Line match = BazUtils.Lookup(_cuts, matcher.MatchHorizontalCut);
                if (match == null)
                {
                    match = BazUtils.Lookup(_cuts, matcher.MatchVerticalCut);
                    _cutterThick = (cutoffRect.LeftBottom.Y - match.P1.Y) * 2;
                    firstCut = CuttingDirection.Vertical;
                }
                else
                {
                    _cutterThick = (cutoffRect.LeftBottom.X - match.P1.X) * 2;
                    firstCut = CuttingDirection.Horizontal;
                }

                // заполняем полученные параметры раскроя
                ParametersCollection pars = new ParametersCollection();
                pars.CutterThickness = (decimal)(_cutterThick * 10.0);
                pars.CutOffLeft = (decimal)((cutoffRect.LeftBottom.X - sheetRect.LeftBottom.X) * 10.0);
                pars.CutOffBottom = (decimal)((cutoffRect.LeftBottom.Y - sheetRect.LeftBottom.Y) * 10.0);
                pars.CutOffRight = (decimal)((sheetRect.RightTop.X - cutoffRect.RightTop.X) * 10.0);
                pars.CutOffTop = (decimal)((sheetRect.RightTop.Y - cutoffRect.RightTop.Y) * 10.0);
                _scheme = new CuttingScheme();
                _scheme.Parameters = pars;
                _scheme.Sheet = new Sheet();
                _scheme.Sheet.Thickness = 16;
                _scheme.Height = (decimal)((sheetRect.RightTop.Y - sheetRect.LeftBottom.Y) * 10.0);
                _scheme.Width = (decimal)((sheetRect.RightTop.X - sheetRect.LeftBottom.X) * 10.0);
                _scheme.Sheet.Width = _scheme.Width;
                _scheme.Sheet.Height = _scheme.Height;

                // составляем сам раскрой
                if (firstCut == CuttingDirection.Vertical)
                {
                    CutHorizontalStrip(_scheme.RootSection, cutoffRect);
                }
                else
                {
                    CutVerticalStrip(_scheme.RootSection, cutoffRect);
                }
                
                // получаем количество листов из строчки под раскроем
                List<Text> sheetInfo = new List<Text>();
                TextMatcher textMatcher = new TextMatcher();
                textMatcher.Bounds = sheetRect.HorizStrip(sheetRect.LeftBottom.Y - 30, sheetRect.LeftBottom.Y);
                BazUtils.TakeFrom<Text>(_texts, sheetInfo, textMatcher.IsInside);
                sheetInfo.Sort(Text.PosYAscending);
                string sheetsCountStr = sheetInfo[0].Value;
                int eqPos = sheetsCountStr.LastIndexOf('=');
                _scheme.Repetitions = int.Parse(sheetsCountStr.Substring(eqPos + 1, sheetsCountStr.Length - eqPos - 1));

                output.Add(_scheme);
            }
        }
예제 #20
0
 public TechPush(ParametersCollection parameters)
     : base(parameters)
 {
 }
예제 #21
0
 /// <summary>
 /// Called when restore state.
 /// </summary>
 /// <param name="state">The state.</param>
 protected virtual void OnRestoreState(ParametersCollection state)
 {
 }
예제 #22
0
 private SystemData(ParametersCollection parameters)
 {
     Parameters = parameters;
 }
예제 #23
0
        /// <summary>
        /// Performs the navigation to the given target
        /// </summary>
        /// <param name="target"></param>
        public void Navigate(NavigateMode mode, string target, params object[] args)
        {
            if (String.IsNullOrEmpty(target))
            {
                IShowMessageViewService showMessageService = ViewServiceLocator.GetViewService<IShowMessageViewService>();

                showMessageService.ButtonSetup  = DialogButton.Ok;
                showMessageService.Caption      = "Warning";
                showMessageService.Text         = "Option not mapped to a view.";

                showMessageService.ShowMessage();

                return;
            }

            Application.Current.Dispatcher.BeginInvoke
            (
                DispatcherPriority.Background,
                new ThreadStart
                (
                    delegate
                    {
                        ParametersCollection    navParams   = null;
                        string                  area        = null;

                        if (args != null && args.Length > 0)
                        {
                            navParams = new ParametersCollection();
                            navParams.Add(NavigationParams.NavigationParamsKey, args);
                        }

                        var smnode = SiteMapService.SiteMap.RootNode.ChildNodes
                            .OfType<NavigationNode>()
                            .Traverse<NavigationNode>(node => ((node.ChildNodes) != null ? node.ChildNodes.OfType<NavigationNode>() : null))
                            .Where(n => n.Url == target).SingleOrDefault();

                        if (smnode != null)
                        {
                            area = smnode.SiteArea;
                        }

                        NavigationRequest   request         = new NavigationRequest(target, navParams, area, mode);
                        IDisposable         navigationToken = nRoute.Navigation.NavigationService.Navigate(request);

                        if (navigationToken != null)
                        {
                            navigationToken.Dispose();
                            navigationToken = null;
                        }
                    }
                )
            );
        }
예제 #24
0
 public static SystemData Parse(IEnumerable <string> input)
 {
     return(new SystemData(ParametersCollection.ParseInput(input)));
 }
예제 #25
0
 public RouteData()
 {
     this._values     = new ParametersCollection();
     this._dataTokens = new ParametersCollection();
 }
예제 #26
0
        public BoundUrl Bind(ParametersCollection currentValues, ParametersCollection values,
                             ParametersCollection defaultValues, ParametersCollection constraints)
        {
            if (currentValues == null)
            {
                currentValues = new ParametersCollection();
            }
            if (values == null)
            {
                values = new ParametersCollection();
            }
            if (defaultValues == null)
            {
                defaultValues = new ParametersCollection();
            }
            ParametersCollection acceptedValues  = new ParametersCollection();
            List <string>        unusedNewValues = new List <string>(values.Keys);

            ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment)
            {
                object obj2;
                object obj3;
                string parameterName = parameterSubsegment.ParameterName;
                bool flag            = values.TryGetValue(parameterName, out obj2);
                if (flag)
                {
                    unusedNewValues.Remove(parameterName);
                }
                bool flag22 = currentValues.TryGetValue(parameterName, out obj3);
                if ((flag && flag22) && !RoutePartsEqual(obj3, obj2))
                {
                    return(false);
                }
                if (flag)
                {
                    if (IsRoutePartNonEmpty(obj2))
                    {
                        acceptedValues.Add(parameterName, obj2);
                    }
                }
                else if (flag22)
                {
                    acceptedValues.Add(parameterName, obj3);
                }
                return(true);
            });

            foreach (var pair in values)
            {
                if (IsRoutePartNonEmpty(pair.Value) && !acceptedValues.ContainsKey(pair.Key))
                {
                    acceptedValues.Add(pair.Key, pair.Value);
                }
            }

            foreach (var pair2 in currentValues)
            {
                string str = pair2.Key;
                if (!acceptedValues.ContainsKey(str) && (GetParameterSubsegment(this.PathSegments, str) == null))
                {
                    acceptedValues.Add(str, pair2.Value);
                }
            }

            ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment)
            {
                object obj2;
                if (!acceptedValues.ContainsKey(parameterSubsegment.ParameterName) &&
                    !IsParameterRequired(parameterSubsegment, defaultValues, out obj2))
                {
                    acceptedValues.Add(parameterSubsegment.ParameterName, obj2);
                }
                return(true);
            });

            if (!ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment)
            {
                object obj2;
                if (IsParameterRequired(parameterSubsegment, defaultValues, out obj2) &&
                    !acceptedValues.ContainsKey(parameterSubsegment.ParameterName))
                {
                    return(false);
                }
                return(true);
            }))
            {
                return(null);
            }

            ParametersCollection otherDefaultValues = new ParametersCollection(defaultValues);

            ForEachParameter(this.PathSegments, delegate(ParameterSubsegment parameterSubsegment)
            {
                otherDefaultValues.Remove(parameterSubsegment.ParameterName);
                return(true);
            });

            foreach (var pair3 in otherDefaultValues)
            {
                object obj2;
                if (values.TryGetValue(pair3.Key, out obj2))
                {
                    unusedNewValues.Remove(pair3.Key);
                    if (!RoutePartsEqual(obj2, pair3.Value))
                    {
                        return(null);
                    }
                }
            }

            StringBuilder builder  = new StringBuilder();
            StringBuilder builder2 = new StringBuilder();
            bool          flag2    = false;

            for (int i = 0; i < this.PathSegments.Count; i++)
            {
                PathSegment segment = this.PathSegments[i];
                if (segment is SeparatorPathSegment)
                {
                    if (flag2 && (builder2.Length > 0))
                    {
                        builder.Append(builder2.ToString());
                        builder2.Length = 0;
                    }
                    flag2 = false;
                    builder2.Append("/");
                }
                else
                {
                    ContentPathSegment segment2 = segment as ContentPathSegment;
                    if (segment2 != null)
                    {
                        bool flag3 = false;
                        foreach (PathSubsegment subsegment2 in segment2.Subsegments)
                        {
                            LiteralSubsegment subsegment3 = subsegment2 as LiteralSubsegment;
                            if (subsegment3 != null)
                            {
                                flag2 = true;
                                builder2.Append(Uri.EscapeUriString(subsegment3.Literal));
                            }
                            else
                            {
                                ParameterSubsegment subsegment4 = subsegment2 as ParameterSubsegment;
                                if (subsegment4 != null)
                                {
                                    object obj3;
                                    object obj4;
                                    if (flag2 && (builder2.Length > 0))
                                    {
                                        builder.Append(builder2.ToString());
                                        builder2.Length = 0;
                                        flag3           = true;
                                    }
                                    flag2 = false;
                                    if (acceptedValues.TryGetValue(subsegment4.ParameterName, out obj3))
                                    {
                                        unusedNewValues.Remove(subsegment4.ParameterName);
                                    }
                                    defaultValues.TryGetValue(subsegment4.ParameterName, out obj4);
                                    if (RoutePartsEqual(obj3, obj4))
                                    {
                                        builder2.Append(Uri.EscapeUriString(Convert.ToString(obj3, CultureInfo.InvariantCulture)));
                                        continue;
                                    }
                                    if (builder2.Length > 0)
                                    {
                                        builder.Append(builder2.ToString());
                                        builder2.Length = 0;
                                    }
                                    builder.Append(Uri.EscapeUriString(Convert.ToString(obj3, CultureInfo.InvariantCulture)));
                                    flag3 = true;
                                }
                            }
                        }
                        if (flag3 && (builder2.Length > 0))
                        {
                            builder.Append(builder2.ToString());
                            builder2.Length = 0;
                        }
                    }
                }
            }

            if (flag2 && (builder2.Length > 0))
            {
                builder.Append(builder2.ToString());
            }
            if (constraints != null)
            {
                foreach (var pair4 in constraints)
                {
                    unusedNewValues.Remove(pair4.Key);
                }
            }

            if (unusedNewValues.Count > 0)
            {
                bool flag5 = true;
                foreach (string str2 in unusedNewValues)
                {
                    object obj5;
                    if (acceptedValues.TryGetValue(str2, out obj5))
                    {
                        builder.Append(flag5 ? '?'
         : '&');
                        flag5 = false;
                        builder.Append(Uri.EscapeDataString(str2));
                        builder.Append('=');
                        builder.Append(Uri.EscapeDataString(Convert.ToString(obj5, CultureInfo.InvariantCulture)));
                    }
                }
            }

            return(new BoundUrl {
                Url = builder.ToString(), Values = acceptedValues
            });
        }
예제 #27
0
파일: dbFacade.cs 프로젝트: Digiman/ASTPP
        /// <summary>
        /// Вставляет несколько записей в таблицу.
        /// </summary>
        /// <param name="tablename">Имя таблицы</param>
        /// <param name="parametersCollection">Массив параметров/записей</param>
        /// <returns>Возвращает 0, если удачно</returns>
        public int InsertMany(string tablename, ParametersCollection[] parametersCollection)
        {
            ConnectionState previousConnectionState = ConnectionState.Closed;
            try
            {
                previousConnectionState = connect.State;
                if (connect.State == ConnectionState.Closed)
                {
                    connect.Open();
                }
                command = new SQLiteCommand(connect);
                foreach (ParametersCollection parameters in parametersCollection)
                {
                    bool ifFirst = true;
                    StringBuilder queryColumns = new StringBuilder("("); //список полей, в которые вставляются новые значения
                    StringBuilder queryValues = new StringBuilder("(");  //список значений для этих полей
                    foreach (Parameter iparam in parameters)
                    {
                        //добавляем новый параметр
                        command.Parameters.Add("@" + iparam.ColumnName, iparam.DbType).Value = Convert.IsDBNull(iparam.Value) ? Convert.DBNull : iparam.Value;
                        //собираем колонки и значения в одну строку
                        if (ifFirst)
                        {
                            queryColumns.Append(iparam.ColumnName);
                            queryValues.Append("@" + iparam.ColumnName);
                            ifFirst = false;
                        }
                        else
                        {
                            queryColumns.Append("," + iparam.ColumnName);
                            queryValues.Append(",@" + iparam.ColumnName);
                        }
                    }
                    queryColumns.Append(")");
                    queryValues.Append(")");
                    //создаем новый запрос
                    string sql = string.Format("INSERT INTO {0} {1} VALUES {2}", tablename, queryColumns, queryValues);
                    command.CommandText = sql;
                    command.ExecuteNonQuery();
                }
            }
            catch (Exception error)
            {
#if DEBUG
                System.Windows.Forms.MessageBox.Show(error.Message, "Ошибка при вставке новой записи в таблицу " + tablename, MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
                return 1;
            }
            finally
            {
                if (previousConnectionState == ConnectionState.Closed)
                {
                    connect.Close();
                }
            }
            return 0;
        }
예제 #28
0
 private static bool IsParameterRequired(ParameterSubsegment parameterSubsegment, ParametersCollection defaultValues,
                                         out object defaultValue)
 {
     if (parameterSubsegment.IsCatchAll)
     {
         defaultValue = null;
         return(false);
     }
     return(!defaultValues.TryGetValue(parameterSubsegment.ParameterName, out defaultValue));
 }
예제 #29
0
파일: dbFacade.cs 프로젝트: Digiman/ASTPP
        /// <summary>
        /// Перезаписывает данные в выбранной таблице.
        /// </summary>
        /// <param name="tablename">Имя таблицы</param>
        /// <param name="collection">Коллекция полей и значений</param>
        /// <param name="whereparams">Набор условий</param>
        /// <param name="whereseparator">Разделитель между условиями OR или AND</param>
        /// <returns>Код ошибки. Если 0, ошибки нет</returns>
        public int Update(string tablename, ParametersCollection collection, object[] whereparams, string whereseparator)
        {
            ConnectionState previousConnectionState = ConnectionState.Closed;
            try
            {
                //проверяем переданные аргументы
                if (whereparams.Length == 0) throw (new ExceptionWarning("Ошибка! Не указано ни одно условие"));
                if (whereparams.Length > 1 && whereseparator.Trim().Length == 0) throw (new ExceptionWarning("При использовании нескольких условий, требуется указать разделитель OR или AND"));

                previousConnectionState = connect.State;
                if (connect.State == ConnectionState.Closed)
                {
                    connect.Open();
                }

                int i = 0;
                //готовим переменную для сбора полей и их значений
                StringBuilder sql_params = new StringBuilder();
                bool ifFirst = true;
                command = new SQLiteCommand(connect);
                //в цикле создаем строку запроса 
                foreach (Parameter param in collection)
                {
                    if (ifFirst)
                    {
                        sql_params.Append(param.ColumnName + " = @param" + i);
                        ifFirst = false;
                    }
                    else
                    {
                        sql_params.Append("," + param.ColumnName + " = @param" + i);
                    }
                    //и добавляем параметры с таким же названием
                    command.Parameters.Add("@param" + i, param.DbType).Value = Convert.IsDBNull(param.Value) ? Convert.DBNull : param.Value;
                    i++;
                }

                //условия для запроса
                StringBuilder sql_where = new StringBuilder();
                ifFirst = true;
                //собираем строку с условиями
                foreach (object item in whereparams)
                {
                    if (ifFirst)
                    {
                        sql_where.Append(item.ToString());
                        ifFirst = false;
                    }
                    else
                    {
                        sql_where.Append(" " + whereseparator + " " + item);
                    }
                }

                //собираем запрос воедино
                command.CommandText = string.Format("UPDATE {0} SET {1} {2}", tablename, sql_params, "WHERE " + sql_where.ToString());
                //выполняем запрос
                command.ExecuteNonQuery();
            }
            catch (ExceptionWarning message)
            {
                System.Windows.Forms.MessageBox.Show(message.MessageText, "Ошибка при обновлении данных в таблице " + tablename, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return 1;
            }
            catch (Exception error)
            {
#if DEBUG
                System.Windows.Forms.MessageBox.Show(error.Message, "Ошибка при обновлении данных в таблице " + tablename, MessageBoxButtons.OK, MessageBoxIcon.Error);
#endif
                return 2;
            }
            finally
            {
                if (previousConnectionState == ConnectionState.Closed)
                {
                    connect.Close();
                }
            }
            return 0;
        }
예제 #30
0
        public ParametersCollection Match(string virtualPath, ParametersCollection defaultValues)
        {
            IList <string> source = RouteParser.SplitUrlToPathSegmentStrings(virtualPath);

            if (defaultValues == null)
            {
                defaultValues = new ParametersCollection();
            }
            ParametersCollection matchedValues = new ParametersCollection();
            bool flag  = false;
            bool flag2 = false;

            for (int i = 0; i < this.PathSegments.Count; i++)
            {
                PathSegment segment = this.PathSegments[i];
                if (source.Count <= i)
                {
                    flag = true;
                }
                string a = flag ? null : source[i];
                if (segment is SeparatorPathSegment)
                {
                    if (!flag && !string.Equals(a, "/", StringComparison.Ordinal))
                    {
                        return(null);
                    }
                }
                else
                {
                    ContentPathSegment contentPathSegment = segment as ContentPathSegment;
                    if (contentPathSegment != null)
                    {
                        if (contentPathSegment.IsCatchAll)
                        {
                            this.MatchCatchAll(contentPathSegment, source.Skip <string>(i), defaultValues, matchedValues);
                            flag2 = true;
                        }
                        else if (!this.MatchContentPathSegment(contentPathSegment, a, defaultValues, matchedValues))
                        {
                            return(null);
                        }
                    }
                }
            }
            if (!flag2 && (this.PathSegments.Count < source.Count))
            {
                for (int j = this.PathSegments.Count; j < source.Count; j++)
                {
                    if (!RouteParser.IsSeparator(source[j]))
                    {
                        return(null);
                    }
                }
            }
            if (defaultValues != null)
            {
                foreach (var pair in defaultValues)
                {
                    if (!matchedValues.ContainsKey(pair.Key))
                    {
                        matchedValues.Add(pair.Key, pair.Value);
                    }
                }
            }
            return(matchedValues);
        }
        public bool Insert(string table, ParametersCollection parameters)
        {
            ConnectionState previousConnectionState = ConnectionState.Closed;
            bool result = false;
            try
            {
                previousConnectionState = SqlCon.State;
                if (SqlCon.State == ConnectionState.Closed)
                {
                    SqlCon.Open();
                }
                SQLiteCommand command = new SQLiteCommand(SqlCon);
                bool ifFirst = true;
                StringBuilder queryColumns = new StringBuilder();
                StringBuilder queryValues = new StringBuilder();
                queryColumns.Append("("); //список полей, в которые вставляются новые значения
                queryValues.Append("(");  //список значений для этих полей
                foreach (Parameter iparam in parameters)
                {
                    //Add new parameter
                    command.Parameters.Add("@" + iparam.ColumnName, iparam.DbType).Value = iparam.Value;
                    //merge columns and values into one string
                    if (ifFirst)
                    {
                        queryColumns.Append(iparam.ColumnName);
                        queryValues.Append(string.Format("@{0}", iparam.ColumnName));
                        ifFirst = false;
                    }
                    else
                    {
                        queryColumns.Append(string.Format(",{0}", iparam.ColumnName));
                        queryValues.Append(string.Format(",@{0}", iparam.ColumnName));
                    }
                }
                queryColumns.Append(")");
                queryValues.Append(")");

                //create new query string
                string sql = string.Format("INSERT INTO {0} {1} VALUES {2}", table, queryColumns.ToString(), queryValues.ToString());
                command.CommandText = sql;
                int count = command.ExecuteNonQuery();
                command.Dispose();
                result = true;
            }
            catch (Exception ex)
            {
                LoggingModule.Instance.WriteMessage(LoggingModule.Severity.Error, ex.Message);
                result = false;
            }

            return result;
        }
예제 #32
0
        private bool MatchContentPathSegment(ContentPathSegment routeSegment, string requestPathSegment,
                                             ParametersCollection defaultValues, ParametersCollection matchedValues)
        {
            if (string.IsNullOrEmpty(requestPathSegment))
            {
                if (routeSegment.Subsegments.Count <= 1)
                {
                    object obj2;
                    ParameterSubsegment subsegment = routeSegment.Subsegments[0] as ParameterSubsegment;
                    if (subsegment == null)
                    {
                        return(false);
                    }
                    if (defaultValues.TryGetValue(subsegment.ParameterName, out obj2))
                    {
                        matchedValues.Add(subsegment.ParameterName, obj2);
                        return(true);
                    }
                }
                return(false);
            }

            int length = requestPathSegment.Length;
            int num2   = routeSegment.Subsegments.Count - 1;
            ParameterSubsegment subsegment2 = null;
            LiteralSubsegment   subsegment3 = null;

            while (num2 >= 0)
            {
                int num3 = length;
                ParameterSubsegment subsegment4 = routeSegment.Subsegments[num2] as ParameterSubsegment;
                if (subsegment4 != null)
                {
                    subsegment2 = subsegment4;
                }
                else
                {
                    LiteralSubsegment subsegment5 = routeSegment.Subsegments[num2] as LiteralSubsegment;
                    if (subsegment5 != null)
                    {
                        subsegment3 = subsegment5;
                        int num4 = requestPathSegment.LastIndexOf(subsegment5.Literal, length - 1, StringComparison.OrdinalIgnoreCase);
                        if (num4 == -1)
                        {
                            return(false);
                        }
                        if ((num2 == (routeSegment.Subsegments.Count - 1)) &&
                            ((num4 + subsegment5.Literal.Length) != requestPathSegment.Length))
                        {
                            return(false);
                        }
                        num3 = num4;
                    }
                }
                if ((subsegment2 != null) && (((subsegment3 != null) && (subsegment4 == null)) || (num2 == 0)))
                {
                    int num5;
                    int num6;
                    if (subsegment3 == null)
                    {
                        if (num2 == 0)
                        {
                            num5 = 0;
                        }
                        else
                        {
                            num5 = num3 + subsegment3.Literal.Length;
                        }
                        num6 = length;
                    }
                    else if ((num2 == 0) && (subsegment4 != null))
                    {
                        num5 = 0;
                        num6 = length;
                    }
                    else
                    {
                        num5 = num3 + subsegment3.Literal.Length;
                        num6 = length - num5;
                    }
                    string str = requestPathSegment.Substring(num5, num6);
                    if (string.IsNullOrEmpty(str))
                    {
                        return(false);
                    }
                    matchedValues.Add(subsegment2.ParameterName, str);
                    subsegment2 = null;
                    subsegment3 = null;
                }
                length = num3;
                num2--;
            }
            if (length != 0)
            {
                return(routeSegment.Subsegments[0] is ParameterSubsegment);
            }
            return(true);
        }
 public NavigationRequest(string url, ParametersCollection requestParameters)
     : this(url, requestParameters, null)
 {
 }
 public NavigationRequest(string url, ParametersCollection requestParameters, string siteArea)
     : base(url, requestParameters, siteArea)
 {
 }
예제 #35
0
파일: HttpUrl.cs 프로젝트: alien-mcl/URSA
        private static string ToRelativeString(string path, ParametersCollection query = null, string fragment = null)
        {
            if (path.Length == 0)
            {
                path = "/";
            }

            return String.Format(
                "{0}{1}{2}",
                path,
                (query != null ? String.Format("?{0}", query.ToString(HttpUrlParser.PathAllowedChars)) : String.Empty),
                (fragment != null ? String.Format("#{0}", UrlParser.ToSafeString(fragment, HttpUrlParser.PathAllowedChars)) : String.Empty));
        }
 public NavigationRequest(string url, ParametersCollection requestParameters, NavigateMode navigationMode)
     : this(url, requestParameters, null, navigationMode)
 {
 }
예제 #37
0
 public void Setup()
 {
     var parameters = new ParametersCollection("&", "=");
     parameters.AddValue("with", "query");
     _url = new HttpUrl(true, "http://temp.uri/whatever/path?with=query#and-fragment", "http", "temp.uri", 80, "/whatever/path", parameters, "and-fragment", "whatever", "path");
 }
 public NavigationRequest(string url, ParametersCollection requestParameters, string siteArea, NavigateMode navigationMode)
     : base(url, requestParameters, siteArea)
 {
     _navigateMode = navigationMode;
 }
예제 #39
0
 /// <summary>
 /// Initializes the specified request parameters.
 /// </summary>
 /// <param name="requestParameters">The request parameters.</param>
 void ISupportNavigationLifecycle.Initialize(ParametersCollection requestParameters)
 {
     this.OnInitialize(requestParameters);
 }
예제 #40
0
 void ISupportNavigationViewState.RestoreState(ParametersCollection state)
 {
     OnRestoreState(state);
 }
예제 #41
0
 /// <summary>
 /// Called when the window is going to be initialized after navigation.
 /// </summary>
 /// <param name="requestParameters">The request parameters.</param>
 protected virtual void OnInitialize(ParametersCollection requestParameters)
 {
 }
예제 #42
0
 public static void MapRoute(string url, ParametersCollection defaults, IRouteHandler handler)
 {
     MapRoute(null, url, defaults, null, null, handler);
 }
예제 #43
0
 public void Setup()
 {
     _parameters = new ParametersCollection("&", "=");
 }
예제 #44
0
 public static void MapRoute(string routeName, string url, ParametersCollection defaults, ParametersCollection constraints,
                             IRouteHandler handler)
 {
     MapRoute(routeName, url, defaults, constraints, null, handler);
 }
예제 #45
0
 public void Setup()
 {
     var parameters = new ParametersCollection(";", "=");
     parameters.AddValue("type", "i");
     _url = new FtpUrl("ftp://temp.uri/whatever/path;type=i", "ftp", null, null, "temp.uri", 21, "/whatever/path", parameters, "whatever", "path");
 }
예제 #46
0
        private static ResponseStatus OnResolveRoute(IUrlRequest request, bool throwException, out IRoutingContext context)
        {
            Guard.ArgumentNotNull(request, "request");
            Guard.ArgumentValue((!ValidateUrl(request.RequestUrl, false)), "request", INVALID_REQUEST_URL);

            // default value
            context = null;

            // we check the url
            if (!ValidateUrl(request.RequestUrl, throwException))
            {
                return(ResponseStatus.UrlInvalid);
            }

            // we get the route data first
            RouteData routeData = RouteTable.Routes.GetRouteData(request);

            if (routeData == null)
            {
                if (throwException)
                {
                    throw new InvalidOperationException(NO_ROUTE_MATCHES);
                }
                return(ResponseStatus.UrlNotFound);
            }

            // we get the route handler
            IRouteHandler routeHandler = routeData.RouteHandler;

            if (routeHandler == null)
            {
                if (throwException)
                {
                    throw new InvalidOperationException(NO_ROUTE_HANDLER);
                }
                return(ResponseStatus.HandlerNotFound);
            }

            // we merge the dictionaries (into the request parameters)
            var _requestParameters = new ParametersCollection();

            // we add the data-tokens specified with route, n_ote these can be overriden
            if (routeData.DataTokens != null && routeData.DataTokens.Count > 0)
            {
                // we add the values, from the routes data, if it exists then we update the value
                foreach (var _parameter in routeData.DataTokens)
                {
                    _requestParameters.Add(_parameter.Key, _parameter.Value);
                }
            }

            // we add the values found in the url merged with the default values, n_ote these can be overriden
            if (routeData.Values != null && routeData.Values.Count > 0)
            {
                // we add the values, from the routes data, if it exists then we update the value
                foreach (var _parameter in routeData.Values)
                {
                    if (_requestParameters.ContainsKey(_parameter.Key))
                    {
                        _requestParameters[_parameter.Key] = _parameter.Value;
                    }
                    else
                    {
                        _requestParameters.Add(_parameter.Key, _parameter.Value);
                    }
                }
            }

            // and our passed in parameters will override any existing entry
            if (request.RequestParameters != null && request.RequestParameters.Count > 0)
            {
                foreach (var _parameter in request.RequestParameters)
                {
                    if (_requestParameters.ContainsKey(_parameter.Key))
                    {
                        _requestParameters[_parameter.Key] = _parameter.Value;
                    }
                    else
                    {
                        _requestParameters.Add(_parameter.Key, _parameter.Value);
                    }
                }
            }

            // we setup the request cotext and get the response
            context = new RoutingContext(request, routeData, _requestParameters);
            return(ResponseStatus.Success);
        }
예제 #47
0
		public ReportDefinitionBase() {
			_widgets.Definition = this;
			templateParameters = new ParametersCollection();
			templateParameters.Report = this;
		}
예제 #48
0
 public LocationAgePush(ParametersCollection parameters)
     : base(parameters)
 {
 }
예제 #49
0
		public Optimizer()
		{
			//m_started = false;
			m_parts = new List<Part>();
			m_sheets = new List<Sheet>();
			m_parameters = new ParametersCollection();
		}
 public virtual void Navigate(string url, ParametersCollection requestParameters)
 {
     OnNavigate(new NavigationRequest(url, requestParameters, NavigateMode.New));
 }