/// <summary>
 /// Allows derived classes to construct an instance of themselves given
 /// an instance of the base class.
 /// </summary>
 /// 
 /// <param name="personInfo">
 /// Information about the person for constructing the instance.
 /// </param>
 /// 
 internal PersonInfo(PersonInfo personInfo)
 {
     _connection = personInfo._connection;
     _personId = personInfo._personId;
     _name = personInfo._name;
     _selectedRecordId = personInfo._selectedRecordId;
 }
        public HVPrincipal(MembershipUser aspUser, PersonInfo pi, string authtoken)
        {
            // null checking
            if (aspUser == null)
                throw new ArgumentNullException("aspUser cannot be null");

            //create the identity
            Identity = new GenericIdentity(aspUser.UserName);

            //save some values for easy retrieving from Database
            Name = pi.Name;
            PersonId = pi.PersonId;
            UserName = pi.PersonId.ToString();
            UserId = pi.PersonId;
            AuthToken = authtoken;
        }
        public HVPrincipal(MembershipUser aspUser, PersonInfo pi, string authtoken)
        {
            // null checking
            if (aspUser == null)
                throw new ArgumentNullException("aspUser cannot be null");

            //create the identity
            Identity = new GenericIdentity(aspUser.UserName);

            //save some values for easy retrieving from Database
            Name = pi.Name;
            PersonId = pi.PersonId;
            UserName = pi.PersonId.ToString();
            UserId = pi.PersonId;
            AuthToken = authtoken;
            if (pi.SelectedRecord == null)
                RecordId = pi.AuthorizedRecords.FirstOrDefault().Value.Id;
            else
                RecordId = pi.SelectedRecord.Id;
        }
 private static string PersonInfoAsCookie(PersonInfo personInfo)
 {
     return PersonInfoAsCookie(personInfo, true);
 }
 /// <summary>
 /// Stores the specified person's information in the cookie.
 /// </summary>
 /// 
 /// <param name="personInfo">
 /// The authenticated person's information.
 /// </param>
 /// 
 /// <param name="existingCookie">
 /// The existing cooke containing the person's information. The expiration date of this 
 /// cookie will be used as the expiration date of the returned cookie.
 /// </param>
 /// 
 /// <returns>
 /// A cookie containing the person's information.
 /// </returns>
 /// 
 /// <remarks>
 /// If <paramref name="personInfo"/> is null, the returned cookie will have an
 /// expiration date in the past, and adding it to a response would result in the cookie
 /// being cleared.
 /// </remarks>
 /// 
 public static HttpCookie SavePersonInfoToCookie(
     PersonInfo personInfo, 
     HttpCookie existingCookie)
 {
     return SavePersonInfoToCookie(personInfo, existingCookie, -1);
 }
 /// <summary>
 /// Stores the specified person's information in the cookie.
 /// </summary>
 /// 
 /// <param name="personInfo">
 /// The authenticated person's information.
 /// </param>
 /// 
 /// <returns>
 /// A cookie containing the person's information.
 /// </returns>
 /// 
 /// <remarks>
 /// If <paramref name="personInfo"/> is null, the returned cookie will have an
 /// expiration date in the past, and adding it to a response would result in the cookie
 /// being cleared.
 /// </remarks>
 /// 
 public static HttpCookie SavePersonInfoToCookie(PersonInfo personInfo)
 {
     return SavePersonInfoToCookie(personInfo, null, -1);
 }
