Esempio n. 1
0
        internal Match(ParseStep parseStep, IEnumerator<ParseStep> stepEnumerator, IEnumerable<IList<ParenCapture>> captureSet)
            : base(0, parseStep.InitialStateIndex, parseStep.MatchedText.Length, parseStep.MatchedText, true)
        {
            _stepEnumerator = stepEnumerator;
            Groups = new GroupCollection();
            Groups.Append(this);
            Captures.Prepend(this);

            foreach (var parenCaptures in captureSet)
            {
                var parenCapture = parenCaptures[0];

                var group = new Group(parenCapture.Number,
                                      parenCapture.Index,
                                      parenCapture.Value.Length,
                                      parenCapture.Value,
                                      parenCapture.Success);
                Groups.Append(group);

                if (parenCapture.Success)
                {
                    group.Captures.Prepend(group);
                }

                if (parenCaptures.Skip(1).All(c => c.Success))
                {
                    for (int i = 1; i < parenCaptures.Count; i++)
                    {
                        group.Captures.Prepend(new Capture(parenCaptures[i].Index,
                                                           parenCaptures[i].Value.Length,
                                                           parenCaptures[i].Value));
                    }
                }
            }
        }
Esempio n. 2
0
        public static Group FindGroupByName(GroupCollection groups, string groupName)
        {
            foreach (var group in groups)
                if (group.Title == groupName)
                    return group;

            return null;
        }
 private UserAdminUtilities()
 {
     Users = new UsersCollection();
     Roles = new RolesCollection();
     Rights = new RightsCollection();
     UserPatterns = new UserPatternCollection();
     organizations = new OrganizationCollection();
     groups = new GroupCollection();
     Desearilize();
 }
        public void Desearilize()
        {
            try
            {
                Users = UsersCollection.Desearilize();
                Rights = RightsCollection.Desearilize();
                Roles = RolesCollection.Desearilize();
                UserPatterns = UserPatternCollection.Desearilize();
                organizations = OrganizationCollection.Desearilize();
                groups = GroupCollection.Desearilize();
            }
            catch
            {

            }
        }
        public void Put(string id, GroupCollection groupCollection)
        {
            GroupCollection oldGroupCollection = securityService.GetGroupCollection(groupCollection.GroupCollectionUId);
            if (oldGroupCollection == null)
                throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);

            // cant change e-mail
            if (oldGroupCollection.GroupCollectionUId.ToLower() != groupCollection.GroupCollectionUId.ToLower())
                throw new HttpResponseException(System.Net.HttpStatusCode.BadRequest);

            if (groupCollection.CollectionGroups == null)
                groupCollection.CollectionGroups = new GroupCollection_Group[0];

            securityService.SaveGroupCollection(groupCollection);

            log.Log(String.Format(SharedStringsLog.GROUP_UPDATE_0, groupCollection.GroupCollectionUId));
        }
Esempio n. 6
0
        public ParticipantModel(Guid guid, RoleModel role, string humanName)
        {
            this.m_Id = guid;
            this.m_Role = role;
            this.m_HumanName = humanName;
            this.m_Groups = new GroupCollection(this, "Groups");
            using( Synchronizer.Lock( this.SyncRoot ) ) {
                // Always add all participants to the AllParticipant group
                this.Groups.Add( Group.AllParticipant );

                // All participants also each belong to their own SingletonGroup.
                this.Groups.Add(new SingletonGroup(this));
            }
            if (PresenterModel.TheInstance != null) {
                PresenterModel.TheInstance.VersionExchange.CreateVersionExchange(this);
            }
        }
Esempio n. 7
0
        /// <summary>
        /// 
        /// </summary>
        //static public GroupCollection CreateLocalGroupCollection(DB db, DTRequest dtRequest)
        public static GroupCollection CreateLocalGroupCollection(DB db, Client client)
        {
            _client = client;
            //_request = dtRequest;

            GroupCollection gs = new GroupCollection();
            DataTable tbl = db.GetGroupDataTable();
            foreach ( DataRow row in tbl.Rows){
                Group g = new Group();
                g.ID = Convert.ToInt32(row["GroupID"]);
                g.Name = row["GroupName"].ToString().Trim();
                CreateStationCollection(db, g);
                gs.Add(g);
            }

            return gs;
        }
Esempio n. 8
0
         public amHealths()
            : base(null)
        {
            _practitioners = new PractitionerCollection(this);
            _patients = new PatientCollection(this);
            _appointments = new AppointmentCollection(this);
            _groups = new GroupCollection(this);
            _members = new MemberCollection(this);
            _queues = new QueueCollection(this);
            _messages = new MessageCollection(this);
            _familys = new FamilyCollection(this);
            _chronics = new ChronicCollection(this);
            _allergys = new AllergyCollection(this);


            _chronicMaps = new ChronicMapCollection(this);
            _allergyMaps = new AllergyMapCollection(this);


        }
        public List <(int, int)> CalculateVisitedBlocksAfterMove(string[] instructions)
        {
            List <(int, int)> visitedBlocks = new List <(int, int)>();

            (int x, int y)currentBlock = (0, 0);
            visitedBlocks.Add(currentBlock);

            CardinalDirection faceDirection = CardinalDirection.North;

            Regex instructionRegex = new Regex(@"^([RL]{1})(\d+)$");

            foreach (string instruction in instructions)
            {
                Match           match  = instructionRegex.Match(instruction);
                GroupCollection groups = match.Groups;

                char turn   = char.Parse(groups[1].Value);
                int  blocks = int.Parse(groups[2].Value);

                switch (faceDirection)
                {
                case CardinalDirection.North:
                    if (turn == 'R')
                    {
                        currentBlock.x += blocks;
                        faceDirection   = CardinalDirection.East;
                    }
                    else
                    {
                        currentBlock.x -= blocks;
                        faceDirection   = CardinalDirection.West;
                    }
                    break;

                case CardinalDirection.East:
                    if (turn == 'R')
                    {
                        currentBlock.y -= blocks;
                        faceDirection   = CardinalDirection.South;
                    }
                    else
                    {
                        currentBlock.y += blocks;
                        faceDirection   = CardinalDirection.North;
                    }
                    break;

                case CardinalDirection.South:
                    if (turn == 'R')
                    {
                        currentBlock.x -= blocks;
                        faceDirection   = CardinalDirection.West;
                    }
                    else
                    {
                        currentBlock.x += blocks;
                        faceDirection   = CardinalDirection.East;
                    }
                    break;

                case CardinalDirection.West:
                    if (turn == 'R')
                    {
                        currentBlock.y += blocks;
                        faceDirection   = CardinalDirection.North;
                    }
                    else
                    {
                        currentBlock.y -= blocks;
                        faceDirection   = CardinalDirection.South;
                    }
                    break;
                }

                visitedBlocks.Add(currentBlock);
            }

            return(visitedBlocks);
        }
Esempio n. 10
0
        public async Task RollAsync(EventContext e)
        {
            string rollResult;

            if (string.IsNullOrWhiteSpace(e.Arguments.ToString()))             // No Arguments.
            {
                rollResult = MikiRandom.Roll(100).ToString();
            }
            else
            {
                if (int.TryParse(e.Arguments.ToString(), out int max))                 // Simple number argument.
                {
                    rollResult = MikiRandom.Roll(max).ToString();
                }
                else                 // Assume the user has entered an advanced expression.
                {
                    Regex  regex           = new Regex(@"(?<dieCount>\d+)d(?<dieSides>\d+)");
                    string fullExpression  = e.Arguments.ToString();
                    int    expressionCount = 0;

                    foreach (Match match in regex.Matches(e.Arguments.ToString()))
                    {
                        GroupCollection groupCollection   = match.Groups;
                        int             dieCount          = int.Parse(groupCollection["dieCount"].Value);
                        int             dieSides          = int.Parse(groupCollection["dieSides"].Value);
                        string          partialExpression = "";

                        for (int i = 0; i < dieCount; i++)
                        {
                            partialExpression += MikiRandom.Roll(dieSides).ToString();
                            if (i + 1 < dieCount)
                            {
                                partialExpression += " + ";
                            }
                        }

                        fullExpression = regex.Replace(fullExpression, $"( {partialExpression} )", 1);
                        expressionCount++;
                    }

                    if (expressionCount > 1)
                    {
                        fullExpression = $"( {fullExpression} )";
                    }

                    Expression evaluation = new Expression(fullExpression);
                    rollResult = evaluation.Evaluate().ToString() + $" `{fullExpression}`";
                }
            }

            if (rollResult == "1" || rollResult.StartsWith("1 "))
            {
                await AchievementManager.Instance.GetContainerById("badluck").CheckAsync(new BasePacket()
                {
                    discordUser    = e.Author,
                    discordChannel = e.Channel
                });
            }

            rollResult = Regex.Replace(rollResult, @"(\s)\s+", "$1");
            rollResult = Regex.Replace(rollResult, @"(\S)([^\d\s])", "$1 $2");

            e.Channel.QueueMessageAsync(e.GetResource(LocaleTags.RollResult, e.Author.Username, rollResult));
        }
