Inheritance: System.Web.Services.WebService
        private ProfileService CreateProfileService()
        {
            var userID         = Guid.Parse(User.Identity.GetUserId());
            var profileService = new ProfileService(userID);

            return(profileService);
        }
Esempio n. 2
0
        public ActionResult LiveId(string action, string stoken)
        {
            var user = Wll.ProcessLogin(Request.Form);

            if (user != null)
            {
                HalfoxUser.Value  = user.Token;
                HalfoxUser.OpenId = user.Id;
                HalfoxUser.IdType = "live";
                var currentProfile = ProfileService.GetInstance().Get();
                if (currentProfile != null)
                {
                    HalfoxUser.Name = currentProfile.NickName ?? "Please setting your profile.";
                    HalfoxUser.Role = currentProfile.Role;
                    HalfoxUser.Id   = currentProfile.Id;
                }
                if (user.UsePersistentCookie)
                {
                    HalfoxUser.Expires = PersistCookie;
                }
            }
            else
            {
                HalfoxUser.Expires = ExpireCookie;
            }
            return(RedirectToAction("Index", "home"));
        }
        public IHttpActionResult GetAll(int TeamID)
        {
            ProfileService profileService = CreateProfileService();
            var            profile        = profileService.GetAllProfilesByTeam(TeamID);

            return(Ok(profile));
        }
Esempio n. 4
0
        // Carry over profile property values from an anonymous to an authenticated state 
        protected void Profile_MigrateAnonymous(Object sender, ProfileMigrateEventArgs e)
        {
            Profile anonymousProfile = PB.ProfileManager.Instance.GetAnonymousUser();
            Profile profile = PB.ProfileManager.Instance.GetCurrentUser(e.Context.User.Identity.Name);

            //Merge anonymous shopping cart items to the authenticated shopping cart items
            foreach (Cart item in anonymousProfile.CartCollection)
                profile.CartCollection.Add(new Cart() { ItemId = item.ItemId, UniqueId = profile.UniqueId, IsShoppingCart = true, Quantity = item.Quantity});

            //Merge anonymous wishlist items to the authenticated wishlist items
            foreach (Cart item in anonymousProfile.WishList)
                profile.WishList.Add(new Cart() { ItemId = item.ItemId, UniqueId = profile.UniqueId, IsShoppingCart = false, Quantity = item.Quantity });


            var profileService = new ProfileService();
            profileService.DeepSave(profile);

            // Clean up anonymous profile
            ProfileManager.DeleteProfile(e.AnonymousID);
            AnonymousIdentificationModule.ClearAnonymousIdentifier();

            //Clear the cart.
            anonymousProfile.CartCollection.Clear();
            anonymousProfile.WishList.Clear();
            profileService.DeepSave(anonymousProfile);
        }
Esempio n. 5
0
        /// <summary>
        /// Delete profile entry view
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DeleteProfileEntry(int id)
        {
            ProfileService svc = new ProfileService();

            svc.DeleteBlogRecord(id);
            return(Redirect("/Account/ProfileTool?GUID=" + AdminToolsGUID));
        }
 public AuthenticationController(SignInManager <ApplicationUser> signInManager, UserManager <ApplicationUser> userManager, IConfigurationRoot configuration, ProfileService profileService)
 {
     this.signInManager  = signInManager;
     this.userManager    = userManager;
     this.configuration  = configuration;
     this.profileService = profileService;
 }
Esempio n. 7
0
        /// <summary>
        /// Gets the page details instance.
        /// </summary>
        /// <param name="userId">User Id for whom page is rendered</param>
        /// <param name="entityType">Entity Type (Community/Content)</param>
        /// <param name="currentPage">Selected page to be rendered</param>
        /// <returns>Page details instance</returns>
        private PageDetails GetPageDetails(long userId, EntityType entityType, int currentPage)
        {
            var pageDetails = new PageDetails(currentPage);

            pageDetails.ItemsPerPage = Constants.EntitiesPerUser;

            var totalItemsForCondition = 0;

            switch (entityType)
            {
            case EntityType.Community:
                totalItemsForCondition = ProfileService.GetCommunitiesCount(userId, userId != CurrentUserId);
                break;

            case EntityType.Content:
                totalItemsForCondition = ProfileService.GetContentsCount(userId, userId != CurrentUserId);
                break;

            default:
                break;
            }

            pageDetails.TotalPages  = (totalItemsForCondition / pageDetails.ItemsPerPage) + ((totalItemsForCondition % pageDetails.ItemsPerPage == 0) ? 0 : 1);
            pageDetails.CurrentPage = currentPage > pageDetails.TotalPages ? pageDetails.TotalPages : currentPage;
            pageDetails.TotalCount  = totalItemsForCondition;

            return(pageDetails);
        }
