Пример #1
0
        private Dictionary <string, string> ProcessTimeWindows()
        {
            Dictionary <string, string> timeWindowInfo = new Dictionary <string, string>();
            Regex r3 = new Regex(@"\s{0,}--DataXQuery--\s{0,}([^;]*?)FROM\s{1,}([^\s]+)(\s{1,})TIMEWINDOW\s{0,}\(\s{0,}(.*?)\s{0,}\)\s{0,}([^;]*?)", RegexOptions.IgnoreCase);

            MatchCollection m3 = r3.Matches(_code);

            if (m3 != null && m3.Count > 0)
            {
                foreach (Match m in m3)
                {
                    var    timeWindowStr = Regex.Replace(m.Groups[4].Value.Trim(), "'", string.Empty, RegexOptions.IgnoreCase);
                    var    newTableName  = m.Groups[2].Value.Trim() + "_" + timeWindowStr.Replace(" ", string.Empty);
                    string newQuery      = m.Groups[0].Value;
                    if (!Regex.Equals(m.Groups[2].Value.Trim().ToLower(), @"dataxprocessedinput"))
                    {
                        throw new Exception("'DataXProcessedInput' is the only table for which the TIMEWINDOW can be specified");
                    }
                    else
                    {
                        newQuery = Regex.Replace(newQuery, @"\bDataXProcessedInput\b", newTableName, RegexOptions.IgnoreCase);
                        newQuery = Regex.Replace(newQuery, m.Groups[4].Value.Trim(), "");
                        newQuery = Regex.Replace(newQuery, @"(TIMEWINDOW\s{0,}\(\s{0,}\)\s{0,})", string.Empty, RegexOptions.IgnoreCase);
                        if (!timeWindowInfo.ContainsKey(newTableName))
                        {
                            timeWindowInfo.Add(newTableName, timeWindowStr);
                        }

                        _code = _code.Replace(m.Groups[0].Value, newQuery);
                    }
                }
            }
            return(timeWindowInfo);
        }
        static void Main()
        {
            int    leftB  = 0;
            int    rightB = 0;
            string input  = Console.ReadLine();
            string output;

            leftB  = new Regex(Regex.Escape("("), RegexOptions.IgnoreCase).Matches(input).Count;
            rightB = new Regex(Regex.Escape(")"), RegexOptions.IgnoreCase).Matches(input).Count;

            if (leftB.Equals(rightB) == false)
            {
                output = "Incorrect";
            }
            else if (input.IndexOf(')') < input.IndexOf('('))
            {
                output = "Incorrect";
            }
            else
            {
                output = "Correct";
            }

            Console.WriteLine(output);
        }
        private void supprimercol_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp;
            Excel.Workbook    xlWorkBook;
            object            misValue = System.Reflection.Missing.Value;

            xlApp               = new Excel.ApplicationClass();
            xlApp.Visible       = true;
            xlApp.DisplayAlerts = false;
            xlWorkBook          = xlApp.Workbooks.Open(prefaceNP, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, true, false);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Historique-s");
            Excel.Range     range       = xlWorkSheet.UsedRange;
            object[,] values = (object[, ])range.Value2;

            int time1 = System.Environment.TickCount;
            ////////////////////////////////////////400000//////////////////////
            int rCnt      = 0;
            int cCnt      = 0;
            int row400000 = 0;

            cCnt = range.Columns.Count;
            for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
            {
                string valuecellabs = Convert.ToString(values[rCnt, cCnt]);
                if (Regex.Equals(valuecellabs, "400000"))
                {
                    row400000 = rCnt;
                    break;
                }
            }

            for (int col = 1; col <= xlWorkSheet.UsedRange.Columns.Count; col++)
            {
                string value = Convert.ToString(values[row400000, col]);
                if (Regex.Equals(value, "-1"))
                {
                    Excel.Range rangeDelx = xlWorkSheet.Cells[row400000, col] as Excel.Range;
                    rangeDelx.EntireColumn.Delete(Excel.XlDeleteShiftDirection.xlShiftToLeft);

                    range  = xlWorkSheet.UsedRange;
                    values = (object[, ])range.Value2;
                    col--;
                }
            }
            xlWorkSheet.SaveAs(prefaceNP, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
            xlApp.DisplayAlerts = true;
            xlWorkBook.Close(true, misValue, misValue);
            xlApp.Quit();

            int    time2 = System.Environment.TickCount;
            int    times = time2 - time1;
            string tim   = Convert.ToString(Convert.ToDecimal(times) / 1000);

            //MessageBox.Show("jobs done " + tim + " seconds used");

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }
Пример #4
0
 public bool Equals(StreamFilter other) =>
 Prefixes == null || other.Prefixes == null
                         ? Prefixes == other.Prefixes &&
 Regex.Equals(other.Regex) &&
 MaxSearchWindow.Equals(other.MaxSearchWindow)
                         : Prefixes.SequenceEqual(other.Prefixes) &&
 Regex.Equals(other.Regex) &&
 MaxSearchWindow.Equals(other.MaxSearchWindow);
Пример #5
0
        /**<summary>Assigns a value (string + Expression()) into variables (dictionary). Outputs "Invalid Assignment!"
         * if assignment is invalid and exits/returns the function</summary>
         *
         * <remarks>The assignment is invalid if fails to meet any one of the following criteria:
         * <list type="bullet">
         * <item><term>If the expression contains more than one "=" characters</term></item>
         * <item><term>If the variables name contains no spaces and no numbers</term></item>
         * <item><term>If the expression is valid, see <see cref="Expression.IsExpressionValid()"/></term></item>
         * </list>
         * </remarks>
         */
        public static void Assign(string assignmentExpression)
        {
            #region CHECK_IF_THE_ASSIGNMENT_IS_CORRECT

            var variableAndExpression = assignmentExpression.Split("=");

            //the assignment expression can only have one equal
            if (variableAndExpression.Length != 2)
            {
                AnsiConsole.MarkupLine("[red]Invalid Assignment![/]");
                return;
            }

            var variable   = variableAndExpression[0].Trim();
            var expression = new Expression(variableAndExpression[1].Trim());

            //checks if the variable's name is valid (no spaces, no numbers)
            variable = new Regex(" +").Replace(variable, " ");
            if (Regex.IsMatch(variable, "\\d+") || variable.Contains(" "))
            {
                AnsiConsole.MarkupLine("[red]Invalid Assignment![/]");
                return;
            }

            //checks if the expression is valid
            if (!expression.IsValid)
            {
                AnsiConsole.MarkupLine("[red]Invalid Assignment![/]");
                return;
            }

            //checks if the variable is already defined as a constant
            if (constants.ContainsKey(variable.Trim().ToLower()))
            {
                AnsiConsole.MarkupLine($"[red]\"{variable}\" is already defined as a constant![/]");
                return;
            }

            //prevents the (re)assigning of a function. ex "sin = 20"
            if (CheckMethods.IsAFunction(variable))
            {
                AnsiConsole.MarkupLine($"[red]You can't (re)assign a function![/]");
                return;
            }

            #endregion

            if (variable.Equals("ans"))
            {
                AnsiConsole.MarkupLine($"[red]You can't re-assign \"{variable}\", it stores the value of the previous " +
                                       "expression.[/]");
                return;
            }


            variables[variable] = expression;
            AnsiConsole.MarkupLine("[blue]Assigned![/]");
        }
Пример #6
0
        public bool UsernameIncorrect(string input)
        {
            string pattern = @"^a-zA-Z";

            if (Regex.Equals(input, pattern))
            {
                return(true);
            }
            return(false);
        }
Пример #7
0
 private bool TitlesAreSimilar(string a, string b)
 {
     // strip prefixes
     a = _reIsNavigationItem.Replace(a, "");
     b = _reIsNavigationItem.Replace(b, "");
     a = new Regex(" ").Replace(a, "");
     b = new Regex(" ").Replace(b, "");
     a = a.ToLower();
     b = b.ToLower();
     return(a.Equals(b));
 }