Esempio n. 11
0
        public List <string> RunCommand(ChannelMessageEventDataModel messageEvent, GroupCollection arguments = null, bool useCache = true)
        {
            Random random = new Random(Guid.NewGuid().GetHashCode());

            int rolls = int.Parse(arguments[1].Value);

            if (rolls > 100)
            {
                return(new List <string> {
                    "Too many rolls!"
                });
            }
            int  dieSize       = int.Parse(arguments[2].Value);
            bool modifier      = false;
            bool subtract      = false;
            bool add           = false;
            int  modifierValue = 0;

            if (arguments.Count > 3)
            {
                modifier = true;
                if (arguments[3].Value == "+")
                {
                    add = true;
                }
                if (arguments[3].Value == "-")
                {
                    subtract = true;
                }
                if (!add && !subtract)
                {
                    return(new List <string> {
                        "Please provide a valid operator of either + or -"
                    });
                }
                modifierValue = int.Parse(arguments[4].Value);
            }

            if (dieSize <= 0)
            {
                return new List <string> {
                           "Die size needs to be greater than 0"
                }
            }
            ;

            if (rolls <= 0)
            {
                return new List <string> {
                           "There needs to be more than 0 rolls"
                }
            }
            ;

            List <int> rollResults = new List <int>(rolls);

            int i = 0;

            while (i < rolls)
            {
                var currentResult = random.Next(1, dieSize + 1);

                if (modifier)
                {
                    if (add)
                    {
                        currentResult += modifierValue;
                    }
                    if (subtract)
                    {
                        currentResult -= modifierValue;
                    }
                }

                rollResults.Add(currentResult);

                i++;
            }

            string result = $"{messageEvent.Nick}'s roll results:";

            result = rollResults.Aggregate(result, (current, roll) => current + $" {roll},");

            result += $" Rolled {rolls}d{dieSize}";
            if (!modifier)
            {
                return(result.SplitInParts().ToList());
            }

            if (add)
            {
                result += $" with a +{modifierValue} modifier";
            }
            if (subtract)
            {
                result += $" with a -{modifierValue} modifier";
            }

            return(result.SplitInParts().ToList());
        }
    }
}
Esempio n. 12
0
 public static string StringValue(this GroupCollection gc, int index)
 {
     return(gc[index].Value);
 }
 public IEnumerable<Signal> ManipulatePort(Port port, SignalSet manipulatedInputs, bool hasManipulatedInputs, GroupCollection groups)
 {
     return _derive(port, manipulatedInputs, _variable, hasManipulatedInputs);
 }
Esempio n. 14
0
        /// <summary>
        /// Command to parse a list add/del/show request from the client, and to carry it out if necessary.
        /// Returns output to be returned to client.
        /// </summary>
        /// <param name="listtype">Type of list to operate on. Same numbers as UserTypeToInt(), and 10=Watchlist 11=BNU 12=BNA</param>
        /// <param name="user">Name of the user (nick) carrying out this operation</param>
        /// <param name="cmdParams">Command parameters</param>
        /// <returns></returns>
        public string HandleListCommand(int listtype, string user, string cmdParams)
        {
            // cmdParams are given like so:
            // - add Tangotango[ x=96][ r=Terrible vandal]
            // - add Tangotango test account x=89
            // - del Tangotango r=No longer needed (r is not handled by CVNBot, but accept anyway)

            Match lc = rlistCmd.Match(cmdParams);

            if (lc.Success)
            {
                try
                {
                    GroupCollection groups = lc.Groups;
                    string          cmd    = groups["cmd"].Captures[0].Value.ToLower();
                    string          item   = groups["item"].Captures[0].Value.Trim();
                    int             len;
                    // Set length defaults: except for blacklist (listtype=1), the default is 0 (indefinite)
                    if (listtype == 1)
                    {
                        // Default expiry for blacklist: 90 days (in seconds)
                        len = 7776000;
                    }
                    else
                    {
                        len = 0;
                    }
                    if (groups["len"].Success)
                    {
                        // Convert input, in hours, to seconds
                        len = Convert.ToInt32(groups["len"].Captures[0].Value) * 3600;
                    }
                    string reason = "No reason given";
                    if (groups["reason"].Success)
                    {
                        reason = groups["reason"].Captures[0].Value;
                    }
                    string project = "";
                    if (groups["project"].Success)
                    {
                        project = groups["project"].Captures[0].Value;
                        if (!Program.prjlist.ContainsKey(project))
                        {
                            return("Project " + project + " is unknown");
                        }
                    }

                    switch (cmd)
                    {
                    case "add":
                        switch (listtype)
                        {
                        case 0:         //Whitelist
                            Program.Broadcast("WL", "ADD", item, len, reason, user);
                            return(AddUserToList(item, "", UserType.whitelisted, user, reason, len));

                        case 1:         //Blacklist
                            Program.Broadcast("BL", "ADD", item, len, reason, user);
                            return(AddUserToList(item, "", UserType.blacklisted, user, reason, len));

                        case 6:         //Greylist
                            return("You cannot directly add users to the greylist");

                        case 2:         //Adminlist
                            if (project == "")
                            {
                                return((string)Program.msgs["20001"]);
                            }
                            return(AddUserToList(item, project, UserType.admin, user, reason, len));

                        case 5:         //Botlist
                            if (project == "")
                            {
                                return((string)Program.msgs["20001"]);
                            }
                            return(AddUserToList(item, project, UserType.bot, user, reason, len));

                        case 10:         //Watchlist
                            if (project == "")
                            {
                                Program.Broadcast("CVP", "ADD", item, len, reason, user);
                            }
                            return(AddPageToWatchlist(item, project, user, reason, len));

                        case 11:         //BNU
                            Program.Broadcast("BNU", "ADD", item, len, reason, user);
                            return(AddItemToList(item, 11, user, reason, len));

                        case 12:         //BNA
                            Program.Broadcast("BNA", "ADD", item, len, reason, user);
                            return(AddItemToList(item, 12, user, reason, len));

                        case 20:         //BES
                            Program.Broadcast("BES", "ADD", item, len, reason, user);
                            return(AddItemToList(item, 20, user, reason, len));

                        default:
                            return("");        //Should never be called, but compiler complains otherwise
                        }

                    case "del":
                        switch (listtype)
                        {
                        case 0:         //Whitelist
                            Program.Broadcast("WL", "DEL", item, 0, reason, user);
                            return(DelUserFromList(item, "", UserType.whitelisted));

                        case 1:         //Blacklist
                            Program.Broadcast("BL", "DEL", item, 0, reason, user);
                            return(DelUserFromList(item, "", UserType.blacklisted));

                        case 6:         //Greylist
                            Program.Broadcast("GL", "DEL", item, 0, reason, user);
                            return(DelUserFromList(item, "", UserType.greylisted));

                        case 2:         //Adminlist
                            if (project == "")
                            {
                                return((string)Program.msgs["20001"]);
                            }
                            return(DelUserFromList(item, project, UserType.admin));

                        case 5:         //Botlist
                            if (project == "")
                            {
                                return((string)Program.msgs["20001"]);
                            }
                            return(DelUserFromList(item, project, UserType.bot));

                        case 10:         //Watchlist
                            if (project == "")
                            {
                                Program.Broadcast("CVP", "DEL", item, len, reason, user);
                            }
                            return(DelPageFromWatchlist(item, project));

                        case 11:         //BNU
                            Program.Broadcast("BNU", "DEL", item, 0, reason, user);
                            return(DelItemFromList(item, 11));

                        case 12:         //BNA
                            Program.Broadcast("BNA", "DEL", item, 0, reason, user);
                            return(DelItemFromList(item, 12));

                        case 20:         //BES
                            Program.Broadcast("BES", "DEL", item, 0, reason, user);
                            return(DelItemFromList(item, 20));

                        default:
                            return("");        //Should never be called, but compiler complains otherwise
                        }

                    case "show":
                        switch (listtype)
                        {
                        case 0:         //Whitelist
                        case 1:         //Blacklist
                        case 6:         //Greylist
                            return(ShowUserOnList(item, ""));

                        case 2:         //Adminlist
                        case 5:         //Botlist
                            if (project == "")
                            {
                                return((string)Program.msgs["20001"]);
                            }
                            return(ShowUserOnList(item, project));

                        case 10:         //Watchlist
                            return(ShowPageOnWatchlist(item, project));

                        case 11:         //BNU
                            return(ShowItemOnList(item, 11));

                        case 12:         //BNA
                            return(ShowItemOnList(item, 12));

                        case 20:         //BES
                            return(ShowItemOnList(item, 20));

                        default:
                            return("");        //Should never be called, but compiler complains otherwise
                        }

                    case "test":
                        switch (listtype)
                        {
                        case 11:         //BNU
                            return(TestItemOnList(item, 11));

                        case 12:         //BNA
                            return(TestItemOnList(item, 12));

                        case 20:         //BES
                            return(TestItemOnList(item, 20));

                        default:
                            return((string)Program.msgs["20002"]);
                        }

                    default:
                        return("");    //Should never be called, but compiler complains otherwise
                    }
                }
                catch (Exception e)
                {
                    logger.Error("Error while handling list command", e);
                    return("Sorry, an error occured while handling the list command: " + e.Message);
                }
            }

            return((string)Program.msgs["20000"]);
        }
