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;

        int eventIndex = 0;
        int currentCount = 0;

        while (eventIndex < events.Count && events[eventIndex].DateTime < endDateTime)
        {
            if (events[eventIndex].OrganizationId == Organization.PPSEid)
            {
                currentCount += events[eventIndex].DeltaCount;
            }

            eventIndex++;
        }

        return currentCount;
    }
    string PrintGeography (Geography geo)
    {
        StringBuilder sbl = new StringBuilder();
        RoleType[] rolesToShow = new RoleType[] { RoleType.OrganizationChairman, RoleType.OrganizationVice1, RoleType.OrganizationSecretary, RoleType.LocalLead, RoleType.LocalDeputy };
        Organizations orgs = Organizations.GetOrganizationsAvailableAtGeography(geo.Identity);
        foreach (Organization org in orgs)
        {
            Dictionary<int, bool> listedPersons = new Dictionary<int, bool>();
            if (org.IsOrInherits(Organization.UPSEid))
            {
                if (org.AnchorGeographyId == geo.Identity || org.UptakeGeographies.Contains(geo))
                {
                    RoleLookup officers = RoleLookup.FromOrganization(org);
                    bool foundRole = false;
                    foreach (RoleType rt in rolesToShow)
                    {
                        foundRole |= officers[rt].Count > 0;
                        if (foundRole) break;
                    }

                    if (foundRole)
                    {
                        sbl.Append("<br><br><b>" + HttpUtility.HtmlEncode(org.Name) + ":</b>");
                        foreach (RoleType rt in rolesToShow)
                            foreach (Activizr.Logic.Pirates.PersonRole r in officers[rt])
                            {
                                if (!listedPersons.ContainsKey(r.PersonId))
                                {
                                    sbl.Append(PrintOfficer(r));
                                    listedPersons[r.PersonId] = true;
                                }
                            }

                        sbl.Append("<br>");
                    }
                }
            }
            else
            {
                RoleLookup officers = RoleLookup.FromGeographyAndOrganization(geo, org);

                if (officers[RoleType.LocalLead].Count > 0 || officers[RoleType.LocalDeputy].Count > 0)
                {
                    sbl.Append("<br><br><b>" + HttpUtility.HtmlEncode(org.Name) + ", " + HttpUtility.HtmlEncode(geo.Name) + ":</b>");
                    foreach (RoleType rt in rolesToShow)
                        foreach (Activizr.Logic.Pirates.PersonRole r in officers[rt])
                            if (!listedPersons.ContainsKey(r.PersonId))
                            {
                                sbl.Append(PrintOfficer(r));
                                listedPersons[r.PersonId] = true;
                            }

                    sbl.Append("<br>");
                }
            }
        }
        return sbl.ToString();
    }
    void PrintGeography (XmlElement currentNode, Geography geo, int level)
    {

        BasicGeographyDesignation[] officialdesignations = geo.GetGeographyDesignations();
        XmlElement thisNode = currentNode;
        if (officialdesignations.Length == 0)
        {
            thisNode = currentNode.OwnerDocument.CreateElement("GEOGRAPHY");
        }
        else if (officialdesignations[0].GeographyLevel == GeographyLevel.Municipality)
        {
            thisNode = currentNode.OwnerDocument.CreateElement("GEOGRAPHY");
        }
        else if (officialdesignations[0].GeographyLevel == GeographyLevel.ElectoralCircuit)
        {
            thisNode = currentNode.OwnerDocument.CreateElement("GEOGRAPHY");
        }

        if (thisNode != currentNode)
        {
            currentNode.AppendChild(thisNode);

            RoleLookup officers = RoleLookup.FromGeographyAndOrganization(geo.Identity, 1);
            thisNode.SetAttribute("name", geo.Name);
            thisNode.SetAttribute("hierlevel", level.ToString());
            thisNode.SetAttribute("geographyid", geo.Identity.ToString());
            if (officialdesignations.Length > 0)
            {
                thisNode.SetAttribute("level", ((int)officialdesignations[0].GeographyLevel).ToString());
                if (valkretsbyte.ContainsKey(officialdesignations[0].Designation))
                    thisNode.SetAttribute("key", valkretsbyte[officialdesignations[0].Designation]);
            }


            if (officers[RoleType.LocalLead].Count > 0)
            {
                foreach (PersonRole r in officers[RoleType.LocalLead])
                {
                    GeneratePerson(thisNode, RoleType.LocalLead, r.Person);
                }

            }
            if (officers[RoleType.LocalDeputy].Count > 0)
            {
                foreach (PersonRole r in officers[RoleType.LocalDeputy])
                {
                    GeneratePerson(thisNode, RoleType.LocalDeputy, r.Person);
                }
            }
        }

        foreach (Geography subGeo in geo.Children)
        {
            PrintGeography(thisNode, subGeo, level+1);
        }

    }
 private void buildgeoTree (TreeViewNode node0, Geography g)
 {
     foreach (Geography cg in g.Children)
     {
         childnr++;
         TreeViewNode node = new TreeViewNode(cg.Name, "" + cg.Identity);
         node0.AddChild(node);
         buildgeoTree(node, cg);
     }
 }
        /// <summary>
        /// Converts a DbGeography to a Geography.
        /// </summary>
        /// <param name="geography">Geography instance to convert.</param>
        /// <returns>New DbGeography instance representing the same value as <paramref name="geography"/>.</returns>
        internal static DbGeography ConvertGeography(Geography geography)
        {
            // DbGeography supports a different WKT format than Geography, so need to strip off the SRID first
            string geographyEWKT = geography.ToString();
            int semicolon = geographyEWKT.IndexOf(';');

            Debug.Assert(semicolon >= 0, "Expected to find a semicolon in the WKT format of Geography instance.");

            string geographyWKT = geographyEWKT.Substring(semicolon + 1);
            return DbGeography.FromText(geographyWKT, geography.CoordinateSystem.Id);
        }
Exemple #6
0
        private string RecurseTreeMap(List <TreeNode <Geography> > geoBranch, bool expanded)
        {
            List <string> elements = new List <string>();

            foreach (TreeNode <Geography> geographyNode in geoBranch)
            {
                Geography geography = geographyNode.Data;
                Country   country   = null;

                string geoName = geography.Localized;

                if (_countryLookup.ContainsKey(geography.Identity))
                {
                    // Special case for country nodes: "[NativeName] ([LocalizedName])", e.g. "Deutschland (Tyskland)" for Germany when in Swedish

                    country = _countryLookup[geography.Identity];
                    string localizedCountryName = country.Localized;
                    string nativeCountryName    = geography.Name.Split('(')[0].Trim();

                    if (localizedCountryName != nativeCountryName)
                    {
                        geoName = nativeCountryName + " (" + localizedCountryName + ")";
                    }
                    else
                    {
                        geoName = nativeCountryName;
                    }
                }

                string element = string.Format("\"id\":{0},\"text\":\"{1}\"", geography.Identity,
                                               JsonSanitize(geoName));

                if (country != null)
                {
                    // this is a country node. Populate with stuff to enable lazy-load of the tree at this point.

                    element += ",\"children1\":\"\",\"state\":\"closed\"," +
                               string.Format("\"countryId\":\"{0}\",\"countryNode\":\"{1}\"", country.Code.ToLowerInvariant(), geography.Identity);

                    // Suppress icon to reaplce with flag
                    element += ",\"iconCls\":\"countryNode\"";
                }
                else if (geographyNode.Children.Count > 0)
                {
                    element += ",\"state\":\"" + (expanded ? "open" : "closed") + "\",\"children\":" +
                               RecurseTreeMap(geographyNode.Children, false);
                }

                elements.Add("{" + element + "}");
            }

            return("[" + String.Join(",", elements.ToArray()) + "]");
        }
            public void VacuousGeographyToGeometry()
            {
                var geog         = "LINESTRING (0 0 1 1, 2 2 1 1)".GetGeog();
                var expectedGeom = "LINESTRING (0 0, 2 2)".GetGeom();

                Logger.LogLine("Input Geometry: {0}", geog);
                Logger.Log("Expected Geography: {0}", expectedGeom);
                var obtainedGeom = Geography.VacuousGeographyToGeometry(geog, Constants.DefaultSRID);

                Logger.Log("Obtained Geography: {0}", obtainedGeom);
                SqlAssert.IsTrue(obtainedGeom.STEquals(expectedGeom));
            }
            public void MakeValidGeographyFromTextTest()
            {
                var geomText     = "LINESTRING(-122.360 47.656, -122.343 47.656)";
                var expectedGeog = "LINESTRING (-122.343 47.655999999999992, -122.36 47.655999999999992)".GetGeog();

                Logger.LogLine("Input Geometry: {0}", geomText);
                var result = Geography.MakeValidGeographyFromText(geomText, Constants.DefaultSRID);

                Logger.LogLine("Expected result: {0}", expectedGeog);
                Logger.LogLine("Obtained result: {0}", result);
                SqlAssert.IsTrue(result.STEquals(expectedGeog));
            }
            public void DensifyGeographyTest()
            {
                var geog         = "LINESTRING(-5 0, 5 0)".GetGeog();
                var expectedGeog = "LINESTRING (-5 0, -3 0, -1.0000000000000004 0, 0.99999999999999956 0, 2.9999999999999978 0, 5 0)".GetGeog();

                Logger.LogLine("Input Geometry: {0}", geog);
                var result = Geography.DensifyGeography(geog, 2.0);

                Logger.LogLine("Expected result: {0}", expectedGeog);
                Logger.LogLine("Obtained result: {0}", result);
                SqlAssert.IsTrue(result.STEquals(expectedGeog));
            }
            public void ConvexHullGeographyTest()
            {
                var geog         = "LINESTRING(-122.360 47.656, -122.343 47.656)".GetGeog();
                var expectedGeog = "LINESTRING (-122.343 47.655999999999992, -122.36 47.655999999999992)".GetGeog();

                Logger.LogLine("Input Geometry: {0}", geog);
                var result = Geography.ConvexHullGeography(geog);

                Logger.LogLine("Expected result: {0}", expectedGeog);
                Logger.LogLine("Obtained result: {0}", result);
                SqlAssert.IsTrue(result.STEquals(expectedGeog));
            }
