public ActionResult Auth()
        {
            const string scope = "https://www.google.com/analytics/feeds/";
            var          next  = Url.FullPath("~/home/authresponse");
            var          url   = AuthSubUtil.getRequestUrl(next, scope, false, true);

            return(Redirect(url));
        }
Beispiel #2
0
        public ActionResult saveToken(string token)
        {
            var sd           = repository.GetSubDomains().Where(x => x.id == subdomainid.Value).Single();
            var sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);

            sd.bloggerSessionKey = sessionToken;
            repository.Save();
            return(View("close"));
        }
Beispiel #3
0
        public VideoAdapter()
        {
            _apiKey = ConfigurationManager.AppSettings["VideoApiKey"] ?? "978012847617.apps.googleusercontent.com";

            AuthSubUtil.getRequestUrl("RedirectUrl", "scope", true, true);

            var request      = GetRequest();
            var videoStreams = request.GetVideoFeed("UserName").Entries.Select(video => video.MediaSource.GetDataStream());
        }
Beispiel #4
0
        public ActionResult googleContacts()
        {
            var continueUrl = string.Concat(GeneralConstants.HTTP_HOST, "/callback?sd=", accountHostname, "&path=",
                                            HttpUtility.UrlEncode("/dashboard/contacts/import"),
                                            "&type=", ContactImportType.GOOGLE);
            var authsubUrl = AuthSubUtil.getRequestUrl(continueUrl, GoogleConstants.FEED_CONTACTS, false, false);

            return(Redirect(authsubUrl));
        }
        public ActionResult AuthResponse(string token)
        {
            var sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);

            var settings = _siteSettingsService.GetSettings();

            settings.AnalyticsToken = sessionToken;
            Db.Save(settings);
            Cache.Trigger(TriggerFor.Id <SiteSettings>(settings.Id));

            return(Redirect(Url.AdminHome()));
        }
Beispiel #6
0
        public ActionResult blogger()
        {
            var viewdata = new NetworkViewModel();

            viewdata.bloggerSessionKey = MASTERdomain.bloggerSessionKey;
            viewdata.blogList          = MASTERdomain.googleBlogs.ToModel();

            var continueUrl = string.Concat(GeneralConstants.HTTP_HOST, "/callback?sd=", accountHostname, "&path=",
                                            HttpUtility.UrlEncode("/dashboard/blogger/saveToken"));

            viewdata.requestUrl = AuthSubUtil.getRequestUrl(continueUrl, GoogleConstants.FEED_BLOGGER, false, true);
            return(View(viewdata));
        }
Beispiel #7
0
        public ActionResult getToken(string upload, string accountid)
        {
            var parameters = new NameValueCollection();

            parameters.Add("upload", upload);
            parameters.Add("sd", accountHostname);
            parameters.Add("path", "/dashboard/gbase/saveToken");
            parameters.Add("accountid", accountid);

            var continueUrl = string.Format("{0}/callback{1}", GeneralConstants.HTTP_SECURE, parameters.ToQueryString(true));

            return(Redirect(AuthSubUtil.getRequestUrl(continueUrl, "https://www.googleapis.com/auth/structuredcontent", false, true)));
        }
Beispiel #8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            GotoAuthSubLink.Visible = false;

            if (Session["token"] != null)
            {
                Response.Redirect("Default.aspx");
            }
            else if (Request.QueryString["token"] != null)
            {
                User u = new User();
                u.Username = "******";
                u.Password = "******";

                PicasaService.setUserCredentials(u.Username, u.Password);

                AlbumQuery albumQuery = new AlbumQuery();
                albumQuery.Uri = new Uri(PicasaQuery.CreatePicasaUri(u.Username));
                //albumQuery.Access = PicasaQuery.AccessLevel.AccessPublic;

                PicasaFeed feed = PicasaService.Query(albumQuery);

                Session["feed"]    = feed;
                Session["service"] = PicasaService;
                Session["user"]    = u;

                if (feed.Entries.Count > 0)
                {
                    AlbumAccessor myAlbum = new AlbumAccessor((PicasaEntry)feed.Entries[0]);
                    Response.Redirect("Default.aspx?album=" + myAlbum.Id, true);
                }
                else
                {
                    Response.Redirect("Default.aspx", true);
                }
            }
            else //no auth data, print link
            {
                GotoAuthSubLink.Text        = "Login to your Google Account";
                GotoAuthSubLink.Visible     = true;
                GotoAuthSubLink.NavigateUrl = AuthSubUtil.getRequestUrl(Request.Url.ToString(),
                                                                        "https://picasaweb.google.com/data/", false, true);
            }
        }