Esempio n. 8
0
 /// <summary>
 /// </summary>
 /// <param name="profileService">
 /// </param>
 public UserSettingsViewModel(ProfileService profileService)
 {
     this.profileService        = profileService;
     this.Title                 = "settings";
     this.LoginLabelText        = StringResources.Command_Login;
     this.ResetLabelText        = StringResources.Command_Logout;
     this.SignupLabelText       = StringResources.Command_CreateAccount;
     this.UserNameLabelText     = StringResources.Label_UserName;
     this.PasswordLabelText     = StringResources.Label_Password;
     this.PlayNextMixText       = StringResources.Label_PlayNextMix;
     this.PreferredListText     = StringResources.Label_PreferredList;
     this.CensorshipEnabledText = StringResources.Label_CensorshipEnabled;
     this.PlayOverWifiOnlyText  = StringResources.Label_PlayOverWifiOnly;
     this.CanLogin              = false;
     this.IsLoggedIn            = false;
     this.SignupCommand         = new DelegateCommand(this.Signup);
     this.LoginCommand          = new DelegateCommand(this.SignIn, this.CanSignIn);
     this.ResetCommand          = new DelegateCommand(this.SignOut, this.CanSignOut);
     this.RegisterErrorHandler <ServiceException>(this.HandleSignInWebException);
     this.PreferredListChoices = new ObservableCollection <string>();
     foreach (var item in this.preferredListMap)
     {
         this.PreferredListChoices.Add(item.Value);
     }
 }
        /// <summary>
        /// Trailer Selected
        /// </summary>
        /// <param name="sender">Sender.</param>
        /// <param name="e">E.</param>
        void OnTrailerSelected(object sender, AdapterView.ItemSelectedEventArgs e)
        {
            _trailer = _trailers[e.Position];
            ProfileService.SetCurrentTrailer(_repository, _trailer);

            RefreshTrailer();
        }
Esempio n. 10
0
 /// <summary>
 /// Initializes ActiveProfile.
 /// </summary>
 /// <remarks>
 /// ActiveProfile is needed throughout the site and it comes from mvc controllers.
 /// </remarks>
 public ChefMvcController()
 {
     _profileService = new ProfileService();
     _currentUserName = SiteContext.Current.UserName;
     var activeProfileVM = ActiveProfileVM.Map(_profileService.GetProfile(_currentUserName));
     ViewBag.ActiveProfile = WebHelper.ToJson(activeProfileVM);
 }
        public void If_role_parameter_empty_reset_user_roles()
        {
            #region Arrange

            var roleProvider = _mocker.DynamicMock <IRoleProvider>();
            var profile      = new ProfileModelDto {
                Role = "", LoginName = "user"
            };
            var service = new ProfileService(roleProvider);

            #endregion

            #region Act
            using (_mocker.Record())
            {
                Expect.Call(roleProvider.GetRolesForUser("user")).Return(new[] { "unusedRole" });
                Expect.Call(() => roleProvider.RemoveUserFromRole("user", "unusedRole"));
            }

            using (_mocker.Playback())
            {
                service.UpdateRole(profile, false);
            }

            #endregion
        }
Esempio n. 12
0
        public async Task CreatePurchaser()
        {
            Purchaser purchaser = new Purchaser()
            {
                CountryId = Id,
                Profile   = new Profile()
            };

            purchaser.Profile.Username = Email;
            purchaser.Profile.Password = "******";
            purchaser.Profile.Usertype = 1;

            Profile testProfile = await ProfileService.GetProfileByUsernameAndpassword(purchaser.Profile.Username, purchaser.Profile.Password);

            if (testProfile.Username == "")
            {
                await PurchaserService.CreatePurchaser(purchaser);

                NavigationManager.NavigateTo($"/user_view/{Id}", true);
            }
            else
            {
                _userAlreadyExists = $"A purchaser with the email '{Email}' already exists";
            }
        }
Esempio n. 13
0
        public async Task SaveUserData()
        {
            var userAndProfile = new UserAndProfileModel
            {
                UserName  = IdentityPage.UserName,
                Password  = IdentityPage.Password,
                Gender    = GenderPage.Gender == false ? "Male" : "Female",
                BirthDate = UserPage.BirthDate,
                FirstName = UserPage.FirstName,
                LastName  = UserPage.LastName,
                Email     = AccountPage.Email,
                Skype     = AccountPage.Skype,
                TenantId  = GlobalSettings.TenantId
            };

            var result = await ProfileService.SignUpAsync(userAndProfile);

            if (result != null)
            {
                bool isAuthenticated =
                    await AuthenticationService.LoginAsync(userAndProfile.UserName, userAndProfile.Password);


                if (isAuthenticated)
                {
                    await Nav.Go <Home>();
                }
                else
                {
                    await Alert.Show("Invalid credentials", "Login failure");
                }
            }
        }
 public void SetUp()
 {
     _service = new ProfileService();
     TestUtils.Create_Auth_User();
     TestUtils.Create_Target_User();
     _targetUserId = _service.GetProfile(Actor.TARGET_USER).Id;
 }
Esempio n. 15
0
        /// <summary>
        /// Gets a user by the username.
        /// </summary>
        /// <param name="username">the username.</param>
        /// <returns>The user if it is found, otherwise returns the anonymous user.</returns>
        public Profile GetCurrentUser(string username)
        {
            //Make sure the username is not empty.
            if (string.IsNullOrEmpty(username.Trim()))
            {
                username = _ANONYMOUS_USERNAME;
            }

            //Get the profile.
            var profileService = new ProfileService();
            Profile profile = profileService.DeepLoadByUsernameApplicationName(username, ".NET Pet Shop 4.0", true, DeepLoadType.IncludeChildren, new Type[] { typeof(Cart) });

            //Check to see if the profile exists.
            if (profile == null)
            {
                //If the username is the Anonymous user then create it.
                if (username == _ANONYMOUS_USERNAME)
                    return CreateUser(username, true);

                return CreateUser(username, false);
            }

            //return profile.
            return profile;
        }
