コード例 #1
0
 public async Task <IReadOnlyList <OAuthTokenClient> > GetClientForTokenAsync(Guid accessToken)
 {
     using (var context = _contextFactory.CreateContext())
     {
         const string Sql = "SELECT \"Key\", UseSandbox, StudentIdentificationSystemDescriptor, EducationOrganizationId, ClaimSetName, NamespacePrefix, ProfileName, CreatorOwnershipTokenId, OwnershipTokenId FROM dbo.GetClientForToken(@p0);";
         return(await context.ExecuteQueryAsync <OAuthTokenClient>(Sql, accessToken));
     }
 }
コード例 #2
0
ファイル: SponsorService.cs プロジェクト: Lietuva2/LT2
        public void ImportExcelData(BankAccountModel.AccountModel model)
        {
            using (var session = usersSessionFactory.CreateContext(true))
            {
                var account =
                    session.BankAccounts.SingleOrDefault(a => a.AccountNo == model.AccountNo);
                if (account == null)
                {
                    account = new BankAccount()
                    {
                        AccountNo = model.AccountNo.Trim()
                    };
                    session.BankAccounts.Add(account);
                }

                account.Balance = (decimal)model.Balance;

                var lastDbDate = account.BankAccountItems.Any() ? account.BankAccountItems.Max(i => i.Date) : DateTime.MinValue;

                foreach (var item in model.Items)
                {
                    if (item.Date > lastDbDate)
                    {
                        var operation = item.Operation;
                        var cutAt     = ", mok. įm. / a. k.";
                        if (operation.Contains(cutAt))
                        {
                            operation = operation.Substring(0, operation.IndexOf(cutAt));
                        }

                        cutAt = ", gav. įm. / a. k.";
                        if (operation.Contains(cutAt))
                        {
                            operation = operation.Substring(0, operation.IndexOf(cutAt));
                        }

                        account.BankAccountItems.Add(new BankAccountItem()
                        {
                            Date      = item.Date,
                            Operation = operation,
                            Expense   = item.ExpenseDecimal,
                            Income    = item.IncomeDecimal
                        });
                    }
                }
            }
        }
コード例 #3
0
        /// <summary>
        /// Look for an existing default application for this particular sandbox type.  Also, make sure that all
        /// Local Education Agency associations are updated.
        /// </summary>
        /// <param name="vendorId"></param>
        /// <param name="sandboxType"></param>
        /// <returns></returns>
        public Application FindOrCreateUpdatedDefaultSandboxApplication(int vendorId, SandboxType sandboxType)
        {
            using (var context = _usersContextFactory.CreateContext())
            {
                var vendor = context.Vendors
                             .Where(x => x.VendorId == vendorId)
                             .Include(x => x.Applications.Select <Application, ICollection <ApplicationEducationOrganization> >(a => a.ApplicationEducationOrganizations))
                             .Single();

                var defaultAppName  = _configuration.GetSection("DefaultApplicationName").Value ?? "Default Sandbox Application";
                var applicationName = defaultAppName + " " + sandboxType;
                var application     = GetApplication(context, vendor, applicationName);

                context.SaveChanges();
                return(application);
            }
        }
コード例 #4
0
ファイル: ProjectService.cs プロジェクト: Lietuva2/LT2
        public ProjectTeamModel GetProjectTeam(string projectId)
        {
            Project project = GetProject(projectId);
            var     idea    = GetIdea(project.IdeaId, "OrganizationId");
            var     model   = new ProjectTeamModel()
            {
                Id      = projectId,
                IdeaId  = idea.Id,
                Subject = idea.Subject,
                IsCurrentUserInvolved = IsCurrentUserInvolved(project),
                IsPendingConfirmation = IsPendingConfirmation(project),
                IsJoinable            = IsJoinable(project, idea),
                OrganizationId        = idea.OrganizationId,
                Members = (from member in project.ProjectMembers
                           select new MemberModel()
                {
                    ObjectId = member.UserObjectId,
                    FullName = GetUserFullName(member.UserObjectId),
                    Role = member.Role
                }).ToList(),
                UnconfirmedMembers = (from member in project.UnconfirmedMembers
                                      select new UserLinkModel()
                {
                    ObjectId = member.UserObjectId,
                    FullName = GetUserFullName(member.UserObjectId)
                }).ToList()
            };

            using (var userSession = userSessionFactory.CreateContext())
            {
                model.InvitedUsers =
                    userSession.UserInvitations.Where(
                        ui => ui.ProjectId == projectId && !ui.Joined)
                    .Select(ui => new InviteUserModel()
                {
                    InvitedUser    = ui.UserEmail,
                    InvitationSent = true,
                    Message        = ui.Message
                }).ToList();
            }
            return(model);
        }