Exemple #11
0
        /// <summary>
        /// Convert Spherical Mercator Coordinates of scene BBox to Unity Coordinates
        /// </summary>
        /// <param name="bbox"> bbox obtained from OSM file </param>
        /// <returns></returns>
        private BBox editbbox(BBox bbox)
        {
            Geography proj       = new Geography();
            Vector2   bottomleft = proj.LatLontoMeters(bbox.bottom, bbox.left);
            Vector2   topright   = proj.LatLontoMeters(bbox.top, bbox.right);

            bbox.meterLeft   = bottomleft.y;
            bbox.meterBottom = bottomleft.x;
            bbox.meterTop    = topright.x;
            bbox.meterRight  = topright.y;
            return(bbox);
        }
Exemple #12
0
        public static People FromOrganizationAndGeography(Organization organization, Geography geography)
        {
            Geographies geoTree = geography.ThisAndBelow();

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

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

            // Filter on memberships

            return(People.LogicalOr(FilterByMembership(people, organization), FilterByApplicant(people, organization)));
        }
Exemple #13
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "application/json";

            string pattern = HttpUtility.UrlDecode(Request.QueryString["Pattern"]);

            string    geographyString = Request.QueryString["GeographyId"];
            int       geographyId     = int.Parse(geographyString);
            Geography geography       = Geography.FromIdentity(geographyId);

            if (
                !CurrentUser.HasAccess(new Access(CurrentOrganization, geography, AccessAspect.PersonData,
                                                  AccessType.Read)))
            {
                throw new UnauthorizedAccessException("nope");
            }

            People matches = People.FromOrganizationAndGeographyWithPattern(CurrentOrganization, geography, pattern);

            // matches = Authorization.FilterPeopleToMatchAuthority(matches, CurrentUser.GetAuthority());

            if (matches == null)
            {
                matches = new People();
            }

            if (matches.Count > 1000)
            {
                matches.RemoveRange(1000, matches.Count - 1000);
            }

            List <string> jsonPeople = new List <string>();

            foreach (Person person in matches)
            {
                string onePerson = '{' +
                                   String.Format(
                    "\"id\":\"{0}\",\"name\":\"{1}\",\"avatar16Url\":\"{2}\",\"geographyName\":\"{3}\",\"mail\":\"{4}\",\"phone\":\"{5}\"",
                    person.Identity,
                    JsonSanitize(person.Canonical),
                    person.GetSecureAvatarLink(16),
                    JsonSanitize(person.Geography.Name),
                    JsonSanitize(person.Mail),
                    JsonSanitize(person.Phone)) + '}';
                jsonPeople.Add(onePerson);
            }

            string result = '[' + String.Join(",", jsonPeople.ToArray()) + ']';

            Response.Output.WriteLine(result);

            Response.End();
        }
Exemple #14
0
        public static void VerifyAsMultiLineString(this Geography data, params PositionData[][] expected)
        {
            VerifyTypedInstance <GeographyMultiLineString>(data, expected == null, (actual) =>
            {
                Assert.Equal(actual.LineStrings.Count, expected.Length);

                for (int i = 0; i < actual.LineStrings.Count; ++i)
                {
                    actual.LineStrings[i].VerifyAsLineString(expected[i]);
                }
            });
        }
Exemple #15
0
        /// <summary>
        /// Converts a DbGeography to a Geography.
        /// </summary>
        /// <param name="geography">Geography instance to convert.</param>
        /// <returns>New DbGeography instance representing the same value as <paramref name="geography"/>.</returns>
        internal static DbGeography ConvertGeography(Geography geography)
        {
            // DbGeography supports a different WKT format than Geography, so need to strip off the SRID first
            string geographyEWKT = geography.ToString();
            int    semicolon     = geographyEWKT.IndexOf(';');

            Debug.Assert(semicolon >= 0, "Expected to find a semicolon in the WKT format of Geography instance.");

            string geographyWKT = geographyEWKT.Substring(semicolon + 1);

            return(DbGeography.FromText(geographyWKT, geography.CoordinateSystem.Id));
        }
    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;
    }
Exemple #17
0
        public static void VerifyAsMultiPoint(this Geography data, params PositionData[] expected)
        {
            VerifyTypedInstance <GeographyMultiPoint>(data, expected == null, (actual) =>
            {
                Assert.Equal(actual.Points.Count, expected.Length);

                for (int i = 0; i < actual.Points.Count; ++i)
                {
                    VerifyAsPoint(actual.Points[i], expected[i]);
                }
            });
        }
Exemple #18
0
    protected void ButtonLogActivity_Click(object sender, EventArgs e)
    {
        // First, if there's an upload that the user hasn't processed, process it first.

        if (this.Upload.UploadedFiles.Count > 0)
        {
            ProcessUpload();
        }

        // If args were invalid, abort

        if (!Page.IsValid)
        {
            return;
        }


        // Read the form data

        int temporaryId = Int32.Parse(this.TemporaryDocumentIdentity.Text);

        int       organizationId = Int32.Parse(this.DropOrganizations.SelectedValue);
        Geography geography      = this.DropGeographies.SelectedGeography;

        DateTime             created      = DateTime.Now;
        DateTime             activityDate = (DateTime)this.DatePicker.SelectedDate;
        string               description  = this.TextDescription.Text;
        ExternalActivityType type         =
            (ExternalActivityType)Enum.Parse(typeof(ExternalActivityType), this.DropActivityType.SelectedValue);

        // Create the activism record

        ExternalActivity activity = ExternalActivity.Create(Organization.FromIdentity(organizationId), geography, type,
                                                            activityDate, description, _currentUser);

        // Move documents to the new activism

        Documents.ForObject(new TemporaryIdentity(temporaryId)).SetForeignObjectForAll(activity);

        // Create the event for PirateBot-Mono to send off mails

        Activizr.Logic.Support.PWEvents.CreateEvent(EventSource.PirateWeb, EventType.ActivismLogged,
                                                    _currentUser.Identity, organizationId, geography.Identity, _currentUser.Identity,
                                                    activity.Identity, string.Empty);

        Page.ClientScript.RegisterStartupScript(typeof(Page), "OkMessage", @"alert ('The activism has been logged.');", true);

        // Clear the text fields

        this.TextDescription.Text           = string.Empty;
        this.TemporaryDocumentIdentity.Text = "0";
    }