Пример #8
0
        private static void CountPol(String enterStr)
        {
            enterStr = new Regex(@"\W").Replace(enterStr, "");
            String newStr = new String(enterStr.ToCharArray().Reverse().ToArray());

            if (enterStr.Equals(newStr))
            {
                Console.WriteLine("Полиндром");
            }
            else
            {
                Console.WriteLine("Не полиндром");
            }
        }
        private void consigneProteger()
        {
            Excel.Application xlApp;
            Excel.Workbook    xlWorkBook;
            object            misValue = System.Reflection.Missing.Value;

            xlApp               = new Excel.ApplicationClass();
            xlApp.Visible       = true;
            xlApp.DisplayAlerts = false;

            xlWorkBook = xlApp.Workbooks.Open(prefaceNP, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, true, false);

            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Historique-s");
            Excel.Range     range       = xlWorkSheet.UsedRange;
            int             rowcount    = xlWorkSheet.UsedRange.Rows.Count;

            object[,] values = (object[, ])range.Value2;

            int rCnt = 0;
            int cCnt = 0;
            int col  = 0;

            rCnt = range.Rows.Count;
            for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
            {
                string valuecellabs = Convert.ToString(values[rCnt, cCnt]);
                if (Regex.Equals(valuecellabs, "15000"))
                {
                    col = cCnt;
                    break;
                }
            }

            //Routine pour modifier col XXXXX marquer ligne proteger -1
            for (int i = 1; i < rowcount - 5; i++)
            {
                if ((xlWorkSheet.Cells[i, 3] as Excel.Range).Locked.ToString() == "True")
                {
                    (xlWorkSheet.Cells[i, col] as Excel.Range).Value2 = "-1";
                }
            }


            xlApp.Save(misValue);
            xlApp.Quit();

            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }
Пример #10
0
        /// <summary>
        /// 检测是否登录成功前的检测
        /// </summary>
        /// <returns></returns>
        public bool GetLoginParamter()
        {
            string html = client.GetStringAsync(SmartQQAPI.GetLoginParamter);

            checkloginData["aid"]       = new Regex("<input type=\"hidden\" name=\"aid\" value=\"(\\d+?)\" />").Match(html).Groups[1].Value;
            checkloginData["mibao_css"] = new Regex("g_mibao_css=encodeURIComponent\\(\"(.+?)\"\\)").Match(html).Groups[1].Value;
            string vsig  = new Regex("g_login_sig=encodeURIComponent\\(\"(.*?)\"\\)").Match(html).Groups[1].Value;
            string vjver = new Regex("g_pt_version=encodeURIComponent\\(\"(\\d +?)\"\\)").Match(html).Groups[1].Value;

            if (!vsig.Equals(""))
            {
                checkloginData["login_sig"] = vsig;
            }
            if (!vjver.Equals(""))
            {
                checkloginData["js_ver"] = vjver;
            }
            return(true);
        }
Пример #11
0
        /// <summary>
        /// Get value of the token from BibTeX stream by regular expression
        /// </summary>
        /// <exception cref="EndOfStreamException"></exception>
        /// <param name="seprators">Instance of Regex provides separators to get token</param>
        /// <returns>Return value of token</returns>
        private string GetToken(Regex seprators)
        {
            StringBuilder token = new StringBuilder();

            try
            {
                //  this._nextCharacter is empty if condition is true.
                if (!this.firstTime)
                {
                    this.nextCharacter = (char)this.tokenStream.ReadByte();
                    this.firstTime     = true;
                }
                // if true then separator is occurred in the BibTeX stream.
                if (!seprators.IsMatch(this.nextCharacter.ToString()))
                {
                    token.Append(this.nextCharacter);
                    this.ReadNextChar();
                }
                else
                {
                    // Read character till separator is not occurred then create token value from read
                    // character
                    while (seprators.IsMatch(this.nextCharacter.ToString()))
                    {
                        token.Append(this.nextCharacter);
                        this.ReadNextChar();
                    }
                    // Ignore empty token if token is not the part of the field value
                    if (token.ToString().Trim().Length == 0 && !seprators.Equals(this.fieldRegEx))
                    {
                        token.Append(this.nextCharacter);
                        this.ReadNextChar();
                    }
                }
            }
            catch (EndOfStreamException)
            {
                this.lastTokenEncountered = true;
            }
            this.prevToPrevToken = this.prevToken;
            this.prevToken       = token.ToString().Trim();
            return(token.ToString());
        }
Пример #12
0
        public void InterceptSpecialCommands(string input)
        {
            Trace.Assert(!String.IsNullOrWhiteSpace(input));
            Trace.Assert(input.StartsWith("."));

            string commandName = new Regex(@"\.([A-z0-9])+").Match(input).Captures[0].Value.Substring(1).Trim();

            if (commandName.Equals("help"))
            {
                console.log(helpManager.GetHelpString());
                return;
            }
            if (!commands.ContainsKey(commandName))
            {
                console.log("Could not find command: " + input);
                return;
            }
            IConsoleCommand command = (IConsoleCommand)kernel.Get(commands[commandName]);

            command.Execute(ParseSpecialCommandInputs(input));
        }
Пример #13
0
        /// <summary>
        /// Method overrides default binding as config file cannot be used
        /// </summary>
        private void SetBindingRedirect()
        {
            AppDomain.CurrentDomain.AssemblyResolve += (sender, resolveArgs) =>
            {
                if (resolveArgs.Name.Contains("resources"))
                {
                    return(null);
                }

                //Bruteforce bidning redirect
                // Get just the name of assmebly
                // Aseembly name excluding version and other metadata
                string name = new Regex(",.*").Replace(resolveArgs.Name, string.Empty);

                if (name.Equals(resolveArgs.Name))
                {
                    return(null);
                }

                // Load whatever version available
                return(Assembly.Load(name));
            };
        }
Пример #14
0
        // void display(int iSalary): đếm và in danh sách nhân viên có mức lương trên iSalary USD. CT sẽ in thông báo nếu hệ thống chưa có dữ liệu hoặc không tìm thấy nhân viên nào.
        public void displaySalary(int iSalary)
        {
            if (ds.Count == 0)
            {
                Console.WriteLine("He thong chua co du lieu");
                return;
            }
            int cntSalary = 0;

            Console.WriteLine("Danh sach nhan vien ");
            foreach (var item in ds.Values)
            {
                if (Regex.Equals(item.baseSalary, iSalary))
                {
                    Console.WriteLine(item);
                    cntSalary++;
                }
            } // ket thuc foreach
            if (cntSalary == 0)
            {
                Console.WriteLine("Khong tim thay !!!");
            }
        }