Beispiel #9
0
        public ActionResult saveToken(string token, bool?upload, long accountid)
        {
            var sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);

            // save accountid
            if (MASTERdomain.gbaseid.HasValue)
            {
                MASTERdomain.googleBase.accountid = accountid;
            }
            else
            {
                MASTERdomain.googleBase = new googleBase()
                {
                    accountid    = accountid,
                    sessiontoken = sessionToken
                };
            }

            repository.Save();

            // check if account exist first
            var gbaseitem = new GoogleBaseExporter(subdomainid.Value, accountHostname);
            var viewmodel = "";

            if (gbaseitem.VerifyAccount())
            {
                // start synchronisation
                var gbase = new NetworksGbase(subdomainid.Value, sessionid.Value, accountHostname);
                new Thread(() => gbase.StartSynchronisation(upload)).Start();
            }
            else
            {
                viewmodel = "Unable to connect to your Google Merchant Center account.";
            }

            return(View("close", (object)viewmodel));
        }
        public ActionResult AuthResponse(string token)
        {
            var      sessionToken = AuthSubUtil.exchangeForSessionToken(token, null);
            Settings settings;

            using (RavenSession.Advanced.DocumentStore.DisableAggressiveCaching())
            {
                settings = RavenSession.Load <Settings>(Settings.DefaultId);
            }
            if (settings == null)
            {
                settings = new Settings
                {
                    Id = Settings.DefaultId
                }
            }
            ;

            settings.SessionToken = sessionToken;
            RavenSession.Store(settings);

            return(RedirectToAction("Config"));
        }
    }
