protected void Page_Load(object sender, EventArgs e)
    {
        // Get organization metadata.

        OrganizationMetadata metadata = OrganizationMetadata.FromUrl(Request.Url.Host);
        Organization         org      = Organization.FromIdentity(metadata.OrganizationId);

        // TODO: Get donation account from org, somehow

        FinancialAccount donationAccount = org.FinancialAccounts.IncomeDonations;

        // Find scope.
        DateTime month = DateTime.Today.AddMonths(-1);

        /*
         * if (month.Day < 5)
         * {
         *  month = month.AddMonths(-1);
         * }*/

        // Set the title.
        Chart.Title = "Donations for " + month.ToString("MMMM yyyy") + " - SEK ";

        // Change the shading mode
        Chart.ShadingEffectMode = ShadingEffectMode.Three;


        // Set the x axis label
        Chart.ChartArea.XAxis.Label.Text = "";

        Chart.XAxis.TimeScaleLabels.Mode = TimeScaleLabelMode.Smart;

        Chart.XAxis.TimeScaleLabels.DayFormatString   = "dd";
        Chart.XAxis.TimeScaleLabels.MonthFormatString = "dd";
        Chart.XAxis.TimeScaleLabels.YearFormatString  = "dd";
        Chart.XAxis.TimeInterval = TimeInterval.Day;

        // Set the y axis label
        //Chart.ChartArea.YAxis.Label.Text = "Ung Pirat SE - medlemsgraf";

        // Set the directory where the images will be stored.
        Chart.TempDirectory = "temp";

        // Set the chart size.
        Chart.Width  = 600;
        Chart.Height = 350;

        decimal donationsTotal;
        int     donationCount;

        Chart.SeriesCollection.Add(GetDonationData(metadata, out donationsTotal, out donationCount));
        Chart.Title += donationsTotal.ToString(CultureInfo.CreateSpecificCulture(org.DefaultCountry.Culture)) + " in " + donationCount.ToString() + " donations";

        Chart.LegendBox.Position = LegendBoxPosition.None;
        Chart.Debug  = false;
        Chart.Mentor = false;
    }
    SeriesCollection GetDonationData(OrganizationMetadata metadata, out decimal donationsTotal, out int donationCount)
    {
        SeriesCollection collection   = new SeriesCollection();
        DateTime         dateIterator = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        Organization     org          = Organization.FromIdentity(metadata.OrganizationId);

        if (DateTime.Now.Day > 4)
        {
            dateIterator = dateIterator.AddMonths(-1);
        }
        else
        {
            dateIterator = dateIterator.AddMonths(-1);  // -2
        }

        DateTime dateStop = dateIterator.AddMonths(1);

        FinancialAccountRows rows = org.FinancialAccounts.IncomeDonations.GetRows(dateIterator, dateIterator.AddMonths(1));

        Series series = new Series();

        series.Name = "";
        DateTime today    = DateTime.Now.Date;
        int      rowIndex = 0;

        donationsTotal = 0.0m;
        donationCount  = rows.Count;

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

        while (dateIterator < dateStop)
        {
            decimal donationsToday = 0.0m;

            DateTime nextDate = dateIterator.AddDays(1);
            while (rowIndex < rows.Count && rows[rowIndex].TransactionDateTime < nextDate)
            {
                donationsToday -= rows[rowIndex].Amount;
                donationsTotal -= rows[rowIndex].Amount;

                rowIndex++;
            }

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

        collection.Add(series);

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

        return(collection);
    }
	SeriesCollection GetDonationData (OrganizationMetadata metadata, out decimal donationsTotal, out int donationCount)
	{
		SeriesCollection collection = new SeriesCollection();
        DateTime dateIterator = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
	    Organization org = Organization.FromIdentity(metadata.OrganizationId);

        if (DateTime.Now.Day > 4)
        {
            dateIterator = dateIterator.AddMonths(-1);
        }
        else
        {
            dateIterator = dateIterator.AddMonths(-1);  // -2
        }

        DateTime dateStop = dateIterator.AddMonths(1);

        FinancialAccountRows rows = org.FinancialAccounts.IncomeDonations.GetRows(dateIterator, dateIterator.AddMonths(1));

		Series series = new Series();
		series.Name = "";
		DateTime today = DateTime.Now.Date;
		int rowIndex = 0;
        donationsTotal = 0.0m;
        donationCount = rows.Count;

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

		while (dateIterator < dateStop)
		{
            decimal donationsToday = 0.0m;

			DateTime nextDate = dateIterator.AddDays (1);
			while (rowIndex < rows.Count && rows[rowIndex].TransactionDateTime < nextDate)
			{
                donationsToday -= rows[rowIndex].Amount;
                donationsTotal -= rows[rowIndex].Amount;

				rowIndex++;
			}

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

		collection.Add(series);

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

		return collection;
	}
    SeriesCollection GetDonationData(OrganizationMetadata metadata)
    {
        string cacheDataKey = "Financials-DonationData-PiratpartietSE";

        FinancialAccountRows rows = (FinancialAccountRows)Cache.Get(cacheDataKey);
        Organization         org  = Organization.FromIdentity(metadata.OrganizationId);

        if (rows == null)
        {
            rows = org.FinancialAccounts.IncomeDonations.GetRows(new DateTime(2008, 1, 1), DateTime.Today);
            Cache.Insert(cacheDataKey, rows, null, DateTime.Today.AddHours(1).ToUniversalTime(), System.Web.Caching.Cache.NoSlidingExpiration);
        }

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

        DateTime today   = DateTime.Now.Date;
        DateTime endDate = today.AddDays(-today.Day);

        Series series = new Series();

        series.Name = "";
        int rowIndex = 0;

        while (dateIterator <= endDate)
        {
            DateTime nextDate           = dateIterator.AddMonths(1);
            decimal  donationsThisMonth = 0.0m;

            while (rowIndex < rows.Count && rows[rowIndex].TransactionDateTime < nextDate)
            {
                donationsThisMonth -= rows[rowIndex].Amount;              // Subtracting because the donation account is sign reversed; we want a positive graph

                rowIndex++;
            }

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

        collection.Add(series);

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

        return(collection);
    }
	SeriesCollection GetDonationData (OrganizationMetadata metadata)
	{
        string cacheDataKey = "Financials-DonationData-PiratpartietSE";

	    FinancialAccountRows rows = (FinancialAccountRows) Cache.Get(cacheDataKey);
	    Organization org = Organization.FromIdentity(metadata.OrganizationId);

        if (rows == null)
        {
            rows = org.FinancialAccounts.IncomeDonations.GetRows(new DateTime(2008, 1, 1), DateTime.Today);
            Cache.Insert(cacheDataKey, rows, null, DateTime.Today.AddHours(1).ToUniversalTime(), System.Web.Caching.Cache.NoSlidingExpiration);
        }

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

        DateTime today = DateTime.Now.Date;
        DateTime endDate = today.AddDays(-today.Day);

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

		while (dateIterator <= endDate)
		{
		    DateTime nextDate = dateIterator.AddMonths(1);
		    decimal donationsThisMonth = 0.0m;

			while (rowIndex < rows.Count && rows[rowIndex].TransactionDateTime < nextDate)
			{
			    donationsThisMonth -= rows[rowIndex].Amount;  // Subtracting because the donation account is sign reversed; we want a positive graph

				rowIndex++;
			}

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

		collection.Add(series);

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

		return collection;

	}
        private void SerializeMetadata(StreamWriter standardInput, HashSet <string> entities, HashSet <string> relationshipEntities)
        {
            EntityMetadata[] entityMetadatas = myPlugin.entityMetadatas;
            if (entities.Any())
            {
                entityMetadatas = entityMetadatas.Where(x => entities.Contains(x.LogicalName) || relationshipEntities.Contains(x.LogicalName)).ToArray();
            }
            var metadata   = new OrganizationMetadata(entityMetadatas, myPlugin.optionSetMetadatas);
            var serializer = new DataContractSerializer(typeof(OrganizationMetadata));

            using (XmlTextWriter writer = new XmlTextWriter(new StreamWriter(standardInput.BaseStream, standardInput.Encoding, 128, true)))
                serializer.WriteObject(writer, metadata);
            standardInput.WriteLine();
            standardInput.WriteLine(Constants.CONSOLE_ENDSTREAM);
        }
Beispiel #7
0
    protected void Page_Load(object sender, EventArgs e)
    {
        OrganizationMetadata metadata = OrganizationMetadata.FromUrl(Request.Url.Host);

        GeographyBallotCoverageLookup lookup = GetLookupFromCache();

        Response.ContentType = "text/plain";
        if (Request["typ"] == null || Request["typ"] == "F")
        {
            Response.Write(lookup[30].WAdvanceVotingCoverage.ToString("##.#", new CultureInfo(Organization.FromIdentity(metadata.OrganizationId).DefaultCountry.Culture)));
        }
        else
        {
            Response.Write(lookup[30].WVotingCoverage.ToString("##.#", new CultureInfo(Organization.FromIdentity(metadata.OrganizationId).DefaultCountry.Culture)));
        }
    }
Beispiel #8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get organization metadata.

        OrganizationMetadata metadata = OrganizationMetadata.FromUrl(Request.Url.Host);
        Organization         org      = Organization.FromIdentity(metadata.OrganizationId);

        // Set the title.
        Chart.Title = "Member birthyears and genders - " + org.NameShort;

        // Change the shading mode
        Chart.ShadingEffectMode = ShadingEffectMode.Three;

        // Set the x axis label
        Chart.ChartArea.XAxis.Label.Text = "";

        Chart.XAxis.TimeScaleLabels.Mode = TimeScaleLabelMode.Smart;

        // Set the y axis label
        Chart.YAxis.Scale = Scale.Stacked;
        // Chart.LegendBox.Template = "%Icon%Name";

        // Set the directory where the images will be stored.
        Chart.TempDirectory = "temp";

        // Set the chart size.
        Chart.Width  = 600;
        Chart.Height = 350;

        string cacheDataKey = cacheDataKeyBase + "-" + metadata.OrganizationId.ToString() + "-" + metadata.Recursive.ToString();

        SeriesCollection data = (SeriesCollection)Cache.Get(cacheDataKey);

        if (data == null)
        {
            data = (SeriesCollection)GetAgeGenderData(metadata);
            Cache.Insert(cacheDataKey, data, null, DateTime.Today.AddDays(1).ToUniversalTime(), System.Web.Caching.Cache.NoSlidingExpiration);
        }

        Chart.SeriesCollection.Add(data);

        Chart.LegendBox.Position = LegendBoxPosition.Top;
        Chart.Debug = false;
        //Chart.Mentor = false;

        // Chart.CacheDuration = 5;  // CANNOT cache charts that generate differently depending on URL! CANNOT!
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get organization metadata.

        OrganizationMetadata metadata = OrganizationMetadata.FromUrl(Request.Url.Host);
        Organization         org      = Organization.FromIdentity(metadata.OrganizationId);

        // Set the title.
        Chart.Title = "Donation history - " + org.NameShort;

        // Change the shading mode
        Chart.ShadingEffectMode = ShadingEffectMode.Three;

        // Set the x axis label
        Chart.ChartArea.XAxis.Label.Text = "";

        Chart.XAxis.TimeScaleLabels.Mode = TimeScaleLabelMode.Smart;

        Chart.XAxis.TimeInterval = TimeInterval.Month;

        // Set the y axis label
        //Chart.ChartArea.YAxis.Label.Text = "Ung Pirat SE - medlemsgraf";

        // Set the directory where the images will be stored.
        Chart.TempDirectory = "temp";

        // Set the chart size.
        Chart.Width  = 600;
        Chart.Height = 350;

        Chart.SeriesCollection.Add(GetDonationData(metadata));

        Chart.LegendBox.Position = LegendBoxPosition.None;
        Chart.Debug  = false;
        Chart.Mentor = false;
    }
    SeriesCollection GetGrowthData (OrganizationMetadata metadata, Geography geo)
    {
        string cacheDataKey = "ChartData-AllMembershipEvents";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                        // Was this person already a member?

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

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

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

                        int membershipCountForPerson = personMembershipCountLookup[personId];

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

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

                            personMembershipCountLookup[personId]--;
                        }
                    }

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

                    // assumes DeltaCount is always 1 or -1
                }

                eventIndex++;
            }

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

        collection.Add(series);

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

        return collection;

    }
