Beispiel #1
0
    protected void RecalculatePersonCount()
    {
        this.ButtonList.Text = "List ";
        int memberCount = 0;

        try
        {
            Organization  selectedOrg = Organization.FromIdentity(Convert.ToInt32(this.DropOrganizations.SelectedValue));
            Organizations orgTree     = selectedOrg.GetTree();

            Geography   selectedGeo = Geography.FromIdentity(Convert.ToInt32(this.DropGeographies.SelectedValue));
            Geographies geoTree     = selectedGeo.GetTree();


            // Optimize a little: if we are at the org's top anchor, do not parse the geography, just select all
            // Removed, doesnt work if people live in other geo.

            if (false && selectedGeo.Identity == selectedOrg.AnchorGeographyId)
            {
                memberCount = orgTree.GetMemberCount();
            }
            else
            {
                memberCount = orgTree.GetMemberCountForGeographies(geoTree);
            }
        }
        catch (Exception)
        {
        }

        this.ButtonList.Text    = "List " + memberCount.ToString("#,##0") + " people";
        this.ButtonList.Enabled = (memberCount > 0 ? true : false);
    }
    protected void RecalculateRecipientCount()
    {
        Organization  selectedOrg = Organization.FromIdentity(Convert.ToInt32(this.DropOrganizations.SelectedValue));
        Organizations orgTree     = selectedOrg.GetTree();

        Geography   selectedGeo = Geography.FromIdentity(Convert.ToInt32(this.DropGeographies.SelectedValue));
        Geographies geoTree     = selectedGeo.GetTree();

        int memberCount = 0;

        // Optimize a little: if we are at the org's top anchor, do not parse the geography, just select all

        switch (this.DropRecipients.SelectedValue)
        {
        case "Members":
            if (selectedGeo.Identity == selectedOrg.AnchorGeographyId)
            {
                memberCount = orgTree.GetMemberCount();
            }
            else
            {
                memberCount = orgTree.GetMemberCountForGeographies(geoTree);
            }
            break;

        case "Officers":
            memberCount = orgTree.GetRoleHolderCountForGeographies(geoTree);
            break;
        }

        this.LabelRecipientCount.Text = " (" + memberCount.ToString("#,##0") + " recipients)";
    }
Beispiel #3
0
        public static People GetActivists(Organization organization, Geography geography)
        {
            var people = new People();

            // Expensive op:
            BasicPersonRole[] basicPersonRoles =
                SwarmDb.GetDatabaseForReading().GetRolesForOrganizationsGeographies(organization.GetTree().Identities,
                                                                                    geography.GetTree().Identities);

            var lookup = new Dictionary <int, bool>();

            foreach (BasicPersonRole basicRole in basicPersonRoles)
            {
                if (basicRole.Type == RoleType.LocalActive || basicRole.Type == RoleType.LocalLead ||
                    basicRole.Type == RoleType.LocalDeputy)
                {
                    if (!lookup.ContainsKey(basicRole.PersonId))
                    {
                        people.Add(Person.FromIdentity(basicRole.PersonId));
                        lookup[basicRole.PersonId] = true;
                    }
                }
            }

            people.Sort();
            return(people);
        }
