private XmlDocument getXmlDoc(string url)
        {
            string xml = "";

            string datestamp = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
            string cached    = BlobJsonResourceManager.Instance.GetJsonResource("skillcowtenjobresults", datestamp, "tenjobs");

            if (cached != null && cached.Trim() != "")
            {
                xml = cached;
            }
            else
            {
                xml = GetHttpResponse(url, null);
                BlobJsonResourceManager.Instance.SaveJsonResource(xml, "tenjobs", "skillcowtenjobresults", datestamp);
            }

            xml = xml.Replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");

            XmlDocument xmldoc = new XmlDocument();

            byte[] byteArray = new byte[xml.Length];
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byteArray = encoding.GetBytes(xml);

            // Load the memory stream
            MemoryStream memoryStream = new MemoryStream(byteArray);

            memoryStream.Seek(0, SeekOrigin.Begin);
            xmldoc.Load(memoryStream);
            return(xmldoc);
        }
        public ActionResult Index(FormCollection collection)
        {
            string email = collection["email"];

            if (email != null)
            {
                AddresseeClient adc          = new AddresseeClient();
                string          partitionkey = AddresseeClient.GetPartitionKeyForEmail(email);

                //Addressee ad = adc.GetByRowKey(email.ToLower());
                Addressee ad = adc.GetByPartitionAndRowKey(partitionkey, email.ToLower());
                if (ad != null)
                {
                    ad.Unsubscribed        = true;
                    ad.UnsubscribedUTCDate = EasternTimeConverter.Convert(DateTime.UtcNow);
                    adc.Update(ad);
                }

                UserProfileClient upc = new UserProfileClient();
                UserProfile       p   = upc.GetByPartitionAndRowKey(partitionkey, email.ToLower());
                if (p != null)
                {
                    p.Unsubscribed = true;
                    upc.Update(p);
                }
            }
            else
            {
                email = "";
            }


            return(RedirectToAction("Unsubscribed", new { email = email }));
        }
示例#3
0
        public ABTestConversion()
        {
            PartitionKey = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");

            // Row key allows sorting, so we make sure the rows come back in time order.
            RowKey = string.Format("{0:10}_{1}", DateTime.MaxValue.Ticks - DateTime.Now.Ticks, Guid.NewGuid());
        }
示例#4
0
        public SiteVisit()
        {
            DateTime t = EasternTimeConverter.Convert(DateTime.UtcNow);

            PartitionKey = t.ToString("yyyyMMdd");
            RowKey       = ShortGuidGenerator.NewGuid();
        }
        public ActionResult _logons()
        {
            ViewBag.StartDate = EasternTimeConverter.Convert(DateTime.UtcNow);
            ViewBag.EndDate   = EasternTimeConverter.Convert(DateTime.UtcNow);

            return(View());
        }
示例#6
0
        public ActionResult GetFormJson(string clientid, string formid)
        {
            try
            {
                Response.ContentType = "application/json";

                string datestamp = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
                string cached    = BlobJsonResourceManager.Instance.GetJsonResource("skillcowschoolforms", datestamp, "form" + formid);
                if (cached != null && cached.Trim() != "")
                {
                    Response.Write(cached);
                    Response.End();
                    return(null);
                }

                SchoolFormParser parser = new SchoolFormParser();
                //SchoolFormParserV2 parser = new SchoolFormParserV2();
                string json = parser.ConvertFormsXmlToJson(clientid, formid);
                //json = json.Replace("reflection.code", json.ToJSONSafeString());

                BlobJsonResourceManager.Instance.SaveJsonResource(json, "form" + formid, "skillcowschoolforms", datestamp);

                Response.Write(json);
                Response.End();
            }
            catch (Exception ex)
            {
                Response.ContentType = "application/json";
                Response.Write(DefaultErrorResponse(ex.Message));
                Response.End();
            }

            return(null);
        }
        public ActionResult GetCourseDetails(string id, string url)
        {
            try
            {
                Response.ContentType = "application/json";

                string datestamp = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
                //string cached = BlobJsonResourceManager.Instance.GetJsonResource("skillcowschoolforms", datestamp, id);
                //if (cached != null && cached.Trim() != "")
                //{
                //    Response.Write(cached);
                //    Response.End();
                //    return null;
                //}

                UdemyCourseParser parser = new UdemyCourseParser();
                string            json   = parser.ParsePage(url);
                BlobJsonResourceManager.Instance.SaveJsonResource(json, id, "skillcowudemycourses", datestamp);

                Response.Write(json);
                Response.End();
            }
            catch (Exception ex)
            {
                Response.ContentType = "application/json";
                Response.Write(DefaultErrorResponse(ex.Message));
                Response.End();
            }

            return(null);
        }