Beispiel #11
0
    SeriesCollection GetAgeGenderData(OrganizationMetadata metadata)
    {
        int  orgId       = metadata.OrganizationId;
        bool recurseTree = metadata.Recursive;

        Series seriesMale   = new Series();
        Series seriesFemale = new Series();

        seriesMale.Name   = "Male";
        seriesFemale.Name = "Female";

        Memberships memberships = null;

        if (recurseTree)
        {
            memberships = Memberships.ForOrganizations(Organization.FromIdentity(orgId).GetTree());
        }
        else
        {
            memberships = Memberships.ForOrganization(Organization.FromIdentity(orgId));
        }

        BasicPerson[] allPeople = PirateDb.GetDatabase().GetAllPeople();

        Dictionary <int, int>          geoLookup       = new Dictionary <int, int>();
        Dictionary <int, PersonGender> genderLookup    = new Dictionary <int, PersonGender>();
        Dictionary <int, int>          birthYearLookup = new Dictionary <int, int>();
        Dictionary <int, bool>         personLookup    = new Dictionary <int, bool>();

        foreach (BasicPerson person in allPeople)
        {
            geoLookup[person.Identity]       = person.GeographyId;
            genderLookup[person.Identity]    = person.IsMale ? PersonGender.Male : PersonGender.Female;
            birthYearLookup[person.Identity] = person.Birthdate.Year;
        }

        int[] male   = new int[200];
        int[] female = new int[200];

        foreach (Membership membership in memberships)
        {
            int          birthYear = 0;
            PersonGender gender    = PersonGender.Unknown;

            if (personLookup.ContainsKey(membership.PersonId))
            {
                continue; // If a person was already counted, do not count again
            }

            if (genderLookup.ContainsKey(membership.PersonId) &&
                (membership.OrganizationId == orgId ||
                 (recurseTree && membership.Organization.Inherits(orgId))))
            {
                birthYear = birthYearLookup[membership.PersonId];
                gender    = genderLookup[membership.PersonId];

                int index = birthYear - 1900;

                if (index < 30 || index >= 100)
                {
                    index = 90; // Put invalid years on 1990, where it won't show up in the noise
                }

                if (gender == PersonGender.Male)
                {
                    male[index]++;
                }
                else
                {
                    female[index]++;
                }

                personLookup[membership.PersonId] = true;
            }
        }

        Element newElement = new Element();

        for (int yearIndex = 30; yearIndex < 100; yearIndex++)
        {
            newElement        = new Element();
            newElement.Name   = (1900 + yearIndex).ToString();
            newElement.YValue = male[yearIndex];
            seriesMale.Elements.Add(newElement);

            newElement        = new Element();
            newElement.Name   = (1900 + yearIndex).ToString();
            newElement.YValue = female[yearIndex];
            seriesFemale.Elements.Add(newElement);
        }

        seriesMale.DefaultElement.Color   = Color.Blue;
        seriesFemale.DefaultElement.Color = Color.Red;

        SeriesCollection collection = new SeriesCollection();

        collection.Add(seriesFemale);
        collection.Add(seriesMale);

        return(collection);
    }
	SeriesCollection GetAgeGenderData(OrganizationMetadata metadata)
	{
		int orgId = metadata.OrganizationId;
		bool recurseTree = metadata.Recursive;

		Series seriesMale = new Series();
		Series seriesFemale = new Series();
		seriesMale.Name = "Male";
		seriesFemale.Name = "Female";

		Memberships memberships = null;
		
		if (recurseTree)
		{
			memberships = Memberships.ForOrganizations(Organization.FromIdentity(orgId).GetTree());
		}
		else
		{
			memberships = Memberships.ForOrganization (Organization.FromIdentity (orgId));
		}

		BasicPerson[] allPeople = PirateDb.GetDatabase().GetAllPeople();

		Dictionary<int, int> geoLookup = new Dictionary<int, int>();
		Dictionary<int, PersonGender> genderLookup = new Dictionary<int, PersonGender>();
		Dictionary<int, int> birthYearLookup = new Dictionary<int, int>();
        Dictionary<int, bool> personLookup = new Dictionary<int, bool>();

		foreach (BasicPerson person in allPeople)
		{
			geoLookup[person.Identity] = person.GeographyId;
			genderLookup[person.Identity] = person.IsMale ? PersonGender.Male : PersonGender.Female;
			birthYearLookup[person.Identity] = person.Birthdate.Year;
		}

		int[] male = new int[200];
		int[] female = new int[200];

		foreach (Membership membership in memberships)
		{
			int birthYear = 0;
			PersonGender gender = PersonGender.Unknown;

            if (personLookup.ContainsKey(membership.PersonId))
            {
                continue; // If a person was already counted, do not count again
            }

			if (genderLookup.ContainsKey(membership.PersonId)
                && (membership.OrganizationId == orgId
                    || (recurseTree && membership.Organization.Inherits(orgId))))
			{
				birthYear = birthYearLookup[membership.PersonId];
				gender = genderLookup[membership.PersonId];

                int index = birthYear - 1900;

                if (index < 30 || index >= 100)
                {
                    index = 90; // Put invalid years on 1990, where it won't show up in the noise
                }

				if (gender == PersonGender.Male)
				{
					male[index]++;
				}
				else
				{
					female[index]++;
				}

                personLookup[membership.PersonId] = true;
			}
		}

		Element newElement = new Element();

		for (int yearIndex = 30; yearIndex < 100; yearIndex++)
		{
			newElement = new Element();
			newElement.Name = (1900 + yearIndex).ToString();
			newElement.YValue = male[yearIndex];
			seriesMale.Elements.Add(newElement);

			newElement = new Element();
			newElement.Name = (1900 + yearIndex).ToString();
			newElement.YValue = female[yearIndex];
			seriesFemale.Elements.Add(newElement);
		}

		seriesMale.DefaultElement.Color = Color.Blue;
		seriesFemale.DefaultElement.Color = Color.Red;

		SeriesCollection collection = new SeriesCollection();
		collection.Add(seriesFemale);
		collection.Add(seriesMale);

		return collection;
	}
    SeriesCollection GetResponseData(OrganizationMetadata metadata)
    {
        Organization organization = Organization.PPSE;

        CommunicationTurnarounds turnarounds = CommunicationTurnarounds.ForOrganization(organization, true);

        SeriesCollection collection = new SeriesCollection();

        DateTime today        = DateTime.Today;
        DateTime dateIterator = today.AddDays(-90);

        int currentIndex = 0;

        // Prepare averages

        DateTime now = DateTime.Now;

        Dictionary <DateTime, int>    caseCountOpen      = new Dictionary <DateTime, int>();
        Dictionary <DateTime, int>    caseCountResponded = new Dictionary <DateTime, int>();
        Dictionary <DateTime, double> caseTimeOpen       = new Dictionary <DateTime, double>();
        Dictionary <DateTime, double> caseTimeResponded  = new Dictionary <DateTime, double>();

        foreach (CommunicationTurnaround turnaround in turnarounds)
        {
            if (turnaround.Open)
            {
                if (!caseCountOpen.ContainsKey(turnaround.DateTimeOpened.Date))
                {
                    caseCountOpen[turnaround.DateTimeOpened.Date] = 0;
                    caseTimeOpen[turnaround.DateTimeOpened.Date]  = 0.0;
                }

                caseCountOpen[turnaround.DateTimeOpened.Date]++;
                caseTimeOpen[turnaround.DateTimeOpened.Date] += (now - turnaround.DateTimeOpened).TotalHours;
            }
            else if (turnaround.Responded)
            {
                if (!caseCountResponded.ContainsKey(turnaround.DateTimeOpened.Date))
                {
                    caseCountResponded[turnaround.DateTimeOpened.Date] = 0;
                    caseTimeResponded[turnaround.DateTimeOpened.Date]  = 0.0;
                }

                caseCountResponded[turnaround.DateTimeOpened.Date]++;
                caseTimeResponded[turnaround.DateTimeOpened.Date] += (turnaround.DateTimeFirstResponse - turnaround.DateTimeOpened).TotalHours;
            }
        }

        Series seriesOpen = new Series();

        seriesOpen.Name = "Still open";
        seriesOpen.DefaultElement.Color = Color.Orange;
        Series seriesResponded = new Series();

        seriesResponded.Name = "Responded";
        seriesResponded.DefaultElement.Color = Color.DarkGreen;

        int dateLabel = -90;

        while (dateIterator < today)
        {
            double avgTimeResponded = 0.0;
            double avgTimeOpen      = 0.0;

            if (caseCountOpen.ContainsKey(dateIterator))
            {
                avgTimeOpen = caseTimeOpen[dateIterator] / (double)caseCountOpen[dateIterator];
            }
            if (caseCountResponded.ContainsKey(dateIterator))
            {
                avgTimeResponded = caseTimeResponded[dateIterator] / (double)caseCountResponded[dateIterator];
            }

            Element elementOpen = new Element();
            elementOpen.XValue = dateLabel;
            elementOpen.YValue = avgTimeOpen - avgTimeResponded;
            seriesOpen.AddElements(elementOpen);

            Element elementResponded = new Element();
            elementResponded.XValue = dateLabel;
            elementResponded.YValue = avgTimeResponded;
            seriesResponded.AddElements(elementResponded);

            dateIterator = dateIterator.AddDays(1);
            dateLabel++;
        }

        collection.Add(seriesResponded);
        collection.Add(seriesOpen);

        return(collection);
    }