Beispiel #4
0
    protected void RecalculatePersonCount()
    {
        this.ButtonSearch.Text = "Search ";
        try
        {
            Organization  selectedOrg = null;
            Organizations orgTree     = null;
            Geography     selectedGeo = null;
            Geographies   geoTree     = null;

            if (this.DropOrganizations.SelectedValue != "0")
            {
                selectedOrg = Organization.FromIdentity(Convert.ToInt32(this.DropOrganizations.SelectedValue));
            }
            else
            {
                selectedOrg = Organization.Root;
            }
            orgTree = selectedOrg.GetTree();

            selectedGeo = Geography.FromIdentity(Convert.ToInt32(this.DropGeographies.SelectedValue));
            geoTree     = selectedGeo.GetTree();

            int memberCount = 0;

            memberCount = orgTree.GetMemberCountForGeographies(geoTree);

            this.ButtonSearch.Text    = "Search " + memberCount.ToString("#,##0") + " people";
            this.ButtonSearch.Enabled = (memberCount > 0 ? true : false);
        }
        catch { }
    }
        public static string GetRecipientCount(int recipientTypeId, int geographyId)
        {
            int personCount = 0;

            AuthenticationData authData  = GetAuthenticationDataAndCulture();
            Geography          geography = Geography.FromIdentity(geographyId);
            Geographies        geoTree   = geography.GetTree();
            Organizations      orgTree   = authData.CurrentOrganization.GetTree();

            switch (recipientTypeId)
            {
            case 0:     // "Select one"
                personCount = 0;
                break;

            case 1:     // Regulars
                personCount = orgTree.GetMemberCountForGeographies(geoTree);
                break;

            case 2:     // Agents
                personCount = Activists.GetCountForGeography(geography);
                break;

            // TODO: Dynamic membership types

            case 101:     // Officers
                personCount = orgTree.GetRoleHolderCountForGeographies(geoTree);
                break;

            case 102:            // Volunteers
                personCount = 0; // TODO
                break;

            default:
                throw new NotImplementedException();
            }

            string result;

            string[] resources = Resources.Pages.Comms.SendMassMessage_RecipientCount.Split('|');

            switch (personCount)
            {
            case 0:
                result = resources[0];
                break;

            case 1:
                result = resources[1];
                break;

            default:
                result = String.Format(resources[2], personCount);
                break;
            }

            return(result);
        }
    protected int GetMemberCount(Organization org, bool recursive, Geography geo, DateTime dateTime)
    {
        string cacheDataKey = "ChartData-AllMembershipEvents-5min";

        MembershipEvents events = (MembershipEvents)Cache.Get(cacheDataKey);

        if (events == null)
        {
            events = MembershipEvents.LoadAll();
            Cache.Insert(cacheDataKey, events, null, DateTime.UtcNow.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        DateTime endDateTime = dateTime;

        Geographies            tree     = geo.GetTree();
        Dictionary <int, bool> treeDict = new Dictionary <int, bool>();

        foreach (Geography g in tree)
        {
            treeDict.Add(g.GeographyId, true);
        }


        int eventIndex   = 0;
        int currentCount = 0;

        Organizations orgtree = null;

        if (DropDownListOrg.SelectedValue == Organization.PPSEid.ToString())
        {
            orgtree = Organizations.FromSingle(Organization.PPSE);
        }
        else
        {
            orgtree = Organization.FromIdentity(Organization.UPSEid).GetTree();
        }

        Dictionary <int, Organization> orgsToInclude = new Dictionary <int, Organization>();

        foreach (Organization o in orgtree)
        {
            orgsToInclude[o.Identity] = o;
        }

        while (eventIndex < events.Count && events[eventIndex].DateTime < endDateTime)
        {
            if (orgsToInclude.ContainsKey(events[eventIndex].OrganizationId) && treeDict.ContainsKey(events[eventIndex].GeographyId))
            {
                currentCount += events[eventIndex].DeltaCount;
            }

            eventIndex++;
        }

        return(currentCount);
    }
    protected int GetMemberCount (Organization org, bool recursive, Geography geo, DateTime dateTime)
    {
        string cacheDataKey = "ChartData-AllMembershipEvents-5min";

        MembershipEvents events = (MembershipEvents)Cache.Get(cacheDataKey);

        if (events == null)
        {
            events = MembershipEvents.LoadAll();
            Cache.Insert(cacheDataKey, events, null, DateTime.UtcNow.AddMinutes(5), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        DateTime endDateTime = dateTime;

        Geographies tree = geo.GetTree();
        Dictionary<int, bool> treeDict = new Dictionary<int, bool>();
        foreach (Geography g in tree)
            treeDict.Add(g.GeographyId, true);


        int eventIndex = 0;
        int currentCount = 0;

        Organizations orgtree = null;

        if (DropDownListOrg.SelectedValue == Organization.PPSEid.ToString())
        {
            orgtree = Organizations.FromSingle(Organization.PPSE);
        }
        else
        {
            orgtree = Organization.FromIdentity(Organization.UPSEid).GetTree();
        }

        Dictionary<int, Organization> orgsToInclude = new Dictionary<int, Organization>();
        foreach (Organization o in orgtree)
        {
            orgsToInclude[o.Identity] = o;
        }

            while (eventIndex < events.Count && events[eventIndex].DateTime < endDateTime)
            {
                if (orgsToInclude.ContainsKey(events[eventIndex].OrganizationId ) && treeDict.ContainsKey(events[eventIndex].GeographyId))
                {

                    currentCount += events[eventIndex].DeltaCount;
                }

                eventIndex++;
            }

        return currentCount;
    }
Beispiel #8
0
        public static People FromOrganizationAndGeography(Organization organization, Geography geography)
        {
            Geographies geoTree = geography.GetTree();

            // First, get list of people in the geography, then filter on memberships

            BasicPerson[] people = SwarmDb.GetDatabaseForReading().GetPeopleInGeographies(geoTree.Identities);

            // Filter on memberships

            return(FilterByMembership(people, organization));
        }
Beispiel #9
0
    protected void RecalculatePersonCount()
    {
        this.ButtonList.Text   = "List ";
        ButtonDupeList.Enabled = false;
        try
        {
            Organization  selectedOrg = Organization.FromIdentity(Convert.ToInt32(this.DropOrganizations.SelectedValue));
            Organizations orgTree     = selectedOrg.GetTree();

            Geography   selectedGeo = Geography.FromIdentity(Convert.ToInt32(this.DropGeographies.SelectedValue));
            Geographies geoTree     = selectedGeo.GetTree();

            int memberCount = 0;

            memberCount = orgTree.GetMemberCountForGeographies(geoTree);

            this.ButtonList.Text    = "List " + memberCount.ToString("#,##0") + " people";
            this.ButtonList.Enabled = (memberCount > 0 ? true : false);

            ButtonDupeList.Enabled     = false;
            ButtonExpiringList.Enabled = false;
            ButtonDupeList.Enabled     = false;
            ButtonExpiringList.Enabled = false;
            PanelForwards.Visible      = false;
            PanelBackwards.Visible     = false;

            Literal1.Text = Literal1.Text.Replace("2500", "3500");

            if (memberCount <= 3500)
            {
                ButtonDupeList.Enabled = true;
                foreach (int handled in handledOrganizations)
                {
                    if (selectedOrg.Inherits(handled) || selectedOrg.Identity == handled)
                    {
                        if (_authority.HasPermission(Permission.CanEditMemberships, selectedOrg.Identity, selectedGeo.Identity, Authorization.Flag.Default))
                        {
                            PanelForwards.Visible = true;
                        }

                        ButtonExpiringList.Enabled = true;
                        if (_authority.HasPermission(Permission.CanSeeExpiredDuringGracePeriod, selectedOrg.Identity, selectedGeo.Identity, Authorization.Flag.Default))
                        {
                            PanelBackwards.Visible = true;
                        }
                    }
                }
            }
        }
        catch { }
    }
Beispiel #10
0
    protected void RecalculatePersonCount()
    {
        this.ButtonList.Text   = "List ";
        ButtonDupeList.Enabled = false;
        try
        {
            Organization  selectedOrg = Organization.FromIdentity(Convert.ToInt32(this.DropOrganizations.SelectedValue));
            Organizations orgTree     = selectedOrg.GetTree();

            Geography   selectedGeo = Geography.FromIdentity(Convert.ToInt32(this.DropGeographies.SelectedValue));
            Geographies geoTree     = selectedGeo.GetTree();

            int memberCount = 0;

            // Optimize a little: if we are at the org's top anchor, do not parse the geography, just select all
            // Removed, doesnt work if people live in other geo.

            if (false && selectedGeo.Identity == selectedOrg.AnchorGeographyId)
            {
                memberCount = orgTree.GetMemberCount();
            }
            else
            {
                memberCount = orgTree.GetMemberCountForGeographies(geoTree);
            }

            this.ButtonList.Text    = "List " + memberCount.ToString("#,##0") + " people";
            this.ButtonList.Enabled = (memberCount > 0 ? true : false);

            ButtonDupeList.Enabled     = false;
            ButtonExpiringList.Enabled = false;

            Literal1.Text = Literal1.Text.Replace("2500", "3500");
            if (memberCount <= 3500)
            {
                ButtonDupeList.Enabled = true;
                foreach (int handled in handledOrganizations)
                {
                    if (selectedOrg.Inherits(handled) || selectedOrg.Identity == handled)
                    {
                        ButtonExpiringList.Enabled = true;
                    }
                }
            }
        }
        catch { }
    }
Beispiel #11
0
        public static People FromOrganizationAndGeographyWithPattern(Organization organization, Geography geography,
                                                                     string pattern)
        {
            Geographies geoTree = geography.GetTree();

            pattern = pattern.Trim();
            if (pattern.Length == 0)
            {
                return(FromOrganizationAndGeography(organization, geography));
            }
            else if (pattern.Length < 3)
            {
                // too short pattern! Return empty set.
                return(new People());
            }

            // First, get list of people in the geography, then filter on memberships

            BasicPerson[] candidates = SwarmDb.GetDatabaseForReading().GetPeopleInGeographiesWithPattern(geoTree.Identities, pattern);

            return(FilterByMembership(candidates, organization));
        }
Beispiel #12
0
    SeriesCollection GetGrowthData(OrganizationMetadata metadata, Geography geo)
    {
        string cacheDataKey = "ChartData-AllMembershipEvents";

        MembershipEvents events = (MembershipEvents)Cache.Get(cacheDataKey);

        if (events == null)
        {
            events = MembershipEvents.LoadAll();
            Cache.Insert(cacheDataKey, events, null, DateTime.Today.AddDays(1).ToUniversalTime(), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        /*
         * using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/Data/MembershipEvents.xml")))
         * {
         *  string xml = reader.ReadToEnd();
         *
         *  events = MembershipEvents.FromXml(xml);
         * }*/

        Organizations          organizations = null;
        Dictionary <int, bool> lookup        = new Dictionary <int, bool>();

        if (metadata.Recursive)
        {
            organizations = Organization.FromIdentity(metadata.OrganizationId).GetTree();
        }
        else
        {
            organizations = Organizations.FromSingle(Organization.FromIdentity(metadata.OrganizationId));
        }

        foreach (Organization org in organizations)
        {
            lookup[org.Identity] = true;
        }

        Dictionary <int, bool> geoDict = null;

        if (geo != null)
        {
            geoDict = new Dictionary <int, bool>();
            Geographies tree = geo.GetTree();

            foreach (Geography g in tree)
            {
                geoDict[g.GeographyId] = true;
            }
        }

        SeriesCollection collection   = new SeriesCollection();
        DateTime         dateIterator = new DateTime(2006, 1, 1);

        DateTime today         = DateTime.Now.Date;
        DateTime endDate       = today;
        string   endDateString = Request.QueryString["EndDate"];

        if (!String.IsNullOrEmpty(endDateString))
        {
            endDate = DateTime.Parse(endDateString).AddDays(1);
        }

        string dayCount = Request.QueryString["Days"];

        if (dayCount != null)
        {
            dateIterator = endDate.AddDays(-Int32.Parse(dayCount));
        }

        Series series = new Series();

        series.Name = "";
        int eventIndex   = 0;
        int currentCount = 0;

        Dictionary <int, int> personMembershipCountLookup = new Dictionary <int, int>();

        while (dateIterator < endDate)
        {
            DateTime nextDate = dateIterator.AddDays(1);
            while (eventIndex < events.Count && events[eventIndex].DateTime < nextDate)
            {
                // This is f*****g problematic because some people can be members of more than one org,
                // so the relatively simple op becomes complicated one of a sudden when we have to keep
                // track of that.

                // The logic is horrible compared to just iterating over DeltaCount over time.

                if (lookup.ContainsKey(events[eventIndex].OrganizationId) &&
                    (geo == null || geoDict.ContainsKey(events[eventIndex].GeographyId)))
                {
                    int personId = events[eventIndex].PersonId;

                    if (events[eventIndex].DeltaCount > 0)
                    {
                        // A membership was added.

                        // Was this person already a member?

                        if (personMembershipCountLookup.ContainsKey(personId))
                        {
                            // yes, increment that person's membership count, not the people count

                            personMembershipCountLookup[personId]++;
                        }
                        else
                        {
                            // no, create the key, increment the people count and set this person's membership count to 1

                            currentCount++;
                            personMembershipCountLookup[personId] = 1;
                        }
                    }
                    else if (events[eventIndex].DeltaCount < 0 && personMembershipCountLookup.ContainsKey(personId))
                    {
                        // a membership was lost

                        int membershipCountForPerson = personMembershipCountLookup[personId];

                        // in the extreme majority of cases, membershipCountForPerson will be 1, meaning this
                        // is their only and now terminated membership

                        if (membershipCountForPerson == 1)
                        {
                            personMembershipCountLookup.Remove(personId);
                            currentCount--;
                        }
                        else
                        {
                            // but this person had more than one, decrement their membership count but not the total

                            personMembershipCountLookup[personId]--;
                        }
                    }

                    // no case for when DeltaCount is 0, it can't be at the time of this writing,
                    // but who knows how PirateWeb will expand and grow

                    // assumes DeltaCount is always 1 or -1
                }

                eventIndex++;
            }

            Element newElement = new Element();
            newElement.XDateTime = dateIterator;
            newElement.YValue    = currentCount;
            series.Elements.Add(newElement);
            dateIterator = nextDate;
        }

        collection.Add(series);

        collection[0].DefaultElement.Color = metadata.Color;

        return(collection);
    }
Beispiel #13
0
        public static Activists FromGeography(Geography geography)
        {
            Geographies geographies = geography.GetTree();

            return(new Activists(SwarmDb.GetDatabaseForReading().GetActivistPersonIds(geographies.Identities)));
        }
Beispiel #14
0
        public static int GetCountForGeography(Geography geography)
        {
            Geographies geographies = geography.GetTree();

            return(SwarmDb.GetDatabaseForReading().GetActivistCountForGeographies(geographies.Identities));
        }
    SeriesCollection GetGrowthData (OrganizationMetadata metadata, Geography geo)
    {
        string cacheDataKey = "ChartData-AllMembershipEvents";

        MembershipEvents events = (MembershipEvents)Cache.Get(cacheDataKey);

        if (events == null)
        {
            events = MembershipEvents.LoadAll();
            Cache.Insert(cacheDataKey, events, null, DateTime.Today.AddDays(1).ToUniversalTime(), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        /*
        using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/Data/MembershipEvents.xml")))
        {
            string xml = reader.ReadToEnd();

            events = MembershipEvents.FromXml(xml);
        }*/

        Organizations organizations = null;
        Dictionary<int, bool> lookup = new Dictionary<int, bool>();

        if (metadata.Recursive)
        {
            organizations = Organization.FromIdentity(metadata.OrganizationId).GetTree();
        }
        else
        {
            organizations = Organizations.FromSingle(Organization.FromIdentity(metadata.OrganizationId));
        }

        foreach (Organization org in organizations)
        {
            lookup[org.Identity] = true;
        }

        Dictionary<int, bool> geoDict = null;
        if (geo != null)
        {
            geoDict = new Dictionary<int, bool>();
            Geographies tree = geo.GetTree();

            foreach (Geography g in tree)
            {
                geoDict[g.GeographyId] = true;
            }
        }

        SeriesCollection collection = new SeriesCollection();
        DateTime dateIterator = new DateTime(2006, 1, 1);

        DateTime today = DateTime.Now.Date;
        DateTime endDate = today;
        string endDateString = Request.QueryString["EndDate"];

        if (!String.IsNullOrEmpty(endDateString))
        {
            endDate = DateTime.Parse(endDateString).AddDays(1);
        }

        string dayCount = Request.QueryString["Days"];

        if (dayCount != null)
        {
            dateIterator = endDate.AddDays(-Int32.Parse(dayCount));
        }

        Series series = new Series();
        series.Name = "";
        int eventIndex = 0;
        int currentCount = 0;

        Dictionary<int, int> personMembershipCountLookup = new Dictionary<int, int>();

        while (dateIterator < endDate)
        {
            DateTime nextDate = dateIterator.AddDays(1);
            while (eventIndex < events.Count && events[eventIndex].DateTime < nextDate)
            {
                // This is f*****g problematic because some people can be members of more than one org,
                // so the relatively simple op becomes complicated one of a sudden when we have to keep
                // track of that.

                // The logic is horrible compared to just iterating over DeltaCount over time.

                if (lookup.ContainsKey(events[eventIndex].OrganizationId)
                    && (geo == null || geoDict.ContainsKey(events[eventIndex].GeographyId)))
                {
                    int personId = events[eventIndex].PersonId;

                    if (events[eventIndex].DeltaCount > 0)
                    {
                        // A membership was added.

                        // Was this person already a member?

                        if (personMembershipCountLookup.ContainsKey(personId))
                        {
                            // yes, increment that person's membership count, not the people count

                            personMembershipCountLookup[personId]++;
                        }
                        else
                        {
                            // no, create the key, increment the people count and set this person's membership count to 1

                            currentCount++;
                            personMembershipCountLookup[personId] = 1;
                        }
                    }
                    else if (events[eventIndex].DeltaCount < 0 && personMembershipCountLookup.ContainsKey(personId))
                    {
                        // a membership was lost

                        int membershipCountForPerson = personMembershipCountLookup[personId];

                        // in the extreme majority of cases, membershipCountForPerson will be 1, meaning this
                        // is their only and now terminated membership

                        if (membershipCountForPerson == 1)
                        {
                            personMembershipCountLookup.Remove(personId);
                            currentCount--;
                        }
                        else
                        {
                            // but this person had more than one, decrement their membership count but not the total

                            personMembershipCountLookup[personId]--;
                        }
                    }

                    // no case for when DeltaCount is 0, it can't be at the time of this writing,
                    // but who knows how PirateWeb will expand and grow

                    // assumes DeltaCount is always 1 or -1
                }

                eventIndex++;
            }

            Element newElement = new Element();
            newElement.XDateTime = dateIterator;
            newElement.YValue = currentCount;
            series.Elements.Add(newElement);
            dateIterator = nextDate;
        }

        collection.Add(series);

        collection[0].DefaultElement.Color = metadata.Color;

        return collection;

    }
Beispiel #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            GetAuthenticationDataAndCulture();

            Response.ContentType = "application/json";

            int rootGeographyId = Geography.RootIdentity;

            // What's our root GeographyId? (probably Geography.RootIdentity...)

            string rootIdString = Request.QueryString["RootGeographyId"];

            if (!string.IsNullOrEmpty(rootIdString))
            {
                rootGeographyId = Int32.Parse(rootIdString);  // will throw if invalid Int32, but who cares
            }

            // Is this stuff in cache already?

            string cacheKey = "Geographies-Json-" + rootGeographyId.ToString(CultureInfo.InvariantCulture) + "-" +
                              Thread.CurrentThread.CurrentCulture.Name;

            string accountsJson =
                (string)Cache[cacheKey];

            if (accountsJson != null)
            {
                Response.Output.WriteLine(accountsJson);
                Response.End();
                return;
            }

            // Not in cache. Construct.

            Geography rootGeography = Geography.FromIdentity(rootGeographyId);

            // Get geography tree

            Geographies geographies = rootGeography.GetTree();

            // Build tree (there should be a template for this)

            Dictionary <int, List <Geography> > treeMap = new Dictionary <int, List <Geography> >();

            foreach (Geography geography in geographies)
            {
                if (!treeMap.ContainsKey(geography.ParentIdentity))
                {
                    treeMap[geography.ParentIdentity] = new List <Geography>();
                }

                treeMap[geography.ParentIdentity].Add(geography);
            }

            int renderRootNodeId = rootGeography.ParentGeographyId;

            // This works as rootGeography will be the only present child in the collection; other children won't be there

            accountsJson = RecurseTreeMap(treeMap, renderRootNodeId, true);

            Cache.Insert(cacheKey, accountsJson, null, DateTime.Now.AddMinutes(5), TimeSpan.Zero);
            // cache lasts for five minutes, no sliding expiration
            Response.Output.WriteLine(accountsJson);

            Response.End();
        }
Beispiel #17
0
        public string SwedishCircuitMapOrgStrengthLookupReplacer(Match match)
        {
            // Five groups: "color" and "id" are the keys, "start", "middle" and "end" are what to paste in between.

            Dictionary <string, int> lookup = new Dictionary <string, int>();

            lookup["2N"] = 2;
            lookup["2S"] = 38;
            lookup["1"]  = 40;

            Organization org = Organization.FromIdentity(1); // Replace later for more generic

            string resultColorString = "#000000";
            string id    = match.Groups["id"].Value;
            int    geoId = 0;

            try
            {
                if (lookup.ContainsKey(id))
                {
                    geoId = lookup[id];
                }
                else
                {
                    geoId = Int32.Parse(id);
                }

                Geography geo = Geography.FromIdentity(geoId);

                RoleLookup officers = RoleLookup.FromGeographyAndOrganization(geo.Identity, org.Identity);

                bool hasLead   = officers[RoleType.LocalLead].Count > 0;
                bool hasSecond = officers[RoleType.LocalDeputy].Count > 0;

                Geographies geoTree = geo.GetTree();

                int cities         = 0;
                int citiesWithLead = 0;

                foreach (Geography localGeo in geoTree)
                {
                    if (localGeo.Identity == geo.Identity)
                    {
                        continue;
                    }

                    if (localGeo.Name.EndsWith("kommun"))
                    {
                        cities++;

                        officers = RoleLookup.FromGeographyAndOrganization(localGeo.Identity, org.Identity);

                        if (officers[RoleType.LocalLead].Count > 0)
                        {
                            citiesWithLead++;
                        }
                    }
                }

                int cityLeadPercent = 100;

                if (cities > 0)
                {
                    cityLeadPercent = citiesWithLead * 100 / cities;
                }

                // Determine color

                Color color = Color.Red;

                if (!hasLead)
                {
                    color = Color.Red;
                }
                else if (cityLeadPercent > 80 && hasSecond)
                {
                    color = Color.Green;
                }
                else
                {
                    // Find a hue between Orange and Light Green. Say, between 30 and 120.

                    cityLeadPercent += 30;
                    if (cityLeadPercent > 120)
                    {
                        cityLeadPercent = 120;
                    }

                    color = ColorFromAhsb(100, cityLeadPercent, 1.0f, 0.5f);
                }

                resultColorString = String.Format("#{0:x2}{1:x2}{2:x2}", color.R, color.G, color.B);
            }
            catch (Exception)
            {
                // Ignore - color will be black
            }

            return(match.Groups["start"].Value + resultColorString + match.Groups["middle"].Value + id +
                   match.Groups["end"].Value);
        }