Esempio n. 15
0
            internal string ProcessLine(string line)
            {
                Match m;

                line = line.Trim(); if (line.Length == 0)
                {
                    return(line);
                }

                switch (m_state)
                {
                case c_Idle:
                    m = m_re_LoadRegion.Match(line);
                    if (m.Success)
                    {
                        m_state = c_LoadRegionPreamble;

                        GroupCollection groups = m.Groups;

                        return(String.Format("    <LoadRegion Name=\"{0}\" Base=\"{1}\" Options=\"{2}\" Size=\"{3}\">", groups[1], groups[2], groups[4], groups[6]));
                    }
                    break;

                case c_LoadRegionPreamble:
                    if (line == "{")
                    {
                        m_state = c_LoadRegion;
                        return("");
                    }
                    break;

                case c_LoadRegion:
                    if (line == "}")
                    {
                        m_state = c_Idle;
                        return("    </LoadRegion>");
                    }

                    m = m_re_ExecRegion.Match(line);
                    if (m.Success)
                    {
                        m_state = c_ExecRegionPreamble;

                        GroupCollection groups = m.Groups;

                        return(String.Format("        <ExecRegion Name=\"{0}\" Base=\"{1}\" Options=\"{2}\" Size=\"{3}\">", groups[1], groups[2], groups[4], groups[6]));
                    }
                    break;

                case c_ExecRegionPreamble:
                    if (line == "{")
                    {
                        m_state = c_ExecRegion;
                        return("");
                    }
                    break;

                case c_ExecRegion:
                    if (line == "}")
                    {
                        m_state = c_LoadRegion;
                        return("        </ExecRegion>");
                    }

                    m = m_re_FileMapping.Match(line);
                    if (m.Success)
                    {
                        GroupCollection groups = m.Groups;

                        return(String.Format("            <FileMapping Name=\"{0}\" Options=\"{1}\" />", groups[1], groups[2]));
                    }
                    break;
                }

                throw Document.ParseException("Invalid scatter file input: {0}", line);
            }
Esempio n. 16
0
        }//Main()

        /// <summary>
        /// Outputs the results of expression pattern results
        /// </summary>
        /// <param name="patternString"></param>
        /// Expression pattern.
        /// <param name="patternDescription"></param>
        /// Text to describe output to user.
        /// <param name="options"></param>
        /// Regex options
        /// <param name="namedGroups"></param>
        /// If not null this will contain a string array of named groups to output.
        public static void ExpressionResults(string patternString,
                                             string patternDescription,
                                             RegexOptions options,
                                             string [] namedGroups)
        {
            Console.WriteLine("{0}\n", patternDescription);
            Console.WriteLine("Pattern: {0}\n", patternString);
            Console.Write("Enter your test input: ");
            string userString = Console.ReadLine();

            Console.WriteLine();
            Regex rgx = new Regex(patternString, options);

            while (true)
            {
                MatchCollection mc = rgx.Matches(userString);

                if (mc.Count > 0)
                {
                    Console.WriteLine("MatchCollection from Matches property");
                    Console.WriteLine("\nTest string with character position");
                    Console.WriteLine("\n{0}", userString);
                    for (int i = 0; i < userString.Length; i++)
                    {
                        Console.Write("-");
                    }//for
                    Console.WriteLine();
                    for (int i = 0; i < userString.Length; i++)
                    {
                        Console.Write(i % 10);
                    }//for
                    Console.WriteLine("\n");

                    //foreach (Match m in mc)
                    for (int i = 0; i < mc.Count; i++)
                    {
                        Match           m   = mc[i];
                        GroupCollection gps = m.Groups;
                        if (namedGroups == null)
                        {
                            Console.WriteLine("Match value item {0}: at index {1}: {2}", i, m.Index, m.Value);
                            Console.WriteLine();
                            for (int j = 0; j < gps.Count; j++)
                            {
                                Group g = gps[j];
                                Console.WriteLine("\tGroup item {0}: at index location {1}: {2}", j, g.Index, g.Value);
                                CaptureCollection caps = g.Captures;
                                for (int k = 0; k < caps.Count; k++)
                                {
                                    Capture c = caps[k];
                                    Console.WriteLine("\t\tCapture item {0} at index location {1}: {2}", k, c.Index, c.Value);
                                } //for
                                Console.WriteLine();
                            }     //for
                        }         //if
                        else
                        {
                            foreach (string s in namedGroups)
                            {
                                Console.WriteLine("Found named group match <{0}> at location {1}: {2}",
                                                  s,
                                                  m.Groups[s].Index,
                                                  m.Groups[s].Value);
                            } //foreach
                        }     //else
                    }         //foreach
                }             //if
                else
                {
                    Console.WriteLine("No matches found");
                }//else
                Console.Write("\nNew test input for {0} or enter to continue: ", patternString);
                userString = Console.ReadLine();
                Console.WriteLine();
                if (userString != "")
                {
                    continue;
                }    //if
                else //exit the loop
                {
                    Console.WriteLine("\n");
                    return;
                } //else
            }     //while (true)
        }         //ExpressionResults()
Esempio n. 17
0
 public IEnumerable <Signal> ManipulatePort(Port port, SignalSet manipulatedInputs, bool hasManipulatedInputs, GroupCollection groups)
 {
     return(_transform(port, manipulatedInputs, hasManipulatedInputs));
 }
Esempio n. 18
0
 public ManipulationPlan EstimatePlan(Port port, GroupCollection groups)
 {
     return(_plan(port));
 }
Esempio n. 19
0
 public static string Get(GroupCollection groups, string name)
 {
     return(groups[name].Value);
 }
Esempio n. 20
0
        internal static object MatchOperator(System.Management.Automation.ExecutionContext context, IScriptExtent errorPosition, object lval, object rval, bool notMatch, bool ignoreCase)
        {
            object       obj3;
            RegexOptions options = ignoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
            Regex        regex   = PSObject.Base(rval) as Regex;

            if (regex == null)
            {
                regex = NewRegex(PSObject.ToStringParser(context, rval), options);
            }
            IEnumerator targetObject = LanguagePrimitives.GetEnumerator(lval);

            if (targetObject == null)
            {
                string input = (lval == null) ? string.Empty : PSObject.ToStringParser(context, lval);
                Match  match = regex.Match(input);
                if (match.Success)
                {
                    GroupCollection groups = match.Groups;
                    if (groups.Count > 0)
                    {
                        Hashtable newValue = new Hashtable(StringComparer.CurrentCultureIgnoreCase);
                        foreach (string str2 in regex.GetGroupNames())
                        {
                            Group group = groups[str2];
                            if (group.Success)
                            {
                                int num;
                                if (int.TryParse(str2, out num))
                                {
                                    newValue.Add(num, group.ToString());
                                }
                                else
                                {
                                    newValue.Add(str2, group.ToString());
                                }
                            }
                        }
                        context.SetVariable(SpecialVariables.MatchesVarPath, newValue);
                    }
                }
                return(BoolToObject(match.Success ^ notMatch));
            }
            ArrayList list = new ArrayList();
            int       num2 = 0;

            try
            {
                while (targetObject.MoveNext())
                {
                    object current = targetObject.Current;
                    string str3    = (current == null) ? string.Empty : PSObject.ToStringParser(context, current);
                    if (regex.Match(str3).Success ^ notMatch)
                    {
                        list.Add(current);
                    }
                    if (num2++ > 0x3e8)
                    {
                        if ((context != null) && context.CurrentPipelineStopping)
                        {
                            throw new PipelineStoppedException();
                        }
                        num2 = 0;
                    }
                }
                obj3 = list.ToArray();
            }
            catch (RuntimeException)
            {
                throw;
            }
            catch (FlowControlException)
            {
                throw;
            }
            catch (ScriptCallDepthException)
            {
                throw;
            }
            catch (Exception exception)
            {
                CommandProcessorBase.CheckForSevereException(exception);
                throw InterpreterError.NewInterpreterExceptionWithInnerException(targetObject, typeof(RuntimeException), errorPosition, "BadEnumeration", ParserStrings.BadEnumeration, exception, new object[] { exception.Message });
            }
            return(obj3);
        }
        //public Zone GetZoneByPosition(ZoneCollectionSingletone collection, XPosition x)
        //{
        //    foreach (Zone z in collection)
        //    {
        //        if (z.ZonePointIntersection(z.Position1, z.Position2, x))
        //            return z;
        //    }
        //    return null;
        //}
        private void Load(String path)
        {
            try
            {
                this.Items = XObject<GroupCollection>.Load(path);
            }
            catch
            {

            }
        }
 public GroupCollection Post(GroupCollection groupCollection)
 {
     groupCollection.GroupCollectionUId = Guid.NewGuid().ToString();
     log.Log(String.Format(SharedStringsLog.GROUP_CREATION_0, groupCollection.GroupCollectionUId));
     return securityService.SaveGroupCollection(groupCollection);
 }
Esempio n. 23
0
 protected override void SetValue(GroupCollection groups, out CommandError error)
 {
     error = null;
 }
Esempio n. 24
0
 public AdvGroupIgnorer()
 {
     this.groups = new GroupCollection();
     this.ignoredGroups = new GroupCollection();
 }