Beispiel #14
0
 public string Metadata
     (string key) => OrganizationMetadata.Search(key, TierSearchOrder);
Beispiel #15
0
    SeriesCollection GetGrowthData(OrganizationMetadata metadata, Geography geo)
    {
        string cacheDataKey = "ChartData-AllMembershipEvents";

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

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

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

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

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

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

        Dictionary <int, bool> geoDict = null;

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

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

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

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

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

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

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

        Series series = new Series();

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

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

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

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

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

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

                        // Was this person already a member?

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

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

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

                        int membershipCountForPerson = personMembershipCountLookup[personId];

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

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

                            personMembershipCountLookup[personId]--;
                        }
                    }

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

                    // assumes DeltaCount is always 1 or -1
                }

                eventIndex++;
            }

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

        collection.Add(series);

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

        return(collection);
    }
Beispiel #16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get organization metadata.

        OrganizationMetadata metadata = OrganizationMetadata.FromUrl(Request.Url.Host);
        Organization         org      = Organization.FromIdentity(metadata.OrganizationId);

        // Set the title.
        Chart.Title = "Member count history - " + org.NameShort;

        // Change the shading mode
        Chart.ShadingEffectMode = ShadingEffectMode.Three;

        // Set the x axis label
        Chart.ChartArea.XAxis.Label.Text = "";

        Chart.XAxis.TimeScaleLabels.Mode = TimeScaleLabelMode.Smart;

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

        if (dayCountString != null)
        {
            int dayCount = Int32.Parse(dayCountString);

            if (dayCount < 32)
            {
                Chart.XAxis.TimeScaleLabels.DayFormatString   = "dd";
                Chart.XAxis.TimeScaleLabels.MonthFormatString = "dd";
                Chart.XAxis.TimeInterval = TimeInterval.Day;
            }
            else if (dayCount < 180)
            {
                Chart.XAxis.TimeInterval = TimeInterval.Month;
            }
        }

        string    geoID       = Request.QueryString["Geo"];
        string    geoValidate = Request.QueryString["Validate"];
        Geography geo         = null;
        int       geoIntId    = -1;

        if (geoID != null || geoValidate != null)
        {
            //want to filter by geography.

            if (geoID == null || geoValidate == null)
            {
                //bad request
                Response.Write("Sorry, that request was not correctly formed");
                Response.End();
            }

            if (geoValidate != MD5.Hash(geoID + "Pirate").Replace(" ", ""))
            {
                //bad request
                Response.Write("Sorry, that request was not correctly formed.");
                Response.End();
            }

            if (!int.TryParse(geoID, out geoIntId))
            {
                //bad request
                Response.Write("Sorry, that request was not correctly formed..");
                Response.End();
            }


            geo = Geography.FromIdentity(geoIntId);

            Chart.Title += " - " + geo.Name;
        }


        // Set the y axis label
        //Chart.ChartArea.YAxis.Label.Text = "Ung Pirat SE - medlemsgraf";

        // Set the directory where the images will be stored.
        Chart.TempDirectory = "temp";

        // Set the chart size.
        Chart.Width  = 600;
        Chart.Height = 350;

        // If different sizes were given as parameters, adjust.

        string xSize  = Request.QueryString["XSize"];
        string ySize  = Request.QueryString["YSize"];
        string format = Request.QueryString["ImageFormat"];

        if (!String.IsNullOrEmpty(xSize))
        {
            Chart.Width = Int32.Parse(xSize);
        }

        if (!String.IsNullOrEmpty(ySize))
        {
            Chart.Height = Int32.Parse(ySize);
        }

        if (!String.IsNullOrEmpty(format))
        {
            Chart.ImageFormat = (ImageFormat)Enum.Parse(typeof(ImageFormat), format);
        }


        Chart.SeriesCollection.Add(GetGrowthData(metadata, geo));

        Chart.LegendBox.Position = LegendBoxPosition.None;
        Chart.Debug  = false;
        Chart.Mentor = false;
    }
    SeriesCollection GetResponseData (OrganizationMetadata metadata)
    {
        Organization organization = Organization.PPSE;

        CommunicationTurnarounds turnarounds = CommunicationTurnarounds.ForOrganization(organization, true);

        SeriesCollection collection = new SeriesCollection();

        DateTime today = DateTime.Today;
        DateTime dateIterator = today.AddDays(-90);

        int currentIndex = 0;

        // Prepare averages

        DateTime now = DateTime.Now;

        Dictionary<DateTime, int> caseCountOpen = new Dictionary<DateTime, int>();
        Dictionary<DateTime, int> caseCountResponded = new Dictionary<DateTime, int>();
        Dictionary<DateTime, double> caseTimeOpen = new Dictionary<DateTime, double>();
        Dictionary<DateTime, double> caseTimeResponded = new Dictionary<DateTime, double>();

        foreach (CommunicationTurnaround turnaround in turnarounds)
        {
            if (turnaround.Open)
            {
                if (!caseCountOpen.ContainsKey(turnaround.DateTimeOpened.Date))
                {
                    caseCountOpen[turnaround.DateTimeOpened.Date] = 0;
                    caseTimeOpen[turnaround.DateTimeOpened.Date] = 0.0;
                }

                caseCountOpen[turnaround.DateTimeOpened.Date]++;
                caseTimeOpen[turnaround.DateTimeOpened.Date] += (now - turnaround.DateTimeOpened).TotalHours;
            }
            else if (turnaround.Responded)
            {
                if (!caseCountResponded.ContainsKey(turnaround.DateTimeOpened.Date))
                {
                    caseCountResponded[turnaround.DateTimeOpened.Date] = 0;
                    caseTimeResponded[turnaround.DateTimeOpened.Date] = 0.0;
                }

                caseCountResponded[turnaround.DateTimeOpened.Date]++;
                caseTimeResponded[turnaround.DateTimeOpened.Date] += (turnaround.DateTimeFirstResponse-turnaround.DateTimeOpened).TotalHours;
            }
        }

        Series seriesOpen = new Series();
        seriesOpen.Name = "Still open";
        seriesOpen.DefaultElement.Color = Color.Orange;
        Series seriesResponded = new Series();
        seriesResponded.Name = "Responded";
        seriesResponded.DefaultElement.Color = Color.DarkGreen;

        int dateLabel = -90;

        while (dateIterator < today)
        {
            double avgTimeResponded = 0.0;
            double avgTimeOpen = 0.0;

            if (caseCountOpen.ContainsKey(dateIterator))
            {
                avgTimeOpen = caseTimeOpen[dateIterator]/(double) caseCountOpen[dateIterator];
            }
            if (caseCountResponded.ContainsKey(dateIterator))
            {
                avgTimeResponded = caseTimeResponded[dateIterator]/(double) caseCountResponded[dateIterator];
            }

            Element elementOpen = new Element();
            elementOpen.XValue = dateLabel;
            elementOpen.YValue = avgTimeOpen - avgTimeResponded;
            seriesOpen.AddElements(elementOpen);

            Element elementResponded = new Element();
            elementResponded.XValue = dateLabel;
            elementResponded.YValue = avgTimeResponded;
            seriesResponded.AddElements(elementResponded);

            dateIterator = dateIterator.AddDays(1);
            dateLabel++;
        }

        collection.Add(seriesResponded);
        collection.Add(seriesOpen);

        return collection;

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Get organization metadata.

        OrganizationMetadata metadata = OrganizationMetadata.FromUrl(Request.Url.Host);
        Organization         org      = Organization.FromIdentity(metadata.OrganizationId);

        // Set the title.
        Chart.Title = "Mail Response Times - " + org.NameShort;

        // Change the shading mode
        Chart.ShadingEffectMode = ShadingEffectMode.Three;


        // Set the x axis label
        Chart.ChartArea.XAxis.Label.Text = "Mail received date (days prior to today)";
        Chart.ChartArea.YAxis.Label.Text = "Average response time in hours";

        Chart.ChartArea.XAxis.Minimum = -90;
        Chart.ChartArea.XAxis.Maximum = 0;

        Chart.Type        = ChartType.Combo;
        Chart.YAxis.Scale = Scale.LogarithmicStacked;


        /*
         * Chart.XAxis.TimeScaleLabels.Mode = TimeScaleLabelMode.Smart;
         *
         * string dayCountString = Request.QueryString["Days"];
         *
         * if (dayCountString != null)
         * {
         *  int dayCount = Int32.Parse(dayCountString);
         *
         *  if (dayCount < 32)
         *  {
         *      Chart.XAxis.TimeScaleLabels.DayFormatString = "dd";
         *      Chart.XAxis.TimeScaleLabels.MonthFormatString = "dd";
         *      Chart.XAxis.TimeInterval = TimeInterval.Day;
         *  }
         *  else if (dayCount < 180)
         *  {
         *      Chart.XAxis.TimeInterval = TimeInterval.Month;
         *  }
         *
         * }*/

        // Set the y axis label
        //Chart.ChartArea.YAxis.Label.Text = "Ung Pirat SE - medlemsgraf";

        // Set the directory where the images will be stored.
        Chart.TempDirectory = "temp";

        // Set the chart size.
        Chart.Width  = 600;
        Chart.Height = 350;

        // If different sizes were given as parameters, adjust.

        string xSize  = Request.QueryString["XSize"];
        string ySize  = Request.QueryString["YSize"];
        string format = Request.QueryString["ImageFormat"];

        if (!String.IsNullOrEmpty(xSize))
        {
            Chart.Width = Int32.Parse(xSize);
        }

        if (!String.IsNullOrEmpty(ySize))
        {
            Chart.Height = Int32.Parse(ySize);
        }

        if (!String.IsNullOrEmpty(format))
        {
            Chart.ImageFormat = (ImageFormat)Enum.Parse(typeof(ImageFormat), format);
        }


        Chart.SeriesCollection.Add(GetResponseData(metadata));
        Chart.LegendBox.Template = "%Icon%Name";
        Chart.Debug  = false;
        Chart.Mentor = false;
    }