Esempio n. 16
0
        public ActionResult WriteTestimonial(Testimonial postedTestimonial)
        {
            this.profileService = new ProfileService(this.documentDbAccess);
            this.ViewBag.TestimonialSubmitted = false;
            this.ViewBag.KeyMatchFailed       = false;
            if (!this.ModelState.IsValid)
            {
                return(this.View(postedTestimonial));
            }

            if (
                !string.Equals(
                    postedTestimonial.AuthorToken.Trim(),
                    WebConfigurationManager.AppSettings[ApplicationConstants.TestimonialToken],
                    StringComparison.OrdinalIgnoreCase))
            {
                this.ViewBag.KeyMatchFailed = true;
                return(this.View(postedTestimonial));
            }

            postedTestimonial.TestimonialId = DateTime.UtcNow.Ticks;
            postedTestimonial.IsApproved    = false;
            postedTestimonial.IsFeatured    = false;
            this.profileService.CleanseTestimonial(ref postedTestimonial);
            this.profileService.AddDocument(postedTestimonial);
            this.TempData["TestimonialSubmitted"] = true;
            return(this.RedirectToRoute("Profile", new { controller = "Profile", action = "WriteTestimonial" }));
        }
Esempio n. 17
0
        /// <summary>
        /// Gets a user by the username.
        /// </summary>
        /// <param name="username">the username.</param>
        /// <returns>The user if it is found, otherwise returns the anonymous user.</returns>
        public Profile GetCurrentUser(string username)
        {
            //Make sure the username is not empty.
            if (string.IsNullOrEmpty(username.Trim()))
            {
                username = _ANONYMOUS_USERNAME;
            }

            //Get the profile.
            var     profileService = new ProfileService();
            Profile profile        = profileService.DeepLoadByUsernameApplicationName(username, ".NET Pet Shop 4.0", true, DeepLoadType.IncludeChildren, new Type[] { typeof(Cart) });

            //Check to see if the profile exists.
            if (profile == null)
            {
                //If the username is the Anonymous user then create it.
                if (username == _ANONYMOUS_USERNAME)
                {
                    return(CreateUser(username, true));
                }

                return(CreateUser(username, false));
            }

            //return profile.
            return(profile);
        }
Esempio n. 18
0
        public ActionResult ChangeProfilePic()
        {
            var service = new ProfileService(null);
            var model   = service.GetProfileEntity(User.Identity.GetUserId());

            return(View("ChangeProfilePic", model));
        }
Esempio n. 19
0
        public async Task <JsonResult> New()
        {
            if (CurrentUserId == 0)
            {
                await TryAuthenticateFromHttpContext(_communityService, _notificationService);
            }
            var result = SessionWrapper.Get <LiveLoginResult>("LiveConnectResult");

            if (result != null && result.Status == LiveConnectSessionStatus.Connected)
            {
                var profileDetails = SessionWrapper.Get <ProfileDetails>("ProfileDetails");

                // While creating the user, IsSubscribed to be true always.
                profileDetails.IsSubscribed = true;

                // When creating the user, by default the user type will be of regular.
                profileDetails.UserType = UserTypes.Regular;

                profileDetails.ID = ProfileService.CreateProfile(profileDetails);
                SessionWrapper.Set("CurrentUserID", profileDetails.ID);
                CreateDefaultUserCommunity(profileDetails.ID);

                // Send New user notification.
                _notificationService.NotifyNewEntityRequest(profileDetails, HttpContext.Request.Url.GetServerLink());
                return(new JsonResult {
                    Data = profileDetails
                });
            }
            return(Json("error: User not logged in"));
        }
Esempio n. 20
0
        private void writeToSellerClicked(object sender, RoutedEventArgs e)
        {
            FarmersMarketContext context        = new FarmersMarketContext((Application.Current as App).ConnectionString);
            ChatService          chatService    = new ChatService(context);
            ProfileService       profileService = new ProfileService(context);

            Chat chat;

            if ((Application.Current as App).currentUser == null)
            {
                MessageBox.Show("Вы не авторизованы в системе");
                return;
            }
            if (chatService.Get(SellerId, profileService.GetCustomer((Application.Current as App).currentUser).Id) == null)             // Если чата нет
            {
                chat = new Chat
                {
                    SellerId   = SellerId,
                    CustomerId = profileService.GetCustomer((Application.Current as App).currentUser).Id
                };
                chatService.Create(chat.SellerId, chat.CustomerId);
            }
            else             // если чат есть
            {
                chat = chatService.Get(SellerId, profileService.GetCustomer((Application.Current as App).currentUser).Id);
            }

            ChatWindow chatWindow = new ChatWindow(chat);

            chatWindow.ShowDialog();
        }