Beispiel #11
0
        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                ShowUsage();
                return;
            }
            string pid           = findValue(args, "pid", null);
            string pname         = findValue(args, "pname", null);
            string authToken     = findValue(args, "a", null);
            string exchangeToken = findValue(args, "e", null);
            string userName      = findValue(args, "user", null);
            string passWord      = findValue(args, "pwd", null);


            bool isRegister = isOption(args, "register", false);
            bool isInsert   = isOption(args, "insert", false);
            bool isClean    = isOption(args, "clean", false);
            bool isShow     = isOption(args, "show", false);
            bool isList     = isOption(args, "list", false);
            bool doCCR      = isOption(args, "ccr", false);
            bool doSummary  = isOption(args, "summary", false);

            if ((pid == null && pname == null && isList == false) && (exchangeToken == null && authToken == null))
            {
                ShowUsage();
                return;
            }

            HealthService service = new HealthService(ApplicationName);

            if (authToken != null)
            {
                Console.WriteLine("Using AuthSubToken: " + authToken);
                GAuthSubRequestFactory factory = new GAuthSubRequestFactory(HealthService.ServiceName, ApplicationName);
                factory.Token          = authToken;
                service.RequestFactory = factory;
            }
            else if (exchangeToken != null)
            {
                Console.WriteLine("Using Onetime token: " + exchangeToken);
                authToken = AuthSubUtil.exchangeForSessionToken(exchangeToken, null);
                Console.WriteLine("Exchanged for Session Token: " + exchangeToken);
                GAuthSubRequestFactory factory = new GAuthSubRequestFactory(HealthService.ServiceName, ApplicationName);
                factory.Token          = authToken;
                service.RequestFactory = factory;
            }
            else
            {
                Console.WriteLine("Setting user credentials for: " + userName);
                service.setUserCredentials(userName, passWord);
            }

            HealthQuery query;

            try
            {
                if (isList == true)
                {
                    HealthFeed feed = service.Query(new HealthQuery(HealthQuery.ProfileListFeed));
                    Console.WriteLine("Feed =" + feed);
                    foreach (AtomEntry entry in feed.Entries)
                    {
                        Console.WriteLine("\tProfile " + entry.Title.Text + " has ID: " + entry.Content.Content);
                    }
                    return;
                }

                if (pid == null && pname != null)
                {
                    // need to find the ID first.
                    // so we get the list feed, find the name in the TITLE, and then
                    // get the ID out of the content field
                    HealthFeed feed = service.Query(new HealthQuery(HealthQuery.ProfileListFeed));
                    foreach (AtomEntry entry in feed.Entries)
                    {
                        if (entry.Title.Text == pname)
                        {
                            pid = entry.Content.Content;
                        }
                    }
                }

                if (authToken != null)
                {
                    if (isRegister == true)
                    {
                        query = new HealthQuery(HealthQuery.AuthSubRegisterFeed);
                    }
                    else
                    {
                        query = new HealthQuery(HealthQuery.AuthSubProfileFeed);
                        if (doSummary == true)
                        {
                            query.Digest = true;
                        }
                    }
                }
                else
                {
                    if (isRegister == true)
                    {
                        query = HealthQuery.RegisterQueryForId(pid);
                    }
                    else
                    {
                        query = HealthQuery.ProfileQueryForId(pid);
                        if (doSummary == true)
                        {
                            query.Grouped   = true;
                            query.GroupSize = 1;
                        }
                    }
                }

                Console.WriteLine("Resolved targetUri to: " + query.Uri.ToString());

                if (doCCR == true)
                {
                    HealthFeed feed = service.Query(query);
                    foreach (HealthEntry e in feed.Entries)
                    {
                        XmlNode ccr = e.CCR;
                        if (ccr != null)
                        {
                            XmlTextWriter writer = new XmlTextWriter(Console.Out);
                            writer.Formatting = Formatting.Indented;
                            ccr.WriteTo(writer);
                        }
                    }
                }
                else
                {
                    if (isShow == true || doSummary == true)
                    {
                        Stream result = service.Query(query.Uri);
                        DumpStream(result);
                    }
                }
                if (isInsert == true)
                {
                    String input = Console.In.ReadToEnd();
                    Console.Write(input);
                    Stream result = service.StringSend(query.Uri, input, GDataRequestType.Insert);
                    DumpStream(result);
                }
                if (isClean == true)
                {
                    int      count = 0;
                    AtomFeed feed  = service.Query(query);
                    Console.WriteLine("Retrieved Feed, now deleting all entries in the feed");
                    foreach (AtomEntry entry in feed.Entries)
                    {
                        Console.WriteLine(".... deleting entry " + entry.Title.Text);
                        entry.Delete();
                        count++;
                    }
                    Console.WriteLine("Deleted " + count + " entries");
                }
            } catch (GDataRequestException e)
            {
                HttpWebResponse response = e.Response as HttpWebResponse;
                Console.WriteLine("Error executing request for Verb, Errorcode: " + response.StatusCode);
                Console.WriteLine(response.StatusDescription);
                Console.WriteLine(e.ResponseString);
            }
        }
Beispiel #12
0
 /// <summary>
 /// Step 2: Read the context and get the token in the query string.
 /// Then exchange it for the Session Token.
 /// </summary>
 /// <param name="context">The context of the application</param>
 public void SetToken()
 {
     this.token = AuthSubUtil.exchangeForSessionToken(HttpContext.Current.Request.QueryString["token"], getRsaKey());
     HttpContext.Current.Session["Google_Token"] = this.token;
     HttpContext.Current.Response.Redirect(contactsPageUrl);
 }
Beispiel #13
0
 /// <summary>
 /// Step 1
 /// </summary>
 /// <returns>Authorization URL</returns>
 public string GetAuthorizationURL()
 {
     return(AuthSubUtil.getRequestUrl(returnUrl, "http://www.google.com/m8/feeds/", true, true));
 }