Beispiel #19
0
        public void OrganizationMetadataCanBeSerialized()
        {
            OrganizationMetadata organizationMetadata =
                new OrganizationMetadata(
                    new EntityMetadata[] {
                new EntityMetadata()
                {
                    LogicalName = "test"
                }
            },
                    new OptionSetMetadataBase[] {
                new OptionSetMetadata()
                {
                    Name = "test option"
                }
            },
                    new SdkMessages(new Dictionary <Guid, SdkMessage>()));

            var    manager = new RecyclableMemoryStreamManager();
            string noise;
            OrganizationMetadata organizationMetadataDeserialized;

            using (var stream = manager.GetStream())
            {
                var serializer = new DataContractSerializer(typeof(OrganizationMetadata));

                using (var writer = new StreamWriter(stream, Encoding.UTF8, 1024, true))
                    using (var xmlwriter = new XmlTextWriter(writer))
                    {
                        writer.WriteLine("Noise");
                        serializer.WriteObject(xmlwriter, organizationMetadata);
                        writer.WriteLine();
                        writer.WriteLine(Constants.CONSOLE_ENDSTREAM);
                        writer.WriteLine("other noise");
                    }

                using (var xmlStream = manager.GetStream())
                {
                    stream.Position = 0;
                    using (var reader = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
                    {
                        noise = reader.ReadLine();
                        using (var writer = new StreamWriter(xmlStream, Encoding.UTF8, 1024, true))
                        {
                            string line = reader.ReadLine();
                            while (line != Constants.CONSOLE_ENDSTREAM && line != null)
                            {
                                writer.WriteLine(line);
                                line = reader.ReadLine();
                            }
                        }
                        xmlStream.Position = 0;

                        using (var xmlreader = new XmlTextReader(xmlStream))
                        {
                            organizationMetadataDeserialized = (OrganizationMetadata)serializer.ReadObject(xmlreader, false);
                        }
                    }
                }
            }

            Assert.Equal("Noise", noise);
            Assert.NotNull(organizationMetadataDeserialized);
        }