示例#8
0
 public SendGridEvent()
 {
     Timestamp    = EasternTimeConverter.Convert(DateTime.UtcNow);
     CreatedOn    = EasternTimeConverter.Convert(DateTime.UtcNow);
     LastUpdated  = EasternTimeConverter.Convert(DateTime.UtcNow);
     Spam         = false;
     Unsubscribed = false;
 }
示例#9
0
 public Addressee(string email)
 {
     PartitionKey        = AddresseeClient.GetPartitionKeyForEmail(email);
     RowKey              = email;
     Timestamp           = EasternTimeConverter.Convert(DateTime.UtcNow);
     Unsubscribed        = false;
     UnsubscribedUTCDate = DateTime.MaxValue;
 }
示例#10
0
        public UXEvent()
        {
            DateTime t = EasternTimeConverter.Convert(DateTime.UtcNow);

            PartitionKey = t.ToString("yyyyMMdd");
            RowKey       = ShortGuidGenerator.NewGuid();
            Timestamp    = t;
        }
示例#11
0
        public SkillCowRequestSubmission()
        {
            DateTime t = EasternTimeConverter.Convert(DateTime.UtcNow);

            PartitionKey = t.ToString("yyyyMMdd");
            RowKey       = ShortGuidGenerator.NewGuid();
            Timestamp    = t;
        }
        public ActionResult Index()
        {
            UXEventClient uxc = new UXEventClient();

            ViewBag.StartDate = EasternTimeConverter.Convert(DateTime.UtcNow);
            ViewBag.EndDate   = EasternTimeConverter.Convert(DateTime.UtcNow);

            return(View(uxc));
        }
        public ActionResult ExportProfiles1()
        {
            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            ViewBag.StartDate = EasternTimeConverter.Convert(DateTime.UtcNow);
            ViewBag.EndDate   = EasternTimeConverter.Convert(DateTime.UtcNow);


            return(View(rsc));
        }
示例#14
0
        public AgentEvent(string agent, string eventtype, string location)
        {
            DateTime t = EasternTimeConverter.Convert(DateTime.UtcNow);

            PartitionKey = t.ToString("yyyyMM");
            RowKey       = ShortGuidGenerator.NewGuid();
            EventTime    = t;
            Agent        = agent;
            EventType    = eventtype;
            Location     = location;
        }
 public PendingSchool()
 {
     PartitionKey = "pendingschool";
     Timestamp    = DateTime.UtcNow;
     RowKey       = ShortGuidGenerator.NewGuid();
     SubmitedOn   = EasternTimeConverter.Convert(DateTime.UtcNow);
     Pending      = true;
     Approved     = false;
     Duplicate    = false;
     Incorrect    = false;
 }
        private string getForm(string clientid, string formid)
        {
            string datestamp = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
            string cached    = BlobJsonResourceManager.Instance.GetJsonResource("skillcowjobforms", datestamp, "form" + formid);

            if (cached != null && cached.Trim() != "")
            {
                return(cached);
            }

            SchoolFormParser parser = new SchoolFormParser();
            string           json   = parser.ConvertFormsXmlToJson(clientid, formid);

            BlobJsonResourceManager.Instance.SaveJsonResource(json, "form" + formid, "skillcowjobforms", datestamp);

            return(json);
        }