Beispiel #14
0
        static void Main(string[] args)
        {
            if (args.Length < 5)
            {
                Console.WriteLine("Not enough parameters. Usage is ExecRequest <service> <cmd> <uri> <username> <password>, where cmd is QUERY, UPDATE, INSERT, DELETE");
                Console.WriteLine("or");
                Console.WriteLine("ExecRequest <service> <cmd> <uri> /a <authsubtoken> - to use a session token");
                Console.WriteLine("or");
                Console.WriteLine("ExecRequest <service> <cmd> <uri> /e <authsubtoken> - to exchance a one time token for a session token");
                return;
            }

            string s   = args[0];
            string cmd = args[1];

            string targetUri = args[2];

            string userName = args[3];
            string passWord = args[4];


            Service service = new Service(s, ApplicationName);

            if (userName.Equals("/a"))
            {
                Console.WriteLine("Using AuthSubToken: " + passWord);
                // password should contain the authsubtoken
                GAuthSubRequestFactory factory = new GAuthSubRequestFactory(s, ApplicationName);
                factory.Token          = passWord;
                service.RequestFactory = factory;
            }
            else if (userName.Equals("/e"))
            {
                Console.WriteLine("Using Onetime token: " + passWord);
                passWord = AuthSubUtil.exchangeForSessionToken(passWord, null);
                Console.WriteLine("Exchanged for Session Token: " + passWord);
                // password should contain the authsubtoken
                GAuthSubRequestFactory factory = new GAuthSubRequestFactory(s, ApplicationName);
                factory.Token          = passWord;
                service.RequestFactory = factory;
            }
            else
            {
                Console.WriteLine("Setting user credentials for: " + userName);
                service.setUserCredentials(userName, passWord);
            }

            try
            {
                if (cmd.Equals("QUERY"))
                {
                    Console.WriteLine("Querying: " + targetUri);
                    Stream result = service.Query(new Uri(targetUri));
                    DumpStream(result);
                }
                if (cmd.Equals("DELETE"))
                {
                    service.Delete(new Uri(targetUri));
                    Console.WriteLine("successfully deleted: " + targetUri);
                }
                if (cmd.Equals("POST"))
                {
                    String input = Console.In.ReadToEnd();
                    Console.Write(input);
                    Stream result = service.StringSend(new Uri(targetUri), input, GDataRequestType.Insert);
                    DumpStream(result);
                }
                if (cmd.Equals("UPDATE"))
                {
                    String input = Console.In.ReadToEnd();
                    Console.Write(input);
                    Stream result = service.StringSend(new Uri(targetUri), input, GDataRequestType.Update);
                    DumpStream(result);
                }
            } catch (GDataRequestException e)
            {
                HttpWebResponse response = e.Response as HttpWebResponse;
                Console.WriteLine("Error executing request for Verb: " + cmd + ", Errorcode: " + response.StatusCode);
                Console.WriteLine(response.StatusDescription);
                Console.WriteLine(e.ResponseString);
            }
        }