Esempio n. 21
0
        /// <summary>
        /// It returns the entity list
        /// </summary>
        /// <param name="userId">User Id for whom page is rendered</param>
        /// <param name="entityType">Entity type (Community/Content)</param>
        /// <param name="pageDetails">Details about the pagination</param>
        /// <returns>List of entity objects</returns>
        private async Task <List <EntityViewModel> > GetEntities(long userId, EntityType entityType, PageDetails pageDetails)
        {
            // TODO: Need to create a model for passing parameters to this controller
            var highlightEntities = new List <EntityViewModel>();

            if (entityType == EntityType.Community)
            {
                var communities = ProfileService.GetCommunities(userId, pageDetails, userId != CurrentUserId);
                foreach (var community in communities)
                {
                    var communityViewModel = new CommunityViewModel();
                    Mapper.Map(community, communityViewModel);
                    highlightEntities.Add(communityViewModel);
                }
            }
            else if (entityType == EntityType.Content)
            {
                var contents = ProfileService.GetContents(userId, pageDetails, userId != CurrentUserId);
                foreach (var content in contents)
                {
                    var contentViewModel = new ContentViewModel();
                    contentViewModel.SetValuesFrom(content);
                    highlightEntities.Add(contentViewModel);
                }
            }

            return(highlightEntities);
        }
Esempio n. 22
0
        //[OutputCache(Duration = 3600 * 6, VaryByParam = "none")]
        public ActionResult SiteMapXml()
        {
            Response.ContentType = "text/xml";
            var model = ProfileService.GetAllProfileGuids();

            return(View(model));
        }
        public async Task <TableLayoutPanel> GetLayoutPanelAsync(User i_LoggedInUser)
        {
            AppConfigService appConfigService = AppConfigService.GetInstance();
            IProfileService  profileService   = new ProfileService();
            ProfileModel     userPorfile      = await profileService.GetUserProfileAsync(i_LoggedInUser);

            TableLayoutPanel panel = new TableLayoutPanel {
                ColumnCount = 2, AutoSize = true, Padding = new Padding(10)
            };

            panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize, 40F));
            panel.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize, 40F));
            panel.RowStyles.Add(new RowStyle(SizeType.AutoSize, 50F));

            int       tempRowIndex          = 0;
            const int k_PropertyColumnIndex = 0;
            const int k_DetailsColumnIndex  = 1;

            foreach (KeyValuePair <string, string> propertyForDisplay in userPorfile.GetPropertiesForDisplay())
            {
                panel.Controls.Add(new Label {
                    Font = new Font(AppUtil.sr_FontFamily, appConfigService.LabelFontSize, FontStyle.Bold), Text = propertyForDisplay.Key, AutoSize = true
                }, k_PropertyColumnIndex, tempRowIndex);
                panel.Controls.Add(new Label {
                    Font = new Font(AppUtil.sr_FontFamily, appConfigService.LabelFontSize), Text = propertyForDisplay.Value, AutoSize = true
                }, k_DetailsColumnIndex, tempRowIndex);
                tempRowIndex++;
            }
            return(panel);
        }
Esempio n. 24
0
        /// <summary>
        /// Rockstar View
        /// </summary>
        /// <returns></returns>
        public ActionResult Rockstar()
        {
            ProfileService         svc   = new ProfileService();
            List <RockstarProfile> model = svc.ReadAllProfiles();

            return(View(model));
        }
Esempio n. 25
0
        public ActionResult EditProfileEntry(RockstarProfile model, HttpPostedFileBase file, HttpPostedFileBase popupFile)
        {
            ProfileService svc = new ProfileService();

            svc.EditProfileRecord(model, file, popupFile);
            return(Redirect("/Account/ProfileTool?GUID=" + AdminToolsGUID));
        }
Esempio n. 26
0
        private PointsSummary GetPointsSummaryData(PointsSummary model)
        {
            DebugUtils.StartLogEvent("OwnerController.GetPointsSummaryData");
            BlueGreenContext bgContext = new BlueGreenContext();
            string           ownerId   = bgContext.OwnerId;

            model.AnnualPoints     = "0";
            model.SavedPoints      = "0";
            model.RestrictedPoints = "0";
            model.AvailablePoints  = "0";
            try
            {
                ProfileService          service = new ProfileService();
                RestOwnerPointsResponse result  = service.GetOwnerPoints(ownerId, null);

                if (result != null && result.Account != null && result.Account.Memberships != null && result.Account.Memberships.VacationClubMembership != null && result.Account.Memberships.VacationClubMembership.Points != null)
                {
                    model.AnnualPoints     = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalAnnualPoints);
                    model.SavedPoints      = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalSavedPoints);
                    model.RestrictedPoints = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalRestrictedPoints);
                    model.AvailablePoints  = FormatUtils.FormatPoints(result.Account.Memberships.VacationClubMembership.Points.TotalPoints);
                }
            } catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("Unexpected exception retreiving points for " + ownerId, ex, bgContext);
            }
            DebugUtils.EndLogEvent("OwnerController.GetPointsSummaryData");


            return(model);
        }
Esempio n. 27
0
        public ActionResult Index(int?key)
        {
            var pageIndex = (key ?? 1);
            int total;
            IEnumerable <Domain.Entities.Profile> profiles;

            if (KatushaProfile == null)
            {
                profiles = ProfileService.GetNewProfiles(p => p.ProfilePhotoGuid != Guid.Empty, out total, pageIndex, DependencyConfig.GlobalPageSize);
            }
            else
            {
                if (KatushaProfile.Gender == (byte)Sex.Female)
                {
                    profiles = ProfileService.GetNewProfiles(p => p.Gender == (byte)Sex.Male, out total, pageIndex, DependencyConfig.GlobalPageSize);
                }
                else
                {
                    profiles = ProfileService.GetNewProfiles(p => p.Gender == (byte)Sex.Female, out total, pageIndex, DependencyConfig.GlobalPageSize);
                }
            }
            var profilesModel        = Mapper.Map <IEnumerable <ProfileModel> >(profiles);
            var profilesAsIPagedList = new StaticPagedList <ProfileModel>(profilesModel, pageIndex, DependencyConfig.GlobalPageSize, total);
            var model = new PagedListModel <ProfileModel> {
                List = profilesAsIPagedList, Total = total
            };

            return(View(model));
        }