示例#17
0
        public HttpResponse logoff(string location, string agent, string code)
        {
            try
            {
                Response.ContentType = "application/json";

                AgentClient ac = new AgentClient();
                Agent       a  = ac.GetAll().Execute().Where(x => x.LoginName == agent).SingleOrDefault();

                if (a == null)
                {
                    throw new Exception("Invalid agent ID or code");
                }

                if (a.LoginCode == code)
                {
                    DateTime nowTime = EasternTimeConverter.Convert(DateTime.UtcNow);


                    AgentEventClient aec       = new AgentEventClient();
                    AgentEvent       lastEvent = aec.GetAll().Execute().Where(x => x.Agent == agent).OrderByDescending(x => x.EventTime).FirstOrDefault();

                    string hoursworked = "No prior logon.";
                    string production  = "No results.";
                    if (lastEvent.EventType == "logon")
                    {
                        long     elapsedTicks = nowTime.Ticks - lastEvent.EventTime.Ticks;
                        TimeSpan ts           = new TimeSpan(elapsedTicks);
                        hoursworked = ts.Hours.ToString() + "h : " + ts.Minutes + "m logged.";

                        //Count how many leads
                        List <SkillCowRequestSubmission> allrecords = new List <SkillCowRequestSubmission>();

                        DateTime cursordate = lastEvent.EventTime;

                        SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();
                        while (cursordate <= nowTime)
                        {
                            CloudTableQuery <SkillCowRequestSubmission> query = rsc.GetAll(cursordate.ToString("yyyyMMdd"));
                            allrecords.AddRange(query.Execute().Where(x => x.UtmCampaign == location && x.UtmContent == agent).OrderBy(x => x.Timestamp));
                            cursordate = cursordate.AddDays(1);
                        }

                        //tally up
                        int totalschoolleads = 0;
                        int totalindeedjobs  = 0;
                        int totalcourses     = 0;
                        foreach (SkillCowRequestSubmission x in allrecords)
                        {
                            switch (x.SourceForm)
                            {
                            case "schoolform":
                                totalschoolleads++;
                                break;

                            case "indeedjob":
                                totalindeedjobs++;
                                break;

                            case "udemycourse":
                                totalcourses++;
                                break;
                            }
                        }
                        if (totalschoolleads + totalindeedjobs + totalcourses > 0)
                        {
                            production  = "\n";
                            production += totalschoolleads + " school leads\n";
                            production += totalindeedjobs + " indeed jobs\n";
                            production += totalcourses + " udemy courses";
                        }
                    }

                    //Log event
                    aec.AddNewItem(new AgentEvent(agent, "logoff", location));

                    a.CurrentLocation = "";
                    a.CurrentStatus   = "loggedoff";
                    ac.Update(a);

#if DEBUG
#else
                    Telephony t = new Telephony();

                    string message = agent + " logged OFF at " + location + "\n" + hoursworked + "\n" + production;
                    //Send to Rick
                    //t.SendSMS("+19174340659", message);

                    t.SendSMS("+19179578770", message);
#endif

                    Response.Write("{\"result\": \"ok\", \"logonname\": \"" + a.LoginName + "\"}");
                    Response.End();
                }
                else
                {
                    throw new Exception("Invalid agent ID or code");
                }
            }
            catch (Exception ex)
            {
                Response.ContentType = "application/json";
                Response.Write(DefaultErrorResponse(ex.Message));
                Response.End();
            }

            return(null);
        }
示例#18
0
 public AdminMisc()
 {
     PartitionKey    = "adminmisc";
     Timestamp       = DateTime.UtcNow;
     LastTimeUpdated = EasternTimeConverter.Convert(DateTime.UtcNow);
 }
示例#19
0
 public UserProfile(string email)
 {
     PartitionKey     = AddresseeClient.GetPartitionKeyForEmail(email);
     RegistrationDate = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
     RowKey           = email;
 }