コード例 #5
0
        protected override void Arrange()
        {
            _transaction = new TransactionScope();

            Factory = Stub <IUsersContextFactory>();

            A.CallTo(() => Factory.CreateContext())
            .Returns(new SqlServerUsersContext());

            SystemUnderTest = new AccessTokenClientRepo(Factory);

            TestFixtureContext = new SqlServerUsersContext();
        }
コード例 #6
0
        private bool PublishProfiles()
        {
            try
            {
                //get the set of profiles from any Profiles.xml files found in assemblies
                var definedProfiles =
                    _profileResourceNamesProvider.GetProfileResourceNames()
                    .Select(x => x.ProfileName)
                    .Distinct();

                using (var usersContext = _usersContextFactory.CreateContext())
                {
                    //determine which Profiles from the Profiles.xml files do not exist in the admin database
                    var publishedProfiles = usersContext.Profiles
                                            .Select(x => x.ProfileName)
                                            .ToList();

                    var profilesToInsert = definedProfiles
                                           .Except(publishedProfiles)
                                           .ToList();

                    //if there are none to insert return
                    if (!profilesToInsert.Any())
                    {
                        return(true);
                    }

                    //for each profile not in the database, add it
                    foreach (var profileName in profilesToInsert)
                    {
                        usersContext.Profiles.Add(
                            new Profile
                        {
                            ProfileName = profileName
                        });
                    }

                    usersContext.SaveChanges();
                }

                return(true);
            }
            catch (Exception exception)
            {
                //If an exception occurs log it and return false since it is an async call.
                _logger.Error("An error occured when attempting to publish Profiles to the admin database.", exception);
                return(false);
            }
        }
コード例 #7
0
        public new bool Execute(params string[] args)
        {
            SendEmail = true;
            SendSms   = false;
            var    msg = base.Execute(args);
            string userFromId;
            var    emailsTo = msg.To.Select(m => m.Address).ToList();

            using (var usersContext = usersContextFactory.CreateContext())
            {
                var usersTo = (from ue in usersContext.UserEmails
                               where emailsTo.Contains(ue.Email)
                               select new { ue.User.ObjectId, ue.Email }).ToList();

                userFromId =
                    usersContext.UserEmails.Where(u => u.Email == msg.From.Address)
                    .Select(u => u.User.ObjectId)
                    .SingleOrDefault();

                using (var context = actionsContextFactory.CreateContext(true))
                {
                    var message = new Data.EF.Actions.Message()
                    {
                        Date             = DateTime.Now,
                        Error            = Exception != null ? Exception.Message : null,
                        From             = msg.From.Address,
                        FromDisplayName  = msg.From.DisplayName,
                        FromUserObjectId = userFromId,
                        Body             = msg.Body,
                        Subject          = msg.Subject
                    };
                    foreach (var to in msg.To)
                    {
                        message.To             = to.Address;
                        message.ToDisplayName  = to.DisplayName;
                        message.ToUserObjectId =
                            usersTo.Where(u => u.Email == to.Address).Select(u => u.ObjectId).SingleOrDefault();
                        context.Messages.Add(message);
                    }
                }
            }

            var success = Exception == null;

            Exception = null;
            return(success);
        }
コード例 #8
0
        protected override void Arrange()
        {
            _transaction = new TransactionScope();
            Factory      = Stub <IUsersContextFactory>();

            var config = new ConfigurationBuilder()
                         .SetBasePath(TestContext.CurrentContext.TestDirectory)
                         .AddJsonFile("appsettings.json", optional: true)
                         .AddEnvironmentVariables()
                         .Build();

            var connectionStringProvider = new ConfigConnectionStringsProvider(config);

            A.CallTo(() => Factory.CreateContext())
            .Returns(new SqlServerUsersContext(connectionStringProvider.GetConnectionString("EdFi_Admin")));

            SystemUnderTest = new AccessTokenClientRepo(Factory, config);

            TestFixtureContext = new SqlServerUsersContext(connectionStringProvider.GetConnectionString("EdFi_Admin"));
        }
コード例 #9
0
ファイル: ChatService.cs プロジェクト: Lietuva2/LT2
 private User GetUser(string objectId)
 {
     using (var context = usersSessionFactory.CreateContext())
     {
         return(context.Users.Where(u => u.ObjectId == objectId).SingleOrDefault());
     }
 }
コード例 #10
0
ファイル: AddressService.cs プロジェクト: Lietuva2/LT2
 public IList <string> GetCountries(string prefix)
 {
     using (var session = usersSessionFactory.CreateContext())
     {
         return(session.Countries.Where(c => c.Name.StartsWith(prefix)).OrderBy(c => c.Name).Take(ItemsCount).Select(c => c.Name).ToList());
     }
 }