Exemple #19
0
        internal static void ProcessAddedMember(BasicEvent newEvent)
        {
            // This function handles the case when a new member has been added. Several things are hardcoded
            // for UP at this point.

            Person       victim       = Person.FromIdentity(newEvent.VictimPersonId);
            Person       perpetrator  = Person.FromIdentity(newEvent.PerpetratorPersonId);
            Organization organization = Organization.FromIdentity(newEvent.OrganizationId);
            Geography    geography    = Geography.FromIdentity(newEvent.GeographyId);

            int[] concernedPeopleId = PirateWeb.Logic.Collections.Roles.GetAllUpwardRoleHolders(newEvent.OrganizationId, newEvent.GeographyId);

            // TODO HERE: Filter to only get the interested people in this event

            string body =
                "A new member has appeared within your area of authority.\r\n\r\n" +
                "Person:       " + victim.Name + "\r\n" +
                "Organization: " + organization.Name + "\r\n" +
                "Geography:    " + geography.Name + "\r\n\r\n" +
                "Event source: " + newEvent.EventSource.ToString() + "\r\n\r\n";

            if (newEvent.EventSource == EventSource.PirateWeb)
            {
                body += "This member was added manually by " + perpetrator.Name + ".\r\n\r\n";
            }

            // Send welcoming mails

            string mailsSent = MailResolver.CreateWelcomeMail(victim, organization);

            body += "Welcoming automails sent:\r\n" + mailsSent +
                    "\r\nTo add an automatic welcome mail for your organization and geography, " +
                    "go to PirateWeb, Communications, Triggered Automails, Automail type \"Welcome\".\r\n\r\n";

            // Add some hardcoded things for UP

            if (organization.Inherits(2))
            {
                int membersTotal = Organization.FromIdentity(2).GetTree().GetMemberCount();
                int membersHere  = organization.GetMemberCount();

                body += "Member count for Ung Pirat SE: " + membersTotal.ToString("#,##0") + "\r\n" +
                        "Member count for " + organization.Name + ": " + membersHere.ToString("#,##0") + "\r\n";
            }


            People concernedPeople = PirateWeb.Logic.Collections.People.FromIdentities(concernedPeopleId);

            new PirateWeb.Utility.Mail.MailTransmitter("PirateWeb", "*****@*****.**",
                                                       "New Member: [" + victim.Name + "] - [" + organization.NameShort + "], [" + geography.Name + "]",
                                                       body, concernedPeople, true).Send();
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        GeographyBallotCoverageLookup lookup = GetLookupFromCache();

        HtmlTableRow  tr = null;
        HtmlTableCell td = null;

        tr = new HtmlTableRow(); mainTable.Rows.Add(tr);
        td = CreateCell(tr, "Geography");

        td = CreateCell(tr, "GeographyId");
        td = CreateCell(tr, "VoterCount");
        td = CreateCell(tr, "AdvanceVotingStationsDistro");
        td = CreateCell(tr, "AdvanceVotingStationsTotal");
        td = CreateCell(tr, "VotingStationsTotal");
        td = CreateCell(tr, "VotingStationsDistroSingle");
        td = CreateCell(tr, "VotingStationsDistroDouble");
        td = CreateCell(tr, "VotingStationsComplete");
        td = CreateCell(tr, "WAdvanceVotingStationsDistro");
        td = CreateCell(tr, "WAdvanceVotingStationsTotal");
        td = CreateCell(tr, "WWAdvanceVotingStationsDistro");
        td = CreateCell(tr, "WWAdvanceVotingStationsTotal");
        td = CreateCell(tr, "WVotingStationsTotal");
        td = CreateCell(tr, "WVotingStationsDistroSingle");
        td = CreateCell(tr, "WVotingStationsDistroDouble");
        td = CreateCell(tr, "WVotingStationsComplete");

        foreach (int geoId in lookup.Keys)
        {
            tr = new HtmlTableRow(); mainTable.Rows.Add(tr);
            GeographyBallotCoverageDataPoint pt = lookup[geoId];

            td = CreateCell(tr, "" + Geography.FromIdentity((pt.GeographyId)).Name);

            td = CreateCell(tr, "" + pt.GeographyId);
            td = CreateCell(tr, "" + pt.VoterCount);
            td = CreateCell(tr, "" + pt.AdvanceVotingStationsDistro);
            td = CreateCell(tr, "" + pt.AdvanceVotingStationsTotal);
            td = CreateCell(tr, "" + pt.VotingStationsTotal);
            td = CreateCell(tr, "" + pt.VotingStationsDistroSingle);
            td = CreateCell(tr, "" + pt.VotingStationsDistroDouble);
            td = CreateCell(tr, "" + pt.VotingStationsComplete);
            td = CreateCell(tr, "" + pt.WAdvanceVotingStationsDistro);
            td = CreateCell(tr, "" + pt.WAdvanceVotingStationsTotal);
            td = CreateCell(tr, "" + pt.WWAdvanceVotingStationsDistro);
            td = CreateCell(tr, "" + pt.WWAdvanceVotingStationsTotal);
            td = CreateCell(tr, "" + pt.WVotingStationsTotal);
            td = CreateCell(tr, "" + pt.WVotingStationsDistroSingle);
            td = CreateCell(tr, "" + pt.WVotingStationsDistroDouble);
            td = CreateCell(tr, "" + pt.WVotingStationsComplete);
        }
    }
Exemple #21
0
    protected void CountrySelectionDrop_SelectedIndexChanged(object sender, EventArgs e)
    {
        CityDrop.Items.Clear();

        Geography Geog = new Geography(CountrySelectionDrop.SelectedItem.ToString());

        foreach (Geography.Cities City in new Geography.Cities().GetCities(Convert.ToInt32(CountrySelectionDrop.SelectedValue)))
        {
            System.Diagnostics.Debug.WriteLine(City.Name);

            CityDrop.Items.Add(City.Name);
        }
    }
Exemple #22
0
        public static OutboundComm CreateParticipantMail(string customSubject, string customBody, Person sender, Person from,
                                                         Organization organization, Geography geography)
        {
            ParticipantResolver resolver = new ParticipantResolver(organization, geography);

            OutboundComm comm = OutboundComm.Create(sender, from, organization,
                                                    resolver, null /*recipientdata*/,
                                                    CommTransmitterClass.CommsTransmitterMail,
                                                    new PayloadEnvelope(new ParticipantMailPayload(customSubject, customBody, organization, sender)).ToXml(),
                                                    OutboundCommPriority.Low);

            return(comm);
        }
        public async Task Run()
        {
            _logger.LogInformation("Adding Geography");
            var geography = new Geography("Fire Swamp", new[] { "Flame Bursts", "Lightning Sand", "ROU" });
            var id        = geography.Id;
            await _repository.Post(geography);

            _logger.LogInformation("Getting Information");
            var dbGeography = await _repository.Get <Geography>(geography.Id);

            _logger.LogInformation($"Name {dbGeography.Name}");
            _logger.LogInformation($"Dangers {string.Join(',', dbGeography.Dangers)}");
        }
Exemple #24
0
 public static void CreateActivistWithLogging(Geography geo, Person newActivist, string logMessage, EventSource evtSrc, bool isPublic, bool isConfirmed, int orgId)
 {
     PWEvents.CreateEvent(evtSrc,
                          EventType.NewActivist,
                          newActivist.Identity,
                          orgId,
                          geo.Identity,
                          newActivist.Identity,
                          0,
                          string.Empty);
     newActivist.CreateActivist(isPublic, isConfirmed);
     PWLog.Write(newActivist, PWLogItem.Person, newActivist.Identity, PWLogAction.ActivistJoin, "New activist joined.", logMessage);
 }
Exemple #25
0
        public static void VerifyAsPolygon(this Geography data, params PositionData[][] expected)
        {
            VerifyTypedInstance <GeographyPolygon>(data, expected == null, (actual) =>
            {
                Assert.AreEqual(actual.Rings.Count, expected.Length);

                for (int i = 0; i < actual.Rings.Count; ++i)
                {
                    // expected[i] can be null
                    actual.Rings[i].VerifyAsLineString(expected[i]);
                }
            });
        }
    protected void ButtonGetCount_Click(object sender, EventArgs e)
    {
        Geography geo = GeographyTreeDropDown1.SelectedGeography;

        if (geo == null)
        {
            geo = Geography.Root;
        }

        this.LabelCountResults.Text   = this.GetMemberCount(Organization.FromIdentity(Convert.ToInt32(DropDownListOrg.SelectedValue)), false, geo, (DateTime)this.PickDateTime.SelectedDate).ToString();
        this.LabelStartDate.Text      = ((DateTime)this.PickDateTime.SelectedDate).Date.ToString("yyyy-MM-dd");
        this.PickEndDate.SelectedDate = this.PickDateTime.SelectedDate.Value.AddDays(30);
    }
 //Generates random geographies for the map.
 //Make actual geography generation later.
 void GenerateRandomGeographyMap(TileMap tileMap)
 {
     GameObject[,] map = tileMap.GetMap();
     for (int i = 0; i < mapHeight; i++)
     {
         for (int k = 0; k < mapWidth; k++)
         {
             Geography.Biome randomBiome = (Geography.Biome)Random.Range(0, 7);
             Geography       geography   = GeographyManager.CreateGeography(randomBiome);
             map[i, k].GetComponent <Tile>().ApplyGeography(geography);
         }
     }
 }
