public static int Set(Education education, Database sharedDb = null) { using (var db = new LcDatabase(sharedDb)) { // Get the home as reference address to insert the new institution, // even if there are lot of chances of error with this assumption, is // better than nothing and we need to fill that fields. var referenceAddress = Address.GetHomeAddress(education.userID); // Gets the ID for 'institution', creating a new one automatically or from // existing one. education.institutionID = db.QueryValue(sqlGetOrInsertInstitution, education.institutionName, referenceAddress.stateProvinceID, referenceAddress.countryID, education.userID ); return((int)db.QueryValue(sqlSet, education.educationID, education.userID, education.institutionID, education.degreeCertificate, education.fieldOfStudy, education.fromYearAttended, education.toYearAttended )); } }
public static int Set(UserPosting entry, Locale locale, LcDatabase sharedDb = null) { using (var db = new LcDatabase(sharedDb)) { var neededSpecializationsText = string.Join(",", entry.neededSpecializationIDs); var desiredSpecializationsText = string.Join(",", entry.desiredSpecializationIDs); db.Execute("BEGIN TRANSACTION"); var id = 0; if (entry.userPostingID > 0) { db.QueryValue(sqlUpdate, entry.userID, entry.userPostingID, entry.title, neededSpecializationsText, desiredSpecializationsText ); id = entry.userPostingID; foreach (var qr in entry.questionsResponses) { qr.userPostingID = id; UserPostingQuestionResponse.Update(qr, db); } } else { id = (int)db.QueryValue(sqlInsert, entry.userID, entry.solutionID, entry.postingTemplateID, entry.statusID, entry.title, neededSpecializationsText, desiredSpecializationsText, locale.languageID, locale.countryID, entry.userID ); foreach (var qr in entry.questionsResponses) { qr.userPostingID = id; UserPostingQuestionResponse.Insert(qr, db); } } db.Execute("COMMIT TRANSACTION"); return(id); } }
public static void checkAccountIsConfirmed(string username) { // #454: User is auto-logged on registering, allowing it to do the Onboarding, // But next times, it is required to confirm email before logged. // Since we set IsConfirmed as true on database to let 'auto-logging on register', // we must check for the existance of a confirmation token: var userId = WebSecurity.GetUserId(username); using (var db = new LcDatabase()) { string token = LcAuth.GetConfirmationToken(userId); if (userId > -1 && !string.IsNullOrWhiteSpace(token)) { // Resend confirmation mail var confirmationUrl = LcUrl.LangUrl + "Account/Confirm/?confirmationCode=" + Uri.EscapeDataString(token ?? ""); var isProvider = (bool)(db.QueryValue("SELECT IsProvider FROM users WHERE UserID=@0", userId) ?? false); if (isProvider) { LcMessaging.SendWelcomeProvider(userId, username); } else { LcMessaging.SendWelcomeCustomer(userId, username); } /// http 409:Conflict throw new HttpException(409, "Your account has not yet been confirmed. Please check your inbox and spam folders and click on the e-mail sent."); } } }
/// <summary> /// Validates that external list of IDs as text are valid numbers and exists on DB /// for the given solutionID and locale /// </summary> /// <param name="list"></param> /// <param name="solutionID"></param> /// <param name="locale"></param> /// <returns>Formatted text for storage with the specializations IDs</returns> public static List <int> ValidateIncomingSpecializations(IEnumerable <string> list, int solutionID, Locale locale) { var sanitizedList = new List <int>(); foreach (var sid in list) { if (!sid.IsInt()) { throw new ConstraintException("Invalid specialization ID"); } sanitizedList.Add(sid.AsInt()); } // Quick return: when no values if (sanitizedList.Count == 0) { return(sanitizedList); } using (var db = new LcDatabase()) { var sql = db.UseListInSqlParameter(sqlCheckSpecializations, 0, sanitizedList, "-1"); if (sanitizedList.Count == (int)db.QueryValue(sql, null, locale.languageID, locale.countryID, solutionID)) { // valid return(sanitizedList); } else { throw new ConstraintException("Some specializations are not valid"); } } }
public static int?GetUserIdByAuthorizationToken(string token) { using (var db = new LcDatabase()) { return((int?)db.QueryValue("SELECT UserID FROM authorizations WHERE DeletedDate is null AND token like @0", token)); } }
private static DateTimeOffset GetUserTrialEndDate(int userID) { using (var db = new LcDatabase()) { return(db.QueryValue("SELECT TrialEndDate FROM users WHERE userID=@0", userID) ?? DateTimeOffset.MaxValue); } }
/// <summary> /// /// </summary> /// <param name="externalListing"></param> /// <returns>Generated ID</returns> public static int Insert(UserExternalListing externalListing) { externalListing.AutoRegisterUserJobTitles(); var sqlInsert = @" INSERT INTO UserExternalListing ( UserID, PlatformID, Title, JobTitles, Notes, CreatedDate, UpdatedDate, ModifiedBy, Active ) VALUES ( @0, @1, @2, @3, @4, getdate(), getdate(), 'sys', 1 ) SELECT @@Identity "; using (var db = new LcDatabase()) { return((int)db.QueryValue(sqlInsert, externalListing.userID, externalListing.platformID, externalListing.title, Newtonsoft.Json.JsonConvert.SerializeObject(externalListing.jobTitles), externalListing.notes )); } }
public static bool MeetsOwnsershipRequirement(int userID) { var sql = @" DECLARE @UserID = @0 DECLARE @hasPaid bit = 0 IF EXISTS ( SELECT * FROM UserPaymentPlan WHERE UserID = @UserID AND PlanStatus IN ('Active', 'Past Due') -- extra check for 'current plan' AND SubscriptionEndDate is null ) BEGIN SET @hasPaid = 1 END SELECT @hasPaid "; using (var db = new LcDatabase()) { return((bool)db.QueryValue(sql, userID)); } }
public static bool HasMembershipRecord(int userID) { using (var db = new LcDatabase()) { return(db.QueryValue("SELECT userid FROM webpages_Membership WHERE userid = @0", userID) != null); } }
public static bool MeetsOwnershipRequirement(int userID) { var sql = @" DECLARE @UserID int = @0 DECLARE @hasListing bit = 0 -- Firts: ensure all account and listing requirements are tested -- before we check listing status EXEC TestAllUserAlerts @UserID -- Check Listing IF EXISTS ( SELECT * FROM userprofilepositions WHERE UserID = @UserID AND Active = 1 AND StatusID = 1 -- active and publicly visible ) BEGIN SET @hasListing = 1 END SELECT @hasListing "; using (var db = new LcDatabase()) { return((bool)db.QueryValue(sql, userID)); } }
static public string GetUserTimeZone(int userID) { using (var db = new LcDatabase()) { // By default is null, in case it has no events will let the client app to auto pick one return((string)N.D(db.QueryValue("SELECT TOP 1 timeZone FROM CalendarProviderAttributes WHERE UserID=@0", userID))); } }
public static string GetEmail(int userID) { using (var db = new LcDatabase()) { return((string)db.QueryValue(@" SELECT email FROM UserProfile WHERE UserID = @0 ", userID)); } }
private static int Insert(UserLicenseCertification item, bool internalUpdate = false) { // TODO, for an admin dashboard, we may need to implement internalUpdate allowing for update of all non-ID fields. if (internalUpdate) { throw new NotImplementedException("Internal update not implemented"); } var user = UserProfile.Get(item.userID); using (var db = new LcDatabase()) { // Constraint: licenses cannot be duplicated for an existant licenseID (>0), but they can for the special wildcard IDs (-1, 0) if (item.licenseCertificationID > 0) { var many = (int)db.QueryValue("SELECT count(*) FROM UserLicenseCertifications WHERE ProviderUserID = @0 AND PositionID = @1 AND LicenseCertificationID = @2", item.userID, item.jobTitleID, item.licenseCertificationID); if (many > 0) { throw new ConstraintException("You have already registered that license, please try to update it if you want to submit a new file."); } } return((int)db.QueryValue(sqlInsertNew, item.userID, item.jobTitleID, item.licenseCertificationID, 2, "", "", null, "", user.firstName, user.lastName, "", "", "", "", "", item.userID, item.submittedImageLocalURL )); } }
public static string GetConfirmationToken(int userID) { using (var db = new LcDatabase()) { return(userID == -1 ? null : // coalesce used to avoid the value 'DbNull' to be returned, just 'empty' when there is no token, // is already confirmed db.QueryValue("SELECT coalesce(ConfirmationToken, '') FROM webpages_Membership WHERE UserID=@0", userID)); } }
public static string GetServiceProfessionalReactionMessage(int userPostingID, int serviceProfessionalUserID) { using (var db = new LcDatabase()) { var sql = @" SELECT TOP 1 message FROM UserPostingReaction WHERE UserPostingID = @0 AND serviceProfessionalUserID = @1 "; return((string)db.QueryValue(sql, userPostingID, serviceProfessionalUserID)); } }
public static int GetExperienceLevelID(int userID, int jobTitleID, int languageID, int countryID) { using (var db = new LcDatabase()) { return((int)((int?)db.QueryValue(@" SELECT UL.experienceLevelID FROM ServiceAttributeExperienceLevel As UL WHERE UL.UserID = @0 AND UL.PositionID = @1 AND UL.LanguageID = @2 AND UL.CountryID = @3 ", userID, jobTitleID, languageID, countryID) ?? 0)); } }
static void Set(int userID, int userListingID, int solutionID, int displayRank, Locale locale, LcDatabase sharedDb = null) { using (var db = new LcDatabase(sharedDb)) { db.QueryValue(sqlSet, userID, userListingID, locale.languageID, locale.countryID, solutionID, displayRank, userID.ToString() ); } }
/// <summary> /// Inserts a new specialization generated by the user /// </summary> /// <param name="name"></param> /// <param name="solutionID"></param> /// <param name="createdBy"></param> /// <param name="enteredByUserID"></param> /// <param name="locale"></param> /// <param name="sharedDb"></param> /// <returns></returns> public static int InsertUserGenerated( string name, int solutionID, int enteredByUserID, Locale locale, LcDatabase sharedDb) { using (var db = new LcDatabase(sharedDb)) { return((int)db.QueryValue(sqlInsertUserGenerated, locale.languageID, locale.countryID, solutionID, name, enteredByUserID)); } }
public static LcRest.UserProfile ConfirmAccount(string confirmationCode) { using (var db = new LcDatabase()) { var userID = (int?)db.QueryValue(@" SELECT UserId FROM webpages_Membership WHERE ConfirmationToken = @0 ", confirmationCode); if (userID.HasValue) { // Check if the account requires to complete the sign-up: // - it happens for user whose record was created by a professional (added him as client) // - so, the user has an accountStatusID serviceProfessional's client // -> On that case, we cannot confirm the account yet, since we need from the client to // complete the sign-up, generating a password by itself. We just follow up returning the user // profile data that can be used to pre-populate the 'client activation' sign-up form. var user = LcRest.UserProfile.Get(userID.Value); if (user.accountStatusID != (int)LcEnum.AccountStatus.serviceProfessionalClient) { // User can confirm it's account, proceed: db.Execute(@" UPDATE webpages_Membership SET ConfirmationToken = null, IsConfirmed = 1 WHERE ConfirmationToken like @0 AND UserID = @1 ", confirmationCode, userID); // In the lines above, we cannot use the aps.net WebSecurity standard logic: // //WebSecurity.ConfirmAccount(confirmationToken) // because the change of confirmation first-time optional step, alert at dashboard // and (sometimes this business logic changes) required for second and following login attempts. // Because of this a hack is done on provider-sign-up login over the IsConfirmed field, and this becomes the ConfirmAccount // standard method unuseful (do nothing, really, because it checks IsConfirmed field previuosly and ever is true, doing nothing -we need set to null // ConfirmationToken to off the alert-). On success, ConfirmationToken is set to null and IsConfirmed to 1 (true), supporting both cases, when IsConfirmed is // already true and when no. db.Execute("EXEC TestAlertVerifyEmail @0", userID); // IMPORTANT: Since 2012-09-27, issue #134, Auto-login is done on succesful confirmation; // some code after next lines (comented as 'starndard logic' will not be executed, and some html, but preserved as documentation) // Confirmation sucess, we need user name (email) to auto-login: FormsAuthentication.SetAuthCookie(user.email, false); } return(user); } } return(null); }
public static int Set(UserBadge entry, Locale locale, LcDatabase sharedDb = null) { using (var db = new LcDatabase(sharedDb)) { return((int)db.QueryValue(sqlSet, entry.userID, entry.userBadgeID, entry.solutionID, entry.badgeURL, entry.type, entry.category, entry.expiryDate, locale.languageID, locale.countryID, entry.createdBy, entry.modifiedBy )); } }
/// <summary> /// Fills in the jobTitles field with values from database for the given /// list of Job Title IDs. /// This way we use stored job titles names rather than anyone provided through the /// external REST API. /// </summary> /// <param name="jobTitleIds"></param> public void FillJobTitlesWithIds(IEnumerable <int> jobTitleIds, int languageID, int countryID) { jobTitles = new Dictionary <int, string>(); using (var db = new LcDatabase()) { foreach (int jobTitleID in jobTitleIds) { var name = (string)db.QueryValue(@"SELECT PositionSingular FROM Positions WHERE Active = 1 AND PositionID = @0 AND LanguageID = @1 AND CountryID = @2 ", jobTitleID, languageID, countryID); if (String.IsNullOrEmpty(name)) { throw new ConstraintException("[[[Invalid Job Title ID]]]"); } jobTitles.Add(jobTitleID, name); } } }
/// <summary> /// Checks if the provided addressID belongs to ALMOST ONE of the UserIDs provided. /// </summary> /// <param name="addressID"></param> /// <param name="userIds"></param> /// <returns></returns> public static bool ItBelongsTo(int addressID, params int[] userIds) { using (var db = new LcDatabase()) { var ownerUserID = (int?)db.QueryValue(@" SELECT userID FROM Address WHERE AddressID = @0 ", addressID); if (ownerUserID.HasValue) { foreach (var userID in userIds) { if (ownerUserID.Value == userID) { return(true); } } } } return(false); }
public static UpcomingAppointmentsInfo GetList(int userID) { var ret = new UpcomingAppointmentsInfo(); using (var db = new LcDatabase()) { dynamic d = null; d = db.QuerySingle(sqlGetBookingsSumSinceDate, userID, DateTime.Now, LcEnum.BookingStatus.confirmed); ret.nextOnes = new Summary { quantity = d.count, time = d.startTime }; // NOTE: what if there is a booking for several days and we are in the middel of that? First work hour on the date? d = db.QuerySingle(sqlGetBookingsSumSinceDate, userID, DateTime.Now, LcEnum.BookingStatus.request); ret.pendingRequests = new Summary { quantity = d.count, time = d.startTime }; // TODO Implement multi-session pending scheduling look-up //d = db.QuerySingle(sqlGetBookingsSumByDateRange, userID, DateTime.Now, ...); //ret.pendingScheduling = new Summary //{ // quantity = d.count, // time = d.startTime //}; ret.pendingScheduling = new Summary(); var nextBookingID = (int?)db.QueryValue(sqlGetNextBookingID, userID, DateTime.Now, LcEnum.BookingStatus.confirmed); if (nextBookingID.HasValue) { ret.nextBooking = Booking.Get(nextBookingID.Value, true, false, userID); } } return(ret); }
/* * Reading payment subscription: * var subscriptionID = GetUserActivePlan(userID).subscriptionID; * LcPayment.Membership.GetUserSubscription(subscriptionID); */ /// <summary> /// For the last payment plan of the user, gets the subscription status (planStatus) /// parsed for the Braintree enumeration, with fallback to UNRECOGNIZED value if /// no payment plan registered. /// This checks for closed plans too (useful to know if last payment was cancelled or suspended). /// </summary> /// <param name="userID"></param> /// <returns></returns> public static Braintree.SubscriptionStatus GetLastPaymentPlanStatus(int userID) { var sql = @" SELECT TOP 1 PlanStatus FROM UserPaymentPlan WHERE UserID = @0 ORDER BY UserPaymentPlanID DESC "; using (var db = new LcDatabase()) { var status = (string)db.QueryValue(sql, userID); if (status == null) { return(Braintree.SubscriptionStatus.UNRECOGNIZED); } else { return(Braintree.SubscriptionStatus.STATUSES.First(x => status == x.ToString())); } } }
/// <summary> /// Searchs for an exact match of a job title given a singular or plural name, and matching language /// </summary> /// <param name="jobTitleName"></param> /// <param name="languageID"></param> /// <param name="countryID"></param> /// <returns></returns> public static int?FindExactName(string jobTitleName, int languageID, int countryID) { if (String.IsNullOrWhiteSpace(jobTitleName)) { return(null); } using (var db = new LcDatabase()) { return((int?)db.QueryValue(@" SELECT PositionID FROM Positions WHERE Active = 1 AND LanguageID = @0 AND CountryID = @1 AND Approved = 1 AND ( PositionSingular like @2 OR PositionPlural like @2 ) ", languageID, countryID, jobTitleName)); } }
public static bool MeetsOwnsershipRequirement(int userID) { var sql = @" DECLARE @UserID int = @0 DECLARE @hasAcknowledgment bit = 0 IF EXISTS ( SELECT * FROM OwnerAcknowledgment WHERE UserID = @UserID AND DateAcknowledged is not null ) BEGIN SET @hasAcknowledgment = 1 END SELECT @hasAcknowledgment "; using (var db = new LcDatabase()) { return((bool)db.QueryValue(sql, userID)); } }
/// <summary> /// Updates an existent subscription, identified by the given userID and email, providing /// the first and last name. /// We require this 'double key' (userID, email) rather than just userID in order to prevent fake calls to the API with /// random IDs, this way the sender must now both values or the operation fails. /// </summary> /// <param name="userID"></param> /// <param name="email"></param> /// <param name="firstName"></param> /// <param name="lastName"></param> public static void UpdateSubscription(int userID, string email, string firstName, string lastName) { var existentUserID = Client.CheckEmailAvailability(email); if (existentUserID != userID) { throw new Exception("[[[Invalid user]]]"); } using (var db = new LcDatabase()) { // If success, it returns the userID otherwise zero db.QueryValue(@" UPDATE users SET firstName = @1, lastName = @2, updatedDate = getdate(), modifiedBy = 'sys' WHERE userID = @0 ", userID, firstName, lastName); } }
/// <summary> /// Creates a new user from a subscription request (newsletter, referral), that has not active account /// (no password, no TOU accepted). /// </summary> /// <param name="email"></param> /// <param name="isServiceProfessional"></param> /// <param name="marketingSource"></param> /// <param name="locale"></param> public static int SubscribeNewUser(string email, bool isServiceProfessional, string marketingSource, Locale locale) { var emailExists = Client.CheckEmailAvailability(email) > 0; if (emailExists) { throw new Exception("[[[Email is already registered, please log-in or request a password reset]]]"); } using (var db = new LcDatabase()) { // If success, it returns the userID otherwise zero return((int)db.QueryValue(@" DECLARE @UserID int BEGIN TRANSACTION -- Create UserProfile record to save email and generate UserID INSERT INTO UserProfile ( Email ) VALUES ( @0 ) SET @UserID = @@Identity -- Create user account record, but account disabled INSERT INTO Users ( UserID, IsProvider, IsCustomer, AccountStatusID, loconomicsMarketingCampaigns, FirstName, LastName, MiddleIn, SecondLastName, marketingSource, preferredLanguageID, preferredCountryID, CreatedDate, UpdatedDate, ModifiedBy, Active ) VALUES ( @UserID, @1, -- Is professional 1, -- Is client -1, 1, '', '', '', '', @2, @3, @4, getdate(), getdate(), 'sys', 1 -- Active ) -- NOTE: since there is no Membership record with password, is not an actual Loconomics User Account -- just what we need on this case IF @@ERROR <> 0 ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION SELECT @UserID ", email, isServiceProfessional, marketingSource, locale.languageID, locale.countryID)); } }
public static int ReferServiceProfessional(string email, string firstName, string lastName, string phone, int referredByUserID, string marketingSource, LcRest.Locale locale) { if (!String.IsNullOrWhiteSpace(email)) { var emailExists = Client.CheckEmailAvailability(email) > 0; if (emailExists) { throw new Exception("That service professional is already registered. Maybe have not a public profile still."); } } else { // We must auto-generate an email placeholder, in order to be able to store a UserProfile and get an UserID // needed to store a record at [users] email = Client.GetEmailForDb(email); } using (var db = new LcDatabase()) { // If success, it returns the userID otherwise zero return((int)db.QueryValue(@" DECLARE @UserID int BEGIN TRANSACTION -- Create UserProfile record to save email and generate UserID INSERT INTO UserProfile ( Email ) VALUES ( @0 ) SET @UserID = @@Identity -- Create user account record, but account disabled INSERT INTO Users ( UserID, IsProvider, IsCustomer, AccountStatusID, referredByUserID, loconomicsMarketingCampaigns, FirstName, LastName, MiddleIn, SecondLastName, marketingSource, preferredLanguageID, preferredCountryID, mobilePhone, CreatedDate, UpdatedDate, ModifiedBy, Active ) VALUES ( @UserID, 1, -- Is professional 1, -- Is client -1, @1, 1, @2, @3, '', '', @4, @5, @6, @7, getdate(), getdate(), 'sys', 1 -- Active ) -- NOTE: since there is no Membership record with password, is not an actual Loconomics User Account -- just what we need on this case IF @@ERROR <> 0 ROLLBACK TRANSACTION ELSE COMMIT TRANSACTION SELECT @UserID ", email, referredByUserID, firstName, lastName, marketingSource, locale.languageID, locale.countryID, phone)); } }
public static UpcomingBookingsInfo GetList(int userID) { var ret = new UpcomingBookingsInfo(); // Preparing dates for further filtering var leftToday = DateTime.Now; var leftTodayEnd = DateTime.Today.AddDays(1).AddSeconds(-1); var tomorrow = DateTime.Today.AddDays(1); var tomorrowEnd = tomorrow.AddDays(1).AddSeconds(-1); // This week is today until the end of Sunday int daysUntilSunday = (((int)DayOfWeek.Monday - (int)DateTime.Today.DayOfWeek + 7) % 7); var thisWeekStart = DateTime.Now; var thisWeekEnd = DateTime.Today.AddDays(daysUntilSunday).AddSeconds(-1); // Next week is from the next Monday until Sunday var nextWeekStart = DateTime.Today.AddDays(daysUntilSunday); var nextWeekEnd = nextWeekStart.AddDays(7).AddSeconds(-1); using (var db = new LcDatabase()) { dynamic d = null; d = db.QuerySingle(sqlGetBookingsSumByDateRange, userID, leftToday, leftTodayEnd); ret.today = new Summary { quantity = d.count, // NOTE: What if the endTime is for a different date? Last work hour on the date? time = d.endTime }; // NOTE: what if there is a booking for several days and we are in the middel of that? First work hour on the date? d = db.QuerySingle(sqlGetBookingsSumByDateRange, userID, tomorrow, tomorrowEnd); ret.tomorrow = new Summary { quantity = d.count, time = d.startTime }; d = db.QuerySingle(sqlGetBookingsSumByDateRange, userID, thisWeekStart, thisWeekEnd); ret.thisWeek = new Summary { quantity = d.count, time = d.startTime }; d = db.QuerySingle(sqlGetBookingsSumByDateRange, userID, nextWeekStart, nextWeekEnd); ret.nextWeek = new Summary { quantity = d.count, time = d.startTime }; var nextBookingID = (int?)db.QueryValue(sqlGetNextBookingID, userID, leftToday); if (nextBookingID.HasValue) { ret.nextBooking = Booking.Get(nextBookingID.Value, true, false, userID); } } return(ret); }