Exemple #7
0
        public static void OnlineSyncUser(ProfileModel profile, PersonInfo info, bool partialSync)
        {
            string syncType = "partial";
            DateTime? lastSyncTime = profile.UserCtx.hv_last_sync_time;
            DateTime timeStamp = DateTime.Now;

            // reset lastsynctime if this is a full sync
            if (!lastSyncTime.HasValue || !partialSync)
            {
                WlkMiTracer.Instance.Log("HVSync.cs:OnlineSyncUser", WlkMiEvent.UserSync,
                      WlkMiCat.Info, string.Format("Full syncing for User: {0}",
                        profile.UserCtx.user_id));
                lastSyncTime = null;
            }

            // Retrieve the latest info from HealthVault
            HealthRecordItemCollection items =
                GetHVItemsOnline(info, lastSyncTime);
            if (items != null && items.Count > 0)
            {
                foreach (HealthRecordItem item in items)
                {
                    // Do the distinct per item work
                    ProcessStepsHealthItem(item, profile);
                }
            }

            //only update the last sync time if we are able to download items
            if (items != null)
            {
                //set last sync time
                profile.UserCtx.hv_last_sync_time = timeStamp;
                profile.Save();
            }

            // Clear the WlkMi data cache if the last sync is null or this is a full sync
            if (!lastSyncTime.HasValue || !partialSync)
            {
                WlkMiTracer.Instance.Log("HVSync.cs:OnlineSyncUser", WlkMiEvent.UserSync,
                      WlkMiCat.Info, string.Format("Full sync deleting information for User: {0}",
                        profile.UserCtx.user_id));
                lastSyncTime = null;
                WalkLogModel.ClearUserCache(profile);
                syncType = "full";
            }

            //Processtotals for this user
            WalkLogModel.ProcessTotals(profile.UserCtx.user_id);

            WlkMiTracer.Instance.Log("HVSync:OnlineSyncUser", WlkMiEvent.UserSync,
                WlkMiCat.Info, string.Format("Completed Online {1} Sync of User: {0}",
                profile.UserCtx.user_id.ToString(), syncType));
        }
        private void CreateAuthCookie(PersonInfo personInfo, MembershipUser user, string authToken)
        {
            // Create a new principal and serialize it
            var hvPrincipal = new HVPrincipal(user, personInfo, authToken);
            var userData = new JavaScriptSerializer().Serialize(hvPrincipal);

            // create an auth ticket
            var authTicket = new FormsAuthenticationTicket(1,
                personInfo.PersonId.ToString(),
                DateTime.Now,
                DateTime.Now.AddHours(2),
                false,
                userData);

            // add the ticket to the cookies
            Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)));
        }
        private static void SavePersonInfoToCookie(
            HttpContext context, 
            PersonInfo personInfo, 
            bool clearIfNull, 
            int cookieTimeout)
        {
            if (personInfo != null || clearIfNull)
            {
                if (HealthWebApplicationConfiguration.Current.UseAspSession)
                {
                    if (personInfo == null)
                    {
                        context.Session.Remove(HealthWebApplicationConfiguration.Current.CookieName);
                    }
                    else
                    {
                        context.Session[HealthWebApplicationConfiguration.Current.CookieName]
                            = PersonInfoAsCookie(personInfo);
                    }
                }
                else
                {
                    HttpCookie existingCookie =
                        context.Request.Cookies[
                            HealthWebApplicationConfiguration.Current.CookieName];
                    HttpCookie cookie =
                        SavePersonInfoToCookie(personInfo, existingCookie, cookieTimeout);

                    context.Response.Cookies.Remove(
                            HealthWebApplicationConfiguration.Current.CookieName);
                    context.Response.Cookies.Add(cookie);
                }
            }
        }
 /// <summary>
 /// Initializes the user data for the page. 
 /// </summary>
 /// 
 /// <param name="logOnRequired"> 
 /// If true and the user hasn't already logged in to HealthVault, 
 /// the page will automatically redirect to the HealthVault logon page 
 /// and then return to this page with the auth-token.
 /// </param>
 /// 
 /// <remarks>
 /// The base implementation of OnPreLoad will automatically call this
 /// method with the value specified in the <see cref="LogOnRequired"/>
 /// property. This method should only be called explicitly if there
 /// is a need to initialize the user data again after the page has
 /// been loaded.
 /// </remarks>
 /// 
 protected void InitializeUserData(bool logOnRequired)
 {
     _personInfo =
         WebApplicationUtilities.PageOnPreLoad(
             Context,
             logOnRequired,
             IsMra,
             ApplicationId);
 }
 /// <summary> 
 /// Cleans the application's session of HealthVault information and 
 /// then repopulates it using the specified authentication token.
 /// </summary>
 /// 
 /// <param name="authToken">
 /// The authentication to use to populate the session with HealthVault
 /// information.
 /// </param>
 /// 
 /// <exception cref="HealthServiceException">
 /// If HealthVault returns an error when getting information
 /// about the person in the <paramref name="authToken"/>.
 /// </exception>
 /// 
 public void RefreshAndPersist(string authToken)
 {
     _personInfo =
         WebApplicationUtilities.RefreshAndSavePersonInfoToCookie(Context, authToken);
 }
 public void RefreshAndPersist()
 {
     _personInfo =
         WebApplicationUtilities.RefreshAndSavePersonInfoToCookie(Context, _personInfo);
 }
        /// <summary>
        /// Creates a new instance of the PersonInfo class using
        /// the specified XML.
        /// </summary>
        /// 
        /// <param name="connection">
        /// An <see cref="ApplicationConnection"/> for the current user. The 
        /// connection can be optionally supplied, but it is overwritten if 
        /// the connection information is in the XML.
        /// </param>
        /// 
        /// <param name="navigator">
        /// The XML containing the person information.
        /// </param>
        /// 
        /// <returns>
        /// A new instance of <see cref="PersonInfo"/> populated with the
        /// person information.
        /// </returns>
        /// 
        /// <exception cref="ArgumentNullException">
        /// The <paramref name="navigator"/> parameter is <b>null</b> or 
        /// <paramref name="connection"/> is <b>null</b> and the XML does not 
        /// contain the connection information.
        /// </exception>
        /// 
        internal static PersonInfo CreateFromXmlExcludeUrl(
            ApplicationConnection connection,
            XPathNavigator navigator)
        {
            Validator.ThrowIfNavigatorNull(navigator);

            PersonInfo personInfo = new PersonInfo(connection);
            personInfo.ParseXmlExcludeUrl(navigator);
            return personInfo;
        }