Exemple #28
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 { }
    }
Exemple #29
0
        public void Resolve(OutboundComm comm)
        {
            Organization organization = Organization.FromIdentity(OrganizationId);
            Geography    geography    = Geography.FromIdentity(GeographyId);

            People allParticipants = People.FromOrganizationAndGeography(organization, geography);

            foreach (Person person in allParticipants)
            {
                // Todo: Check if still participant? Check if declined correspondence?

                comm.AddRecipient(person);
            }
        }
Exemple #30
0
        public IHttpActionResult DeleteGeography(string id)
        {
            Geography geography = db.Geographies.Find(id);

            if (geography == null)
            {
                return(NotFound());
            }

            db.Geographies.Remove(geography);
            db.SaveChanges();

            return(Ok(geography));
        }
        public void FastGeoJsonWriterShouldSerializeSameGeographyAsGeoJsonObjectWriter()
        {
            var geographys = new Geography[]
            {
                GeographyFactory.Polygon().Ring(33.1, -110).LineTo(1,2).LineTo(35.97, -110.15).LineTo(11.45, 87.75).Ring(35.97, -110).LineTo(0.03, -0.01).LineTo(45.23, 23.10).Build(),
                GeographyFactory.Point(32, -100).Build(),
                GeographyFactory.LineString(32, -100).LineTo(0, 100).LineTo(0.9, -10.3).LineTo(16.85, 35).Build(),
                GeographyFactory.MultiPoint().Point(10.2, 11.2).Point(0.1, 0.1).Build(),
                GeographyFactory.MultiPolygon().Polygon().Ring(33.1, -110).LineTo(35.97, -110.15).LineTo(11.45, 87.75).LineTo(-1, -0.9).Ring(35.97, -110).LineTo(0.03, -0.01).LineTo(45.23, 23.10).LineTo(9.01, 1).Polygon().Ring(35.97, -110).LineTo(0.03, -0.01).LineTo(45.23, 23.10).LineTo(0.9, 100.5).Ring(33.1, -110).LineTo(35.97, -110.15).LineTo(11.45, 87.75).LineTo(88.77, 33.55).Build()
            };

            var converter = new GeographyTypeConverter();
            ValidateSerializationResultShouldBeSame(OriginalWriteJsonLight, (instance, writer) => converter.WriteJsonLight(instance, writer), geographys);
        }
Exemple #32
0
        public void LoadData(Geography geography)
        {
            isNew            = false;
            current          = geography;
            txtCaption.Text  = current.Caption;
            txtRevision.Text = current.Revision;
            cmbParent.SelectItem(current.Parent);
            txtMaxZoom.Text       = current.MaxZoom.ToString();
            txtFieldCodeSize.Text = current.FieldCodeSize.ToString();
            cmbGradient.SelectItem <Gradient>(current.Gradient);
            txtLuminance.Text = (current.GradientLuminance.HasValue ? current.GradientLuminance.Value.ToString() : "");

            chPartialCoverage.Checked = current.PartialCoverage != null;
            if (chPartialCoverage.Checked)
            {
                txtCoverage.Text = current.PartialCoverage;
            }

            if (uFile.HasFile)
            {
                cmbChildren.Enabled         = false;
                cmbHousehold.Enabled        = false;
                cmbPopulation.Enabled       = false;
                cmbFieldCaptionName.Enabled = false;
                cmbFieldCodeName.Enabled    = false;
                cmbParentItem.Enabled       = false;
                cmbParent.Enabled           = false;
                cmbUrbanity.Enabled         = false;
                uFile.EnabledButtons        = false;
                chPartialCoverage.Enabled   = false;
                uFileMissings.Enabled       = false;

                if (string.IsNullOrEmpty(current.FieldCodeName) == false)
                {
                    cmbFieldCodeName.Items.Add(current.FieldCodeName);
                    cmbFieldCodeName.SelectedIndex = 0;
                }

                if (string.IsNullOrEmpty(current.FieldUrbanityName) == false)
                {
                    cmbUrbanity.Items.Add(current.FieldUrbanityName);
                    cmbUrbanity.SelectedIndex = 0;
                }
                if (string.IsNullOrEmpty(current.FieldCaptionName) == false)
                {
                    cmbFieldCaptionName.Items.Add(current.FieldCaptionName);
                    cmbFieldCaptionName.SelectedIndex = 0;
                }
            }
        }
Exemple #33
0
            /// <summary>Indicates a Geography Intersects() method.</summary>
            /// <returns>The operation result.</returns>
            /// <param name="operand1">The Operand 1, point.</param>
            /// <param name="operand2">The Operand 2, polygon.</param>
            public override bool Intersects(Geography operand1, Geography operand2)
            {
                var point   = operand1 as GeographyPoint;
                var polygon = operand2 as GeographyPolygon;

                if ((point != null) && (polygon != null))
                {
                    // mock logic for Intersects() method
                    return(polygon.Rings.Count <= 2 &&
                           polygon.Rings[0].Points[0].Latitude < 32.1);
                }

                throw new NotImplementedException();
            }
Exemple #34
0
 public string GeographyToGmlV3(Geography geography)
 {
     try
     {
         GmlFormatter gmlFormatter = GmlFormatter.Create();
         var          result       = gmlFormatter.Write(geography);
         result = result.Replace(@"gml:srsName=""http://www.opengis.net/def/crs/EPSG/0/4326""", "");
         return(result);
     }
     catch
     {
         return(null);
     }
 }
        /// <summary>
        /// Called when a GeometryCollection is either the top level type, or when a GeometryCollection has been nested inside
        /// another GeometryCollection (which is legal, but apparently discouraged.)
        /// </summary>
        /// <param name="reader">A JsonReader positioned at the beginning of the geometries array.</param>
        /// <returns>The list of Geographies which were extracted.</returns>
        private List <Geography> ProcessGeometryCollection(JsonReader reader)
        {
            List <Geography> result = new List <Geography>();

            reader.Expect(JsonToken.StartArray);

            while (reader.Read() && reader.TokenType != JsonToken.EndArray)
            {
                Geography geography = ProcessSingleGeography(reader);

                result.Add(geography);
            }

            return(result);
        }
        public QuestionsPage()
        {
            this.InitializeComponent();
            subject = new SubjectViewModel();
            correct_answer = new English();
            maths = new Maths();
            business = new Business();
            accounting = new Accounting();
            geography = new Geography();
            history = new History();
            life = new Life();
            physics = new Physics();
            time.Start();

        }
 public void LoadData(ClippingRegionItem country)
 {
     current             = country;
     txtDescription.Text = country.Caption;
     using (new WaitCursor())
     {
         var parents = UI.GetGeographies();
         cmbGeography.FillRecursive(parents);
         currentGeography = UI.GetItems <Geography>().Where(x => x.Country == country && x.IsTrackingLevel).FirstOrDefault();
         if (currentGeography != null)
         {
             cmbGeography.SelectItem(currentGeography);
         }
     }
 }
 public Role(BasicPersonRole org)
     : base(org)
 {
     organisationName = Organization.FromIdentity(this.OrganizationId).Name;
     personName       = Person.FromIdentity(this.PersonId).Name;
     roleName         = Enum.GetName(this.Type.GetType(), this.Type);
     geographyName    = "";
     if (RoleTypes.ClassOfRole(this.Type) == RoleClass.Local)
     {
         if (GeographyId > 0)
         {
             geographyName = Geography.FromIdentity(GeographyId).Name;
         }
     }
 }
        static ODataSpatialTypeUtil()
        {
            // Geometry type values.
            GeometryValue = GeometryFactory.Point(32.0, -10.0).Build();
            GeometryPointValue = GeometryFactory.Point(33.1, -11.0).Build();
            GeometryLineStringValue = GeometryFactory.LineString(33.1, -11.5).LineTo(35.97, -11).Build();
            GeometryPolygonValue = GeometryFactory.Polygon().Ring(33.1, -13.6).LineTo(35.97, -11.15).LineTo(11.45, 87.75).Ring(35.97, -11).LineTo(36.97, -11.15).LineTo(45.23, 23.18).Build();
            GeometryCollectionValue = GeometryFactory.Collection().Point(-19.99, -12.0).Build();
            GeometryMultiPointValue = GeometryFactory.MultiPoint().Point(10.2, 11.2).Point(11.9, 11.6).Build();
            GeometryMultiLineStringValue = GeometryFactory.MultiLineString().LineString(10.2, 11.2).LineTo(11.9, 11.6).LineString(16.2, 17.2).LineTo(18.9, 19.6).Build();
            GeometryMultiPolygonValue = GeometryFactory.MultiPolygon().Polygon().Ring(10.2, 11.2).LineTo(11.9, 11.6).LineTo(11.45, 87.75).Ring(16.2, 17.2).LineTo(18.9, 19.6).LineTo(11.45, 87.75).Build();

            // Geography type values.
            GeographyValue = GeographyFactory.Point(32.0, -100.0).Build();
            GeographyPointValue = GeographyFactory.Point(33.1, -110.0).Build();
            GeographyLineStringValue = GeographyFactory.LineString(33.1, -110.0).LineTo(35.97, -110).Build();
            GeographyPolygonValue = GeographyFactory.Polygon().Ring(33.1, -110.0).LineTo(35.97, -110.15).LineTo(11.45, 87.75).Ring(35.97, -110).LineTo(36.97, -110.15).LineTo(45.23, 23.18).Build();
            GeographyCollectionValue = GeographyFactory.Collection().Point(-19.99, -12.0).Build();
            GeographyMultiPointValue = GeographyFactory.MultiPoint().Point(10.2, 11.2).Point(11.9, 11.6).Build();
            GeographyMultiLineStringValue = GeographyFactory.MultiLineString().LineString(10.2, 11.2).LineTo(11.9, 11.6).LineString(16.2, 17.2).LineTo(18.9, 19.6).Build();
            GeographyMultiPolygonValue = GeographyFactory.MultiPolygon().Polygon().Ring(10.2, 11.2).LineTo(11.9, 11.6).LineTo(11.45, 87.75).Ring(16.2, 17.2).LineTo(18.9, 19.6).LineTo(11.45, 87.75).Build();
        }
 public ActionResult Create(Geography geography)
 {
     if (Session["login_status"] != null)
     {
         int[] z = (int[])Session["function_id"];
         if (z.Contains(7))
         {
             var isexist = from g in db.Geographies
                           where g.geography_name == geography.geography_name
                           select g;
             if (isexist.Count() > 0)
             {
                 TempData["errorMessage"] = "This Geography Already Exist";
                 return RedirectToAction("Index");
             }
             if (ModelState.IsValid)
             {
                 geography.status_id = 1;
                 geography.created_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
                 geography.updated_date = Convert.ToDateTime(DateTime.Now.ToString()).ToString("yyyy-MM-dd");
                 db.Geographies.Add(geography);
                 db.SaveChanges();
                 TempData["errorMessage"] = "Geography Added Successfully";
                 return RedirectToAction("Index");
             }
             return RedirectToAction("Index");
         }
         else
         {
             return RedirectToAction("../Home/Dashboard");
         }
     }
     else
     {
         return RedirectToAction("../Home");
     }
 }
        /// <summary>
        /// Try to parse the given text to a Geography object.
        /// </summary>
        /// <param name="text">Text to parse.</param>
        /// <param name="targetValue">Geography to return.</param>
        /// <param name="reason">The detailed reason of parsing error.</param>
        /// <returns>True if succeeds, false if not.</returns>
        private static bool TryUriStringToGeography(string text, out Geography targetValue, out string reason)
        {
            reason = null;

            if (!TryRemoveLiteralPrefix(ExpressionConstants.LiteralPrefixGeography, ref text))
            {
                targetValue = default(Geography);
                return false;
            }

            if (!TryRemoveQuotes(ref text))
            {
                targetValue = default(Geography);
                return false;
            }

            try
            {
                targetValue = LiteralUtils.ParseGeography(text);
                return true;
            }
            catch (ParseErrorException e)
            {
                targetValue = default(Geography);
                reason = e.Message;
                return false;
            }
        }