示例#20
0
 public UserAccount()
 {
     Timestamp      = DateTime.UtcNow;
     EmailConfirmed = false;
     CreatedOn      = EasternTimeConverter.Convert(DateTime.UtcNow);
 }
 public LockedModeUser()
 {
     Timestamp = EasternTimeConverter.Convert(DateTime.UtcNow);
     CreatedOn = EasternTimeConverter.Convert(DateTime.UtcNow);
 }
        public static List <AgentDailyActivity> Create(List <Agent> agentprofiles, DateTime startdate, DateTime enddate, string agent)
        {
            AgentEventClient  aec        = new AgentEventClient();
            List <AgentEvent> allrecords = new List <AgentEvent>();

            DateTime cursordate = startdate;

            if (agent != null && agent != "")
            {
                while (cursordate <= enddate)
                {
                    allrecords.AddRange(aec.GetAllByPartition(cursordate.ToString("yyyyMM")).Where(x => x.EventTime.ToString("yyyyMMdd") == cursordate.ToString("yyyyMMdd") && x.Agent == agent).OrderBy(x => x.Timestamp));
                    cursordate = cursordate.AddDays(1);
                }
            }
            else
            {
                while (cursordate <= enddate)
                {
                    allrecords.AddRange(aec.GetAllByPartition(cursordate.ToString("yyyyMM")).Where(x => x.EventTime.ToString("yyyyMMdd") == cursordate.ToString("yyyyMMdd")).OrderBy(x => x.Timestamp));
                    cursordate = cursordate.AddDays(1);
                }
            }

            List <AgentDailyActivity> retlist = new List <AgentDailyActivity>();

            List <AgentLocationDate> alds = GetAgentDateList(allrecords);

            DateTime currenttime = EasternTimeConverter.Convert(DateTime.UtcNow);

            foreach (AgentLocationDate ald in alds)
            {
                try
                {
                    if (ald.Agent == "victorr")
                    {
                        Console.Write("");
                    }
                    AgentEvent logonevent  = GetLogonEvent(allrecords, ald);
                    AgentEvent logoffevent = GetLogoffEvent(allrecords, ald);

                    double hoursworked = 0;

                    Agent a = agentprofiles.SingleOrDefault(x => x.LoginName == ald.Agent.Replace("cindy", "sydneyc"));
                    bool  currentlyloggedon = false;
                    if (a.CurrentStatus == "loggedon" && logonevent != null && logonevent.EventTime.ToString("yyyyMMdd") == currenttime.ToString("yyyyMMdd"))
                    {
                        currentlyloggedon = true;
                    }


                    if (logonevent != null && logoffevent != null)
                    {
                        if (currentlyloggedon)
                        {
                            //relogged on
                            hoursworked = (double)(currenttime.Ticks - logonevent.EventTime.Ticks) / TimeSpan.TicksPerHour;
                        }
                        else
                        {
                            hoursworked = (double)(logoffevent.EventTime.Ticks - logonevent.EventTime.Ticks) / TimeSpan.TicksPerHour;
                        }
                    }
                    else if (logonevent != null && logoffevent == null && logonevent.EventTime.ToString("yyyyMMdd") == currenttime.ToString("yyyyMMdd"))
                    {
                        hoursworked = (double)(currenttime.Ticks - logonevent.EventTime.Ticks) / TimeSpan.TicksPerHour;
                    }


                    retlist.Add(new AgentDailyActivity
                    {
                        FormattedDate = ald.Date,
                        Agent         = ald.Agent,
                        Location      = ald.Location,

                        LogonTime = logonevent != null ? logonevent.EventTime.ToString("HH:mm") : "",
                        LogonHour = logonevent != null ? int.Parse(logonevent.EventTime.ToString("HH")) : -1,


                        LogoffTime = logoffevent != null && !currentlyloggedon ? logoffevent.EventTime.ToString("HH:mm") : "",
                        LogoffHour = logoffevent != null && !currentlyloggedon ? int.Parse(logoffevent.EventTime.ToString("HH")) : -1,

                        Hours = hoursworked
                    });
                }
                catch (Exception ex)
                {
                    Console.Write(ex.Message);
                }
            }

            return(retlist);
        }
示例#23
0
        //
        // GET: /SchoolNewsletter/

        public SchoolNewsletter()
        {
            Timestamp = EasternTimeConverter.Convert(DateTime.UtcNow);
        }