Esempio n. 28
0
        private ActionResult ConnectUser(bool rememberMe, string userTokenString)
        {
            var token = JwtHelper.DecodeToken(userTokenString);

            var profileService = new ProfileService(token);

            var    myProfile = profileService.GetMyProfile();
            string userData  = JsonConvert.SerializeObject(new PrincessSerializable()
            {
                Id            = myProfile.Id,
                Picture       = myProfile.Picture,
                PrincessTitle = myProfile.PrincessTitle,
                Token         = userTokenString,
                Username      = myProfile.Username,
                UserHashId    = myProfile.UserHashId
            });

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                1,
                myProfile.UserHashId,
                DateTime.Now,
                DateTime.Now.AddMinutes(15),
                rememberMe, //pass here true, if you want to implement remember me functionality
                userData);

            string     encTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie faCookie  = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);

            Response.Cookies.Add(faCookie);
            return(RedirectToAction("Index", "Profil"));
        }
        public IHttpActionResult Get(Guid UserID)
        {
            ProfileService profileService = CreateProfileService();
            var            profile        = profileService.GetProfile(UserID);

            return(Ok(profile));
        }
Esempio n. 30
0
        public ProfileController(ILogger <HomeController> logger,
                                 LocalizationService localizationService,
                                 StatusService statusService,
                                 ProfileRepository profileRepository,
                                 ContentRepository contentRepository,
                                 AccountRepository accountRepository,
                                 FileStorageService fileStorageService,
                                 IHostingEnvironment environment,
                                 LocalizationRepository localizationRepository,
                                 ViewFieldsRepository viewFieldsRepository,
                                 ProfileService profileService,
                                 EmailService emailService,
                                 CityRepository cityRepository

                                 )
        {
            _logger = logger;
            _localizationService    = localizationService;
            _statusService          = statusService;
            _profileRepository      = profileRepository;
            _contentRepository      = contentRepository;
            _accountRepository      = accountRepository;
            _fileStorageService     = fileStorageService;
            _localizationRepository = localizationRepository;
            _environment            = environment;
            _viewFieldsRepository   = viewFieldsRepository;
            _profileService         = profileService;
            _emailService           = emailService;
            _cityRepository         = cityRepository;
        }
Esempio n. 31
0
        private void OnDoubleClick(ProfileEntry profile)
        {
            Focus(profile);

            ProfileService.Force(profile.Profile);
            OnCancelButtonPressed();
        }
Esempio n. 32
0
 public void LoginAllServices(AccountService accountService, ProfileService profileService, BalanceTransferService balanceTransferService, TransferService transferService)
 {
     accountService.Login(this.client.Authenticator);
     profileService.Login(this.client.Authenticator);
     balanceTransferService.Login(this.client.Authenticator);
     transferService.Login(this.client.Authenticator);
 }
 public MoviesController(ILogger <MoviesController> logger, IOptions <AppSettings> appSettings)
 {
     _movieService   = new MovieService();
     _profileService = new ProfileService();
     _logger         = logger;
     _appSettings    = appSettings.Value;
 }
Esempio n. 34
0
        public void Should_Match_Remaining_Quantity(List <int> ownings, int soldQuantity, int expected)
        {
            var profile = new Profile();

            foreach (var owning in ownings)
            {
                profile.Ownings.Add(new Owning
                {
                    Name             = StockName,
                    PurchaseQuantity = owning,
                    PurchaseDate     = DateTime.UtcNow + new TimeSpan(owning, 0, 0, 0),
                    PurchaseValue    = 10 + owning
                });
            }
            var       service    = new ProfileService(null);
            OwningDto soldOwning = new OwningDto()
            {
                Name             = StockName,
                PurchaseQuantity = soldQuantity,
                SellValue        = 45,
                SellDate         = DateTime.UtcNow
            };

            service.SellFromOwning(profile, soldOwning);
            Assert.Equal(expected, profile.Ownings.Where(x => x.Name == soldOwning.Name).Sum(y => y.PurchaseQuantity));
        }
Esempio n. 35
0
 public ServiceAdapter()
 {
     authServ = new AuthenticationService();
     proServ = new ProfileService();
     dbcServ = new DaybookClientService();
     authServ.CookieContainer = new System.Net.CookieContainer();
     Instance = this;
 }
        public void ProfileTest()
        {
            var target = new ProfileService();

            var actual = target.Profile(2);

            Assert.AreEqual(4, actual);
        }
Esempio n. 37
0
        public PreviewTemplate(string html, EditProfile edit)
        {
            InitializeComponent();

            Profiles = edit.Profiles;
            EditForm = edit;
            Html = html;
        }
Esempio n. 38
0
        public ProfileView(ProfileService profile, ulong id, uint project)
        {
            InitializeComponent();

            Profiles = profile;
            Core = profile.Core;
            Trust = Core.Trust;

            UserID = id;
            ProjectID = project;
        }