コード例 #11
0
 public Data.EF.Users.Notification GetNotification(int id)
 {
     using (var session = usersSessionFactory.CreateContext())
     {
         return(session.Notifications.Where(u => u.Id == id).SingleOrDefault());
     }
 }
コード例 #12
0
ファイル: EmailScheduler.cs プロジェクト: Lietuva2/LT2
        /// <summary>
        /// Sends the query email.
        /// </summary>
        private void SendMyNewsEmails()
        {
            var stopwatchEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableStopWatch"] ?? "false");
            var threshold        = Convert.ToInt32(ConfigurationManager.AppSettings["Threshold"] ?? "10");
            var watch            = Stopwatch.StartNew();
            var globalWatch      = Stopwatch.StartNew();

            if (!stopwatchEnabled)
            {
                watch.Stop();
                globalWatch.Stop();
            }

            var userIds = userService.GetNewsLetterUserIds();

            if (stopwatchEnabled)
            {
                watch.Stop();
                if (watch.ElapsedMilliseconds > threshold)
                {
                    Log.Information("GetNewsLetterUserIds elapsed time: " + watch.ElapsedMilliseconds);
                }
            }

            Log.Information(string.Format("Preparing to send email to {0} users...", userIds.Count));
            int userCount = 0;

            foreach (var userId in userIds)
            {
                if (stopwatchEnabled)
                {
                    watch.Restart();
                }
                var emails = userService.GetUserEmails(userId);
                if (stopwatchEnabled)
                {
                    watch.Stop();
                    if (watch.ElapsedMilliseconds > threshold)
                    {
                        Log.Information(string.Format("GetUserEmails elapsed time: {0}, userId={1}", watch.ElapsedMilliseconds, userId));
                    }
                }

                if (emails.Count == 0)
                {
                    continue;
                }

                if (stopwatchEnabled)
                {
                    watch.Restart();
                }
                var count = newsFeedService.GetUnreadNewsCount(userId);
                if (stopwatchEnabled)
                {
                    watch.Stop();
                    if (watch.ElapsedMilliseconds > threshold)
                    {
                        Log.Information(string.Format("GetUnreadNewsCount elapsed time: {0}, userId={1}", watch.ElapsedMilliseconds, userId));
                    }
                }

                if (count == 0)
                {
                    continue;
                }


                var user = userService.GetUser(userId);
                if (stopwatchEnabled)
                {
                    watch.Restart();
                }
                var list = newsFeedService.GetNewsFeedPage(userId, user.LastNewsLetterSendDate).List.List.Where(l => !l.IsRead).ToList();
                if (stopwatchEnabled)
                {
                    watch.Stop();
                    if (watch.ElapsedMilliseconds > threshold)
                    {
                        Log.Information(string.Format("GetNewsFeedPage elapsed time: {0}, userId={1}", watch.ElapsedMilliseconds, userId));
                    }

                    watch.Restart();
                }
                if (!list.Any())
                {
                    continue;
                }

                if (count < list.Count())
                {
                    count = list.Count();
                }

                foreach (var email in emails)
                {
                    notification.To             = email;
                    notification.News           = string.Empty;
                    notification.NewsCount      = count;
                    notification.NewsCountText  = GlobalizedSentences.GetNewsCountText(count);
                    notification.NewsLetterFreq = Globalization.Resources.Services.NewsLetterFreq.ResourceManager.GetString(user.Settings.NewsLetterFrequency.ToString()).ToLower();

                    foreach (var item in list)
                    {
                        notification.News += Web.Helpers.SpecificHtmlHelpers.GetNewsFeedEntry(item) + "<br/>" +
                                             (item.Problem != null ? item.Subject : "") + "<br/>" + item.Text.NewLineToHtml();
                        notification.News += "<br/><br/>";
                    }


                    using (var session = usersContextFactory.CreateContext())
                    {
                        var not = session.Notifications.Single(n => n.Id == (int)NotificationTypes.NewsLetter);
                        notification.MessageTemplate = not.Message;
                        notification.Subject         = not.Subject;
                        if (notification.Execute())
                        {
                            userService.UpdateNewsLetterDate(userId);
                            userCount++;
                        }
                    }
                }

                if (stopwatchEnabled)
                {
                    watch.Stop();
                    if (watch.ElapsedMilliseconds > threshold)
                    {
                        Log.Information(string.Format("Send mail elapsed time: {0}, userId={1}", watch.ElapsedMilliseconds, userId));
                    }
                }
            }

            if (stopwatchEnabled)
            {
                globalWatch.Stop();
                Log.Information("Total elapsed time: " + globalWatch.ElapsedMilliseconds);
            }

            Log.Information(string.Format("Sent {0} emails...", userCount));
        }