Exemple #42
0
    //Generates Habitat biome based on temp, alt, geography, and climate if the hex is being regenerated
    public void GenerateBiome()
    {
        Biome biome = Biome.Ocean;
        int roll;

        if(MapController.worldTemp < MapController.Temperature.Temperate){
            if(localTemp == Temperature.Scorching){
                localTemp = Temperature.Hot;
            }
        }
        if(MapController.worldTemp > MapController.Temperature.Temperate){
            if(localTemp == Temperature.Arctic){
                localTemp = Temperature.Cold;
            }
        }

        if(localAlt != Altitude.Deep && localAlt != Altitude.Shallow){
            if(localTemp == Temperature.Cold){
                if (localGeo == Geography.Mountains)
                {
                    roll = Random.Range(9, 11);
                }
                else
                {
                    roll = Random.Range(8, 13);
                    if (roll == 11) { roll = 5; }
                }
                biome = (Biome)roll;
            }
            if(localTemp == Temperature.Temperate){
                if(localAlt == Altitude.High || localGeo == Geography.Mountains){
                    roll = Random.Range(0, 6);
                    if(roll == 0)											                    { biome = Biome.Forest; }
                    if (roll == 1)                                                              { biome = Biome.Grassland; }
                    if (roll == 2)                                                              { biome = Biome.Lentic; }
                    if (roll == 3)                                                              { biome = Biome.Lotic; }
                    if (roll > 3)																{ biome = Biome.Chaparral; }

                    if(localClimate == Climate.Wet)										        { biome = Biome.Rainforest;}
                    if(localClimate > Climate.Temperate)										{ biome = Biome.Chaparral;}
                    if (biome == Biome.Grassland && localClimate == Climate.Arid)               { biome = Biome.Savanna;}
                    if (biome == Biome.Grassland && localClimate == Climate.Desert)             { biome = Biome.Desert; }
                }
                else if(localAlt == Altitude.Medium){
                    if (localClimate < Climate.Temperate)
                    {
                        roll = Random.Range(0, 6);

                        if (roll < 2)                                                           { biome = Biome.Grassland; }
                        if (roll == 2)                                                          { biome = Biome.Lentic; }
                        if (roll == 3)                                                          { biome = Biome.Lotic; }
                        if (roll == 4)                                                          { biome = Biome.Rainforest; }
                        if (roll == 5)                                                          { biome = Biome.Forest; }
                    }
                    else if (localClimate < Climate.Temperate)
                    {
                        roll = Random.Range(0, 6);

                        if (roll == 0)                                                          { biome = Biome.Chaparral; }
                        if (roll == 1)                                                          { biome = Biome.Desert; }
                        if (roll == 2)                                                          { biome = Biome.Lotic; }
                        if (roll == 3)                                                          { biome = Biome.Forest; }
                        if (roll > 3)                                                           { biome = Biome.Savanna; }
                    }
                }
            }
            if(localTemp == Temperature.Hot){
                if(localGeo == Geography.Mountains || localAlt == Altitude.High){
                    roll = Random.Range(14, 16);												biome = (Biome)roll;
                }
                else if (localGeo == Geography.Flat)
                {
                    roll = Random.Range(0, 6);
                    if (roll == 0) { biome = Biome.Forest; }
                    if (roll == 1) { biome = Biome.Grassland; }
                    if (roll == 2) { biome = Biome.Rainforest; }
                    if (roll == 3) { biome = Biome.Desert; }
                    if (roll > 3) { biome = Biome.Savanna; }
                }
                else
                {
                    roll = Random.Range(0, 6);
                    if (roll == 0) { biome = Biome.Forest; }
                    if (roll == 1) { biome = Biome.Grassland; }
                    if (roll == 2) { biome = Biome.Savanna; }
                    if (roll == 3) { biome = Biome.Chaparral; }
                    if (roll == 4) { biome = Biome.Rainforest; }
                    if (roll == 5) { biome = Biome.Desert; }
                }
            }
        }
        if(biome == Biome.Chaparral){
            if(NeighborContainsAlt(Altitude.Deep) || NeighborContainsAlt(Altitude.Shallow))		{roll = Random.Range(0,3);}
            else 																				{roll = Random.Range(0,1);}
            if(roll > 0)																		{biome = Biome.Lotic;}
        }

        if(localAlt == Altitude.Deep){
            if(localTemp == Temperature.Temperate){
                roll = Random.Range(1, 5);														biome = (Biome)roll;}
            if(localTemp == Temperature.Hot && NeighborContainsAlt(Altitude.Shallow)){
                roll = Random.Range(1, 3);														biome = (Biome)roll;}
            else 																				{biome = Biome.Ocean;}
        }
        if (localAlt == Altitude.Shallow)
        {
            if (!NeighborContainsGeo(Geography.SaltWater)) { roll = Random.Range(6, 8); }
            else { roll = Random.Range(7, 8); }

            if (localGeo == Geography.SaltWater)
            {
                if (localTemp >= Temperature.Temperate)
                {
                    roll = Random.Range(2, 4); biome = (Biome)roll;
                }
                if (NeighborContainsAlt(Altitude.Medium)) { biome = Biome.Estuary; }
                else { biome = Biome.Shelf; }
            }
            if (localClimate <= Climate.Arid)
            {
                if (NeighborContainsAlt(Altitude.Low) || NeighborContainsAlt(Altitude.Medium))
                {
                    if (localTemp >= Temperature.Hot)
                    {
                        roll = Random.Range(13, 16); biome = (Biome)roll;
                    }
                    else if (localTemp <= Temperature.Cold)
                    {
                        roll = Random.Range(7, 10);
                        if (roll == 7)
                        {
                            biome = Biome.Arctic;
                        }
                        else
                        {
                            biome = (Biome)roll;
                        }
                    }
                }
            }

            biome = (Biome)roll;
        }

        if(localGeo == Geography.SaltWater){
            if(localTemp > Temperature.Cold || localTemp < Temperature.Scorching){
                if(localClimate > Climate.Temperate){
                    roll = Random.Range(0, 4);
                    if(roll == 0)																{biome = Biome.Reef;}
                }
            }
        }

        if(localTemp == Temperature.Arctic){
            if(localAlt == Altitude.Shallow){
                localGeo = baseGeo;
            }
            if (localAlt == Altitude.Deep)
            {
                if (Random.Range(0, 3) == 0)
                {
                    localGeo = baseGeo;
                }
            }

            if (localClimate > Climate.Temperate) { biome = Biome.Taiga; }
            else
            {
                roll = Random.Range(0, 3);
                if (roll == 0) { biome = Biome.Tundra; }
                else { biome = Biome.Arctic; }

                if (gridLocation.y == 2 && localClimate < Climate.Temperate) { biome = Biome.Desert; }
            }
        }

        if (localTemp == Temperature.Scorching)
        {
            if (localAlt == Altitude.Shallow)
            {
                localGeo = baseGeo;
            }
            if (localAlt == Altitude.Deep)
            {
                if (Random.Range(0, 3) == 0)
                {
                    localGeo = baseGeo;
                }
            }
            else
            {
                if(localClimate < Climate.Temperate)                                            { biome = (Biome)Random.Range(14, 16); }
                if(localClimate == Climate.Temperate)											{ biome = Biome.Savanna; }
                if(localClimate == Climate.Humid)												{ biome = Biome.Grassland; }
                if(localClimate == Climate.Wet)													{ biome = Biome.Rainforest; }
            }
        }

        if(biome == Biome.Desert && localGeo == Geography.Mountains){
            roll = Random.Range(2, 4);															localGeo = (Geography)roll; }

        localBiome = biome;
        localType = SetBiomeType(localBiome);

        //Corrects geo to match in salt water biomes.
        if (localType == BiomeType.SALTWATER)
        {
            if (localGeo != Geography.SaltWater && localGeo != Geography.Islands)
            {
                if (baseGeo == Geography.Mountains)
                {
                    localGeo = Geography.Islands;
                }
                else
                {
                    localGeo = Geography.SaltWater;
                }
            }
        }
        else if (localGeo == Geography.SaltWater || localGeo == Geography.Islands)
        {
            if (localType != BiomeType.SALTWATER)
            {
                localGeo = baseGeo;
            }
        }
    }