Beispiel #15
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            string[] uris;
            string   povtoruvanje = "";
            mwGoogleEvent.ActiveViewIndex = 0;



            if ((Request.QueryString["token"] != null) && Session["sessionToken"] == null)
            {
                Session["sessionToken"] = AuthSubUtil.exchangeForSessionToken(Request.QueryString["token"], null);
            }
            GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cl", "FEITPortal");
            authFactory.Token = (string)Session["sessionToken"];
            myCalendarService.RequestFactory = authFactory;
            CalendarQuery query = new CalendarQuery();
            query.Uri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
            try
            {
                CalendarFeed resultFeed = myCalendarService.Query(query);
                foreach (CalendarEntry entry in resultFeed.Entries)
                {
                    uris = entry.Id.Uri.ToString().Split('/');
                    ListItem li = new ListItem();
                    li.Text  = entry.Title.Text;
                    li.Value = uris[8];
                    ddlKalendari.Items.Add(li);
                }
            }
            catch (Exception ex)
            {
                hlGcal1.Visible  = true;
                hlNazad1.Visible = true;
                lblGreska.Text   = "Немате креирано Google Calendar";
                mwGoogleEvent.ActiveViewIndex = 3;
            }


            Calendar.COURSE_EVENTS_INSTANCEDataTable nastan = (Calendar.COURSE_EVENTS_INSTANCEDataTable)Session["gNastan"];



            foreach (Calendar.COURSE_EVENTS_INSTANCERow r in nastan)
            {
                CoursesTier CourseTier = new CoursesTier(Convert.ToInt32(Session["COURSE_ID"]));
                novNastan.Content.Language = r.COURSE_EVENT_ID.ToString();
                novNastan.Title.Text       = r.TITLE;
                novNastan.Content.Content  = "Предмет: " + CourseTier.Name + " Опис: " + r.DESCRIPTION + " Тип: " + r.TYPEDESCRIPTION + " ID:" + r.COURSE_EVENT_ID.ToString();
                Where mesto = new Where();
                mesto.ValueString = r.ROOM;
                novNastan.Locations.Add(mesto);
                int recType = Convert.ToInt32(r.RECURRENCE_TYPE);


                DateTime startDate = Convert.ToDateTime(r.STARTDATE);
                DateTime endDate   = Convert.ToDateTime(r.ENDDATE);
                DateTime startTime = Convert.ToDateTime(r.STARTIME);
                DateTime endTime   = Convert.ToDateTime(r.ENDTIME);
                TimeSpan span      = endTime - startTime;

                if (recType != 0)
                {
                    Recurrence rec = new Recurrence();
                    string     recData;
                    string     dStart = "DTSTART;TZID=" + System.TimeZone.CurrentTimeZone.StandardName + ":" + startDate.ToString("yyyyMMddT") + startTime.AddHours(-1).ToString("HHmm") + "00\r\n";
                    string     dEnd   = "DTEND;TZID=" + System.TimeZone.CurrentTimeZone.StandardName + ":" + startDate.ToString("yyyyMMddT") + startTime.AddHours(-1 + span.Hours).ToString("HHmm") + "00\r\n";
                    string     rRule  = "";
                    povtoruvanje = "<b>Повторување:</b> ";

                    switch (recType)
                    {
                    case 1:
                        rRule         = "RRULE:FREQ=DAILY;INTERVAL=" + r.RECURRENCE_NUMBER + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n";
                        povtoruvanje += "Дневно, секој " + r.RECURRENCE_NUMBER.ToString() + " ден <br> </br> <br> </br>";
                        break;

                    case 2:
                        string daysInWeek = "";
                        string denovi     = "";

                        if (r.DAYSINWEEK[0] == '1')
                        {
                            daysInWeek += "MO,";
                            denovi     += " Понеделник,";
                        }
                        if (r.DAYSINWEEK[1] == '1')
                        {
                            daysInWeek += "TU,";
                            denovi     += " Вторник,";
                        }
                        if (r.DAYSINWEEK[2] == '1')
                        {
                            daysInWeek += "WE,";
                            denovi     += " Среда,";
                        }
                        if (r.DAYSINWEEK[3] == '1')
                        {
                            daysInWeek += "TH,";
                            denovi     += " Четврток,";
                        }
                        if (r.DAYSINWEEK[4] == '1')
                        {
                            daysInWeek += "FR,";
                            denovi     += " Петок,";
                        }
                        if (r.DAYSINWEEK[5] == '1')
                        {
                            daysInWeek += "SA,";
                            denovi     += " Сабота,";
                        }
                        if (r.DAYSINWEEK[6] == '1')
                        {
                            daysInWeek += "SU,";
                            denovi     += " Недела,";
                        }
                        daysInWeek    = daysInWeek.Substring(0, daysInWeek.Length - 1);
                        denovi        = denovi.Substring(0, denovi.Length - 1);
                        rRule         = "RRULE:FREQ=WEEKLY;INTERVAL=" + r.RECURRENCE_NUMBER + ";BYDAY=" + daysInWeek + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n";
                        povtoruvanje += "Неделно, секоја " + r.RECURRENCE_NUMBER + " недела и тоа во: " + denovi + " <br> </br> <br> </br>";
                        break;

                    case 3:
                        rRule         = "RRULE:FREQ=MONTHLY;INTERVAL=" + r.RECURRENCE_NUMBER + ";UNTIL=" + endDate.ToString("yyyyMMddTHHmm") + "00Z\r\n";
                        povtoruvanje += "Месечно, секој " + r.RECURRENCE_NUMBER + " месец <br> </br> <br> </br>";
                        break;
                    }
                    recData              = dStart + dEnd + rRule;
                    rec.Value            = recData;
                    novNastan.Recurrence = rec;
                }
                else
                {
                    When vreme = new When();
                    vreme.StartTime = r.STARTIME;
                    vreme.EndTime   = r.ENDTIME;
                    novNastan.Times.Add(vreme);
                }


                lblPrikaz.Text += "<b>Наслов: </b>" + r.TITLE + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Опис: </b>" + r.DESCRIPTION + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Просторија: </b>" + r.ROOM + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Тип: </b>" + r.TYPEDESCRIPTION + "<br> </br> <br> </br>";
                lblPrikaz.Text += povtoruvanje;
                lblPrikaz.Text += "<b>Почетен датум: </b>" + startDate.ToShortDateString() + "  <b>Краен датум: </b>" + endDate.ToShortDateString() + "<br> </br> <br> </br>";
                lblPrikaz.Text += "<b>Време: Од </b>" + startTime.ToShortTimeString() + " <b>До</b> " + endTime.ToShortTimeString();
            }
            Session["novNastan"] = novNastan;
        }
    }