Пример #15
0
    void Load()
    {
        //print("Load: " + SaveName);
        if (string.IsNullOrEmpty(SaveName))
        {
            return;
        }

        LoadUI.SetActive(false);
        ControlScript.CurrentMode = ControlScript.Mode.Build;
        string data = PlayerPrefs.GetString(SaveName + "Data");

        using (StringReader sr = new StringReader(data))
        {
            int        i             = 0;
            GameObject temp          = null;
            object     tempComponent = null;
            FieldInfo  tempFieldInfo = null;
            bool       powerline     = false;
            while (true)
            {
                string line = sr.ReadLine();
                if (string.IsNullOrEmpty(line))
                {
                    break;
                }
                if (line.Contains("Player "))
                {
                    line = Regex.Replace(line, "Player ", "");
                    line = Regex.Replace(line, @"\(", "");
                    line = Regex.Replace(line, @"\)", "");
                    line = Regex.Replace(line, @"\t", "");
                    line = Regex.Replace(line, @"\s", "");
                    string[] pos = Regex.Split(line, ",");
                    //print(pos[2]);
                    GameObject.Find("Player").transform.position = new Vector3(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2]));
                }
                if (line[0] != '\t')
                {
                    i = 0;
                    foreach (GameObject prefab in Prefabs)
                    {
                        if (Regex.Equals(line.Replace("(Clone)", ""), prefab.name.Replace("(Clone)", "")))
                        {
                            temp      = (GameObject)Instantiate(prefab);
                            temp.name = temp.name.Replace("(Clone)", "");

                            //print("Prefab: " + prefab);
                            powerline = false;
                            i         = 1;

                            if (temp.name == "Power Line")
                            {
                                powerline = true;
                            }
                            if (ControlScript.CurrentMode == ControlScript.Mode.Build)
                            {
                                if (temp.layer == 8)
                                {
                                    temp.GetComponent <SpriteRenderer>().enabled = true;
                                }
                                else if (temp.layer == 10)
                                {
                                    temp.GetComponent <SpriteRenderer>().enabled = false;
                                }
                                else if (temp.name == "Power Line")
                                {
                                    temp.GetComponent <LineRenderer>().enabled = false;
                                }
                            }
                            else if (ControlScript.CurrentMode == ControlScript.Mode.Connect)
                            {
                                if (temp.layer == 8)
                                {
                                    temp.GetComponent <SpriteRenderer>().enabled = false;
                                }
                                else if (temp.layer == 10)
                                {
                                    temp.GetComponent <SpriteRenderer>().enabled = true;
                                }
                                else if (temp.name == "Power Line")
                                {
                                    temp.GetComponent <LineRenderer>().enabled = true;
                                }
                            }
                            else if (ControlScript.CurrentMode == ControlScript.Mode.Play)
                            {
                                if (temp.layer == 8)
                                {
                                    temp.GetComponent <SpriteRenderer>().enabled = false;
                                }
                                else if (temp.layer == 10)
                                {
                                    temp.GetComponent <SpriteRenderer>().enabled = false;
                                }
                                else if (temp.name == "Power Line")
                                {
                                    temp.GetComponent <LineRenderer>().enabled = false;
                                }
                            }
                            break;
                        }
                    }
                }
                else
                {
                    if (i == 1)
                    {
                        line = Regex.Replace(line, @"\(", "");
                        line = Regex.Replace(line, @"\)", "");
                        line = Regex.Replace(line, @"\t", "");
                        line = Regex.Replace(line, @"\s", "");
                        string[] pos = Regex.Split(line, ",");
                        //print(pos[2]);
                        temp.transform.position = new Vector3(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2]));
                        i++;
                    }
                    else if (i == 2)
                    {
                        line = Regex.Replace(line, @"\(", "");
                        line = Regex.Replace(line, @"\)", "");
                        line = Regex.Replace(line, @"\t", "");
                        line = Regex.Replace(line, @"\s", "");
                        string[] pos = Regex.Split(line, ",");
                        temp.transform.rotation = new Quaternion(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2]), float.Parse(pos[3]));
                        i++;
                    }
                    else if (i >= 3)
                    {
                        if (powerline)
                        {
                            line = Regex.Replace(line, @"\(", "");
                            line = Regex.Replace(line, @"\)", "");
                            line = Regex.Replace(line, @"\t", "");
                            line = Regex.Replace(line, @"\s", "");
                            string[] pos = Regex.Split(line, ",");
                            Vector3  v   = new Vector3(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2]));
                            temp.GetComponent <LineRenderer>().SetPosition(i - 3, v);
                            temp.GetComponent <PowerLineScript>().AddConnectedDotsFromLoad(v);
                            i++;
                        }
                        else
                        {
                            if (line[0] == '\t')
                            {
                                if (line[1] != '\t')
                                {
                                    //component
                                    line = Regex.Replace(line, @"\t", "");
                                    //print("Component: " + line);
                                    tempComponent = temp.GetComponent(line);
                                }
                                else
                                {
                                    if (line[2] != '\t')
                                    {
                                        //Variable
                                        line = Regex.Replace(line, @"\t", "");
                                        //print("Variable: " + line);

                                        tempFieldInfo = tempComponent.GetType().GetField(line);
                                        //Value
                                    }
                                    else
                                    {
                                        //Value
                                        line = Regex.Replace(line, @"\t", "");
                                        if (tempFieldInfo.FieldType == typeof(bool))
                                        {
                                            //print(line);
                                            //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, bool.Parse(line));
                                            tempFieldInfo.SetValue(tempComponent, bool.Parse(line));
                                        }
                                        if (tempFieldInfo.FieldType == typeof(int))
                                        {
                                            //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, int.Parse(line));
                                            tempFieldInfo.SetValue(tempComponent, int.Parse(line));
                                        }
                                        if (tempFieldInfo.FieldType == typeof(float))
                                        {
                                            //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, float.Parse(line));
                                            tempFieldInfo.SetValue(tempComponent, float.Parse(line));
                                        }
                                        if (tempFieldInfo.FieldType == typeof(LogicGate.GateType))
                                        {
                                            //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, line);
                                            switch (line)
                                            {
                                            case "AND": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.AND));
                                                break;

                                            case "OR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.OR));
                                                break;

                                            case "XOR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.XOR));
                                                break;

                                            case "NOT": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.NOT));
                                                break;

                                            case "NAND": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.NAND));
                                                break;

                                            case "NOR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.NOR));
                                                break;

                                            case "XNOR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.XNOR));
                                                break;

                                            default:
                                                break;
                                            }
                                        }
                                        if (tempFieldInfo.FieldType == typeof(IOObject.Direction))
                                        {
                                            //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, line);
                                            switch (line)
                                            {
                                            case "Up": tempFieldInfo.SetValue(tempComponent, IOObject.Direction.Up);
                                                break;

                                            case "Down": tempFieldInfo.SetValue(tempComponent, IOObject.Direction.Down);
                                                break;

                                            case "Left": tempFieldInfo.SetValue(tempComponent, IOObject.Direction.Left);
                                                break;

                                            case "Right": tempFieldInfo.SetValue(tempComponent, IOObject.Direction.Right);
                                                break;

                                            default:
                                                break;
                                            }
                                        }
                                        if (tempFieldInfo.FieldType == typeof(FacingDirection))
                                        {
                                            //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, line);
                                            switch (line)
                                            {
                                            case "Up": tempFieldInfo.SetValue(tempComponent, FacingDirection.Up);
                                                break;

                                            case "Down": tempFieldInfo.SetValue(tempComponent, FacingDirection.Down);
                                                break;

                                            case "Left": tempFieldInfo.SetValue(tempComponent, FacingDirection.Left);
                                                break;

                                            case "Right": tempFieldInfo.SetValue(tempComponent, FacingDirection.Right);
                                                break;

                                            default:
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Loading = false;
    }
Пример #16
0
        public static bool IsAPalindrome(string phrase)
        {
            var cleanPhrase = new Regex(@"[\s.;,?%0-9]").Replace(phrase, string.Empty);

            return(cleanPhrase.Equals(new string(cleanPhrase.Reverse().ToArray()), StringComparison.OrdinalIgnoreCase));
        }
Пример #17
0
 public bool Equals(Core.Matcher other)
 {
     return(other.GetType() == typeof(RegexMatcher) && regex.Equals(((RegexMatcher)other).regex));
 }
Пример #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.AppendText("Start decoupage");
            string pathnotapme = @"D:\ptw\notepme";
            //pathstylerfinal =  @textBox12.Text + "\\changeStyle\\divi\\final";

            string openfilex = @"D:\ptw\Histo.xlsx";

            ////////////////open excel///////////////////////////////////////
            Thread.Sleep(3000);
            Excel.Application xlApp;
            Excel.Workbook    xlWorkBook;
            Excel.Workbook    xlWorkBookx1;
            Excel.Workbook    xlWorkBooknewx1;
            object            misValue = System.Reflection.Missing.Value;

            //////////creat modele histox.xls pour fichier diviser////////////////////////////////
            Excel.Application xlAppRef;
            Excel.Workbook    xlWorkBookRef;
            xlAppRef               = new Excel.ApplicationClass();
            xlAppRef.Visible       = false;; xlAppRef.DisplayAlerts = false; xlAppRef.ScreenUpdating = false;
            xlAppRef.DisplayAlerts = false;
            xlWorkBookRef          = xlAppRef.Workbooks.Open(openfilex, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //xlWorkBookRef = xlAppRef.Workbooks.Open(openfilex, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);


            Excel.Worksheet xlWorkSheetRef = (Excel.Worksheet)xlWorkBookRef.Worksheets.get_Item("Historique");
            Excel.Range     rangeRefall    = xlWorkSheetRef.get_Range("A1", "W" + getRowsLimit(xlWorkSheetRef));
            object[,] valuess = (object[, ])rangeRefall.Value2;
            //bug : le seul moyen pour supprimer la dernière colonne est de chnager la largeur de toutes les colonnes (on ne sait pas pourquoi) !!!

            // xlWorkSheetRef.Cells.ColumnWidth = 20;
            int rowcount = rangeRefall.Rows.Count;
            int colcount = rangeRefall.Columns.Count;

            Excel.Range rangeRef = xlWorkSheetRef.get_Range("A" + getRowsLimit(xlWorkSheetRef), "W" + getRowsLimit(xlWorkSheetRef));
            rangeRef.EntireRow.Copy(misValue);

            rangeRef.EntireRow.PasteSpecial(Excel.XlPasteType.xlPasteValues, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone, misValue, misValue);
            Excel.Range rangeRefdel = xlWorkSheetRef.UsedRange.get_Range("X1", xlWorkSheetRef.Cells[1, xlWorkSheetRef.UsedRange.Columns.Count - 1]) as Excel.Range;
            rangeRefdel.EntireColumn.ClearContents();
            rangeRefdel.EntireColumn.ClearFormats();
            rangeRefdel.EntireColumn.Clear();
            try
            {
                rangeRefdel = xlWorkSheetRef.UsedRange.get_Range("A" + (1 + getRowsLimit(xlWorkSheetRef)), "A" + xlWorkSheetRef.UsedRange.Rows.Count) as Excel.Range;
            }
            catch (Exception rx)
            {
                textBox1.AppendText(rx.ToString());
            }
            rangeRefdel.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

            rangeRefdel = xlWorkSheetRef.UsedRange.get_Range("A1", "W" + (getRowsLimit(xlWorkSheetRef) - 1)) as Excel.Range;
            rangeRefdel.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
            Excel.Range rangeA1 = xlWorkSheetRef.Cells[1, 1] as Excel.Range;
            rangeA1.Activate();

            xlWorkSheetRef.SaveAs(@"D:\ptw\Histo.xlsx", misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
            xlWorkBookRef.Close(true, misValue, misValue);
            xlAppRef.Quit();
            //////////////////////////////////////////////////////////////////////////////////
            Thread.Sleep(3000);
            xlApp                           = new Excel.ApplicationClass();
            xlApp.Visible                   = false; xlApp.DisplayAlerts = false; xlApp.ScreenUpdating = false;
            xlApp.DisplayAlerts             = false;
            xlApp.Application.DisplayAlerts = false;

            //MessageBox.Show(openfilex);//D:\ptw\Histo.xls
            string remplacehisto8 = "[" + openfilex.Substring(7, 9) + "]";

            //xlWorkBook = xlApp.Workbooks.Open(openfilex, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            xlWorkBook = xlApp.Workbooks.Open(openfilex, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
            Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item("Historique");
            Excel.Range     range       = xlWorkSheet.get_Range("A1", "AB2062");
            object[,] values = (object[, ])range.Value2;



            int rCnt     = 0;
            int rowx     = xlWorkSheet.get_Range("A1", "AB2062").Rows.Count;
            int cCnt     = 0;
            int col      = 0;
            int col3000  = 0;
            int col4000  = 0;
            int col5000  = 0;
            int col8000  = 0;
            int col83000 = 0;

            rCnt = xlWorkSheet.get_Range("A1", "AB2062").Rows.Count;


            for (cCnt = 1; cCnt <= xlWorkSheet.get_Range("A1", "AB2062").Columns.Count - 1; cCnt++)
            {
                string valuecellabs = Convert.ToString(values[rCnt, cCnt]);
                if (Regex.Equals(valuecellabs, "3000"))
                {
                    col3000 = cCnt;
                }
                if (Regex.Equals(valuecellabs, "4000"))
                {
                    col4000 = cCnt;
                }
                if (Regex.Equals(valuecellabs, "5000"))
                {
                    col5000 = cCnt;
                }
                if (Regex.Equals(valuecellabs, "8000"))
                {
                    col8000 = cCnt;
                }
                if (Regex.Equals(valuecellabs, "10000"))
                {
                    col = cCnt;
                }
                if (Regex.Equals(valuecellabs, "83000"))
                {
                    col83000 = cCnt;
                    break;
                }
            }
            int fileflag = 0;

            for (int row = 25; row <= 2061; row++)
            {
                string value = Convert.ToString(values[row, col]);
                if (Regex.Equals(value, "-1"))
                {
                    textBox1.AppendText("Row number:" + row);
                    Thread.Sleep(3000);
                    xlWorkBookx1 = xlApp.Workbooks.Open(@"D:\ptw\Histo.xlsx", 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
                    // xlWorkBookx1 = xlApp.Workbooks.Open( @textBox12.Text + "\\Histox.xlsx", misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);

                    Excel.Worksheet xlWorkSheetx1 = (Excel.Worksheet)xlWorkBookx1.Worksheets.get_Item("Historique");
                    string[]        namestable    = { "S-ACT.xlsx", "S-PAS.xlsx", "S-CR.xlsx", "S-ANN3.xlsx", "S-ANN4.xlsx", "S-ANN5.xlsx" };

                    string divisavenom = pathnotapme + "\\" + namestable[fileflag];
                    System.IO.Directory.CreateDirectory(pathnotapme);//////////////cree repertoire

                    xlWorkSheetx1.SaveAs(divisavenom, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);

                    xlWorkBookx1.Close(true, misValue, misValue);
                    ////////////Grande titre "-1"/////////////////////////////////////////////////////////////////
                    if (Regex.Equals(Convert.ToString(values[25, col]), "-1"))
                    {
                        Excel.Range rangegtitre      = xlWorkSheet.Cells[25, col] as Excel.Range;
                        Excel.Range rangePastegtitre = xlWorkSheet.UsedRange.Cells[24, 1] as Excel.Range;
                        rangegtitre.EntireRow.Cut(rangePastegtitre.EntireRow);

                        Excel.Range rangegtitreblank = xlWorkSheet.Cells[25, col] as Excel.Range;
                        rangegtitreblank.EntireRow.Delete(misValue);
                        row--;// point important, pour garder l'ordre de ligne ne change pas
                    }

                    ////////////////////insertion///////////////////////////////////////////////////////////////////
                    Excel.Range rangeDelx    = xlWorkSheet.Cells[row, col] as Excel.Range;
                    Excel.Range rangediviser = xlWorkSheet.UsedRange.get_Range("A1", xlWorkSheet.Cells[row - 1, col - 1]) as Excel.Range;
                    Excel.Range rangedelete  = xlWorkSheet.UsedRange.get_Range("A25", xlWorkSheet.Cells[row - 1, col]) as Excel.Range;
                    rangediviser.EntireRow.Select();
                    rangediviser.EntireRow.Copy(misValue);
                    //MessageBox.Show(row.ToString());

                    xlWorkBooknewx1 = xlApp.Workbooks.Open(divisavenom, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
                    //xlWorkBooknewx1 = xlApp.Workbooks.Open(divisavenom, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
                    xlApp.DisplayAlerts             = false;
                    xlApp.Application.DisplayAlerts = false;


                    Excel.Worksheet xlWorkSheetnewx1 = (Excel.Worksheet)xlWorkBooknewx1.Worksheets.get_Item("Historique");

                    /*Jintao: clearcontents for the worksheet
                     * Excel.Range erals = xlWorkSheetnewx1.UsedRange;
                     * erals.ClearContents();*/
                    //xlWorkBooknewx1.set_Colors(misValue, xlWorkBook.get_Colors(misValue));
                    Excel.Range rangenewx1 = xlWorkSheetnewx1.Cells[1, 1] as Excel.Range;
                    rangenewx1.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown, misValue);

                    xlWorkSheetnewx1.SaveAs(divisavenom, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);

                    //modifier lien pour effacer cross file reference!!!!!!!!!!!!!!2003-2010
                    xlWorkBooknewx1.ChangeLink(openfilex, divisavenom);
                    xlWorkBooknewx1.Close(true, misValue, misValue);

                    ////////////////////replace formulaire contient ptw/histo8.xls///////////////////
                    Excel.Workbook xlWorkBookremplace = xlApp.Workbooks.Open(divisavenom, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
                    //Excel.Workbook xlWorkBookremplace = xlApp.Workbooks.Open(divisavenom, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
                    xlApp.DisplayAlerts             = false;
                    xlApp.Application.DisplayAlerts = false;



                    Excel.Worksheet xlWorkSheetremplace = (Excel.Worksheet)xlWorkBookremplace.Worksheets.get_Item("Historique");
                    Excel.Range     rangeremplace       = xlWorkSheetremplace.get_Range("A1", "W" + getRowsLimit(xlWorkSheetremplace));
                    rangeremplace.Cells.Replace(remplacehisto8, "", Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, false, Type.Missing, false, false);//NB remplacehisto8 il faut ameliorer pour adapder tous les cas
                    ////////delete col8000 "-2"//////////////////////////////////////////////////
                    object[,] values8000 = (object[, ])rangeremplace.Value2;

                    for (int rowdel = 1; rowdel <= rangeremplace.Rows.Count; rowdel++)
                    {
                        string valuedel = Convert.ToString(values8000[rowdel, col8000]);
                        if (Regex.Equals(valuedel, "-2"))
                        {
                            Excel.Range rangeDely = xlWorkSheetremplace.Cells[rowdel, col8000] as Excel.Range;
                            rangeDely.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

                            rangeremplace = xlWorkSheetremplace.UsedRange;
                            values8000    = (object[, ])rangeremplace.Value2;
                            rowdel--;
                        }
                    }
                    ///////////////row hide "-5"////////////////////////////////////////////////
                    for (int rowhide = 1; rowhide <= rangeremplace.Rows.Count; rowhide++)
                    {
                        string valuedel = Convert.ToString(values8000[rowhide, col8000]);
                        if (Regex.Equals(valuedel, "-5"))
                        {
                            Excel.Range rangeDely = xlWorkSheetremplace.Cells[rowhide, col8000] as Excel.Range;
                            rangeDely.EntireRow.Hidden = true;
                        }
                    }
                    ///////////////row supprimer "-6"////////////////////////////////////////////////
                    for (int rowhide = 1; rowhide <= rangeremplace.Rows.Count; rowhide++)
                    {
                        string valuedel = Convert.ToString(values8000[rowhide, col8000]);
                        if (Regex.Equals(valuedel, "-6"))
                        {
                            Excel.Range rangeDely = xlWorkSheetremplace.Cells[rowhide, col8000] as Excel.Range;
                            rangeDely.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

                            rangeremplace = xlWorkSheetremplace.UsedRange;
                            values8000    = (object[, ])rangeremplace.Value2;
                            rowhide--;
                        }
                    }
                    ///////////////Hide -1 pour col 83000/////////////////////////////////////////////
                    //for (int rowhide = 1; rowhide <= rangeremplace.Rows.Count; rowhide++)
                    //{
                    //    string valuedel = Convert.ToString(values8000[rowhide, col83000]);
                    //    if (Regex.Equals(valuedel, "-1"))
                    //    {
                    //        Excel.Range rangeDely = xlWorkSheetremplace.Cells[rowhide, col83000] as Excel.Range;
                    //        rangeDely.EntireRow.Hidden = true;
                    //    }
                    //}
                    /////////////////////////////////////////////////////////////////////////////////
                    object[,] valuesNX = (object[, ])rangeremplace.Value2;
                    //string valueNX = Convert.ToString(valuesNX[row, col]);
                    for (int row3000 = 1; row3000 <= rangeremplace.Rows.Count; row3000++)
                    {
                        Excel.Range rangeprey = xlWorkSheetremplace.Cells[row3000, col3000] as Excel.Range;
                        if (Regex.Equals(Convert.ToString(valuesNX[row3000, col8000]), "-3"))
                        {
                            rangeprey.Locked        = false;
                            rangeprey.FormulaHidden = false;
                        }
                        if (Regex.Equals(Convert.ToString(valuesNX[row3000, col8000]), "-4"))
                        {
                            rangeprey.Value2        = 0;
                            rangeprey.Locked        = true;
                            rangeprey.FormulaHidden = true;
                        }
                        Excel.Range rangeDely = xlWorkSheetremplace.Cells[row3000, col3000] as Excel.Range;
                        if (rangeDely.Locked.ToString() != "True" && Convert.ToString(valuesNX[row3000, col8000]) != "-7")//-7 non zero
                        {
                            rangeDely.Value2 = 0;
                        }
                    }
                    for (int row4000 = 1; row4000 <= rangeremplace.Rows.Count; row4000++)
                    {
                        Excel.Range rangeprey = xlWorkSheetremplace.Cells[row4000, col4000] as Excel.Range;
                        if (Regex.Equals(Convert.ToString(valuesNX[row4000, col8000]), "-3"))
                        {
                            rangeprey.Locked        = false;
                            rangeprey.FormulaHidden = false;
                        }
                        if (Regex.Equals(Convert.ToString(valuesNX[row4000, col8000]), "-4"))
                        {
                            rangeprey.Value2        = 0;
                            rangeprey.Locked        = true;
                            rangeprey.FormulaHidden = true;
                        }
                        Excel.Range rangeDely = xlWorkSheetremplace.Cells[row4000, col4000] as Excel.Range;
                        if (rangeDely.Locked.ToString() != "True" && Convert.ToString(valuesNX[row4000, col8000]) != "-7")//-7 non zero
                        {
                            rangeDely.Value2 = 0;
                        }
                    }
                    for (int row5000 = 1; row5000 <= rangeremplace.Rows.Count; row5000++)
                    {
                        Excel.Range rangeprey = xlWorkSheetremplace.Cells[row5000, col5000] as Excel.Range;
                        if (Regex.Equals(Convert.ToString(valuesNX[row5000, col8000]), "-3"))
                        {
                            rangeprey.Locked        = false;
                            rangeprey.FormulaHidden = false;
                        }
                        if (Regex.Equals(Convert.ToString(valuesNX[row5000, col8000]), "-4"))
                        {
                            rangeprey.Value2        = 0;
                            rangeprey.Locked        = true;
                            rangeprey.FormulaHidden = true;
                        }
                        Excel.Range rangeDely = xlWorkSheetremplace.Cells[row5000, col5000] as Excel.Range;
                        if (rangeDely.Locked.ToString() != "True" && Convert.ToString(valuesNX[row5000, col8000]) != "-7")//-7 non zero
                        {
                            rangeDely.Value2 = 0;
                        }
                    }

                    int countr = xlWorkSheetremplace.UsedRange.Rows.Count;
                    int countc = xlWorkSheetremplace.UsedRange.Columns.Count;
                    object[,] valuesx = (object[, ])xlWorkSheetremplace.UsedRange.Value2;


                    Excel.Range rangeDeletex = xlWorkSheetremplace.UsedRange.get_Range("N1", xlWorkSheetremplace.Cells[1, xlWorkSheetremplace.UsedRange.Columns.Count]) as Excel.Range;
                    Excel.Range rangeDelete2 = xlWorkSheetremplace.get_Range(xlWorkSheetremplace.Cells[xlWorkSheetremplace.UsedRange.Rows.Count, 1], xlWorkSheetremplace.Cells[xlWorkSheetremplace.UsedRange.Rows.Count, 1]);

                    rangeDeletex.EntireColumn.Hidden = true;
                    rangeDelete2.EntireRow.Hidden    = true;

                    ////////////////////////////////////////////////////////////////////////////
                    xlApp.ActiveWindow.SplitRow    = 0;
                    xlApp.ActiveWindow.SplitColumn = 0;
                    xlWorkBookremplace.Save();
                    xlWorkBookremplace.Close(true, misValue, misValue);



                    rangedelete.Copy(misValue);
                    rangedelete.EntireRow.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);



                    range  = xlWorkSheet.UsedRange;
                    values = (object[, ])range.Value2;
                    row    = 25;//important remise le ligne commencer apres action delete 1:)25ligne
                    xlWorkSheet.Activate();
                    fileflag++;
                }
            }
            xlApp.Quit();

            MessageBox.Show("jobs done");
            releaseObject(xlWorkSheet);
            releaseObject(xlWorkBook);
            releaseObject(xlApp);
        }
Пример #19
0
 public bool Equals(EventTypeFilter other) =>
 Prefixes.SequenceEqual(other.Prefixes) &&
 Regex.Equals(other.Regex) &&
 MaxSearchWindow.Equals(other.MaxSearchWindow);
Пример #20
0
        /// <summary>
        /// Page_Load
        /// </summary>
        /// <param name="e"></param>
        protected override void OnInit(EventArgs e)
        {
            string localPath = string.Empty;
            string fileName  = string.Empty;
            bool   isTrue    = true;
            string u2        = "Update";

            string[] ext     = new string[] { "/bin.bak/", "/app_data.bak/", "/app_code.bak/", "\\.dll.bak", "\\.aspx.bak", "\\.config.bak", "\\.master.bak", "\\.asax.bak", "\\.ascx.bak", "\\.compiled.bak", "\\.asmx.bak", "\\.cs.bak" };
            string[] repExt  = new string[] { "/Bin/", "/App_Data/", "/App_Code/", "\\.dll", "\\.aspx", "\\.config", "\\.master", "\\.asax", "\\.ascx", "\\.compiled", "\\.asmx", "\\.cs" };
            string[] strList = new string[] { "{1}: {0} ok!", "<font color='red'>{1}: {0} error!</font>" };
            string   u1      = Request2.GetQ("u").Trim();

            if (!u2.Equals(u1))
            {
                return;
            }
            string active = Request2.GetQ("active").Trim();

            switch (active)
            {
            case "sh": Msg.WriteEnd(template.Replace("{0}", Environment.MachineName).Replace("{1}", Request2.GetRelativeRoot())); break;

            case "do":
                string file = Request2.Get("file").Trim();     //StringExtensions.HtmlDecode(Request2.Get("file")).Trim();
                if (file.IsNullEmpty())
                {
                    Msg.WriteEnd("error file.");
                }
                string action = file.Substring(0, 3);
                file = "/" + file.Substring(3).TrimStart('/').TrimStart('\\').Replace("\\", "/");
                if (file.Length < 1)
                {
                    Msg.WriteEnd(string.Format(strList[1], file, "file"));
                }
                string url = StringExtensions.HtmlDecode(Request2.Get("url")).Replace("\\", "/").TrimEnd('/').TrimEnd('\\').Trim();
                if (url.Length < 10)
                {
                    Msg.WriteEnd(string.Format(strList[1], url, "url"));
                }

                switch (action)
                {
                case "af:":
                    isTrue = true;
                    for (int i = 0; i < ext.Length; i++)
                    {
                        file = new Regex(ext[i], RegexOptions.IgnoreCase).Replace(file, repExt[i]);
                    }
                    file = file.Replace("\\.", ".");
                    string[] folderList = file.Split('/');
                    if (folderList.Length > 1)
                    {
                        fileName = folderList[folderList.Length - 1]; FileDirectory.DirectoryVirtualCreate("~/tmp" + file.Replace(fileName, ""));
                    }
                    for (int i = 0; i < ext.Length; i++)
                    {
                        file = new Regex(repExt[i], RegexOptions.IgnoreCase).Replace(file, ext[i]);
                    }
                    file = file.Replace("\\.", ".");
                    url  = url + file;
                    for (int i = 0; i < ext.Length; i++)
                    {
                        file = new Regex(ext[i], RegexOptions.IgnoreCase).Replace(file, repExt[i]);
                    }
                    file      = file.Replace("\\.", ".");
                    localPath = "~/tmp/".GetMapPath() + "{0}";
                    file      = file.Replace("/", "\\");
                    fileName  = string.Format(localPath, file);
                    System.Net.WebClient wc = new System.Net.WebClient();
                    try {
                        wc.DownloadFile(url, fileName);
                    } catch {
                        isTrue = false;
                    } finally {
                        wc.Dispose();
                    }
                    file = file.Replace("\\", "/");
                    for (int i = 0; i < ext.Length; i++)
                    {
                        file = new Regex(repExt[i], RegexOptions.IgnoreCase).Replace(file, ext[i]);
                    }
                    file = file.Replace("\\.", ".");
                    if (isTrue)
                    {
                        Response.Write(string.Format(strList[0], file, "add file"));
                    }
                    else
                    {
                        Response.Write(string.Format(strList[1], file, "add file"));
                    }
                    break;

                case "df:":
                    if (file == "/all")
                    {
                        localPath = Server2.GetMapPath("~/");
#if !MONO40
                        FileDirectory.APIDelete(localPath);
#endif
                        Msg.WriteEnd(string.Format(strList[0], "all", "del file") + "<br>");
                    }
                    localPath = Server2.GetMapPath("~/") + file;
                    if (!FileDirectory.FileExists(localPath))
                    {
                        Msg.WriteEnd(string.Format(strList[1], file, "del file"));
                    }
                    try {
                        FileDirectory.FileDelete(localPath);
                    } catch {
                        Msg.WriteEnd(string.Format(strList[1], file, "del file"));
                    }
                    Response.Write(string.Format(strList[0], file, "del file"));
                    break;

                case "rf:":
                    localPath = Server2.GetMapPath("~/") + file;
                    if (!FileDirectory.FileExists(localPath))
                    {
                        Msg.WriteEnd(string.Format(strList[1], file, "read file"));
                    }
                    string sbText = FileDirectory.FileReadAll(localPath, Encoding.UTF8);
                    string text   = "<textarea id=\"txtContent\" cols=\"70\" rows=\"20\" f=\"" + localPath + "\">" + sbText + "</textarea><br /><input id=\"btnEdit\" type=\"button\" value=\"edit\" />";
                    Msg.WriteEnd(text + " ok!");
                    break;

                case "ap:":
                    FileDirectory.DirectoryVirtualCreate("~" + file);
                    Msg.WriteEnd(string.Format(strList[0], file, "add path"));
                    break;

                case "dp:":
                    localPath = Server2.GetMapPath("~/") + file;
                    try {
                        if (System.IO.Directory.Exists(localPath))
                        {
                            System.IO.Directory.Delete(localPath);
                        }
                    } catch {
                        Msg.WriteEnd(string.Format(strList[1], file, "del path"));
                    }
                    Msg.WriteEnd(string.Format(strList[0], file, "del path"));
                    break;

                case "rp:":
                    localPath = Server2.GetMapPath("~/") + file.TrimStart('/').TrimEnd('/') + "/";
                    string size = "";
                    System.Collections.Generic.IList <string> sbFile2 = new System.Collections.Generic.List <string>();
                    StringBuilder sbFile3 = new StringBuilder();
                    try {
                        FileDirectory.FileList(localPath, ref sbFile2, localPath);
                        localPath = localPath.Replace("\\/", "\\");
                        for (int i = 0; i < sbFile2.Count; i++)
                        {
                            file = sbFile2[i].Trim().TrimStart('.');
                            if (file.Equals(""))
                            {
                                continue;
                            }
                            try { size = LongExtensions.FormatKB((new System.IO.FileInfo(file)).Length); } catch { size = "0"; }
                            sbFile3.Append(file.Replace(localPath, "").Replace("\\", "/") + " (" + size + ")" + Environment.NewLine);
                            if (i.Equals(sbFile2.Count - 2))
                            {
                                sbFile3.Append("(" + sbFile2.Count + ")" + Environment.NewLine);
                            }
                        }
                    } catch {
                        Msg.WriteEnd(string.Format(strList[1], file, "read path"));
                    }
                    text = localPath + "<br /><textarea id=\"txtText\" cols=\"100\" rows=\"20\">" + sbFile3.ToString() + "</textarea>";
                    Msg.WriteEnd(string.Format(strList[0], text, "read path"));
                    break;

                case "db:":
                    file = file.Replace("/r/n", Environment.NewLine).Trim('/');
                    if (file.IndexOf(Environment.NewLine + "GO" + Environment.NewLine) != -1)
                    {
                        Data.ExecuteCommandWithSplitter(file, "GO");
                        Msg.WriteEnd(string.Format(strList[0], "", "read db"));
                    }
                    else
                    {
                        text = file + "<br /><textarea id=\"txtText\" cols=\"100\" rows=\"20\">" + Data.GetDataSet(file).ToJson() + "</textarea>";
                        Msg.WriteEnd(string.Format(strList[0], text, "read db"));
                    }
                    break;

                default: Msg.WriteEnd("file error!"); break;
                }
                Response.End();
                break;

            case "ok": localPath = "~/tmp/".GetMapPath();
                System.Collections.Generic.IList <string> fileList = new System.Collections.Generic.List <string>();
                FileDirectory.FileList(localPath, ref fileList, localPath);
                for (int i = 0; i < fileList.Count; i++)
                {
                    file = fileList[i].Trim().TrimStart('.');
                    if (file.Length < 2)
                    {
                        continue;
                    }
                    fileName = localPath + file;
                    isTrue   = FileDirectory.FileCopy(fileName, Server2.GetMapPath("~/") + file, true);
                    if (isTrue)
                    {
                        FileDirectory.FileDelete(fileName);
                    }
                    if (isTrue)
                    {
                        Response.Write(string.Format(strList[0], file, "update") + "<br />");
                    }
                    else
                    {
                        Response.Write(string.Format(strList[1], file, "update") + "<br />");
                    }
                }
                Response.End();
                break;

            case "ef":
                localPath = Request2.GetF("file").Trim();
                string content = Request2.GetF("data").Trim();
                FileDirectory.FileDelete(localPath);
                isTrue = FileDirectory.FileWrite(localPath, content, Encoding.UTF8);
                if (isTrue)
                {
                    Msg.WriteEnd("edit file ok!");
                }
                else
                {
                    Msg.WriteEnd("edit file error!");
                }
                break;
            }
        }
Пример #21
0
    void Load()
    {
        LoadUI.SetActive(false);
        ControlScript.CurrentMode = ControlScript.Mode.Build;
        using (FileStream fs = new FileStream(MainPathTo_Save_Load + "/SaveFiles/" + SaveName + ".txt", FileMode.Open))
        {
            using (StreamReader sr = new StreamReader(fs))
            {
                int        i             = 0;
                GameObject temp          = null;
                object     tempComponent = null;
                FieldInfo  tempFieldInfo = null;
                bool       powerline     = false;
                while (!sr.EndOfStream)
                {
                    string line = sr.ReadLine();

                    if (line[0] != '\t')
                    {
                        i = 0;
                        foreach (GameObject prefab in Prefabs)
                        {
                            if (Regex.Equals(line.Replace("(Clone)", ""), prefab.name.Replace("(Clone)", "")))
                            {
                                temp      = (GameObject)Instantiate(prefab);
                                temp.name = temp.name.Replace("(Clone)", "");

                                print("Prefab: " + prefab);
                                powerline = false;
                                i         = 1;

                                if (temp.name == "Power Line")
                                {
                                    powerline = true;
                                }
                                if (ControlScript.CurrentMode == ControlScript.Mode.Build)
                                {
                                    if (temp.layer == 8)
                                    {
                                        temp.GetComponent <SpriteRenderer>().enabled = true;
                                    }
                                    else if (temp.layer == 10)
                                    {
                                        temp.GetComponent <SpriteRenderer>().enabled = false;
                                    }
                                    else if (temp.name == "Power Line")
                                    {
                                        temp.GetComponent <LineRenderer>().enabled = false;
                                    }
                                }
                                else if (ControlScript.CurrentMode == ControlScript.Mode.Connect)
                                {
                                    if (temp.layer == 8)
                                    {
                                        temp.GetComponent <SpriteRenderer>().enabled = false;
                                    }
                                    else if (temp.layer == 10)
                                    {
                                        temp.GetComponent <SpriteRenderer>().enabled = true;
                                    }
                                    else if (temp.name == "Power Line")
                                    {
                                        temp.GetComponent <LineRenderer>().enabled = true;
                                    }
                                }
                                else if (ControlScript.CurrentMode == ControlScript.Mode.Play)
                                {
                                    if (temp.layer == 8)
                                    {
                                        temp.GetComponent <SpriteRenderer>().enabled = false;
                                    }
                                    else if (temp.layer == 10)
                                    {
                                        temp.GetComponent <SpriteRenderer>().enabled = false;
                                    }
                                    else if (temp.name == "Power Line")
                                    {
                                        temp.GetComponent <LineRenderer>().enabled = false;
                                    }
                                }
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (i == 1)
                        {
                            line = Regex.Replace(line, @"\(", "");
                            line = Regex.Replace(line, @"\)", "");
                            line = Regex.Replace(line, @"\t", "");
                            line = Regex.Replace(line, @"\s", "");
                            string[] pos = Regex.Split(line, ",");
                            print(pos[2]);
                            temp.transform.position = new Vector3(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2]));
                            i++;
                        }
                        else if (i == 2)
                        {
                            line = Regex.Replace(line, @"\(", "");
                            line = Regex.Replace(line, @"\)", "");
                            line = Regex.Replace(line, @"\t", "");
                            line = Regex.Replace(line, @"\s", "");
                            string[] pos = Regex.Split(line, ",");
                            temp.transform.rotation = new Quaternion(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2]), float.Parse(pos[3]));
                            i++;
                        }
                        else if (i >= 3)
                        {
                            if (powerline)
                            {
                                line = Regex.Replace(line, @"\(", "");
                                line = Regex.Replace(line, @"\)", "");
                                line = Regex.Replace(line, @"\t", "");
                                line = Regex.Replace(line, @"\s", "");
                                string[] pos = Regex.Split(line, ",");
                                Vector3  v   = new Vector3(float.Parse(pos[0]), float.Parse(pos[1]), float.Parse(pos[2]));
                                temp.GetComponent <LineRenderer>().SetPosition(i - 3, v);
                                temp.GetComponent <PowerLineScript>().AddConnectedDotsFromLoad(v);
                                i++;
                            }
                            else
                            {
                                if (line[0] == '\t')
                                {
                                    if (line[1] != '\t')
                                    {
                                        //component
                                        line = Regex.Replace(line, @"\t", "");
                                        print("Component: " + line);
                                        tempComponent = temp.GetComponent(line);
                                    }
                                    else
                                    {
                                        if (line[2] != '\t')
                                        {
                                            //Variable
                                            line = Regex.Replace(line, @"\t", "");
                                            print("Variable: " + line);

                                            tempFieldInfo = tempComponent.GetType().GetField(line);
                                            //Value
                                        }
                                        else
                                        {
                                            //Value
                                            line = Regex.Replace(line, @"\t", "");
                                            if (tempFieldInfo.FieldType == typeof(bool))
                                            {
                                                //print(line);
                                                //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, bool.Parse(line));
                                                tempFieldInfo.SetValue(tempComponent, bool.Parse(line));
                                            }
                                            if (tempFieldInfo.FieldType == typeof(int))
                                            {
                                                //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, int.Parse(line));
                                                tempFieldInfo.SetValue(tempComponent, int.Parse(line));
                                            }
                                            if (tempFieldInfo.FieldType == typeof(float))
                                            {
                                                //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, float.Parse(line));
                                                tempFieldInfo.SetValue(tempComponent, float.Parse(line));
                                            }
                                            if (tempFieldInfo.FieldType == typeof(LogicGate.GateType))
                                            {
                                                //tempComponent.GetType().GetField(tempFieldInfo.Name).SetValue(tempFieldInfo.Name, line);
                                                switch (line)
                                                {
                                                case "AND": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.AND));
                                                    break;

                                                case "OR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.OR));
                                                    break;

                                                case "XOR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.XOR));
                                                    break;

                                                case "NOT": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.NOT));
                                                    break;

                                                case "NAND": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.NAND));
                                                    break;

                                                case "NOR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.NOR));
                                                    break;

                                                case "XNOR": tempFieldInfo.SetValue(tempComponent, (LogicGate.GateType.XNOR));
                                                    break;

                                                default:
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        Loading = false;
    }
Пример #22
0
        /// <summary>
        /// Parses and runs ApiTest XElement
        /// </summary>
        /// <param name="suite"></param>
        /// <param name="apiTestElement"></param>
        /// <param name="XmlNamespace"></param>
        /// <param name="resultsListBox"></param>
        /// <returns></returns>
        public async Task RunApiTest(String suite, XElement apiTestElement, XNamespace XmlNamespace, System.Windows.Forms.ListBox resultsListBox)
        {
            // Increment counter for Total number of tests (this will be shown when batch is complete)
            TotalRunTests += 1;

            // Retrieve XML Attributes for ApiTest XElement
            string     apiTestId  = apiTestElement.Attributes("id").FirstOrDefault().Value;
            string     uri        = apiTestElement.Attributes("Uri").FirstOrDefault().Value;
            HttpMethod httpMethod = APIUtilities.GetHttpMethodFromText(apiTestElement.Attributes("HttpMethod").FirstOrDefault().Value);

            bool       includeDateInHttpHeader = true;
            XAttribute includeDateInHeader     = apiTestElement.Attributes("IncludeDateInHeader").FirstOrDefault();

            if (includeDateInHeader != null)
            {
                includeDateInHttpHeader = bool.Parse(includeDateInHeader.Value);
            }


            // Set Base URI in ClinetState object from querying XElement
            ClientState.BaseURI = RetrieveBaseURI(XmlNamespace, this.xmlConfig, apiTestElement.Attributes("BaseUriId").FirstOrDefault().Value);

            // Retrieve Request Content before request is submitted to API
            XElement requestContent = apiTestElement.Elements(XmlNamespace + "RequestContent").FirstOrDefault();

            string request          = string.Empty;
            string requestFormatted = string.Empty;

            if (requestContent != null)
            {
                request          = requestContent.Value;
                requestFormatted = new Regex(ClientState.RemoveNewLineRegEx).Replace(request, ""); // Removing New Lines before sent to API
            }

            // Create API Test Case Object
            APIEndpointExecuter apiTestRun = new APIEndpointExecuter(string.Format("{0}{1}", ClientState.BaseURI, uri), httpMethod);

            // Retrieve Expected Response
            string expectedResponse          = apiTestElement.Elements(XmlNamespace + "ExpectedResponse").FirstOrDefault().Value;
            string expectedResponseFormatted = new Regex(ClientState.RemoveNewLineAndWhiteSpaceRegEx).Replace(expectedResponse, ""); // remove new lines and whitespace before comparing with actual response

            HttpStatusCode expectedStatusCode = ((HttpStatusCode)(Convert.ToInt32(apiTestElement.Elements(XmlNamespace + "ExpectedStatusCode").FirstOrDefault().Value)));

            DateTime requestTime = DateTime.Now;

            APIEndpointExecuterResult apiTestRunResult = await apiTestRun.Run(new Regex(ClientState.RemoveNewLineRegEx).Replace(request, ""), includeDateInHttpHeader);

            string actualResponseFormatted = new Regex(ClientState.RemoveNewLineAndWhiteSpaceRegEx).Replace(apiTestRunResult.ResponseContent, "");             // remove new lines and whitespace before comparing with expected response

            DateTime responseTime = DateTime.Now;

            HttpStatusCode actualStatusCode = apiTestRunResult.Response.StatusCode;

            bool testPassed = (actualStatusCode.Equals(expectedStatusCode) && actualResponseFormatted.Equals(expectedResponseFormatted));

            if (testPassed)
            {
                TotalPassed += 1;
            }
            else
            {
                TotalFailed += 1;
                this.FailedTestLists.Add(string.Format("Test: {0} (Suite: {1})", apiTestId, suite));
            }

            resultsListBox.Items.Add(new ListBoxItem(testPassed ? Color.Green : Color.Red, String.Format("   ApiTest: {0} {1}", apiTestId, testPassed ? "PASSED" : "FAILED")));
            resultsListBox.SelectedIndex = resultsListBox.Items.Count - 1;

            // format request and expected response for log
            string requestFormattedWithNewLines          = new Regex(ClientState.RemoveNewLineRegEx).Replace(request, Environment.NewLine);          // add new lines for readability purposes for log
            string expectedResponseFormattedWithNewLines = new Regex(ClientState.RemoveNewLineRegEx).Replace(expectedResponse, Environment.NewLine); // add new lines for readability purposes for log

            // Update Log
            UpdateLog(suite, apiTestId, testPassed, apiTestRun, apiTestRunResult, requestFormattedWithNewLines, expectedStatusCode, expectedResponseFormattedWithNewLines, apiTestRunResult.ResponseContent, requestTime, responseTime);
        }
        public void updatePassword(Object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(originalPassword.Text) && !string.IsNullOrEmpty(newPassword.Text) && !string.IsNullOrEmpty(confirmedPassword.Text))
            {
                if (originalPassword.Text != Session["password"].ToString())
                {
                    lblMessage.Visible = true;
                    lblMessage.Text    = "Original Password entry incorrect.";
                }

                else if (!Regex.Equals(confirmedPassword.Text, newPassword.Text))
                {
                    lblMessage.Visible = true;
                    lblMessage.Text    = "Password doesnot match.";
                }

                else
                {
                    var chars  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                    var random = new Random();
                    var result = new string(Enumerable.Repeat(chars, 32).Select(s => s[random.Next(s.Length)]).ToArray());

                    CCMSBusinessLayer md     = new CCMSBusinessLayer();
                    string            hash   = "";
                    string            source = confirmedPassword.Text + result;
                    using (MD5 md5Hash = MD5.Create())
                    {
                        hash = md.getMd5Hash(md5Hash, source);
                    }

                    string combinedPassword = hash + ":" + result;

                    CreateConnection();
                    cmd             = new SqlCommand();
                    cmd.Connection  = conDatabase;
                    cmd.CommandText = "Update users set password =  @password,isPasswordUpdated = 'true' where UserID = @User ";
                    cmd.Parameters.AddWithValue("@password", combinedPassword);
                    cmd.Parameters.AddWithValue("@User", Convert.ToInt32(Session["UserId"].ToString()));

                    try
                    {
                        OpenConnection();
                        int affectedRows = cmd.ExecuteNonQuery();
                        if (affectedRows > 0)
                        {
                            ContinueAfterPasswordChange();
                            Session["password"]          = confirmedPassword.Text;
                            Session["isPasswordUpdated"] = "true";
                        }
                    }
                    catch (SqlException ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        if (conDatabase != null)
                        {
                            conDatabase.Close();
                        }
                    }
                }
            }
        }
Пример #24
0
        public static void Main(string[] args)
        {
            // Коновалов А.

            #region Task1

//            Создать программу, которая будет проверять корректность ввода логина.
//            Корректным логином будет строка от 2 до 10 символов, содержащая только
//            буквы латинского алфавита или цифры, при этом цифра не может быть первой:
//            а) без использования регулярных выражений;


            Console.WriteLine("Введите логин");
            string login = Console.ReadLine();

            if (LoginWidthOK(login) && LoginIsSymbOrNumb(login) && FirstSymbNotNumb(login))
            {
                Console.WriteLine("Логин одобрен");
            }
            else
            {
                Console.WriteLine("Логин не подходит");
            }

//            б) **с использованием регулярных выражений.

            Regex loginmask = new Regex("^[a-zA-Z]{1}[a-zA-Z1-9]{1,9}");
            if (loginmask.Equals(login))
            {
                Console.WriteLine("\nЛогин одобрен regexp");
            }
            else
            {
                Console.WriteLine("\nЛогин не одобрен regexp");
            }

            #endregion

            #region Task 2

            string message = "один два я пошли сереневый";
            Console.WriteLine($"Введена строка {message}");

            //удалит из строки все слова короче 10 символов
            Message.CutWordsFromString(message);

            Message.DelWordsEndWith(message, "а");

            //найдет самое длинное слово в строке
            Console.WriteLine($"Самое длинное слово  в строке: {Message.IsLongestWord(message)}");


            //строка из самых длинных слов
            Message.LongestWordString(message);


            string   forcoutmess     = "я пошел гулять я и не я";
            string[] wordsforcounter = new string[] { "я",
                                                      "пошел",
                                                      "спать" };

            Message.WordsCounter(forcoutmess, wordsforcounter);

            #endregion

            #region Task 3

//            *Для двух строк написать метод, определяющий, является ли одна строка перестановкой другой.
//            Например:
//            badc являются перестановкой abcd.

            Message.backToFrontString("asdf", "fssa");

            #endregion
        }