Exemple #14
0
        /// <summary>
        /// Create a new step to HealthVault
        /// </summary>
        public static bool SaveStepsToHV(PersonInfo info, DateTime dateRecorded,
            long steps, ProfileModel profile)
        {
            ApproximateDateTime hvDate = new ApproximateDateTime(
                new ApproximateDate(dateRecorded.Year, dateRecorded.Month, dateRecorded.Day),
                new ApproximateTime(
                    dateRecorded.Hour, dateRecorded.Minute, dateRecorded.Second));

            Exercise newData = new Exercise(hvDate,
                new CodableValue("walk", new CodedValue("walk", "aerobic-activities")));

            newData.Details.Add(ExerciseDetail.Steps_count,
                new ExerciseDetail(new CodedValue(ExerciseDetail.Steps_count, "exercise-detail-names"),
                    new StructuredMeasurement(
                        (double)steps,
                        new CodableValue("Count", new CodedValue("Count", "exercise-units")))));

            if (profile.UserCtx.user_stride > 0)
            {
                double? distance = DataConversion.GetDistanceFromSteps(profile.UserCtx.user_stride,
                    steps);
                if (distance.HasValue && distance.Value > 0)
                {
                    newData.Distance = new Length(DataConversion.ConvertMilesToMeters(distance.Value));
                }

                if (profile.UserCtx.user_weight > 0)
                {
                    newData.Details.Add(ExerciseDetail.CaloriesBurned_calories,
                        new ExerciseDetail(new CodedValue(ExerciseDetail.CaloriesBurned_calories, "exercise-detail-names"),
                            new StructuredMeasurement(
                                DataConversion.GetEnergyFromSteps(profile.UserCtx.user_stride,
                                profile.UserCtx.user_weight, (int)steps).Value,
                                new CodableValue("Calories", new CodedValue("Calories", "exercise-units")))
                        ));
                }
            }
            info.SelectedRecord.NewItem(newData);
            return true; //Success
        }