Esempio n. 39
0
        public InternalsForm(CoreUI ui)
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            UI = ui;
            Core = ui.Core;

            Boards = Core.GetService(ServiceIDs.Board) as BoardService;
            Mail = Core.GetService(ServiceIDs.Mail) as MailService;
            Profiles = Core.GetService(ServiceIDs.Profile) as ProfileService;

            Text = "Internals (" + Core.Network.GetLabel() + ")";

            treeStructure.Nodes.Add( new StructureNode("", new ShowDelegate(ShowNone), null));

            // core
                // identity
                // networks (global/operation)
                    // cache
                    // logs
                    // routing
                    // search
                    // store
                    // tcp
                // Components
                    // Link
                    // Location
                    // ...
                // rudp
                    // sessions[]

            // core
            StructureNode coreNode = new StructureNode("Core", new ShowDelegate(ShowCore), null);

            // identity
            coreNode.Nodes.Add( new StructureNode(".Identity", new ShowDelegate(ShowIdentity), null));

            // networks
            if(Core.Context.Lookup != null)
                LoadNetwork(coreNode.Nodes, "Lookup", Core.Context.Lookup.Network);

            LoadNetwork(coreNode.Nodes, "Organization", Core.Network);

            // components
            StructureNode componentsNode = new StructureNode("Components", new ShowDelegate(ShowNone), null);
            LoadComponents(componentsNode);
            coreNode.Nodes.Add(componentsNode);

            treeStructure.Nodes.Add(coreNode);
            coreNode.Expand();
        }
Esempio n. 40
0
        public EditProfile(ProfileService control, ProfileView view)
        {
            InitializeComponent();

            Core     = control.Core;
            Links    = Core.Trust;
            Profiles = control;
            MainView = view;

            TextFields = new Dictionary<string, string>(view.TextFields);
            FileFields = new Dictionary<string, string>(view.FileFields);
        }
Esempio n. 41
0
        /// <summary>
        /// Creates the authenticated user.
        /// </summary>
        public static IdentityResult Create_Auth_User()
        {
            ProfileService service = new ProfileService();

            return service.CreateUserProfile(new Profile
            {
                UserName = Actor.AUTH_USER,
                Email = Actor.AUTH_USER + "@notset.com",
                FirstName = "Tom",
                LastName = "Cat",
                Locations = "San Gabriel, CA, USA",
                ProfileStyle = ProfileStyle.GetDefault()
            });
        }
Esempio n. 42
0
        /// <summary>
        /// Creates the target user.
        /// </summary>
        public static IdentityResult Create_Target_User()
        {
            ProfileService service = new ProfileService();

            return service.CreateUserProfile(new Profile
            {
                UserName = Actor.TARGET_USER,
                Email = Actor.TARGET_USER + "@notset.com",
                FirstName = "Jerry",
                LastName = "Mouse",
                Locations = "Pasadena, CA, USA",
                ProfileStyle = ProfileStyle.GetDefault()
            });
        }
 public void SetUp()
 {
     _service = new ProfileService();
     _profile = new Profile()
     {
         UserName = Actor.AUTH_USER,
         Email = "*****@*****.**",
         FirstName = "Tom",
         LastName = "Cat",
         Locations = "Pasadena, CA, USA",
         Headline = "American chef, author, and television personality",
         Bio = "He is a cat chef.",
         BgImg = "A02.jpg",
         ProfileStyle = ProfileStyle.GetDefault(),
     };
 }
 public void SetUp()
 {
     _service = new ProfileService();
     _profile = new Profile()
     {
         UserName = "******", // Note "admin" is a reserved username
         Email = "*****@*****.**",
         FirstName = "admin",
         LastName = "admin",
         Locations = "",
         Headline = "",
         Bio = "",
         BgImg = "A02.jpg",
         ProfileStyle = ProfileStyle.GetDefault(),
     };
 }
    /// <summary>
    /// Execute is called when the user chooses the feature action from the feature actions context menu. Only called if
    /// CanExecute returned true.
    /// </summary>
    public async void Execute(ESRI.ArcGIS.OperationsDashboard.DataSource dataSource, client.Graphic feature)
    {
      //This feature action relies on a profile graph widget to create a graph based on the profile line
      //Check if the view has a ProfileGraphWidget widget to display the output graph
      ProfileGraphFromMap profileWidget = OperationsDashboard.Instance.Widgets.FirstOrDefault(w => w.GetType() == typeof(ProfileGraphFromMap)) as ProfileGraphFromMap;
      if (profileWidget == null)
      {
        MessageBox.Show("Add the Profile Graph Widget to the view to execute this feature action", "Profile Graph Widget Required");
        return;
      }

      //Send the feature to the Elevation Analysis service to get the profile line
      ProfileService service = new ProfileService();
      Profile = await service.GetProfileLine(feature.Geometry);
      if (Profile == null)
      {
        MessageBox.Show("Failed to get elevation profile");
        return;
      }

      //Send the result (Profile) to the profile graph widget and ask it to generate the graph
      profileWidget.MapWidget = MapWidget.FindMapWidget(dataSource);
      profileWidget.Profile = Profile;
      profileWidget.UpdateControls();
    }