Esempio n. 25
0
        /// <summary>
        /// Uses systemctl (relies on systemd) and also checks /etc/init.d
        /// </summary>
        public void ExecuteLinux()
        {
            try
            {
                var result = ExternalCommandRunner.RunExternalCommand("systemctl", "list-units --type service");

                //Split lines and remove header
                var lines = result.Split('\n').Skip(1);

                foreach (var _line in lines)
                {
                    var _fields = _line.Split('\t');

                    if (_fields.Length == 5)
                    {
                        var obj = new ServiceObject(_fields[0])
                        {
                            DisplayName = _fields[4],
                            State       = _fields[3],
                        };

                        DatabaseManager.Write(obj, RunId);
                    }
                }
            }
            catch (ExternalException)
            {
                Log.Error("Error executing {0}", "systemctl list-units --type service");
            }

            try
            {
                var result = ExternalCommandRunner.RunExternalCommand("ls", "/etc/init.d/ -l");

                var    lines   = result.Split('\n').Skip(1);
                String pattern = @".*\s(.*)";

                foreach (var _line in lines)
                {
                    Match           match       = Regex.Match(_line, pattern);
                    GroupCollection groups      = match.Groups;
                    var             serviceName = groups[1].ToString();

                    var obj = new ServiceObject(serviceName)
                    {
                        DisplayName = serviceName,
                    };

                    DatabaseManager.Write(obj, RunId);
                }
            }
            catch (ExternalException)
            {
                Log.Error("Error executing {0}", "ls /etc/init.d/ -l");
            }


            // CentOS
            // chkconfig --list

            // BSD
            // service -l
            // this provides very minor amount of info
        }
Esempio n. 26
0
 protected GroupIgnorer(GroupIgnorer copy)
     : base(copy)
 {
     this.groups = new GroupCollection(copy.groups);
 }
Esempio n. 27
0
        private static String XmlDirtyMatchReplaceMinifier(String xmlDocument, String[] looseAssemblyNames, String[] finalDiscardableRegExStringArray, Boolean useCDATA)
        {
            // replacing spaces before > or /> in valid elements
            xmlDocument = Regex.Replace(xmlDocument, @"(\<\/?[\w\:_]+([\s/]+[a-zA-Z0-9\.\-\:=_]+\s*=\s*(""[^""]*""|'[^']*'))*)\s+(\/?>)", "$1$+");

            // replacing :nil="true" with :nil="1" as it does not matter in .NET
            xmlDocument = Regex.Replace(xmlDocument, @":(nil|boolean)\s*=\s*([""'])true[""']", ":$1=${2}1${2}");
            xmlDocument = Regex.Replace(xmlDocument, @":(nil|boolean)\s*=\s*([""'])false[""']", ":$1=${2}0${2}");

            // replacing spaces between things like:
            // Microsoft.IdentityModel, Version=3.5.0.0, PublicKeyToken=31bf3856ad364e35
            // clr-namespace:System.Diagnostics; assembly=system
            // {         x:Type      Diag:Process   }
            // Int32 Compare(System.String, System.String)
            xmlDocument = Regex.Replace(xmlDocument, @"([a-zA-Z0-9\.\-\:=_\s]+[;,]\s*)+([a-zA-Z0-9\.\-\:=_\s]+)[""'\]\<]", delegate(Match m) {
                // we do not want to remove spaces when two alphanumeric strings are next to each other
                String finalVal = m.Value;
                finalVal        = Regex.Replace(finalVal, @"([^\w])[\s]+([\w])", "$1$2");
                finalVal        = Regex.Replace(finalVal, @"([\w])[\s]+([^\w])", "$1$2");
                finalVal        = Regex.Replace(finalVal, @"([^\w])[\s]+([^\w])", "$1$2");
                return(finalVal);
            });

            xmlDocument = Regex.Replace(xmlDocument, @"([""'])\s*\{\s*([^&""'}\s]+)\s+([^&""'}\s]+)\s*\}\s*([""'])", "$1{$2 $3}$4");

            xmlDocument = Regex.Replace(xmlDocument, @"([""'])\s*\{\s*([^&""'}\s]+)\s*\}\s*([""'])", "$1{$2}$3");

            //xmlDocument = Regex.Replace(xmlDocument, @"([a-zA-Z0-9\.\-_]+\(([a-zA-Z0-9\.\-_]+\s*,)+\s*([a-zA-Z0-9\.\-_]+\s*)\))", delegate (Match m) { return m.Value.Replace(" ", ""); });

            // replacing not strong (loose) assembly names

            if (looseAssemblyNames != null)
            {
                foreach (String asmName in looseAssemblyNames)
                {
                    xmlDocument = Regex.Replace(xmlDocument, @"([""',=/>])\s*(" + asmName + @")([;,][a-zA-Z0-9\.\-\:=]+\s*)+([""'\]\<])", "$1$2$+");
                }
            }

            if (finalDiscardableRegExStringArray != null)
            {
                foreach (String dRegEx in finalDiscardableRegExStringArray)
                {
                    xmlDocument = Regex.Replace(xmlDocument, dRegEx, "");
                }
            }

            if (useCDATA)
            {
                // at this point, we want to decode all HTML encodings of valid XML elements and use CDATA
                // we assume we are not already in CDATA! (big assumption)
                // if we really want to save space, we need to have around 4 encoded values but we also ignore that for now

                string          htmlEncodedPattern = @"(?<=>\s*)(\&lt;([\w\:_\-]+)[^<]+)(?=\s*<)";
                Regex           htmlEncodedRegEx   = new Regex(htmlEncodedPattern, RegexOptions.Compiled);
                MatchCollection htmlEncodedMatches = htmlEncodedRegEx.Matches(xmlDocument);

                foreach (Match match in htmlEncodedMatches)
                {
                    GroupCollection groups           = match.Groups;
                    String          htmlEncodedValue = groups[1].Value;
                    String          newValue         = System.Web.HttpUtility.HtmlDecode(htmlEncodedValue);

                    // now we can also minify this probably
                    try
                    {
                        newValue = Minify(newValue, null, null);
                    }
                    catch (Exception e)
                    {
                        //
                    }

                    xmlDocument = xmlDocument.Replace(htmlEncodedValue, "<![CDATA[" + newValue + "]]>");
                }
            }

            return(xmlDocument);
        }
 public IEnumerable<Signal> ManipulatePort(Port port, SignalSet manipulatedInputs, bool hasManipulatedInputs, GroupCollection groups)
 {
     return _simplify(port, manipulatedInputs, hasManipulatedInputs);
 }
Esempio n. 29
0
        private static String XmlParserNamespaceMinifier(String xmlDocument)
        {
            Dictionary <string, string> namespaceLocalNames = new Dictionary <string, string>();

            // finding xmlns definitions
            string          pattern = @"xmlns:([^=]+)\s*=\s*[""']([^""']*)[""']";
            Regex           namespaceLocalNameRegEx = new Regex(pattern, RegexOptions.Compiled);
            MatchCollection matches = namespaceLocalNameRegEx.Matches(xmlDocument);

            foreach (Match match in matches)
            {
                // We need to ignore XMLNS in internal XML objects that are encoded or within CDATA
                Regex isNotInternalRegEx = new Regex(@"(?<!\<\!\[CDATA\[\s*)<[\w:.]+[^<>]+" + Regex.Escape(match.Value));

                if (isNotInternalRegEx.IsMatch(xmlDocument))
                {
                    GroupCollection groups         = match.Groups;
                    String          namespaceValue = groups[2].Value;
                    if (Uri.UnescapeDataString(namespaceValue) != namespaceValue)
                    {
                        // URL decoding name spaces
                        string newNamespaceValue = Uri.UnescapeDataString(namespaceValue);
                        xmlDocument    = Regex.Replace(xmlDocument, namespaceValue, newNamespaceValue);
                        namespaceValue = newNamespaceValue;
                    }
                    String namespaceLocalName = "";
                    if (namespaceLocalNames.TryGetValue(namespaceValue, out namespaceLocalName))
                    {
                        // replacing duplicate namespace localname and its usage
                        xmlDocument = ReplaceNamespaceNameAndValue(xmlDocument, groups[1].Value, namespaceLocalName);
                    }
                    else
                    {
                        namespaceLocalNames.Add(namespaceValue, groups[1].Value);
                    }
                }
            }

            // removing soap encodingStyle as it's not being used

            string          encodingStylePattern = @"([^\s]+):encodingStyle\s*=\s*[""']";
            Regex           encodingStyleRegEx   = new Regex(encodingStylePattern, RegexOptions.Compiled);
            MatchCollection encodingStyleMatches = namespaceLocalNameRegEx.Matches(xmlDocument);

            foreach (Match match in encodingStyleMatches)
            {
                GroupCollection groups             = match.Groups;
                String          namespaceLocalName = groups[1].Value;

                var namespaceValue = namespaceLocalNames.FirstOrDefault(x => x.Value == namespaceLocalName).Key;

                if (namespaceValue != null && namespaceValue.Equals("http://schemas.xmlsoap.org/soap/envelope/"))
                {
                    // so encodingStyle is useless
                    xmlDocument = Regex.Replace(xmlDocument, namespaceLocalName + @":encodingStyle\s*=\s*[""'][^""']*[""']", "");
                }
            }

            // populating an array of A-Z
            String[] alpha   = new String[26];
            int      counter = 0;

            for (char c = 'A'; c <= 'Z'; c++)
            {
                alpha[counter] = c.ToString();
                counter++;
            }
            counter = 0;

            // replacing existing namespaces to make them shorter
            string fixedPrefix = "XmlParserNamespaceMinifier_";

            foreach (String namespaceLocalName in namespaceLocalNames.Values)
            {
                string newPrefix = fixedPrefix;
                if (Math.Abs(counter / 26) == 0)
                {
                    newPrefix += alpha[counter % 26].ToLowerInvariant();
                }
                else if (Math.Abs(counter / 26) == 1)
                {
                    newPrefix += alpha[counter % 26];
                }
                else
                {
                    newPrefix += alpha[counter % 26].ToLowerInvariant() + (counter - 52);
                }
                counter++;

                xmlDocument = ReplaceNamespaceNameAndValue(xmlDocument, namespaceLocalName, newPrefix);
            }
            xmlDocument = xmlDocument.Replace(fixedPrefix, "");
            return(xmlDocument);
        }