Exemple #15
0
        /// <summary>
        /// Create a new miles to HealthVault
        /// </summary>
        public static bool SaveMilesToHV(PersonInfo info, DateTime dateRecorded,
            double distance, ProfileModel profile)
        {
            ApproximateDateTime hvDate = new ApproximateDateTime(
                new ApproximateDate(dateRecorded.Year, dateRecorded.Month, dateRecorded.Day),
                new ApproximateTime(
                    dateRecorded.Hour, dateRecorded.Minute, dateRecorded.Second));

            Exercise newData = new Exercise((ApproximateDateTime)hvDate,
                new CodableValue("walk", new CodedValue("walk", "aerobic-activities")));

            DisplayValue hvDisplay = new DisplayValue(distance, "Miles");

            //convert miles into meters
            if (distance > 0)
            {
                newData.Distance = new Length(DataConversion.ConvertMilesToMeters(distance),
                    hvDisplay);
            }

            if (profile.UserCtx.user_stride > 0)
                newData.Details.Add(ExerciseDetail.Steps_count,
                    new ExerciseDetail(new CodedValue(ExerciseDetail.Steps_count, "exercise-detail-names"),
                        new StructuredMeasurement(
                            DataConversion.GetStepsFromDistanceAndStride(distance, profile.UserCtx.user_stride),
                            new CodableValue("Count", new CodedValue("Count", "exercise-units")))));

            if (profile.UserCtx.user_weight > 0)
                newData.Details.Add(ExerciseDetail.CaloriesBurned_calories,
                    new ExerciseDetail(new CodedValue(ExerciseDetail.CaloriesBurned_calories, "exercise-detail-names"),
                        new StructuredMeasurement(
                            DataConversion.GetEnergyFromDistanceAndWeightNotNullable(distance, profile.UserCtx.user_weight),
                            new CodableValue("Calories", new CodedValue("Calories", "exercise-units")))
                            ));

            info.SelectedRecord.NewItem(newData);
            return true; //Success
        }
        private static string PersonInfoAsCookie(PersonInfo personInfo, bool keepSizeUnderLimit)
        {
            string cookie = PersonInfoAsCookie(personInfo, PersonInfo.CookieOptions.Default);

            if (cookie.Length <= CookieMaxSize || !keepSizeUnderLimit)
            {
                return cookie;
            }

            // The cookie is too big to fit. Try it without app settings...
            cookie = PersonInfoAsCookie(personInfo, PersonInfo.CookieOptions.MinimizeApplicationSettings);
            if (cookie.Length <= CookieMaxSize)
            {
                return cookie;
            }

            // That didn't help. Try it with minimal records...
            cookie = PersonInfoAsCookie(personInfo, PersonInfo.CookieOptions.MinimizeRecords);
            if (cookie.Length <= CookieMaxSize)
            {
                return cookie;
            }

            // Reduce both...
            cookie = PersonInfoAsCookie(
                            personInfo,
                            PersonInfo.CookieOptions.MinimizeApplicationSettings |
                            PersonInfo.CookieOptions.MinimizeRecords);
            return cookie;
        }
        private static string PersonInfoAsCookie(PersonInfo personInfo, PersonInfo.CookieOptions cookieOptions)
        {
            string personInfoXml = personInfo.GetXmlForCookie(cookieOptions);

            int version = GetMarshalCookieVersion();
            switch (version)
            {
                case 1:
                    return "1:" + MarshalCookieVersion1(personInfoXml);
                case 2:
                    return "2:" + MarshalCookieVersion2(personInfoXml);
                default:
                    throw new ArgumentException(
                        ResourceRetriever.FormatResourceString(
                            "UnknownCookieVersion",
                            version));
            }
        }
 /// <summary>
 /// Handles the PreLoad event for the page.
 /// </summary>
 /// 
 /// <param name="e">
 /// Event arguments for the event.
 /// </param>
 /// 
 /// <remarks>
 /// The base implementation calls <see cref="WebApplicationUtilities.PageOnPreLoad(HttpContext,bool)"/>
 /// and then calls the 
 /// <see cref='System.Web.UI.Page.OnPreLoad(EventArgs)'/>.
 /// 
 /// If a derived class overrides this method, it must call the base 
 /// implementation so that the user data gets initialized.
 /// </remarks>
 /// 
 protected override void OnPreLoad(EventArgs e)
 {
     _personInfo =
         WebApplicationUtilities.PageOnPreLoad(
             Context,
             LogOnRequired,
             IsMra,
             ApplicationId);
     base.OnPreLoad(e);
 }
        private static HttpCookie SavePersonInfoToCookie(
            PersonInfo personInfo,
            HttpCookie existingCookie,
            int cookieTimeout)
        {
            HttpCookie cookie =
                new HttpCookie(HealthWebApplicationConfiguration.Current.CookieName);
            cookie.HttpOnly = true;
            cookie.Secure = HealthWebApplicationConfiguration.Current.UseSslForSecurity;

            if (personInfo == null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }
            else
            {
                if (cookieTimeout > 0)
                {
                    // If a greater than zero cookie timeout is in the
                    // query, then it means the user wishes the
                    // persist their auth token. Use this value.
                    cookieTimeout = Math.Min(
                        cookieTimeout,
                        HealthWebApplicationConfiguration.Current.MaxCookieTimeoutMinutes);

                    // Save the absolute expiration in the cookie. This
                    // is when the auth token itself expires.
                    // Therefore, we do not want this to be a sliding
                    // expiration. We want the cookie expiration to
                    // match the auth token expiration. Whenever the
                    // cookie is re-written, we need to preserve the
                    // expiration date of that cookie.
                    cookie.Expires =
                        DateTime.Now.AddMinutes(cookieTimeout);
                    cookie[WcTokenExpiration] =
                        cookie.Expires.ToUniversalTime().ToString();
                }
                else if (existingCookie != null)
                {
                    // If we do not have an explicit cookie timeout to
                    // set but have an existing cookie, then we want
                    // to preserve the expiration on the new cookie.
                    string expirationString =
                        existingCookie[WcTokenExpiration];

                    // If the expiration was not set in the existing
                    // cookie, then it is a session cookie. Do not
                    // overwrite the expiration on it.
                    if (!String.IsNullOrEmpty(expirationString))
                    {
                        DateTime expiration;

                        if (!DateTime.TryParse(expirationString, out expiration))
                        {
                            // Somehow the expiration cookie value
                            // failed to parse. Set it to the
                            // web.config timeout value.
                            cookieTimeout =
                                HealthWebApplicationConfiguration.Current.CookieTimeoutMinutes;

                            if (cookieTimeout > 0)
                            {
                                cookie.Expires =
                                    DateTime.Now.AddMinutes(cookieTimeout);
                                cookie[WcTokenExpiration] =
                                    cookie.Expires.ToUniversalTime().ToString();
                            }
                        }
                        else
                        {
                            cookie.Expires = expiration.ToLocalTime();
                            cookie[WcTokenExpiration] =
                                cookie.Expires.ToUniversalTime().ToString();
                        }
                    }
                }
                else
                {
                    // We do not have an explicit cookie timeout to
                    // set and no exiting cookie. Set the cookie
                    // timeout to the one in web.config.
                    cookieTimeout =
                        HealthWebApplicationConfiguration.Current.CookieTimeoutMinutes;

                    if (cookieTimeout > 0)
                    {
                        // We only set the expiration if it is not a
                        // session cookie.
                        // NOTE: We do not write the expiration date
                        // out to the cookie to preserve existing
                        // behavior.
                        cookie.Expires = DateTime.Now.AddMinutes(cookieTimeout);
                    }
                }

                cookie[WcTokenPersonInfo]
                    = PersonInfoAsCookie(personInfo);
            }

            if (!String.IsNullOrEmpty(HealthWebApplicationConfiguration.Current.CookieDomain))
            {
                cookie.Domain = HealthWebApplicationConfiguration.Current.CookieDomain;
            }

            if (!String.IsNullOrEmpty(HealthWebApplicationConfiguration.Current.CookiePath))
            {
                cookie.Path = HealthWebApplicationConfiguration.Current.CookiePath;
            }

            return cookie;
        }
        /// <summary> 
        /// Cleans the application's session of HealthVault information and 
        /// then repopulates it.
        /// </summary>
        /// 
        /// <param name="context">
        /// The current request context.
        /// </param>
        /// 
        /// <param name="personInfo">
        /// The information about the authenticated person that needs refreshing.
        /// </param>
        /// 
        /// <exception cref="InvalidOperationException">
        /// If a person isn't logged on when this is called.
        /// </exception>
        /// 
        /// <remarks>
        /// This method should be called anytime an action occurs that will affect the 
        /// <see cref="PersonInfo"/> object for the authenticated person. This includes changing
        /// the person's authorization for the application or changing the selected record.
        /// </remarks>
        /// 
        public static PersonInfo RefreshAndSavePersonInfoToCookie(
            HttpContext context, 
            PersonInfo personInfo)
        {
            Validator.ThrowInvalidIfNull(personInfo, "PersonNotLoggedIn");

            personInfo = HealthVaultPlatform.GetPersonInfo(personInfo.ApplicationConnection);

            SavePersonInfoToCookie(context, personInfo);
            return personInfo;
        }
 /// <summary>
 /// Stores the specified person's information in the cookie.
 /// </summary>
 /// 
 /// <param name="context">
 /// The current request context.
 /// </param>
 /// 
 /// <param name="personInfo">
 /// The authenticated person's information.
 /// </param>
 /// 
 /// <remarks>
 /// If <paramref name="personInfo"/> is null, this call will not clear the cookie.
 /// </remarks>
 /// 
 public static void SavePersonInfoToCookie(HttpContext context, PersonInfo personInfo)
 {
     SavePersonInfoToCookie(context, personInfo, false);
 }
 /// <summary>
 /// Stores the specified person's information in the cookie.
 /// </summary>
 /// 
 /// <param name="context">
 /// The current request context.
 /// </param>
 /// 
 /// <param name="personInfo">
 /// The person's information to store. If null and <paramref name="clearIfNull"/> is true,
 /// the cookie will be cleared and the person will be logged off from HealthVault.
 /// </param>
 /// 
 /// <param name="clearIfNull">
 /// If true and <paramref name="personInfo"/> is null, the cookie will be cleared and the
 /// person will be logged off from HealthVault.
 /// </param>
 /// 
 public static void SavePersonInfoToCookie(
     HttpContext context,
     PersonInfo personInfo,
     bool clearIfNull)
 {
     SavePersonInfoToCookie(context, personInfo, clearIfNull, -1);
 }
        private void SaveUser(PersonInfo personInfo, string token)
        {
            // create a new context
            var context = new HVDbContext();

            // check if the user already exists
            var user = (from t in context.HealthVaultUsers
                        where t.PersonId.Equals(personInfo.PersonId)
                        select t).FirstOrDefault();

            if (user == null)
            {
                // add user to collection
                context.HealthVaultUsers.Add(new HealthVaultUser()
                {
                    HealthRecordState = personInfo.SelectedRecord.State.ToString(),
                    Name = personInfo.SelectedRecord.Name,
                    PersonId = personInfo.PersonId,
                    RecordId = personInfo.SelectedRecord.Id,
                    WCToken = token,
                    PersonInfoObject = personInfo.GetXml()
                });
            }
            else
            {
                // update the user
                user.HealthRecordState = personInfo.SelectedRecord.State.ToString();
                user.Name = personInfo.SelectedRecord.Name;
                user.PersonId = personInfo.PersonId;
                user.RecordId = personInfo.SelectedRecord.Id;
                user.WCToken = token;
                user.PersonInfoObject = personInfo.GetXml();
            }

            // save the record
            context.SaveChanges();
        }
Exemple #24
0
        public static HealthRecordItemCollection GetHVItemsOnline(PersonInfo info, DateTime? lastSync)
        {
            HealthRecordSearcher searcher = info.SelectedRecord.CreateSearcher();

            HealthRecordFilter filter = new HealthRecordFilter(Exercise.TypeId,
                AerobicSession.TypeId);

            if (lastSync.HasValue)
                filter.UpdatedDateMin = (DateTime)lastSync;

            // TODO: Add filter so that we get only items with steps
            searcher.Filters.Add(filter);
            HealthRecordItemCollection items = searcher.GetMatchingItems()[0];

            return items;
        }