Exemple #43
0
    public void CorrectGeos()
    {
        if (localGeo != Geography.SaltWater)
        {
            baseGeo = localGeo;
        }
        else
        {
            if (localGeo == Geography.Islands)
            {
                baseGeo = Geography.Mountains;
            }

            else
            {
                baseGeo = (Geography)Random.Range(2, 5);
            }
        }
    }
Exemple #44
0
    //randomly generates geography based on altitude and neighboring altitudes
    public void GenerateGeo()
    {
        Geography geo = Geography.Hills;

        if(localAlt == Altitude.High){
            if(!NeighborContainsAlt(Altitude.High))												{geo = (Geography)Random.Range(3, (int)Geography.Mountains + 1);}
            else 																				{geo = (Geography)Random.Range(2, (int)Geography.Mountains + 1);}
        }
        if(localAlt == Altitude.Medium){
            if(NeighborContainsAlt(Altitude.High))												{geo = (Geography)Random.Range(3, (int)Geography.Mountains + 1);}
            else 																				{geo = (Geography)Random.Range(2, (int)Geography.Mountains + 1);}
        }
        if(localAlt <= Altitude.Low){
            if(NeighborContainsAlt(Altitude.High))												{geo++;}
            else																				{geo = (Geography)Random.Range(2, 3);}
        }

        if(localAlt == Altitude.Deep){
            if(!isBorder && !NeighborContainsAlt(Altitude.Deep))								{localAlt = Altitude.Shallow;}
            else 																				{geo = Geography.SaltWater;}
        }
        if(localAlt == Altitude.Shallow){
            if(!NeighborContainsAlt(Altitude.Deep))                                             { geo = (Geography)Random.Range(1, (int)Geography.Mountains + 1); }
            else if(NeighborContainsAlt(Altitude.Deep))											{ geo = (Geography)Random.Range(0, 2); }
            else                                                                                { geo = (Geography)Random.Range(1, (int)Geography.Mountains + 1); }

        }
        if(geo < 0){
            if(localAlt == Altitude.Deep)														{geo = Geography.SaltWater;}
            else				 																{GenerateGeo();}
        }
        if(geo > Geography.Mountains)															{geo = Geography.Mountains;}

        localGeo = geo;
    }
    private string GenerateAdministrators (Organization org, Geography geo)
    {
        RoleLookup officers = RoleLookup.FromGeographyAndOrganization(geo.Identity, org.Identity);

        return GenerateAdministrators(org, geo, officers);
    }
Exemple #46
0
 internal static string ToWellKnownText(Geography instance)
 {
     return Formatter.Write(instance);
 }
    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;

    }
    private string GenerateAdministrators (Organization org, Geography geo, RoleLookup officers)
    {
        List<Person> aggregate = new List<Person>();
        foreach (PersonRole role in officers[RoleType.LocalActive])
        {
            aggregate.Add(role.Person);
        }
        foreach (PersonRole role in officers[RoleType.LocalAdmin])
        {
            aggregate.Add(role.Person);
        }

        StringBuilder result = new StringBuilder("<b>Administrators at this level:</b><br/>");
        if (aggregate.Count > 0)
        {
            result.Append(GeneratePerson(aggregate[0]));

            for (int index = 1; index < aggregate.Count; index++)
            {
                result.Append(", ").Append(GeneratePerson(aggregate[index]));
            }
        }
        else
        {
            result.Append("none");
        }

        result.Append("<br/>");
        return result.ToString();
    }
 public static double? Distance(this Geography operand1, Geography operand2)
 {
     return OperationsFor(new Geography[] { operand1, operand2 }).IfValidReturningNullable<SpatialOperations, double>(ops => ops.Distance(operand1, operand2));
 }
    private string GenerateActivists (Organization org, Geography geo)
    {
        People activists = Roles.GetActivists(org, geo);

        StringBuilder result = new StringBuilder("<b>Activists at this level or below:</b><br/>");

        if (activists.Count > 0)
        {
            result.Append(GeneratePerson(activists[0]));

            for (int index = 1; index < activists.Count; index++)
            {
                result.Append(", ").Append(GeneratePerson(activists[index]));
            }
        }
        else
        {
            result.Append("none");
        }

        result.Append("<br/>");
        return result.ToString();
    }
    private void Populate ()
    {
        Geography wasSelectedGeo = this.SelectedGeography;

        Tree.Nodes.Clear();

        if (roots == null)
        {
            roots = Geographies.FromSingle(Geography.Root);
        }

        RadTreeNode topNode = new RadTreeNode("", "");


        foreach (Geography root in roots)
        {
            Geographies geos = root.GetTree();

            // We need a real f*****g tree structure.

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

            foreach (Geography geo in geos)
            {
                if (!lookup.ContainsKey(geo.ParentIdentity))
                {
                    lookup[geo.ParentIdentity] = new Geographies();
                }

                lookup[geo.ParentIdentity].Add(geo);
            }
            topNode.Nodes.Add(RecursiveAdd(lookup, geos[0].ParentIdentity)[0]);
        }

        //Re-added selection of first node to avoid crash in alert activists /JL 2010-12-21
        if (roots.Count > 1)
        {
            //need the dummy root
            Tree.Nodes.Add(topNode);
            topNode.Enabled = false;
            topNode.Expanded = true;
            topNode.Nodes[0].Selected = true;

        }
        else
        {
            Tree.Nodes.Add(topNode.Nodes[0]);
            Tree.Nodes[0].Selected = true;
        }

        if (wasSelectedGeo != null)
            SelectedGeography = wasSelectedGeo;

        Tree.Nodes[0].Expanded = true;

    }