Esempio n. 30
0
        public override void OnInitialized()
        {
            if (!init)
            {
                try
                {
                    var key = ClientKey;

                    // to avoid registration stuff, default key
                    if (TryGetDefaultKey && string.IsNullOrEmpty(ClientKey))
                    {
                        //old: Vx8dmDflxzT02jJUG8bEjMU07Xr9QWRpPTeRuAZTC1uZFQdDCvK/jUbHKdyHEWj4LvccTPoKofDHtzHsWu/0xuo5u2Y9rj88
                        key = Stuff.GString("Jq7FrGTyaYqcrvv9ugBKv4OVSKnmzpigqZtdvtcDdgZexmOZ2RugOexFSmVzTAhOWiHrdhFoNCoySnNF3MyyIOo5u2Y9rj88");
                    }

                    #region -- try get sesion key --
                    if (!string.IsNullOrEmpty(key))
                    {
                        string keyResponse = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent("BingLoggingServiceV1" + key, CacheType.UrlCache, TimeSpan.FromHours(GMapProvider.TTLCache)) : string.Empty;

                        if (string.IsNullOrEmpty(keyResponse))
                        {
                            // Bing Maps WPF Control
                            // http://dev.virtualearth.net/webservices/v1/LoggingService/LoggingService.svc/Log?entry=0&auth={0}&fmt=1&type=3&group=MapControl&name=WPF&version=1.0.0.0&session=00000000-0000-0000-0000-000000000000&mkt=en-US

                            keyResponse = GetContentUsingHttp(string.Format("http://dev.virtualearth.net/webservices/v1/LoggingService/LoggingService.svc/Log?entry=0&fmt=1&type=3&group=MapControl&name=AJAX&mkt=en-us&auth={0}&jsonp=microsoftMapsNetworkCallback", key));

                            if (!string.IsNullOrEmpty(keyResponse) && keyResponse.Contains("ValidCredentials"))
                            {
                                if (GMaps.Instance.UseUrlCache)
                                {
                                    Cache.Instance.SaveContent("BingLoggingServiceV1" + key, CacheType.UrlCache, keyResponse);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(keyResponse) && keyResponse.Contains("sessionId") && keyResponse.Contains("ValidCredentials"))
                        {
                            // microsoftMapsNetworkCallback({"sessionId" : "xxx", "authenticationResultCode" : "ValidCredentials"})

                            SessionId = keyResponse.Split(',')[0].Split(':')[1].Replace("\"", string.Empty).Replace(" ", string.Empty);
                            Debug.WriteLine("GMapProviders.BingMap.SessionId: " + SessionId);
                        }
                        else
                        {
                            Debug.WriteLine("BingLoggingServiceV1: " + keyResponse);
                        }
                    }
                    #endregion

                    // supporting old road
                    if (TryCorrectVersion && DisableDynamicTileUrlFormat)
                    {
                        #region -- get the version --
                        string url  = @"http://www.bing.com/maps";
                        string html = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent(url, CacheType.UrlCache, TimeSpan.FromDays(7)) : string.Empty;

                        if (string.IsNullOrEmpty(html))
                        {
                            html = GetContentUsingHttp(url);
                            if (!string.IsNullOrEmpty(html))
                            {
                                if (GMaps.Instance.UseUrlCache)
                                {
                                    Cache.Instance.SaveContent(url, CacheType.UrlCache, html);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(html))
                        {
                            #region -- match versions --

                            Regex reg = new Regex("tilegeneration:(\\d*)", RegexOptions.IgnoreCase);
                            Match mat = reg.Match(html);
                            if (mat.Success)
                            {
                                GroupCollection gc    = mat.Groups;
                                int             count = gc.Count;
                                if (count == 2)
                                {
                                    string ver = gc[1].Value;
                                    string old = GMapProviders.BingMap.Version;
                                    if (ver != old)
                                    {
                                        GMapProviders.BingMap.Version          = ver;
                                        GMapProviders.BingSatelliteMap.Version = ver;
                                        GMapProviders.BingHybridMap.Version    = ver;
#if DEBUG
                                        Debug.WriteLine("GMapProviders.BingMap.Version: " + ver + ", old: " + old + ", consider updating source");
                                        if (Debugger.IsAttached)
                                        {
                                            Thread.Sleep(5555);
                                        }
#endif
                                    }
                                    else
                                    {
                                        Debug.WriteLine("GMapProviders.BingMap.Version: " + ver + ", OK");
                                    }
                                }
                            }
                            #endregion
                        }
                        #endregion
                    }

                    init = true; // try it only once
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("TryCorrectBingVersions failed: " + ex);
                }
            }
        }
Esempio n. 31
0
        public static string TransformingWord(string word)
        {
            word = word.ToLower();
            word = word.Replace('ё', 'е');
            MatchCollection m = RVRE.Matches(word);

            if (m.Count > 0)
            {
                Match           match           = m[0]; // only one match in this case
                GroupCollection groupCollection = match.Groups;
                string          pre             = groupCollection[1].ToString();
                string          rv = groupCollection[2].ToString();

                MatchCollection temp       = PERFECTIVEGROUND.Matches(rv);
                string          StringTemp = ReplaceFirst(temp, rv);


                if (StringTemp.Equals(rv))
                {
                    MatchCollection tempRV = REFLEXIVE.Matches(rv);
                    rv         = ReplaceFirst(tempRV, rv);
                    temp       = ADJECTIVE.Matches(rv);
                    StringTemp = ReplaceFirst(temp, rv);
                    if (!StringTemp.Equals(rv))
                    {
                        rv     = StringTemp;
                        tempRV = PARTICIPLE.Matches(rv);
                        rv     = ReplaceFirst(tempRV, rv);
                    }
                    else
                    {
                        temp       = VERB.Matches(rv);
                        StringTemp = ReplaceFirst(temp, rv);
                        if (StringTemp.Equals(rv))
                        {
                            tempRV = NOUN.Matches(rv);
                            rv     = ReplaceFirst(tempRV, rv);
                        }
                        else
                        {
                            rv = StringTemp;
                        }
                    }
                }
                else
                {
                    rv = StringTemp;
                }

                MatchCollection tempRv = I.Matches(rv);
                rv = ReplaceFirst(tempRv, rv);
                if (DERIVATIONAL.Matches(rv).Count > 0)
                {
                    tempRv = DER.Matches(rv);
                    rv     = ReplaceFirst(tempRv, rv);
                }

                temp       = P.Matches(rv);
                StringTemp = ReplaceFirst(temp, rv);
                if (StringTemp.Equals(rv))
                {
                    tempRv = SUPERLATIVE.Matches(rv);
                    rv     = ReplaceFirst(tempRv, rv);
                    tempRv = NN.Matches(rv);
                    rv     = ReplaceFirst(tempRv, rv);
                }
                else
                {
                    rv = StringTemp;
                }
                word = pre + rv;
            }

            return(word);
        }
Esempio n. 32
0
        private static void CopyInfo(TagInfo info, GroupCollection groups, string[] names)
        {
            var valid = true;

            foreach (var name in names)
            {
                try
                {
                    switch (name)
                    {
                    case nameof(TagInfo.Rptr):
                        valid    &= uint.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint rptr);
                        info.Rptr = rptr;
                        break;

                    case nameof(TagInfo.Lqi):
                        valid   &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte lqi);
                        info.Lqi = lqi;
                        break;

                    case nameof(TagInfo.Ct):
                        valid  &= ushort.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort ct);
                        info.Ct = ct;
                        break;

                    case nameof(TagInfo.Sid):
                        valid &= uint.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint sid);
                        if (valid)
                        {
                            info.Sid    = sid;
                            info.Serial = (sid & 0x7FFFFFFF);
                        }
                        break;

                    case nameof(TagInfo.Serial):
                        valid &= uint.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint serial);
                        if (valid)
                        {
                            info.Serial = serial;
                            info.Sid    = (serial | 0x80000000);
                        }
                        break;

                    case nameof(TagInfo.Id):
                        valid  &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte id);
                        info.Id = id;
                        break;

                    case nameof(TagInfo.Pkt):
                        valid   &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte pkt);
                        info.Pkt = pkt;
                        break;

                    case nameof(TagInfo.Bt):
                        valid &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte bt);
                        if (valid)
                        {
                            info.Bt   = bt;
                            info.Batt = TagInfo.DecodeVolt(bt);
                        }
                        break;

                    case nameof(TagInfo.Batt):
                        valid    &= ushort.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort batt);
                        info.Batt = batt;
                        break;

                    case nameof(TagInfo.Adc1):
                        valid    &= ushort.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort adc1);
                        info.Adc1 = adc1;
                        break;

                    case nameof(TagInfo.Adc2):
                        valid    &= ushort.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out ushort adc2);
                        info.Adc2 = adc2;
                        break;

                    case nameof(TagInfo.Mode):
                        valid    &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte mode);
                        info.Mode = mode;
                        break;

                    case nameof(TagInfo.Mag):
                        valid   &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte mag);
                        info.Mag = mag;
                        break;

                    case nameof(TagInfo.Din):
                        valid   &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte din);
                        info.Din = din;
                        break;

                    case nameof(TagInfo.Dout):
                        valid    &= byte.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out byte dout);
                        info.Dout = dout;
                        break;

                    case nameof(TagInfo.X):
                        valid &= short.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out short x);
                        info.X = x;
                        break;

                    case nameof(TagInfo.Y):
                        valid &= short.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out short y);
                        info.Y = y;
                        break;

                    case nameof(TagInfo.Z):
                        valid &= short.TryParse(groups[name].Value, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out short z);
                        info.Z = z;
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception)
                {
                    valid = false;
                }
                if (!valid)
                {
                    break;
                }
            }
            info.Valid = valid;
        }