Esempio n. 46
0
        private static string FleshMotd(ProfileService service, string template, ulong id, uint project)
        {
            // extract motd template
            string startTag = "<?motd:start?>";
            string nextTag = "<?motd:next?>";

            int start = template.IndexOf(startTag) + startTag.Length;
            int end = template.IndexOf("<?motd:end?>");

            if (end < start)
                return "";

            string motdTemplate = template.Substring(start, end - start);

            // get links in chain up
            List<ulong> uplinks = new List<ulong>();
            uplinks.Add(id);
            uplinks.AddRange(service.Core.Trust.GetUplinkIDs(id, project));
            uplinks.Reverse();

            // build cascading motds
            string finalMotd = "";

            foreach (ulong uplink in uplinks)
            {
                OpProfile upperProfile = service.GetProfile(uplink);

                if (upperProfile != null)
                {
                    Dictionary<string, string> textFields = new Dictionary<string, string>();

                    LoadProfile(service, upperProfile, null, textFields, null);

                    string motdTag = "MOTD-" + project.ToString();
                    if(!textFields.ContainsKey(motdTag))
                        textFields[motdTag] = "No announcements";

                    textFields["MOTD"] = textFields[motdTag];

                    string currentMotd = motdTemplate;
                    currentMotd = FleshTemplate(service, uplink, project, currentMotd, textFields, null);

                    if (finalMotd == "")
                        finalMotd = currentMotd;

                    else if(finalMotd.IndexOf(nextTag) != -1)
                        finalMotd = finalMotd.Replace(nextTag, currentMotd);
                }
            }

            finalMotd = finalMotd.Replace(nextTag, "");

            return finalMotd;
        }
Esempio n. 47
0
        private void Main_Load(object sender, EventArgs e)
        {
            if (Settings.Default.LastFormWasMaximized)
            {
                WindowState = FormWindowState.Maximized;
            }
            else
            {
                if (Settings.Default.LastFormHeight > 0)
                {
                    Height = Settings.Default.LastFormHeight;
                }

                if (Settings.Default.LastFormWidth > 0)
                {
                    Width = Settings.Default.LastFormWidth;
                }
            }
            _profileService = ProfileService.Init();
            _tokenService = new TokenService();
            toggleConfigurationGroup(false);
            toggleProfileButtons(false);
            loadProfiles();
        }
Esempio n. 48
0
 /// <summary>
 /// Deletes the target user.
 /// </summary>
 public static void Delete_Target_User()
 {
     ProfileService service = new ProfileService();
     service.DeleteProfile(Actor.TARGET_USER);
 }
Esempio n. 49
0
        public static string FleshTemplate(ProfileService service, ulong id, uint project, string template, Dictionary<string, string> textFields, Dictionary<string, string> fileFields)
        {
            string final = template;

            // get link
            OpLink link = service.Core.Trust.GetLink(id, project);

            if (link == null)
                return "";

            // replace fields
            while (final.Contains("<?"))
            {
                // get full tag name
                int start = final.IndexOf("<?");
                int end = final.IndexOf("?>");

                if (end == -1)
                    break;

                string fulltag = final.Substring(start, end + 2 - start);
                string tag = fulltag.Substring(2, fulltag.Length - 4);

                string[] parts = tag.Split(new char[] { ':' });

                bool tagfilled = false;

                if (parts.Length == 2)
                {

                    if (parts[0] == "text" && textFields.ContainsKey(parts[1]))
                    {
                        final = final.Replace(fulltag, textFields[parts[1]]);
                        tagfilled = true;
                    }

                    else if (parts[0] == "file" && fileFields != null && fileFields.ContainsKey(parts[1]) )
                    {
                        string path = fileFields[parts[1]];

                        if (File.Exists(path))
                        {
                            path = "file:///" + path;
                            path = path.Replace(Path.DirectorySeparatorChar, '/');
                            final = final.Replace(fulltag, path);
                            tagfilled = true;
                        }
                    }

                    // load default photo if none in file
                    else if (parts[0] == "file" && fileFields != null && parts[1] == "Photo")
                    {
                        string path = service.ExtractPath;

                        // create if needed, clear of pre-existing data
                        if (!Directory.Exists(path))
                            Directory.CreateDirectory(path);

                        path += Path.DirectorySeparatorChar + "DefaultPhoto.jpg";
                        ProfileRes.DefaultPhoto.Save(path);

                        if (File.Exists(path))
                        {
                            path = "file:///" + path;
                            path = path.Replace(Path.DirectorySeparatorChar, '/');
                            final = final.Replace(fulltag, path);
                            tagfilled = true;
                        }
                    }

                    else if (parts[0] == "link" && link != null)
                    {
                        tagfilled = true;

                        if (parts[1] == "name")
                            final = final.Replace(fulltag, service.Core.GetName(id));

                        else if (parts[1] == "title")
                        {
                            if (link.Uplink != null && link.Uplink.Titles.ContainsKey(id))
                                final = final.Replace(fulltag, link.Uplink.Titles[id]);
                            else
                                final = final.Replace(fulltag, "");
                        }
                        else
                            tagfilled = false;
                    }

                    else if (parts[0] == "motd")
                    {
                        if (parts[1] == "start")
                        {
                            string motd = FleshMotd(service, template, link.UserID, project);

                            int startMotd = final.IndexOf("<?motd:start?>");
                            int endMotd = final.IndexOf("<?motd:end?>");

                            if (endMotd > startMotd)
                            {
                                endMotd += "<?motd:end?>".Length;

                                final = final.Remove(startMotd, endMotd - startMotd);

                                final = final.Insert(startMotd, motd);
                            }
                        }

                        if (parts[1] == "next")
                            return final;
                    }
                }

                if (!tagfilled)
                    final = final.Replace(fulltag, "");
            }

            return final;
        }