Beispiel #16
0
        private List <Friend> GetGmailContacts(int page, List <int> selectedIndexs)
        {
            int            pageSize = 10;
            List <Friend>  friends  = new List <Friend>();
            MembershipUser mu       = Membership.GetUser();
            RegisteredUser user     = registeredUserRepository.GetByMembershipId(Convert.ToInt32(mu.ProviderUserKey));

            if (Session["GMailToken"] == null)
            {
                String token = Request.QueryString["token"];
                Session["GMailToken"] = AuthSubUtil.exchangeForSessionToken(token, null).ToString();
            }

            GAuthSubRequestFactory authFactory = new GAuthSubRequestFactory("cp", "testingFADE");
            RequestSettings        rs          = new RequestSettings("testingFADE", (String)Session["GMailToken"]);

            rs.AutoPaging = true;
            ContactsRequest cr = new ContactsRequest(rs);

            Feed <Contact> contacts = cr.GetContacts();
            int            i        = 1;

            if (page > 0)
            {
                foreach (Contact e in contacts.Entries)
                {
                    if (i < (page * pageSize) - 9)
                    {
                        i++;
                        continue;
                    }
                    if (i > (page * pageSize))
                    {
                        break;
                    }
                    if (e.PrimaryEmail == null)
                    {
                        continue;
                    }
                    Friend friend = new Friend();
                    friend.FirstName    = e.Title;
                    friend.EmailAddress = e.PrimaryEmail.Address;
                    friend.InvitedBy    = user;
                    friends.Add(friend);
                    i++;
                }
                ViewData["Pages"] = Common.Paging(contacts.TotalResults, page, pageSize, 10);
            }
            else if (selectedIndexs != null)
            {
                foreach (Contact e in contacts.Entries)
                {
                    if (!selectedIndexs.Exists(delegate(int record) { if (record == i)
                                                                      {
                                                                          return(true);
                                                                      }
                                                                      return(false); }))
                    {
                        i++;
                        continue;
                    }
                    Friend friend = new Friend();
                    friend.FirstName    = e.Title;
                    friend.EmailAddress = e.PrimaryEmail.Address;
                    friend.InvitedBy    = user;
                    friends.Add(friend);
                    i++;
                }
            }

            return(friends);
        }
        public ActionResult Analytics(int?duration)
        {
            CacheContext.InvalidateOn(TriggerFrom.Any <SiteSettings>());

            var settings = _siteSettingsService.GetSettings();

            if (string.IsNullOrEmpty(settings.AnalyticsToken))
            {
                const string scope = "https://www.google.com/analytics/feeds/";
                var          next  = Url.Absolute(Url.AnalyticsWidget().AuthResponse());
                var          auth  = new Authorize
                {
                    Url = AuthSubUtil.getRequestUrl(next, scope, false, true)
                };
                return(View("AnalyticsAuthorize", auth));
            }

            if (string.IsNullOrEmpty(settings.AnalyticsProfileId))
            {
                var config = new Config
                {
                    Accounts = GetAccounts(settings),
                    Profiles = GetProfiles(settings)
                };

                return(View("AnalyticsConfig", config));
            }

            duration = duration ?? 30;
            var model = new ViewModels.Widgets.Analytics
            {
                Duration     = duration.Value,
                Start        = DateTime.Today.AddDays(-1 * duration.Value),
                End          = DateTime.Now,
                Visits       = new Dictionary <DateTime, int>(),
                PageViews    = new Dictionary <string, int>(),
                PageTitles   = new Dictionary <string, string>(),
                TopReferrers = new Dictionary <string, int>(),
                TopSearches  = new Dictionary <string, int>()
            };

            if (model.Start > model.End)
            {
                var tempDate = model.Start;
                model.Start = model.End;
                model.End   = tempDate;
            }

            var profiles = GetProfiles(settings);
            var profile  = profiles.SingleOrDefault(x => x.Id == settings.AnalyticsProfileId);

            if (profile == null)
            {
                throw new Exception("Unable to find the specified analytics profile: " + settings.AnalyticsProfileId);
            }
            model.Profile = profile;

            var authFactory = new GAuthSubRequestFactory("analytics", "MvcKickstart")
            {
                Token = settings.AnalyticsToken
            };

            var analytics = new AnalyticsService(authFactory.ApplicationName)
            {
                RequestFactory = authFactory
            };

            var profileId = "ga:" + settings.AnalyticsProfileId;

            // Get from All Visits
            var visits = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics    = "ga:visits",
                Dimensions = "ga:date",
                Sort       = "ga:date"
            };
            var count = 0;

            foreach (DataEntry entry in analytics.Query(visits).Entries)
            {
                var value = entry.Metrics.First().IntegerValue;

                model.Visits.Add(model.Start.AddDays(count++), value);
            }

            // Get Site Usage
            var siteUsage = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics = "ga:visits,ga:pageviews,ga:percentNewVisits,ga:avgTimeOnSite,ga:entranceBounceRate,ga:exitRate,ga:pageviewsPerVisit,ga:avgPageLoadTime"
            };
            var siteUsageResult = (DataEntry)analytics.Query(siteUsage).Entries.FirstOrDefault();

            if (siteUsageResult != null)
            {
                foreach (var metric in siteUsageResult.Metrics)
                {
                    switch (metric.Name)
                    {
                    case "ga:visits":
                        model.TotalVisits = metric.IntegerValue;
                        break;

                    case "ga:pageviews":
                        model.TotalPageViews = metric.IntegerValue;
                        break;

                    case "ga:percentNewVisits":
                        model.PercentNewVisits = metric.FloatValue;
                        break;

                    case "ga:avgTimeOnSite":
                        model.AverageTimeOnSite = TimeSpan.FromSeconds(metric.FloatValue);
                        break;

                    case "ga:entranceBounceRate":
                        model.EntranceBounceRate = metric.FloatValue;
                        break;

                    case "ga:exitRate":
                        model.PercentExitRate = metric.FloatValue;
                        break;

                    case "ga:pageviewsPerVisit":
                        model.PageviewsPerVisit = metric.FloatValue;
                        break;

                    case "ga:avgPageLoadTime":
                        model.AveragePageLoadTime = TimeSpan.FromSeconds(metric.FloatValue);
                        break;
                    }
                }
            }

            // Get Top Pages
            var topPages = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics          = "ga:pageviews",
                Dimensions       = "ga:pagePath,ga:pageTitle",
                Sort             = "-ga:pageviews",
                NumberToRetrieve = 20
            };

            foreach (DataEntry entry in analytics.Query(topPages).Entries)
            {
                var value = entry.Metrics.First().IntegerValue;
                var url   = entry.Dimensions.Single(x => x.Name == "ga:pagePath").Value.ToLowerInvariant();
                var title = entry.Dimensions.Single(x => x.Name == "ga:pageTitle").Value;

                if (!model.PageViews.ContainsKey(url))
                {
                    model.PageViews.Add(url, 0);
                }
                model.PageViews[url] += value;

                if (!model.PageTitles.ContainsKey(url))
                {
                    model.PageTitles.Add(url, title);
                }
            }

            // Get Top Referrers
            var topReferrers = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics          = "ga:visits",
                Dimensions       = "ga:source,ga:medium",
                Sort             = "-ga:visits",
                Filters          = "ga:medium==referral",
                NumberToRetrieve = 5
            };

            foreach (DataEntry entry in analytics.Query(topReferrers).Entries)
            {
                var visitCount = entry.Metrics.First().IntegerValue;
                var source     = entry.Dimensions.Single(x => x.Name == "ga:source").Value.ToLowerInvariant();

                model.TopReferrers.Add(source, visitCount);
            }

            // Get Top Searches
            var topSearches = new DataQuery(profileId, model.Start, model.End)
            {
                Metrics          = "ga:visits",
                Dimensions       = "ga:keyword",
                Sort             = "-ga:visits",
                Filters          = "ga:keyword!=(not set);ga:keyword!=(not provided)",
                NumberToRetrieve = 5
            };

            foreach (DataEntry entry in analytics.Query(topSearches).Entries)
            {
                var visitCount = entry.Metrics.First().IntegerValue;
                var source     = entry.Dimensions.Single(x => x.Name == "ga:keyword").Value.ToLowerInvariant();

                model.TopSearches.Add(source, visitCount);
            }

            return(View(model));
        }