示例#24
0
 public UserProfile()
 {
     PartitionKey     = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
     RegistrationDate = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
     RowKey           = ShortGuidGenerator.NewGuid();
 }
        public ActionResult GetAgentPerformance(string startdate, string enddate)
        {
            //try
            //{
            Response.ContentType = "application/json";



            string datestamp = EasternTimeConverter.Convert(DateTime.UtcNow).ToString("yyyyMMdd");
            string cached    = BlobJsonResourceManager.Instance.GetJsonResource("skillcowagentdashboard", datestamp, "range" + startdate + enddate);

            if (cached != null && cached.Trim() != "")
            {
                Response.Write(cached);
                Response.End();
                return(null);
            }


            SkillCowRequestSubmissionClient rsc = new SkillCowRequestSubmissionClient();

            DateTime dstartdate = DateTime.ParseExact(startdate, "yyyyMMdd", CultureInfo.InvariantCulture);
            DateTime denddate   = DateTime.ParseExact(enddate, "yyyyMMdd", CultureInfo.InvariantCulture);


            AgentClient  ac             = new AgentClient();
            List <Agent> agentsprofiles = new List <Agent>(ac.GetAll().Execute());

            //Get agent hours
            List <AgentDailyActivity> tempactivity = AgentDailyActivity.Create(agentsprofiles, dstartdate, denddate, null);
            Dictionary <string, IGrouping <string, AgentDailyActivity> > agenthours = new Dictionary <string, IGrouping <string, AgentDailyActivity> >();

            foreach (IGrouping <string, AgentDailyActivity> ag in tempactivity.GroupBy(x => x.Agent))
            {
                agenthours.Add(ag.Key, ag);
            }

            List <SkillCowRequestSubmission> allrecords = rsc.GetKioskLeads(dstartdate, denddate);


            List <object> agents = new List <object>();

            foreach (KeyValuePair <string, IGrouping <string, AgentDailyActivity> > kv in agenthours)
            {
                Agent agentprofile = agentsprofiles.SingleOrDefault(x => x.LoginName == kv.Key.Replace("cindy", "sydneyc"));

                List <object> dates = new List <object>();

                double totalhours = 0;

                Dictionary <string, List <double> > aggregate = new Dictionary <string, List <double> >();

                aggregate.Add("hours", new List <double>());
                aggregate.Add("billablehours", new List <double>());
                aggregate.Add("hourlyearnings", new List <double>());
                aggregate.Add("validschoolleadsnetwork", new List <double>());
                aggregate.Add("companyvalidschoolleadsnetwork", new List <double>());
                aggregate.Add("invalidschoolleadsnetwork", new List <double>());
                aggregate.Add("companyinvalidschoolleadsnetwork", new List <double>());
                aggregate.Add("commissionsschoolleadsnetwork", new List <double>());
                aggregate.Add("AvgRetentionSchoolLeads", new List <double>());
                aggregate.Add("CompanyAvgRetentionSchoolLeads", new List <double>());
                aggregate.Add("AvgLPH", new List <double>());
                aggregate.Add("Stochastic", new List <double>());
                aggregate.Add("CompanyAverageLPHMean", new List <double>());

                List <object> ProductionChartData = new List <object>();

                ProductionChartData.Add(new string[] { "Date", "Best", "Worst", "Average", kv.Key });

                DateTime cursordate = dstartdate;
                while (cursordate <= denddate)
                {
                    IEnumerable <SkillCowRequestSubmission> companyvalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                              x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                              x.GradYear != "GET THIS" &&
                                                                                                              x.GradYear != "undefined" &&
                                                                                                              (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5)) &&
                                                                                                              x.SourceForm == "schoolform");

                    IEnumerable <SkillCowRequestSubmission> companyinvalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                                x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                                !(x.GradYear != "GET THIS" && x.GradYear != "undefined" && (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5))) &&
                                                                                                                x.SourceForm == "schoolform");

                    IEnumerable <SkillCowRequestSubmission> validnetworkschoolleads = allrecords.Where(x =>
                                                                                                       x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                       x.GradYear != "GET THIS" &&
                                                                                                       x.GradYear != "undefined" &&
                                                                                                       (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5)) &&
                                                                                                       x.SourceForm == "schoolform" &&
                                                                                                       x.UtmContent == kv.Key);

                    IEnumerable <SkillCowRequestSubmission> invalidnetworkschoolleads = allrecords.Where(x =>
                                                                                                         x.PartitionKey == cursordate.ToString("yyyyMMdd") &&
                                                                                                         !(x.GradYear != "GET THIS" && x.GradYear != "undefined" && (int.Parse(x.GradYear) < DateTime.UtcNow.Year || (int.Parse(x.GradYear) == DateTime.UtcNow.Year && DateTime.UtcNow.Month > 5))) &&
                                                                                                         x.SourceForm == "schoolform" &&
                                                                                                         x.UtmContent == kv.Key);

                    AgentDailyActivity locationday = null;
                    if (agenthours.ContainsKey(kv.Key))
                    {
                        locationday = agenthours[kv.Key].SingleOrDefault(x => x.FormattedDate == cursordate.ToString("yyyyMMdd"));
                    }

                    int validnetworkschoolleadcount = validnetworkschoolleads.Count();