Esempio n. 50
0
 /// <summary>
 /// Deletes the authenticated user.
 /// </summary>
 public static void Delete_Auth_User()
 {
     ProfileService service = new ProfileService();
     service.DeleteProfile(Actor.AUTH_USER);
 }
 public void SetUp()
 {
     _service = new ProfileService();
     _group = _service.CreateGroup(Actor.AUTH_USER, "Test Group");
 }
Esempio n. 52
0
 public ProfileUI(CoreUI ui, OpService service)
 {
     UI = ui;
     Core = ui.Core;
     Profile = service as ProfileService;
 }
Esempio n. 53
0
        private static string LoadProfile(ProfileService service, OpProfile profile, string tempPath, Dictionary<string, string> textFields, Dictionary<string, string> fileFields)
        {
            string template = null;

            textFields.Clear();
            textFields["local_help"] = (profile.UserID == service.Core.UserID) ? "<font size=2>Right-click or click <a href='http://edit'>here</a> to Edit</font>" : "";

            if(fileFields != null)
                fileFields.Clear();

            if (!profile.Loaded)
                service.LoadProfile(profile.UserID);

            try
            {
                using (TaggedStream stream = new TaggedStream(service.GetFilePath(profile), service.Core.GuiProtocol))
                using (IVCryptoStream crypto = IVCryptoStream.Load(stream, profile.File.Header.FileKey))
                {
                    int buffSize = 4096;
                    byte[] buffer = new byte[4096];
                    long bytesLeft = profile.EmbeddedStart;
                    while (bytesLeft > 0)
                    {
                        int readSize = (bytesLeft > (long)buffSize) ? buffSize : (int)bytesLeft;
                        int read = crypto.Read(buffer, 0, readSize);
                        bytesLeft -= (long)read;
                    }

                    // load file
                    foreach (ProfileAttachment attached in profile.Attached)
                    {
                        if (attached.Name.StartsWith("template"))
                        {
                            byte[] html = new byte[attached.Size];
                            crypto.Read(html, 0, (int)attached.Size);

                            UTF8Encoding utf = new UTF8Encoding();
                            template = utf.GetString(html);
                        }

                        else if (attached.Name.StartsWith("fields"))
                        {
                            byte[] data = new byte[attached.Size];
                            crypto.Read(data, 0, (int)attached.Size);

                            int start = 0, length = data.Length;
                            G2ReadResult streamStatus = G2ReadResult.PACKET_GOOD;

                            while (streamStatus == G2ReadResult.PACKET_GOOD)
                            {
                                G2ReceivedPacket packet = new G2ReceivedPacket();
                                packet.Root = new G2Header(data);

                                streamStatus = G2Protocol.ReadNextPacket(packet.Root, ref start, ref length);

                                if (streamStatus != G2ReadResult.PACKET_GOOD)
                                    break;

                                if (packet.Root.Name == ProfilePacket.Field)
                                {
                                    ProfileField field = ProfileField.Decode(packet.Root);

                                    if (field.Value == null)
                                        continue;

                                    if (field.FieldType == ProfileFieldType.Text)
                                        textFields[field.Name] = UTF8Encoding.UTF8.GetString(field.Value);
                                    else if (field.FieldType == ProfileFieldType.File && fileFields != null)
                                        fileFields[field.Name] = UTF8Encoding.UTF8.GetString(field.Value);
                                }
                            }
                        }

                        else if (attached.Name.StartsWith("file=") && fileFields != null)
                        {
                            string name = attached.Name.Substring(5);

                            try
                            {
                                string fileKey = null;
                                foreach (string key in fileFields.Keys)
                                    if (name == fileFields[key])
                                    {
                                        fileKey = key;
                                        break;
                                    }

                                fileFields[fileKey] = tempPath + Path.DirectorySeparatorChar + name;

                                using (FileStream extract = new FileStream(fileFields[fileKey], FileMode.CreateNew, FileAccess.Write))
                                {
                                    long remaining = attached.Size;
                                    byte[] buff = new byte[2096];

                                    while (remaining > 0)
                                    {
                                        int read = (remaining > 2096) ? 2096 : (int)remaining;
                                        remaining -= read;

                                        crypto.Read(buff, 0, read);
                                        extract.Write(buff, 0, read);
                                    }
                                }
                            }
                            catch
                            { }
                        }
                    }
                }
            }
            catch (Exception)
            {
            }

            return template;
        }
 public void SetUp()
 {
     _service = new ProfileService();
 }
Esempio n. 55
0
        /// <summary>
        /// Creates a new user.
        /// </summary>
        /// <param name="username">The username.</param>
        /// <param name="isAnonymous">True if the the user anonymous.</param>
        /// <returns>A newly created user.</returns>
        public Profile CreateUser(string username, bool isAnonymous)
        {
            var profile = new Profile();
            profile.Username = username;
            profile.ApplicationName = ".NET Pet Shop 4.0";
            profile.IsAnonymous = isAnonymous;
            profile.LastActivityDate = DateTime.Now;
            profile.LastUpdatedDate = DateTime.Now;

            var profileService = new ProfileService();
            profileService.DeepSave(profile);

            return profile;
        }