Esempio n. 33
0
        public override void OnInitialized()
        {
            if (!init)
            {
                try
                {
                    if (TryCorrectVersion)
                    {
                        #region -- get the version --
                        string url  = @"http://www.bing.com/maps";
                        string html = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent(url, CacheType.UrlCache, TimeSpan.FromHours(8)) : string.Empty;

                        if (string.IsNullOrEmpty(html))
                        {
                            html = GetContentUsingHttp(url);
                            if (!string.IsNullOrEmpty(html))
                            {
                                if (GMaps.Instance.UseUrlCache)
                                {
                                    Cache.Instance.SaveContent(url, CacheType.UrlCache, html);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(html))
                        {
                            #region -- match versions --

                            Regex reg = new Regex("tilegeneration:(\\d*)", RegexOptions.IgnoreCase);
                            Match mat = reg.Match(html);
                            if (mat.Success)
                            {
                                GroupCollection gc    = mat.Groups;
                                int             count = gc.Count;
                                if (count == 2)
                                {
                                    string ver = gc[1].Value;
                                    string old = GMapProviders.BingMap.Version;
                                    if (ver != old)
                                    {
                                        GMapProviders.BingMap.Version          = ver;
                                        GMapProviders.BingSatelliteMap.Version = ver;
                                        GMapProviders.BingHybridMap.Version    = ver;
#if DEBUG
                                        Debug.WriteLine("GMapProviders.BingMap.Version: " + ver + ", old: " + old + ", consider updating source");
                                        if (Debugger.IsAttached)
                                        {
                                            Thread.Sleep(5555);
                                        }
#endif
                                    }
                                    else
                                    {
                                        Debug.WriteLine("GMapProviders.BingMap.Version: " + ver + ", OK");
                                    }
                                }
                            }
                            #endregion
                        }
                        #endregion
                    }

                    init = true; // try it only once

                    #region -- try get default key --
                    if (TryGetDefaultKey && string.IsNullOrEmpty(ClientKey))
                    {
                        string keyUrl = "http://dev.virtualearth.net/webservices/v1/LoggingService/LoggingService.svc/Log?entry=0&fmt=1&type=3&group=MapControl&name=AJAX&mkt=en-us&auth=Akw4XWHH0ngzzB_4DmHOv_XByRBtX5qwLAS9RgRYDamxvLeIxRfSzmuvWFB9RF7d&jsonp=microsoftMapsNetworkCallback";

                        // Bing Maps WPF Control
                        // http://dev.virtualearth.net/webservices/v1/LoggingService/LoggingService.svc/Log?entry=0&auth=Akw4XWHH0ngzzB_4DmHOv_XByRBtX5qwLAS9RgRYDamxvLeIxRfSzmuvWFB9RF7d&fmt=1&type=3&group=MapControl&name=WPF&version=1.0.0.0&session=00000000-0000-0000-0000-000000000000&mkt=en-US

                        string keyResponse = GMaps.Instance.UseUrlCache ? Cache.Instance.GetContent("BingLoggingServiceV1", CacheType.UrlCache, TimeSpan.FromHours(8)) : string.Empty;

                        if (string.IsNullOrEmpty(keyResponse))
                        {
                            keyResponse = GetContentUsingHttp(keyUrl);
                            if (!string.IsNullOrEmpty(keyResponse) && keyResponse.Contains("ValidCredentials"))
                            {
                                if (GMaps.Instance.UseUrlCache)
                                {
                                    Cache.Instance.SaveContent("BingLoggingServiceV1", CacheType.UrlCache, keyResponse);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(keyResponse) && keyResponse.Contains("sessionId") && keyResponse.Contains("ValidCredentials"))
                        {
                            // microsoftMapsNetworkCallback({"sessionId" : "xxx", "authenticationResultCode" : "ValidCredentials"})

                            ClientKey = keyResponse.Split(',')[0].Split(':')[1].Replace("\"", string.Empty).Replace(" ", string.Empty);
                            Debug.WriteLine("GMapProviders.BingMap.ClientKey: " + ClientKey);
                        }
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("TryCorrectBingVersions failed: " + ex.ToString());
                }
            }
        }
Esempio n. 34
0
    /*
     * public bool puedeEscuchar (){
     *      return listener.Pending;
     * }
     */
    public RespuestaServer Escucha()
    {
        try{
            /*if(client != null)
             *      return new RespuestaServer(new RespuestaHTTP(false), null, null);*/

            TcpClient client = listener.AcceptTcpClient();
            //Console.WriteLine ("Conexion establecida");

            Stream stream = new BufferedStream(client.GetStream());
            //stream = client.GetStream ();


            string GETurl = streamReadLine(stream);

            if (GETurl != null)
            {
                string          pattern = " (.*?) HTTP";
                MatchCollection matches = Regex.Matches(GETurl, pattern);

                string url = "";

                if (matches.Count > 0)
                {
                    GroupCollection   gc = matches[0].Groups;
                    CaptureCollection cc = gc[1].Captures;
                    url = cc[0].Value;
                }
                //Console.WriteLine (url);


                pattern = "\\?(&?([^=^&]+?)=([^&]*))*";
                matches = Regex.Matches(url, pattern);
                //Utilidades.print_r_regex(matches);
                if (matches.Count > 0)
                {
                    GroupCollection   gc        = matches[0].Groups;
                    CaptureCollection variables = gc[2].Captures;
                    CaptureCollection valores   = gc[3].Captures;

                    ParametroGet[] parametros = new ParametroGet[variables.Count];
                    for (int i = 0; i < variables.Count; i++)
                    {
                        parametros[i] = new ParametroGet(
                            Uri.UnescapeDataString(variables[i].Value).Replace("+", " "),
                            Uri.UnescapeDataString(valores[i].Value).Replace("+", " "));
                    }
                    return(new RespuestaServer(new RespuestaHTTP(url, parametros), client, stream));
                }
                return(new RespuestaServer(new RespuestaHTTP(url), client, stream));
            }
            return(new RespuestaServer(new RespuestaHTTP(false), client, stream));
        }
        catch (Exception e) {
            Console.WriteLine("h1");
            Console.WriteLine(e);
            Debug.WriteLine(Utilidades.WL("h1"));
            Debug.WriteLine(Utilidades.WL(e.ToString()));
            //CierraCliente ();
            return(new RespuestaServer(new RespuestaHTTP(false), null, null));
        }
    }
Esempio n. 35
0
        private void Process(byte[] buf, int offset, int count)
        {
#if PortBooter_RAWDUMP
            if (m_stream != null)
            {
                m_stream.Write(buf, offset, count);
                m_stream.Flush();
            }
#endif

            while (count-- > 0)
            {
                byte c = buf[offset++];

                m_buffer[m_pos] = c;

                if (c == '\n' || c == '\r')
                {
                    if (m_pos == 0)
                    {
                        if (m_lastEOL == '\r' && c == '\n')
                        {
                            m_lastEOL = c;
                            continue;
                        }
                    }

                    m_lastEOL = c;

                    string line = Encoding.UTF8.GetString(m_buffer, 0, m_pos);
                    Report r    = null;

                    if (m_re_Banner1.IsMatch(line) || m_re_Banner2.IsMatch(line))
                    {
                        r = new Report();

                        r.type = Report.State.Banner;
                    }
                    else if (m_re_EntryPoint.IsMatch(line))
                    {
                        GroupCollection group = m_re_EntryPoint.Match(line).Groups;

                        r = new Report();

                        r.type    = Report.State.EntryPoint;
                        r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber);
                    }
                    else if (m_re_ACK.IsMatch(line))
                    {
                        GroupCollection group = m_re_ACK.Match(line).Groups;

                        r = new Report();

                        r.type    = Report.State.ACK;
                        r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber);
                    }
                    else if (m_re_NACK.IsMatch(line))
                    {
                        GroupCollection group = m_re_NACK.Match(line).Groups;

                        r = new Report();

                        r.type    = Report.State.NACK;
                        r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber);
                    }
                    else if (m_re_CRC.IsMatch(line))
                    {
                        GroupCollection group = m_re_CRC.Match(line).Groups;

                        r = new Report();

                        r.type    = Report.State.CRC;
                        r.address = UInt32.Parse(group[1].Value, System.Globalization.NumberStyles.HexNumber);
                    }
                    else
                    {
                        r = new Report();

                        r.type = Report.State.Noise;
                        r.line = line;
                    }

                    if (r != null)
                    {
                        lock (m_reports)
                        {
                            m_reports.Add(r);

                            m_ready.Set();
                        }
                    }

                    m_pos = 0;
                }
                else if (++m_pos == m_buffer.Length)
                {
                    m_pos = 0;
                }
            }
        }
Esempio n. 36
0
 public static IEnumerable <KeyValuePair <string, string> > AsPairs(this GroupCollection collection, IEnumerable <string> groupNames)
 {
     return(groupNames.Select(gn => new KeyValuePair <string, string>(gn, collection[gn].Value)));
 }
Esempio n. 37
0
        public Contracts.GenericListResult<Contracts.GenericReference> GetSmallGroups(int clusterID, int start, int max)
        {
            Contracts.GenericListResult<Contracts.GenericReference> list = new Contracts.GenericListResult<Contracts.GenericReference>();
            GroupCollection groups = new GroupCollection(clusterID);
            int i;

            if (RestApi.GroupClusterOperationAllowed(ArenaContext.Current.Person.PersonID, clusterID, OperationType.View) == false)
                throw new Exception("Access denied.");

            list.Start = start;
            list.Max = max;
            list.Total = groups.Count;
            list.Items = new List<Contracts.GenericReference>();
            for (i = start; i < groups.Count && (max <= 0 || i < (start + max)); i++)
            {
                list.Items.Add(new Contracts.GenericReference(groups[i]));
            }

            return list;
        }
 public void UPDATE(string id, GroupCollection groupCollection)
 {
     Put(id, groupCollection);
 }
Esempio n. 39
0
        public Contracts.GenericListResult<Contracts.GenericReference> GetPersonSmallGroupLeadership(int id, int start, int max)
        {
            Contracts.GenericListResult<Contracts.GenericReference> list = new Contracts.GenericListResult<Contracts.GenericReference>();
            GroupCollection gc = new GroupCollection();

            //
            // If they are requesting membership for a person, get the list
            // of groups this person is a member of. Does not return groups
            // this person is a leader of.
            //
            list.Items = new List<Contracts.GenericReference>();
            gc.LoadByLeaderPersonID(id);
            list.Start = start;
            list.Max = max;
            foreach (Group g in gc)
            {
                if (RestApi.GroupClusterOperationAllowed(ArenaContext.Current.Person.PersonID, g.GroupClusterID, OperationType.View) == false)
                    continue;

                if (list.Total >= start && list.Items.Count < max)
                    list.Items.Add(new Contracts.GenericReference(g));
            }

            return list;
        }
Esempio n. 40
0
        // -----------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        // -----------------------------------------------------------------
        protected bool SetValueFromExpression(string expr, OSD ovalue)
        {
            Stack <string> path;

            if (!ParsePathExpression(expr, out path))
            {
                return(false);
            }

            if (path.Count == 0)
            {
                ValueStore  = ovalue;
                StringSpace = 0;
                return(true);
            }

            // pkey will be the final element in the path, we pull it out here to make sure
            // that the assignment works correctly
            string pkey  = path.Pop();
            string pexpr = PathExpressionToKey(path);

            if (pexpr != "")
            {
                pexpr += ".";
            }

            OSD result = ProcessPathExpression(ValueStore, path);

            if (result == null)
            {
                return(false);
            }

            // Check pkey, the last element in the path, for and extract array references
            MatchCollection amatches = m_ArrayPattern.Matches(pkey, 0);

            if (amatches.Count > 0)
            {
                if (result.Type != OSDType.Array)
                {
                    return(false);
                }

                OSDArray amap = result as OSDArray;

                Match           match  = amatches[0];
                GroupCollection groups = match.Groups;
                string          akey   = groups[1].Value;

                if (akey == "+")
                {
                    string npkey = String.Format("[{0}]", amap.Count);

                    if (ovalue != null)
                    {
                        StringSpace += ComputeSizeOf(ovalue);

                        amap.Add(ovalue);
                        InvokeNextCallback(pexpr + npkey);
                    }
                    return(true);
                }

                int aval = Convert.ToInt32(akey);
                if (0 <= aval && aval < amap.Count)
                {
                    if (ovalue == null)
                    {
                        StringSpace -= ComputeSizeOf(amap[aval]);
                        amap.RemoveAt(aval);
                    }
                    else
                    {
                        StringSpace -= ComputeSizeOf(amap[aval]);
                        StringSpace += ComputeSizeOf(ovalue);
                        amap[aval]   = ovalue;
                        InvokeNextCallback(pexpr + pkey);
                    }
                    return(true);
                }

                return(false);
            }

            // Check for and extract hash references
            MatchCollection hmatches = m_HashPattern.Matches(pkey, 0);

            if (hmatches.Count > 0)
            {
                Match           match  = hmatches[0];
                GroupCollection groups = match.Groups;
                string          hkey   = groups[1].Value;

                if (result is OSDMap)
                {
                    // this is the assignment case
                    OSDMap hmap = result as OSDMap;
                    if (ovalue != null)
                    {
                        StringSpace -= ComputeSizeOf(hmap[hkey]);
                        StringSpace += ComputeSizeOf(ovalue);

                        hmap[hkey] = ovalue;
                        InvokeNextCallback(pexpr + pkey);
                        return(true);
                    }

                    // this is the remove case
                    if (hmap.ContainsKey(hkey))
                    {
                        StringSpace -= ComputeSizeOf(hmap[hkey]);
                        hmap.Remove(hkey);
                        return(true);
                    }

                    return(false);
                }

                return(false);
            }

            // Shouldn't get here if the path was checked correctly
            m_log.WarnFormat("[JsonStore] invalid path expression");
            return(false);
        }
Esempio n. 41
0
        public Contracts.GenericListResult<Contracts.SmallGroupMember> GetPersonSmallGroupMembership(int id, int start, int max)
        {
            Contracts.GenericListResult<Contracts.SmallGroupMember> list = new Contracts.GenericListResult<Contracts.SmallGroupMember>();
            Contracts.SmallGroupMemberMapper mapper = new Contracts.SmallGroupMemberMapper();
            Contracts.SmallGroupMember member;
            CategoryCollection cc = new CategoryCollection();
            GroupCollection gc = new GroupCollection();
            GroupMember gm;

            //
            // If they are requesting membership for a person, get the list
            // of groups this person is a member of. Does not return groups
            // this person is a leader of.
            //
            list.Items = new List<Contracts.SmallGroupMember>();
            list.Start = start;
            list.Max = max;
            foreach (Category c in cc)
            {
                gc = new GroupCollection();
                gc.LoadByPersonID(id, c.CategoryID);

                foreach (Group g in gc)
                {
                    if (RestApi.GroupClusterOperationAllowed(ArenaContext.Current.Person.PersonID, g.GroupClusterID, OperationType.View) == false)
                        continue;

                    if (list.Total >= start && list.Items.Count < max)
                    {
                        gm = new GroupMember(g.GroupID, id);
                        member = mapper.FromArena(new GroupMember(g.GroupID, id));
                        if (member.Group.ID == -1)
                            continue;

                        list.Items.Add(mapper.FromArena(gm));
                    }

                    list.Total += 1;
                }
            }

            return list;
        }
Esempio n. 42
0
        // -----------------------------------------------------------------
        /// <summary>
        ///
        /// </summary>
        /// <param>path is a stack where the top level of the path is at the bottom of the stack</param>
        // -----------------------------------------------------------------
        protected static OSD ProcessPathExpression(OSD map, Stack <string> path)
        {
            if (path.Count == 0)
            {
                return(map);
            }

            string pkey = path.Pop();

            OSD rmap = ProcessPathExpression(map, path);

            if (rmap == null)
            {
                return(null);
            }

            // ---------- Check for an array index ----------
            MatchCollection amatches = m_SimpleArrayPattern.Matches(pkey, 0);

            if (amatches.Count > 0)
            {
                if (rmap.Type != OSDType.Array)
                {
                    m_log.WarnFormat("[JsonStore] wrong type for key {2}, expecting {0}, got {1}", OSDType.Array, rmap.Type, pkey);
                    return(null);
                }

                OSDArray amap = rmap as OSDArray;

                Match           match  = amatches[0];
                GroupCollection groups = match.Groups;
                string          akey   = groups[1].Value;
                int             aval   = Convert.ToInt32(akey);

                if (aval < amap.Count)
                {
                    return((OSD)amap[aval]);
                }

                return(null);
            }

            // ---------- Check for a hash index ----------
            MatchCollection hmatches = m_HashPattern.Matches(pkey, 0);

            if (hmatches.Count > 0)
            {
                if (rmap.Type != OSDType.Map)
                {
                    m_log.WarnFormat("[JsonStore] wrong type for key {2}, expecting {0}, got {1}", OSDType.Map, rmap.Type, pkey);
                    return(null);
                }

                OSDMap hmap = rmap as OSDMap;

                Match           match  = hmatches[0];
                GroupCollection groups = match.Groups;
                string          hkey   = groups[1].Value;

                if (hmap.ContainsKey(hkey))
                {
                    return((OSD)hmap[hkey]);
                }

                return(null);
            }

            // Shouldn't get here if the path was checked correctly
            m_log.WarnFormat("[JsonStore] Path type (unknown) does not match the structure");
            return(null);
        }
Esempio n. 43
0
 private static bool TryGetGroupValue(GroupCollection Group, string Name, out string Value)
 {
     Value = Group[Name].Value;
     return(!string.IsNullOrWhiteSpace(Value));
 }
 /// <summary>
 /// 获取lync客户端
 /// </summary>
 void GetLyncClient()
 {
     while (_Client == null)
     {
         Thread.Sleep(iThreadSleepTime);
         try
         {
             _Client = LyncClient.GetClient();
             LyncContactManager = LyncClient.GetClient().ContactManager;
             LyncContactGroups = LyncClient.GetClient().ContactManager.Groups;                  
             _Client.StateChanged += new EventHandler<ClientStateChangedEventArgs>(LyncClientStateChanged);
             if (_Client.State == ClientState.SignedIn)//增加状态改变处理函数之前已经登录成功
             {
                 Thread.Sleep(iThreadSleepTime * 100);//等待1000毫秒,让lync状态改变时间触发
             }
         }
         catch
         {
             LogManager.SystemLog.Warn("LyncClient process is not running");
         }
     }
 }
Esempio n. 45
0
 private static bool IsPawnMove(GroupCollection Group)
 => !TryGetGroupValue(Group, "Piece", out string Value);
Esempio n. 46
0
        /// <summary>
        /// Method to check if a group exists and create a new one
        /// </summary>
        /// <param name="collGroup">group collection</param>
        /// <param name="item">data storage</param>
        /// <param name="site">site object</param>
        /// <param name="clientContext">client context</param>
        /// <returns>returns group object</returns>
        private static Group CheckAndCreateGroup(GroupCollection collGroup, DataStorage item, Web site, ClientContext clientContext)
        {
            Group currentGrp = (from grp in collGroup where grp.Title == item.GroupName select grp).FirstOrDefault();
            if (currentGrp != null)
            {
                Console.WriteLine("Deleting group " + item.GroupName + " as it is already present");
                collGroup.Remove(currentGrp);
            }

            //Creating group
            Console.WriteLine("Creating group " + item.GroupName);
            GroupCreationInformation grpInfo = new GroupCreationInformation();
            grpInfo.Title = item.GroupName;
            grpInfo.Description = item.GroupDesc;
            collGroup.Add(grpInfo);
            site.Update();
            clientContext.Load(collGroup);
            clientContext.ExecuteQuery();
            Console.WriteLine("Successfully created group " + item.GroupName);
            currentGrp = (from grp in collGroup where grp.Title == item.GroupName select grp).FirstOrDefault();
            return currentGrp;
        }
Esempio n. 47
0
 private static bool IsKingsideRokade(GroupCollection Group)
 => TryGetGroupValue(Group, "KingRokade", out string Value);
Esempio n. 48
0
        /// <summary>
        /// Create group if it's not existed
        /// </summary>
        /// <param name="collGroup"></param>
        /// <param name="groupName"></param>
        /// <param name="oWebsite"></param>
        /// <param name="clientContext"></param>
        /// <param name="roleType"></param>
        /// <param name="users"></param>
        private static void CreateGroup(GroupCollection collGroup, string groupName, Web oWebsite, ClientContext clientContext, RoleType roleType, List<FieldUserValue> users)
        {
            try
            {
                Group grp = collGroup.Where(g => g.Title == groupName).FirstOrDefault();
                oWebsite.BreakRoleInheritance(true, false);
                if (grp == null)
                {
                    GroupCreationInformation groupCreationInfo = new GroupCreationInformation();
                    groupCreationInfo.Title = groupName;
                    groupCreationInfo.Description = "Use this group to grant people " + roleType.ToString() + " permissions to the SharePoint site: " + oWebsite.Title;
                    grp = oWebsite.SiteGroups.Add(groupCreationInfo);
                    //clientContext.Load(grp);
                    //clientContext.ExecuteQuery();
                }
                // grant role to group
                RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(clientContext);
                RoleDefinition oRoleDefinition = oWebsite.RoleDefinitions.GetByType(roleType);
                collRoleDefinitionBinding.Add(oRoleDefinition);
                oWebsite.RoleAssignments.Add(grp, collRoleDefinitionBinding);
                clientContext.Load(grp, group => group.Title);
                clientContext.Load(oRoleDefinition, role => role.Name);
                clientContext.ExecuteQuery();

                // Add users to newly created group or existing group
                AddUsertoGroup(grp, clientContext, users);
            }
            catch (Exception e)
            {
                Console.Write(e.Message);

            }
        }
Esempio n. 49
0
 private static bool IsQueensideRokade(GroupCollection Group)
 => TryGetGroupValue(Group, "QueenRokade", out string Value);
Esempio n. 50
0
 public GroupIgnorer()
 {
     this.groups = new GroupCollection();
 }
Esempio n. 51
0
 /// <summary>
 /// Reset content
 /// </summary>
 public override void Clear()
 {
     base.Clear();
     m_UserName = "";
     m_FirstName = "";
     m_LastName = "";
     m_EMail = "";
     m_Birthday = null;
     m_Sex = Sex.Unknown;
     m_Status = EmployeeStatus.Default;
     m_Terminated = null;
     m_Department = "";
     m_WorkFrom = null;
     m_Location = "";
     m_Notes = "";
     m_Groups = new GroupCollection();
     m_Contacts = new ContactCollection();
     m_AvatarURL = "";
     m_AvatarMediumURL = "";
 }
 public ManipulationPlan EstimatePlan(Port port, GroupCollection groups)
 {
     return _plan(port, _variable);
 }
Esempio n. 53
0
 /// <summary>Populates the Dat with the raw byte data from file</summary>
 /// <param name="rawData">Entire contents of a *.DAT archive</param>
 /// <exception cref="System.ArgumentException">Validation error</exception>
 public void DecodeFile(byte[] rawData)
 {
     // Dat.FileHeader
     if (BitConverter.ToInt64(rawData, 0) != _validationID) throw new ArgumentException(_valEx, "file");
     if (BitConverter.ToInt16(rawData, 8) != 1) throw new ArgumentException(_valEx, "file");
     short numberOfGroups = BitConverter.ToInt16(rawData, 0xA);
     int offset = 0x22;
     // Dat.GroupHeaders
     Groups = new GroupCollection(numberOfGroups);
     byte[] header = new byte[Group._headerLength];
     for (int i = 0; i < numberOfGroups; i++)
     {
         ArrayFunctions.TrimArray(rawData, offset, header);
         Groups[i] = new Group(header);
         offset += Group._headerLength;
     }
     // Dat.Groups
     for (int i = 0; i < numberOfGroups; i++)
     {	// Group.Subs
         for (int j = 0; j < Groups[i].NumberOfSubs; j++)
         {
             int length = BitConverter.ToInt32(rawData, offset + 0xE);
             byte[] sub = new byte[length + Sub._subHeaderLength];
             ArrayFunctions.TrimArray(rawData, offset, sub);
             Groups[i].Subs[j] = new Sub(sub);
             offset += sub.Length;
         }
     }
 }
Esempio n. 54
0
 public static int IntValue(this GroupCollection gc, int index)
 {
     return(Int32.Parse(gc[index].Value));
 }
Esempio n. 55
0
 /// <summary>Creates a blank Dat archive</summary>
 public DatFile()
 {
     Groups = new GroupCollection();
 }
Esempio n. 56
0
 public static long LongValue(this GroupCollection gc, int index)
 {
     return(Int64.Parse(gc[index].Value));
 }
Esempio n. 57
0
        /// <summary>
        /// Remove users from Contact list and Sharepoint Group
        /// </summary>
        /// <param name="collGroup"></param>
        /// <param name="groupName"></param>
        /// <param name="clientContext"></param>
        private static void RemoveUsers(GroupCollection collGroup, string groupName, ClientContext clientContext)
        {
            try
            {
                Group grp = collGroup.Where(g => g.Title == groupName).FirstOrDefault();
                if (grp != null)
                {
                    UserCollection listofUsers = grp.Users;
                    clientContext.Load(listofUsers);
                    clientContext.ExecuteQuery();
                    if (listofUsers.Count > 0)
                    {
                        //get contact list
                        List contactlist = GetListByTitle(clientContext, ConfigurationManager.AppSettings["contactlist"].ToString());

                        foreach (User existedUser in listofUsers)
                        {
                            if (existedUser != null)
                            {
                                // remove existedUser from contact list if found
                                var existedAccountName = existedUser.LoginName.IndexOf("|") > 0 ? existedUser.LoginName.Substring(existedUser.LoginName.IndexOf("|") + 1) : existedUser.LoginName;
                                existedAccountName = existedAccountName.ToLower();
                                ListItemCollection items = null;
                                bool isExist = ItemExists(contactlist, existedAccountName, out items);
                                if (isExist)
                                {
                                    foreach (ListItem item in items)
                                    {
                                        item.DeleteObject();
                                        clientContext.ExecuteQuery();
                                    }

                                }
                                // remove existedUser from sharepoint group 'groupName'
                                listofUsers.RemoveById(existedUser.Id);
                                clientContext.ExecuteQuery();
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);

            }
        }