#warning TO DO: Replace with hourly pay rate from admin
                    double hoursworked = (locationday != null ? locationday.Hours : 0);

                    double lunch = 0;
                    if (hoursworked > 7)
                    {
                        lunch = 1;
                    }
                    else if (hoursworked > 4)
                    {
                        lunch = 0.5;
                    }

                    double billablehours = hoursworked - lunch;

                    double hourlyrate     = agentprofile.PayPerHour;
                    double hourlyearnings = billablehours * hourlyrate;
                    double CommissionRatePerSchoolLeadNetwork = agentprofile.PayPerLead; //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerSchoolLeadDirect  = agentprofile.PayPerLead; //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerJobLeadNetwork    = 0.25;                    //TO DO: Replace with hourly pay rate from admin
                    double CommissionRatePerJobLeadDirect     = 0.25;                    //TO DO: Replace with hourly pay rate from admin
                    double CommissionsSchoolLeadsNetwork      = validnetworkschoolleadcount * CommissionRatePerSchoolLeadNetwork;

                    int    uniquestudents          = validnetworkschoolleads.GroupBy(x => x.Email).Count();
                    double AvgRetentionSchoolLeads = uniquestudents > 0 ? (double)validnetworkschoolleadcount / uniquestudents : 0;

                    int    companyuniquestudents          = companyvalidnetworkschoolleads.GroupBy(x => x.Email).Count();
                    double CompanyAvgRetentionSchoolLeads = companyuniquestudents > 0 ? (double)companyvalidnetworkschoolleads.Count() / companyvalidnetworkschoolleads.GroupBy(x => x.Email).Count() : 0;



                    double AvgLPH = locationday != null && locationday.Hours > 0 ? CalculateLPH(validnetworkschoolleadcount, locationday.Hours) : 0;
                    double CompanyAverageLPHMean = GetAvgLPHMean(cursordate, companyvalidnetworkschoolleads, agenthours);
                    double CompanyAverageLPHMax  = GetAvgLPHMax(cursordate, companyvalidnetworkschoolleads, agenthours);
                    double CompanyAverageLPHMin  = GetAvgLPHMin(cursordate, companyvalidnetworkschoolleads, agenthours);

                    double Stochastic = 0;
                    if (CompanyAverageLPHMax - CompanyAverageLPHMin > 0 && AvgLPH > 0)
                    {
                        Stochastic = (AvgLPH - CompanyAverageLPHMin) / (CompanyAverageLPHMax - CompanyAverageLPHMin);
                    }



                    dates.Add(new
                    {
                        Agent = kv.Key,
                        Date  = cursordate.ToString("MMM-d"),

                        ValidSchoolLeadsNetwork        = validnetworkschoolleadcount,
                        CompanyValidSchoolLeadsNetwork = companyvalidnetworkschoolleads.Count(),
                        //ValidSchoolLeadsDirect = GetValidSchoolLeads(allrecords),
                        //ValidJobLeadsNetwork = GetValidSchoolLeads(allrecords),
                        //ValidJobLeadsDirect = GetValidSchoolLeads(allrecords),
                        InvalidSchoolLeadsNetwork        = invalidnetworkschoolleads.Count(),
                        CompanyInvalidSchoolLeadsNetwork = companyinvalidnetworkschoolleads.Count(),
                        //InvalidSchoolLeadsDirect = GetValidSchoolLeads(allrecords),
                        //InvalidJobLeadsNetwork = GetValidSchoolLeads(allrecords),
                        //InvalidJobLeadsDirect = GetValidSchoolLeads(allrecords),
                        //IndeedJobs = GetValidSchoolLeads(allrecords),
                        //UdemyCourses = GetValidSchoolLeads(allrecords),
                        UniqueStudents                 = validnetworkschoolleads.GroupBy(x => x.Email).Count(),
                        AvgRetentionSchoolLeads        = AvgRetentionSchoolLeads,
                        CompanyAvgRetentionSchoolLeads = CompanyAvgRetentionSchoolLeads,

                        CompanyAvgLPHMax  = CompanyAverageLPHMax,
                        CompanyAvgLPHMean = CompanyAverageLPHMean,
                        CompanyAvgLPHMin  = CompanyAverageLPHMin,
                        AvgLPH            = AvgLPH,

                        Hours         = hoursworked,
                        BillableHours = billablehours,
                        Lunch         = lunch,
                        Logon         = locationday != null ? locationday.LogonTime : "",
                        Logoff        = locationday != null ? locationday.LogoffTime : "",

                        HourlyRate     = hourlyrate,
                        HourlyEarnings = hourlyearnings,

                        CommissionRatePerSchoolLeadNetwork = CommissionRatePerSchoolLeadNetwork,
                        CommissionRatePerSchoolLeadDirect  = CommissionRatePerSchoolLeadDirect,
                        CommissionRatePerJobLeadNetwork    = CommissionRatePerJobLeadNetwork,
                        CommissionRatePerJobLeadDirect     = CommissionRatePerJobLeadDirect,

                        CommissionsSchoolLeadsNetwork = CommissionsSchoolLeadsNetwork,

                        TotalEarnings = hourlyearnings + CommissionsSchoolLeadsNetwork,

                        Stochastic = Stochastic,

                        Payments    = 0,
                        Adjustments = 0

                                      //,CumulativeEarnings
                    });


                    //Build production chart data arrays
                    if (hoursworked > 0)
                    {
                        try
                        {
                            ProductionChartData.Add(new object[] {
                                cursordate.ToString("MMM-d"),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMax)),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMin)),
                                float.Parse(String.Format("{0:0.0}", CompanyAverageLPHMean)),
                                float.Parse(String.Format("{0:0.0}", AvgLPH))
                            });
                        }
                        catch (Exception ex)
                        {
                            Console.Write(ex.Message);
                        }

                        //running totals
                        totalhours += hoursworked;
                        if (locationday != null)
                        {
                            aggregate["hours"].Add(hoursworked);
                            aggregate["billablehours"].Add(billablehours);
                        }
                        aggregate["hourlyearnings"].Add(hourlyearnings);

                        aggregate["validschoolleadsnetwork"].Add(validnetworkschoolleadcount);
                        aggregate["companyvalidschoolleadsnetwork"].Add(companyvalidnetworkschoolleads.Count());

                        aggregate["invalidschoolleadsnetwork"].Add(invalidnetworkschoolleads.Count());
                        aggregate["companyinvalidschoolleadsnetwork"].Add(companyinvalidnetworkschoolleads.Count());

                        aggregate["commissionsschoolleadsnetwork"].Add(CommissionsSchoolLeadsNetwork);

                        aggregate["AvgRetentionSchoolLeads"].Add(AvgRetentionSchoolLeads);
                        aggregate["CompanyAvgRetentionSchoolLeads"].Add(CompanyAvgRetentionSchoolLeads);
                        aggregate["AvgLPH"].Add(AvgLPH);
                        aggregate["CompanyAverageLPHMean"].Add(CompanyAverageLPHMean);
                        aggregate["Stochastic"].Add(Stochastic);
                    }



                    cursordate = cursordate.AddDays(1);
                }

                double aggregatelph = aggregate["AvgLPH"].Average();


                agents.Add(new
                {
                    Id    = kv.Key,
                    Dates = dates.ToArray(),

                    TotalHours          = totalhours,
                    TotalBillableHours  = aggregate["billablehours"].Sum(),
                    AvgHoursPerDay      = aggregate.ContainsKey("hours") ? aggregate["hours"].Average() : 0,
                    TotalHourlyEarnings = aggregate["hourlyearnings"].Sum(),

                    TotalValidSchoolLeadsNetwork        = aggregate["validschoolleadsnetwork"].Sum(),
                    AvgValidSchoolLeadsNetwork          = aggregate["validschoolleadsnetwork"].Average(),
                    CompanyTotalValidSchoolLeadsNetwork = aggregate["companyvalidschoolleadsnetwork"].Sum(),

                    TotalInvalidSchoolLeadsNetwork        = aggregate["invalidschoolleadsnetwork"].Sum(),
                    AvgInvalidSchoolLeadsNetwork          = aggregate["invalidschoolleadsnetwork"].Average(),
                    CompanyTotalInvalidSchoolLeadsNetwork = aggregate["companyinvalidschoolleadsnetwork"].Sum(),

                    //totalvalidschoolleadsdirect = 0;
                    //totalvalidjobleadsnetwork = 0;
                    //totalvalidjobleadsdirect = 0;

                    TotalCommissionCchoolLeadsNetwork = aggregate["commissionsschoolleadsnetwork"].Sum(),

                    TotalEarnings = aggregate["hourlyearnings"].Sum() + aggregate["commissionsschoolleadsnetwork"].Sum(),

                    //totalcommissionschoolleadsdirect = 0;
                    //totalcommissionjobleadsnetwork = 0;
                    //totalcommissionjobleadsdirect = 0;

                    AvgRetentionSchoolLeads        = aggregate["AvgRetentionSchoolLeads"].Average(),
                    CompanyAvgRetentionSchoolLeads = aggregate["CompanyAvgRetentionSchoolLeads"].Average(),

                    AvgLPH = aggregatelph,
                    CompanyAverageLPHMean = aggregate["CompanyAverageLPHMean"].Average(),

                    Stochastic = aggregate["Stochastic"].Average(),

                    ProductionChartData = ProductionChartData.ToArray()
                });
            }


            string retvalue = (new { result = "ok", agents = agents.ToArray() }).ToJSON();

            //Save cached version
            BlobJsonResourceManager.Instance.SaveJsonResource(retvalue, "range" + startdate + enddate, "skillcowagentdashboard", datestamp);

            Response.Write(retvalue);
            Response.End();
            //}
            //catch (Exception ex)
            //{
            //    Response.ContentType = "application/json";
            //    Response.Write(DefaultErrorResponse(ex.Message));
            //    Response.End();
            //}

            return(null);
        }
        public HttpResponseMessage Report()
        {
            SendGridEventClient sgec = new SendGridEventClient();
            string str = Request.Content.ReadAsStringAsync().Result;

            if (JToken.Parse(str).Type == JTokenType.Array)
            {
                dynamic stuff = JArray.Parse(str);
                foreach (dynamic item in stuff)
                {
                    if (item["event"] != null && item["email"] != null)
                    {
                        string eventType = item["event"];
                        string email     = item["email"];
                        email = email.ToLower();
                        SendGridEvent eventItem = sgec.GetByPartitionAndRowKey(SendGridEventClient.GetPartitionKeyForEmail(email), email);
                        if (eventItem != null)
                        {
                            switch (eventType)
                            {
                            case "click":
                                eventItem.Clicked++;
                                break;

                            case "open":
                                eventItem.Opened++;
                                break;

                            case "dropped":
                                eventItem.Delivered = false;
                                break;

                            case "bounce":
                                eventItem.Delivered = false;
                                break;

                            case "delivered":
                                eventItem.Delivered = true;
                                break;

                            case "unsubscribe":
                                eventItem.Unsubscribed = true;
                                break;

                            case "spam":
                                eventItem.Spam = true;
                                break;

                            default:
                                continue;
                            }
                            eventItem.LastUpdated = EasternTimeConverter.Convert(DateTime.UtcNow);
                            sgec.Update(eventItem);
                        }
                        else
                        {
                            eventItem = new SendGridEvent {
                                PartitionKey = SendGridEventClient.GetPartitionKeyForEmail(email), RowKey = email, Email = email, Delivered = true, Clicked = 0, Opened = 0
                            };
                            switch (eventType)
                            {
                            case "click":
                                eventItem.Clicked = 1;
                                break;

                            case "open":
                                eventItem.Opened = 1;
                                break;

                            case "dropped":
                                eventItem.Delivered = false;
                                break;

                            case "bounce":
                                eventItem.Delivered = false;
                                break;

                            case "delivered":
                                break;

                            case "unsubscribe":
                                eventItem.Unsubscribed = true;
                                break;

                            case "spam":
                                eventItem.Spam = true;
                                break;

                            default:
                                continue;
                            }
                            sgec.AddNewItem(eventItem);
                        }
                    }
                }
            }
            return(new HttpResponseMessage {
                StatusCode = HttpStatusCode.OK
            });
        }