Exemple #52
0
    int PrintGeography (XmlElement currentNode, Geography geo, int level)
    {

        XmlElement thisNode = currentNode.OwnerDocument.CreateElement("GEOGRAPHY");

        currentNode.AppendChild(thisNode);

        thisNode.SetAttribute("name", geo.Name);
        thisNode.SetAttribute("geographyid", geo.Identity.ToString());

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

        int totOfficers = GenerateOfficers(thisNode, officers);

        Geography supGeo = geo.Parent;
        if (supGeo != null && supGeo.GeographyId != Geography.SwedenId)
        {
            totOfficers += PrintGeography(currentNode, supGeo, level + 1);
        }
        return totOfficers;
    }
 protected void Tree_PreRender (object sender, EventArgs e)
 {
     if (Tree.Nodes.Count == 0)
     {
         this.root = Geography.Root;
         Populate(3);
     }
 }
 /// <summary>Determines the distance of the geography.</summary>
 /// <returns>The operation result.</returns>
 /// <param name="operand1">The first operand.</param>
 /// <param name="operand2">The second operand.</param>
 public static double? Distance(this Geography operand1, Geography operand2)
 {
     return OperationsFor(operand1, operand2).IfValidReturningNullable(ops => ops.Distance(operand1, operand2));
 }
Exemple #55
0
    private Color32 SetGeoColor(Geography val)
    {
        Color32 tempColor = new Color32(255, 255, 255, 255);

        if (val == Geography.SaltWater)                             { tempColor = new Color32(50, 100, 220, 255); }
        else if (val == Geography.Islands)                          { tempColor = new Color32(60, 200, 220, 255); }
        else if (val == Geography.Flat)                             { tempColor = new Color32(80, 255, 160, 255); }
        else if (val == Geography.Hills)                            { tempColor = new Color32(255, 255, 120, 255); }
        else if (val == Geography.Mountains)                        { tempColor = new Color32(255, 120, 120, 255); }

        return tempColor;
    }
 /// <summary>
 /// Geography Distance
 /// </summary>
 /// <param name="operand1">Operand 1</param>
 /// <param name="operand2">Operand 2</param>
 /// <returns>The operation result</returns>
 public virtual double Distance(Geography operand1, Geography operand2)
 {
     throw new NotImplementedException();
 }
 public override double Distance(Geography operand1, Geography operand2)
 {
     return this.distanceFunc(operand1, operand2);
 }
 /// <summary>
 /// Get the Well Known Text format that DbGeography supports. This is a little different from the Well Known Text that is output
 /// by Microsoft.Data.Spatial.Geography types, so we can't just directly use that representation here.
 /// </summary>
 /// <param name="geography">Geography instance to convert to Well Known Text.</param>
 /// <returns>Well Known Text for the specified geography instance.</returns>
 private static string GetWellKnownText(Geography geography)
 {
     string extendedWKT = geography.ToString();
     int semicolon = extendedWKT.IndexOf(';');
     Assert.IsTrue(semicolon > 0, "Expected to find a semicolon in the extended WellKnownText output (using ToString) for the type {0}", geography.GetType());
     return extendedWKT.Substring(semicolon + 1);
 }
 /// <summary>Determines if geography point and polygon will intersect.</summary>
 /// <returns>The operation result.</returns>
 /// <param name="operand1">The first operand.</param>
 /// <param name="operand2">The second operand.</param>
 public static bool? Intersects(this Geography operand1, Geography operand2)
 {
     return OperationsFor(operand1, operand2).IfValidReturningNullable(ops => ops.Intersects(operand1, operand2));
 }
        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            lblPopup.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            lblNumberOfQuestions.Text = selItem + " questions will be generated randomly";
            btnFinish.IsEnabled = true;
            btnStartAgain.IsEnabled = true;
            //lblTotalMarks.Visibility = Windows.UI.Xaml.Visibility.Visible;
            if (countTimer < 5 || countTimer < 15 || countTimer20 < 61 || countTimer30 < 75 || countTimer50 < 120)
            {
                lblTimeRunning.Text = "Dear learner, you are running out of time";
            }
            btnStartAgain.Visibility = Windows.UI.Xaml.Visibility.Visible;
            if (countTimer == 0)
            {
                messageBox("You have ran out of time ,your total mark = " + marks + "/" + 10);
                lblTimeElapsed.Text = "You have ran out of time ,your total mark = " + marks + "/" + 10;
                radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblQuestion.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnStartAgain.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            else if (countTimer20 == 0)
            {
                messageBox("You have ran out of time ,your total mark = " + marks + "/" + 20);
                lblTimeElapsed.Text = "You have ran out of time ,your total mark = " + marks + "/" + 20;
                radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblQuestion.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnFinish.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
            else if (countTimer30 == 0)
            {
                messageBox("You have ran out of time ,your total mark = " + marks + "/" + 30);
                lblTimeElapsed.Text = "You have ran out of time ,your total mark = " + marks + "/" + 30;
                radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblQuestion.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnFinish.Visibility = Windows.UI.Xaml.Visibility.Visible;
                btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            else if (countTimer50 == 0)
            {
                messageBox("You have ran out of time ,your total mark = " + marks + "/" + 50);
                lblTimeElapsed.Text = "You have ran out of time ,your total mark = " + marks + "/" + 50;
                radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblQuestion.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnFinish.Visibility = Windows.UI.Xaml.Visibility.Visible;
                btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
            }
            radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Visible;
            radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Visible;
            radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Visible;
            lblDisplayMark.Visibility = Windows.UI.Xaml.Visibility.Visible;
            lblTop.Visibility = Windows.UI.Xaml.Visibility.Visible;
            lblTop2.Visibility = Windows.UI.Xaml.Visibility.Visible;
            btnFinish.Visibility = Windows.UI.Xaml.Visibility.Visible;
            btnNext.Visibility = Windows.UI.Xaml.Visibility.Visible;

            module = new InsertModule();
            int number = 0;
            myList = new List<SubjectViewModel>();
            subjects = new ObservableCollection<SubjectViewModel>();
            subjectsList = new List<SubjectViewModel>();

            subjectModel = new SubjectsViewModel();

            string grade = item.Substring(0, item.IndexOf(":"));
            table = item.Substring(item.IndexOf(":") + 1);

            btnNext.Content = "Question " + countButton + ".";
            try
            {
                if (table.Equals("English"))
                {

                    subjects = subjectModel.getEnglishQuestions1(grade);
                    subjectsList = subjectModel.getEnglishQuestion(grade);
                    myList = subjectModel.getEnglishQuestion(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;

                    it = names[number];

                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));

                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + "." + it.Substring(0, it.IndexOf("#"));
                    correct_answer = subject.getEnglishCorrectAnswer(pass_question);

                    if (subject.verifyExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];

                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }
                }
                else if (table.Equals("Maths"))
                {
                    subjects = subjectModel.getMathsQuestions1(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;
                    it = names[number];
                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));
                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + "." + it.Substring(0, it.IndexOf("#"));
                    maths = subject.getMathsCorrectAnswer(pass_question);
                    if (subject.verifyMathsExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];
                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }

                }
                else if (table.Equals("Business"))
                {
                    subjects = subjectModel.getBusinessQuestions1(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;
                    it = names[number];
                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));
                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + "." + it.Substring(0, it.IndexOf("#"));
                    business = subject.getBusinessCorrectAnswer(pass_question);
                    if (subject.verifyBusinessExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];
                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }

                }
                else if (table.Equals("Accounting"))
                {
                    subjects = subjectModel.getAccountingQuestions1(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;
                    it = names[number];
                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));
                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + "." + it.Substring(0, it.IndexOf("#"));
                    accounting = subject.getAccountingCorrectAnswer(pass_question);
                    if (subject.verifyAccountingExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];
                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }

                }
                else if (table.Equals("Geography"))
                {
                    subjects = subjectModel.getGeographyQuestions1(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;
                    it = names[number];
                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));
                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + "." + it.Substring(0, it.IndexOf("#"));
                    geography = subject.getGeographyCorrectAnswer(pass_question);
                    if (subject.verifyGeographyExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];
                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }

                }
                else if (table.Equals("History"))
                {
                    subjects = subjectModel.getHistoryQuestions1(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;
                    it = names[number];
                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));
                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + "." + it.Substring(0, it.IndexOf("#"));
                    history = subject.getHistoryCorrectAnswer(pass_question);
                    if (subject.verifyHistoryExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];
                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }

                }
                else if (table.Equals("Life"))
                {
                    subjects = subjectModel.getLifeOrientationQuestions1(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;
                    it = names[number];
                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));
                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + "." + it.Substring(0, it.IndexOf("#"));
                    life = subject.getLifeCorrectAnswer(pass_question);
                    if (subject.verifyLifeOriontationExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];
                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }

                }
                else if (table.Equals("Physics"))
                {
                    subjects = subjectModel.getPhysicsQuestions1(grade);
                    int totalItems = subjects.Count();
                    int count = 0;
                    names = new string[subjects.Count()];
                    foreach (var i in subjects)
                    {
                        names[count] = i.QUESTION + "#" + i.ANSWER + "#" + i.ANSWER1 + "#" + i.ANSWER2;
                        count++;
                    }
                    combo.SelectedIndex.ToString();
                    string answer1 = string.Empty, answer2 = string.Empty, answer3 = string.Empty;
                    if (readQuestion.Equals(number)) { }
                    number = random.Next(0, totalItems);
                    readQuestion = number;
                    it = names[number];
                    names = it.Split('#');
                    answer1 = names[1];
                    answer2 = names[2];
                    answer3 = names[3];
                    pass_question = it.Substring(0, it.IndexOf("#"));
                    myQuestion = pass_question;
                    lblQuestion.Text = countButton + ".  " + it.Substring(0, it.IndexOf("#"));
                    physics = subject.getPhysicsCorrectAnswer(pass_question);
                    if (subject.verifyPhysicsExist(pass_question, answer1))
                    {
                        string[] answers_array = { answer1, answer2, answer3 };
                        Random ran = new Random();
                        int num = 0;
                        num = ran.Next(0, 2);
                        int num1 = ran.Next(0, 2);
                        int num2 = ran.Next(0, 2);
                        if (num == num1)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[0];
                        }
                        else if (num == num2)
                        {
                            radAnswer1.Content = answers_array[0];
                            radAnswer2.Content = answers_array[1];
                            radAnswer3.Content = answers_array[2];
                        }
                        else if (num1 == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else if (num == num1 && num == num2)
                        {
                            radAnswer1.Content = answers_array[2];
                            radAnswer2.Content = answers_array[0];
                            radAnswer3.Content = answers_array[1];
                        }
                        else
                        {
                            radAnswer1.Content = answers_array[num];
                            radAnswer2.Content = answers_array[num1];
                            radAnswer3.Content = answers_array[num2];
                        }
                    }

                }
            }
            catch
            {

            }

            radAnswer1.IsChecked = false;
            radAnswer2.IsChecked = false;
            radAnswer3.IsChecked = false;

            radAnswer1.IsEnabled = true;
            radAnswer2.IsEnabled = true;
            radAnswer3.IsEnabled = true;
            // time.Interval = new TimeSpan(0, 0, 0, 1);
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            if (combo.SelectedItem != null)
            {
                selItem = int.Parse(combo.SelectedItem.ToString());
                //messageBox("Selected is " + selItem);
                if (countButton > selItem)
                {
                    btnNext.Content = "Finish";
                    if (marks > 0)
                    {
                        if (selItem == 10)
                        {

                            marks = (marks / 10) * 100;
                        }
                        if (selItem == 20)
                        {
                            marks = (marks / 20) * 100;
                        }
                        if (selItem == 30)
                        {
                            marks = (marks / 30) * 100;
                        }
                        if (selItem == 50)
                        {
                            marks = (marks / 50) * 100;
                        }
                    }
                    time.Stop();
                    ////////////////////////////////////////////////////////////////////////////////////////

                    string message = "";
                    if (marks < 50)
                    {
                        // message = "Sorry You failed the test";
                        lblTotalMarks.Text = "Complete!!! :Total marks " + marks + "% ";
                        //lblTotalMarks.Text = message;
                    }
                    else if (marks >= 50 && marks < 75)
                    {
                        message = "You passed the test with an avarage score";
                        lblTotalMarks.Text = "Complete!!! :Total marks " + marks + "% ";
                    }
                    else if (marks >= 75)
                    {
                        message = "Passed with Distinction";
                        lblTotalMarks.Text = "Complete!!! :Total marks " + marks + "% ";

                    }
                    lblNumberOfQuestions.Visibility = Windows.UI.Xaml.Visibility.Collapsed;//lblTotalMarks.Text = message;
                    //messageBox("Complete!!! :Total marks " + marks + "% " + message);
                    //lblTotalMarks.Text = "Complete!!! :Total marks " + marks + "% " + message;
                    if (table.Equals("Accounting"))
                    {
                        subject.removeAllAccountingQuestions(); module.pupulateAccountingTable();
                    }
                    else if (table.Equals("Business"))
                    {
                        subject.removeAllBusinessQuestions(); module.pupulateBusinessTable();
                    }
                    else if (table.Equals("English"))
                    {
                        subject.removeAll(); module.populateEnglishTables();
                    }
                    else if (table.Equals("Geography"))
                    {
                        subject.removeAllGeographyQuestions(); module.pupulateGeographyTable();
                    }
                    else if (table.Equals("History"))
                    {
                        subject.removeAllHistoryQuestions(); module.pupulateHistoryTable();
                    }
                    else if (table.Equals("Life"))
                    {
                        subject.removeAllLifeQuestions(); module.pupulateLifeOrientationTable();
                    }
                    else if (table.Equals("Maths"))
                    {
                        subject.removeAllMathsQuestions(); module.pupulateMathsTable();
                    }
                    else if (table.Equals("Physics"))
                    {
                        subject.removeAllPhysicsQuestions(); module.pupulatePhysicsTable();
                    }
                    btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    lblQuestion.Text = "";
                    btnFinish.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                }

            }
            else
            {
                lblNumberOfQuestions.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                if (countButton > 10)
                {
                    time.Stop();
                    btnNext.Content = "Finish";
                    if (marks > 0)
                    {
                        if (selItem == 10)
                        {
                            marks = (marks / 10) * 100;

                        }
                    }
                    string message = "";
                    if (marks < 50)
                    {
                        message = "Sorry You failed the test";
                        lblTotalMarks.Text = "Complete!!! :Total marks " + marks + "% ";

                    }
                    else if (marks >= 50 && marks < 75)
                    {
                        message = "You passed the test with an avarage mark";
                        lblTotalMarks.Text = "Complete!!! :Total marks " + marks + "% ";
                    }
                    else if (marks >= 75)
                    {
                        message = "Passed with Distinction";
                        lblTotalMarks.Text = "Complete!!! :Total marks " + marks + "% ";
                    }
                    double store = marks = (marks / 10) * 100;
                    //messageBox("Complete!!! :Total marks " + store + "% ");
                    //lblTotalMarks.Text = "Complete!!! :Total marks " + store + "% "+message;
                    lblNumberOfQuestions.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    lblQuestion.Text = "";
                    btnFinish.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    if (table.Equals("Accounting"))
                    {
                        subject.removeAllAccountingQuestions(); module.pupulateAccountingTable();
                    }
                    else if (table.Equals("Business"))
                    {
                        subject.removeAllBusinessQuestions(); module.pupulateBusinessTable();
                    }
                    else if (table.Equals("English"))
                    {
                        subject.removeAll(); module.populateEnglishTables();
                    }
                    else if (table.Equals("Geography"))
                    {
                        subject.removeAllGeographyQuestions(); module.pupulateGeographyTable();
                    }
                    else if (table.Equals("History"))
                    {
                        subject.removeAllHistoryQuestions(); module.pupulateHistoryTable();
                    }
                    else if (table.Equals("Life"))
                    {
                        subject.removeAllLifeQuestions(); module.pupulateLifeOrientationTable();
                    }
                    else if (table.Equals("Maths"))
                    {
                        subject.removeAllMathsQuestions(); module.pupulateMathsTable();
                    }
                    else if (table.Equals("Physics"))
                    {
                        subject.removeAllPhysicsQuestions(); module.pupulatePhysicsTable();
                    }
                }
            }
            /*if (!(radAnswer1.IsChecked == true) || !(radAnswer2.IsChecked == true) || !(radAnswer3.IsChecked == true))
            {
                messageBox("You have to select at least one of the answers");
            }*/
            if (countTimer == 0 || countTimer20 == 0 || countTimer30 == 0 || countTimer50 == 0)
            {
                lblQuestion.Text = "";
                lblTop.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTop2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer1.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer2.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                radAnswer3.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                lblTimeRunning.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                btnNext.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                time.Stop();
            }
            countButton++;
            subject.remove(pass_question);
            subject.removeMaths(pass_question);
            subject.removeBusiness(pass_question);
            subject.removeAccounting(pass_question);
            subject.removeGeography(pass_question);
            subject.removeHistory(pass_question);
            subject.removeLifeOrientation(pass_question);
            subject.removePhysics(pass_question);
            lblWrong.Text = "";



        }