public ActionResult SectionCreate(PageTemplateSection section) { ValidatePageTemplateSectionName(section); if (section.PageTemplateId == default(int)) { return(HttpBadRequest("Page Template id is 0")); } IGstoreDb db = GStoreDb; PageTemplate template = db.PageTemplates.FindById(section.PageTemplateId); if (template == null) { return(HttpNotFound("Page Template not found. Page Template Id: " + section.PageTemplateId)); } if (section.ClientId != template.ClientId) { return(HttpBadRequest("View Model ClientId: " + section.ClientId + " does not match template client id: " + section.ClientId)); } if (ModelState.IsValid) { section = GStoreDb.PageTemplateSections.Add(section); GStoreDb.SaveChanges(); AddUserMessage("Page Template Section Created", "Page Template Section created successfully", UserMessageType.Success); return(RedirectToAction("SectionIndex", new { id = section.PageTemplateId })); } section.PageTemplate = template; this.BreadCrumbsFunc = htmlHelper => this.PageTemplateSectionBreadcrumb(htmlHelper, section, false); return(View(section)); }
public ActionResult FieldCreate(WebFormField webFormField) { if (webFormField.WebFormId == default(int)) { return(HttpBadRequest("Web Form id is 0")); } IGstoreDb db = GStoreDb; WebForm webForm = db.WebForms.FindById(webFormField.WebFormId); if (webForm == null) { return(HttpNotFound("Web Form not found. Web Form id: " + webFormField.WebFormId)); } if (webForm.WebFormFields.Any(f => f.Name.ToLower() == (webFormField.Name ?? "").ToLower())) { ModelState.AddModelError("Name", "A field with the name '" + webFormField.Name + "' already exists. Choose a new name or edit the original."); } if (ModelState.IsValid) { webFormField.ClientId = webForm.ClientId; webFormField.WebFormId = webForm.WebFormId; webFormField.DataTypeString = webFormField.DataType.ToDisplayName(); webFormField = GStoreDb.WebFormFields.Add(webFormField); GStoreDb.SaveChanges(); AddUserMessage("Web Form Field Created", "Web Form Field '" + webFormField.Name.ToHtml() + "' [" + webFormField.WebFormFieldId + "] created successfully", UserMessageType.Success); return(RedirectToAction("FieldIndex", new { id = webFormField.WebFormId })); } webFormField.WebForm = webForm; this.BreadCrumbsFunc = htmlHelper => this.WebFormFieldBreadcrumb(htmlHelper, webFormField); return(View(webFormField)); }
public static void SetDefaultsForNew(this Client client, IGstoreDb db) { client.Name = "New Client"; client.Order = 1000; if (!db.Clients.IsEmpty()) { client.Order = db.Clients.All().Max(c => c.ClientId) + 10; if (db.Clients.All().Any(c => c.Name.ToLower() == client.Name.ToLower())) { bool nameIsDirty = true; int counter = 1; do { counter++; client.Name = "New Client " + counter; nameIsDirty = db.Clients.All().Any(c => c.Name.ToLower() == client.Name.ToLower()); } while (nameIsDirty); } } client.Folder = client.Name; client.IsPending = false; client.EndDateTimeUtc = DateTime.UtcNow.AddYears(100); client.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1); client.EnableNewUserRegisteredBroadcast = true; client.EnablePageViewLog = true; client.UseSendGridEmail = false; client.UseTwilioSms = false; }
protected override bool AuthorizeCore(HttpContextBase httpContext) { if (_actions == null || _actions.Count == 0) { throw new ApplicationException("AuthorizeGStoreAction was called with no action specified. You must specify at least one or more actions to the constructor."); } if (!httpContext.User.IsRegistered()) { return(false); } if (httpContext.User.IsInRole("SystemAdmin")) { return(true); } IGstoreDb db = RepositoryFactory.StoreFrontRepository(httpContext); UserProfile userProfile = db.GetCurrentUserProfile(true, true); StoreFrontConfiguration storeFrontConfig = db.GetCurrentStoreFrontConfig(httpContext.Request, false, _treatInactiveStoreFrontAsActive); if (storeFrontConfig == null) { //no storefront, return(AuthorizationExtensions.Authorization_IsAuthorized(null, userProfile, _allowAnyMatch, _actions.ToArray())); } return(storeFrontConfig.StoreFront.Authorization_IsAuthorized(userProfile, _allowAnyMatch, _actions.ToArray())); }
protected string UserName() { string userName = string.Empty; if (Context.User != null && Context.User.Identity != null && Context.User.Identity.IsAuthenticated) { IGstoreDb ctx = RepositoryFactory.StoreFrontRepository(this.Context.Request.GetHttpContext()); UserProfile profile = UserProfileExtensions.GetCurrentUserProfile(ctx, true, true); userName = profile.FullName; } else { if (Context.RequestCookies.ContainsKey("ChatName")) { Cookie cookie; Context.RequestCookies.TryGetValue("ChatName", out cookie); userName = "******" + cookie.Value + "]"; } else { userName = "******" + base.Context.ConnectionId; } } return(userName); }
private static void LogBadRequest(HttpException ex, HttpContext context, RouteData routeData, BaseController controller) { string source = ex.Source; IGstoreDb db = RepositoryFactory.SystemWideRepository(context.User); db.LogBadRequest(context.Request.RequestContext.HttpContext, routeData, controller); }
public OrderAdminBaseController(IGstoreDb dbContext) : base(dbContext) { this._logActionsAsPageViews = false; this._throwErrorIfUserProfileNotFound = true; this._useInactiveStoreFrontAsActive = false; this._useInactiveStoreFrontConfigAsActive = true; }
public ActionResult ListItemCreate(ValueListItem valueListItem) { if (valueListItem.ValueListId == default(int)) { return(HttpBadRequest("Value List id is 0")); } IGstoreDb db = GStoreDb; ValueList valueList = db.ValueLists.FindById(valueListItem.ValueListId); if (valueList == null) { return(HttpNotFound("Value List not found. Value List id: " + valueListItem.ValueListId)); } if (valueList.ValueListItems.Any(vl => vl.Name.ToLower() == valueListItem.Name.ToLower())) { ModelState.AddModelError("Name", "An item with name '" + valueListItem.Name + "' already exists. Choose a new name or edit the original value."); } if (ModelState.IsValid) { valueListItem.ClientId = valueList.ClientId; valueListItem.ValueListId = valueList.ValueListId; valueListItem = GStoreDb.ValueListItems.Add(valueListItem); GStoreDb.SaveChanges(); AddUserMessage("Value List Item Created", "Value List Item '" + valueListItem.Name.ToHtml() + "' [" + valueListItem.ValueListItemId + "] created successfully", UserMessageType.Success); return(RedirectToAction("ListItemIndex", new { id = valueListItem.ValueListId })); } valueListItem.ValueList = valueList; this.BreadCrumbsFunc = htmlHelper => this.ValueListItemBreadcrumb(htmlHelper, valueListItem, false); return(View(valueListItem)); }
public static bool ValidateBlogUrlName(this IGstoreDb db, GStoreData.ControllerBase.BaseController controller, string urlName, int storeFrontId, int clientId, int?currentBlogId) { string nameField = "UrlName"; if (string.IsNullOrWhiteSpace(urlName)) { string errorMessage = "URL Name is required \n Please enter a unique URL name for this Blog"; controller.ModelState.AddModelError(nameField, errorMessage); return(false); } if (urlName.Trim().ToLower() == "all") { string errorMessage = "URL Name cannot be 'All'\n Please enter a unique URL name for this Blog"; controller.ModelState.AddModelError(nameField, errorMessage); return(false); } Blog conflict = db.Blogs.Where(p => p.ClientId == clientId && p.StoreFrontId == storeFrontId && p.UrlName.ToLower() == urlName && (p.BlogId != currentBlogId)).FirstOrDefault(); if (conflict == null) { return(true); } string errorConflictMessage = "URL Name '" + urlName + "' is already in use for Blog '" + conflict.Name + "' [" + conflict.BlogId + "] in Store Front '" + conflict.StoreFront.CurrentConfig().Name.ToHtml() + "' [" + conflict.StoreFrontId + "]. \n You must enter a unique URL Name or change the conflicting Blog URL Name."; controller.ModelState.AddModelError(nameField, errorConflictMessage); return(false); }
public SystemAdminBaseController(IGstoreDb dbContext) : base(dbContext) { this._logActionsAsPageViews = false; this._throwErrorIfUserProfileNotFound = false; this._throwErrorIfStoreFrontNotFound = false; }
public BlogAdminBaseController(IGstoreDb dbContext) : base(dbContext) { this._logActionsAsPageViews = false; this._throwErrorIfUserProfileNotFound = true; this._useInactiveStoreFrontAsActive = false; this._useInactiveStoreFrontConfigAsActive = true; }
/// <summary> /// Returns a list of ClientRoleAction for a user. Note: This is for database mapping only, identity roles like systemadmin will only return roles explicitly linked /// </summary> /// <param name="db"></param> /// <param name="userProfile"></param> /// <param name="storeFront"></param> /// <returns></returns> public static List <ClientRoleAction> Authorization_ListDefinedRoleActions(this IGstoreDb db, UserProfile userProfile, StoreFront storeFront) { //returns true if there is an active ClientUserRoleAction return(db.ClientRoleActions .Where(cra => cra.ClientRole.ClientUserRoles.AsQueryable().WhereIsActiveAndIsInScope(storeFront).Any(cur => cur.UserProfileId == userProfile.UserProfileId)) .WhereIsActive() .ToList()); }
/// <summary> /// saves form data to database, is isRegisterPage = true, also updates user profile /// </summary> /// <param name="db"></param> /// <param name="modelStateDictionary"></param> /// <param name="webForm"></param> /// <param name="page"></param> /// <param name="userProfile"></param> /// <param name="request"></param> /// <param name="storeFrontConfiguration"></param> /// <param name="formSubject"></param> /// <param name="formBodyText"></param> /// <param name="isRegisterPage"></param> /// <returns></returns> private static WebFormResponse ProcessWebForm_ToDatabase(BaseController controller, WebForm webForm, Page page, string formSubject, string formBodyText, bool isRegisterPage, WebFormResponse oldResponseToUpdateOrNull) { if (controller == null) { throw new ArgumentNullException("controller"); } IGstoreDb db = controller.GStoreDb; UserProfile userProfile = controller.CurrentUserProfileOrNull; StoreFrontConfiguration storeFrontConfiguration = controller.CurrentStoreFrontConfigOrThrow; WebFormResponse webFormResponse = null; if (oldResponseToUpdateOrNull == null) { webFormResponse = db.WebFormResponses.Create(); webFormResponse.SetDefaults(userProfile); } else { webFormResponse = oldResponseToUpdateOrNull; } webFormResponse.StoreFrontId = storeFrontConfiguration.StoreFrontId; webFormResponse.StoreFront = storeFrontConfiguration.StoreFront; webFormResponse.ClientId = storeFrontConfiguration.ClientId; webFormResponse.Client = storeFrontConfiguration.Client; webFormResponse.PageId = (page == null ? null : (int?)page.PageId); webFormResponse.Page = page; webFormResponse.WebFormId = webForm.WebFormId; webFormResponse.WebForm = webForm; webFormResponse.IsPending = false; webFormResponse.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1); webFormResponse.EndDateTimeUtc = DateTime.UtcNow.AddYears(100); webFormResponse.BodyText = formBodyText; webFormResponse.Subject = formSubject; FillWebFormResponses(controller, webFormResponse, webForm, oldResponseToUpdateOrNull); if (oldResponseToUpdateOrNull == null) { webFormResponse = db.WebFormResponses.Add(webFormResponse); } else { webFormResponse = db.WebFormResponses.Update(oldResponseToUpdateOrNull); } db.SaveChanges(); if (isRegisterPage && (userProfile != null)) { userProfile.RegisterWebFormResponseId = webFormResponse.WebFormResponseId; db.UserProfiles.Update(userProfile); db.SaveChangesDirect(); } //for checkout page and other pages return object return(webFormResponse); }
private static void LogException(string message, Exception ex, Models.SystemEventLevel systemEventLevel, HttpContext context, RouteData routeData, BaseController controller) { string source = ex.Source; IGstoreDb db = RepositoryFactory.SystemWideRepository(context.User); string exceptionMessage = ex.Message; string baseExceptionMessage = ex.GetBaseException().Message; string baseExceptionToString = ex.GetBaseException().ToString(); db.LogSystemEvent(context.Request.RequestContext.HttpContext, routeData, source, systemEventLevel, message, exceptionMessage, baseExceptionMessage, baseExceptionToString, controller); }
public static Models.UserProfile GetUserProfile(this AspNetIdentityUser user, IGstoreDb GStoreDb, bool throwExceptionIfNotFound = false) { Models.UserProfile profile = GStoreDb.UserProfiles.SingleOrDefault(up => up.UserId == user.Id); if (throwExceptionIfNotFound && profile == null) { throw new ApplicationException("Cannot find user profile for user id: " + user.Id + "\n\tEmail: " + user.Email + "\n\tUserName: " + user.UserName); } return profile; }
public static StoreBinding AutoMapBinding(this IGstoreDb db, GStoreData.ControllerBase.BaseController baseController) { if (Settings.AppEnableBindingAutoMapCatchAll) { return(db.AutoMapBindingToCatchAll(baseController)); } else { return(db.AutoMapBindingToCurrentUrl(baseController)); } }
/// <summary> /// Returns a repository for the current store front and sets clientid and storefrontid /// </summary> /// <param name="httpContext"></param> /// <param name="throwErrorIfStoreFrontNotFound"></param> /// <returns></returns> public static IGstoreDb StoreFrontRepository(HttpContextBase httpContext) { if (httpContext == null) { throw new ApplicationException("HTTP Context is null, call repository method with valid context"); } string userName = (httpContext.User == null ? "" : httpContext.User.Identity.Name); IGstoreDb db = NewRepository(userName); return(db); }
public static Page ResetContentToDefault(this Page page, IGstoreDb db) { List<PageSection> sections = page.Sections.ToList(); foreach (PageSection section in sections) { db.PageSections.Delete(section); } db.Pages.Update(page); db.SaveChanges(); return page; }
public static Page ResetContentToDefault(this Page page, IGstoreDb db) { List <PageSection> sections = page.Sections.ToList(); foreach (PageSection section in sections) { db.PageSections.Delete(section); } db.Pages.Update(page); db.SaveChanges(); return(page); }
public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("Page Template id is null")); } IGstoreDb db = GStoreDb; PageTemplate pageTemplate = db.PageTemplates.FindById(id.Value); if (pageTemplate == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = htmlHelper => this.PageTemplateBreadcrumb(htmlHelper, pageTemplate.ClientId, pageTemplate, false); return(View(pageTemplate)); }
public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("User Profile id is null")); } IGstoreDb db = GStoreDb; UserProfile profile = db.UserProfiles.FindById(id.Value); if (profile == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = htmlHelper => this.UserProfileBreadcrumb(htmlHelper, profile.ClientId, profile.StoreFrontId, profile, false); return(View(profile)); }
public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("Web Form Id is null")); } IGstoreDb db = GStoreDb; WebForm webForm = db.WebForms.FindById(id.Value); if (webForm == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = htmlHelper => this.WebFormBreadcrumb(htmlHelper, webForm.ClientId, webForm); return(View(webForm)); }
public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("Value List Id is null")); } IGstoreDb db = GStoreDb; ValueList valueList = db.ValueLists.FindById(id.Value); if (valueList == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = htmlHelper => this.ValueListBreadcrumb(htmlHelper, valueList.ClientId, valueList); return(View(valueList)); }
// GET: SystemAdmin/ClientSysAdmin/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("Client id is null")); } IGstoreDb db = GStoreDb; Client client = db.Clients.FindById(id.Value); if (client == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = html => this.ClientBreadcrumb(html, id, false); return(View(client)); }
public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("Theme id is null")); } IGstoreDb db = GStoreDb; Theme theme = db.Themes.FindById(id.Value); if (theme == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = htmlHelper => this.ThemeBreadcrumb(htmlHelper, theme.ClientId, theme, false); return(View(theme)); }
// GET: SystemAdmin/StoreFrontSysAdmin/Delete/5 public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("StoreFront id is null")); } IGstoreDb db = GStoreDb; StoreFront storeFront = db.StoreFronts.FindById(id.Value); if (storeFront == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = htmlHelper => this.StoreFrontBreadcrumb(htmlHelper, storeFront.ClientId, storeFront, false); return(View(storeFront)); }
public ActionResult Delete(int?id) { if (id == null) { return(HttpBadRequest("Store Binding Id is null")); } IGstoreDb db = GStoreDb; StoreBinding storeBinding = db.StoreBindings.FindById(id.Value); if (storeBinding == null) { return(HttpNotFound()); } this.BreadCrumbsFunc = html => this.BindingBreadcrumb(html, storeBinding.ClientId, storeBinding.StoreFront, storeBinding); return(View(storeBinding)); }
public ActionResult Create(Client client, bool?populateThemes, bool?populatePageTemplates, bool?populateSampleWebForms) { //check if client name or folder is already taken ValidateClientName(client); ValidateClientFolder(client); if (ModelState.IsValid) { IGstoreDb db = GStoreDb; client = db.Clients.Create(client); client.UpdateAuditFields(CurrentUserProfileOrThrow); client = db.Clients.Add(client); AddUserMessage("Client Added", "Client '" + client.Name.ToHtml() + "' [" + client.ClientId + "] created successfully!", UserMessageType.Success); db.SaveChanges(); string clientFolderVirtualPath = client.ClientVirtualDirectoryToMap(Request.ApplicationPath); try { client.CreateClientFolders(Request.ApplicationPath, Server); AddUserMessage("Client Folders Created", "Client Folders were created in '" + clientFolderVirtualPath.ToHtml(), UserMessageType.Success); } catch (Exception ex) { AddUserMessage("Error Creating Client Folders!", "There was an error creating client folders in '" + clientFolderVirtualPath.ToHtml() + "'. You will need to create the folder manually. Error: " + ex.Message.ToHtml(), UserMessageType.Warning); } if (populateThemes.HasValue && populateThemes.Value) { List <Theme> newThemes = db.CreateSeedThemes(client); AddUserMessage("Populated Themes", "New Themes added: " + newThemes.Count, UserMessageType.Success); } if (populatePageTemplates.HasValue && populatePageTemplates.Value) { List <PageTemplate> newPageTemplates = db.CreateSeedPageTemplates(client); AddUserMessage("Populated Page Templates", "New Page Templates added: " + newPageTemplates.Count, UserMessageType.Success); } if (populateSampleWebForms.HasValue && populateSampleWebForms.Value) { List <WebForm> newWebForms = db.CreateSeedWebForms(client); AddUserMessage("Populated Simple Web Forms", "New Forms added: " + newWebForms.Count, UserMessageType.Success); } return(RedirectToAction("Index")); } this.BreadCrumbsFunc = html => this.ClientBreadcrumb(html, 0, false, "New"); return(View(client)); }
public ActionResult RecordSummary(int?id) { if (!id.HasValue) { return(HttpBadRequest("store front id is null")); } IGstoreDb db = GStoreDb; StoreFront storeFront = db.StoreFronts.FindById(id.Value); if (storeFront == null) { return(HttpNotFound()); } ViewData.Add("RecordSummary", ChildRecordSummary(storeFront, GStoreDb)); this.BreadCrumbsFunc = htmlHelper => this.StoreFrontBreadcrumb(htmlHelper, storeFront.ClientId, storeFront, false); return(View(storeFront)); }
public ActionResult FieldDelete(int?id) { if (!id.HasValue) { return(HttpBadRequest("Web Form Field id is null")); } IGstoreDb db = GStoreDb; WebFormField webFormField = db.WebFormFields.FindById(id.Value); if (webFormField == null) { return(HttpNotFound("Web Form Field not found. Web Form Field id: " + id)); } this.BreadCrumbsFunc = htmlHelper => this.WebFormFieldBreadcrumb(htmlHelper, webFormField); return(View(webFormField)); }
public ActionResult RecordSummary(int?id) { if (!id.HasValue) { return(HttpBadRequest("client id is null")); } IGstoreDb db = GStoreDb; Client client = db.Clients.FindById(id.Value); if (client == null) { return(HttpNotFound()); } ViewData.Add("RecordSummary", ChildRecordSummary(client, GStoreDb)); this.BreadCrumbsFunc = html => this.ClientBreadcrumb(html, id, false); return(View(client)); }
public ActionResult SectionDelete(int?id) { if (!id.HasValue) { return(HttpBadRequest("Page Template Section id is null")); } IGstoreDb db = GStoreDb; PageTemplateSection section = db.PageTemplateSections.FindById(id.Value); if (section == null) { return(HttpNotFound("Page Template Section not found by id: " + id)); } this.BreadCrumbsFunc = htmlHelper => this.PageTemplateSectionBreadcrumb(htmlHelper, section, false); return(View(section)); }
public ActionResult ListItemDelete(int?id) { if (!id.HasValue) { return(HttpBadRequest("Value List Item id is null")); } IGstoreDb db = GStoreDb; ValueListItem valueListItem = db.ValueListItems.FindById(id.Value); if (valueListItem == null) { return(HttpNotFound("Value List Item not found. Value List Item id: " + id)); } this.BreadCrumbsFunc = htmlHelper => this.ValueListItemBreadcrumb(htmlHelper, valueListItem, false); return(View(valueListItem)); }
public ActionResult SectionIndex(int?id) { if (!id.HasValue) { return(HttpBadRequest("Page Template id is null")); } IGstoreDb db = GStoreDb; PageTemplate template = db.PageTemplates.FindById(id.Value); if (template == null) { return(HttpNotFound("Page Template not found. Page Template id: " + id)); } this.BreadCrumbsFunc = htmlHelper => this.PageTemplateSectionsBreadcrumb(htmlHelper, template, false); return(View(template)); }
/// <summary> /// Processes paypal payment on an order if it has not been done already /// Saves Payment to cart, does not mark cart status /// Exceptions thrown if cart.StatusPlacedOrder = true or cart.OrderId.HasValue /// Otherwise, payment will be processed and if failed, a record with failure code will be returned /// </summary> /// <returns></returns> public static Payment ProcessPayPalPaymentForOrderAndSavePayment(this Cart cart, StoreFrontConfiguration storeFrontConfig, IGstoreDb db) { if (storeFrontConfig == null) { throw new ArgumentNullException("storeFrontConfig"); } if (cart == null) { throw new ArgumentNullException("cart"); } if (!cart.StatusPaymentInfoConfirmed) { throw new ApplicationException("cart.StatusPaymentInfoConfirmed = false. Be sure cart is updated with payment info status = true when payment is selected."); } if (cart.CartPaymentInfo == null) { throw new ArgumentNullException("cart.PaymentInfo"); } if (cart.OrderId.HasValue) { throw new ApplicationException("cart.OrderId.HasValue is set. This cart already has been processed and converted into an order. Order Id: " + cart.OrderId.Value); } if (cart.StatusPlacedOrder) { throw new ApplicationException("cart.StatusPlacedOrder = true. This cart already has been processed and converted into an order."); } if (cart.CartPaymentInfo.PayPalPaymentId.ToLower() != cart.CartPaymentInfo.PayPalReturnPaymentId.ToLower()) { throw new ApplicationException("PayPal Payment id mismatch. PaymentId: " + cart.CartPaymentInfo.PayPalPaymentId + " ReturnPaymentId: " + cart.CartPaymentInfo.PayPalReturnPaymentId); } if (cart.CartPaymentInfo.PaymentSource != Models.BaseClasses.GStorePaymentSourceEnum.PayPal) { throw new ApplicationException("Payment Source not supported: " + cart.CartPaymentInfo.PaymentSource.ToString()); } Payment payment = db.Payments.Create(); payment.SetDefaultsForNew(storeFrontConfig); payment.PaymentSource = cart.CartPaymentInfo.PaymentSource; payment.ProcessDateTimeUtc = DateTime.UtcNow; payment.CartId = cart.CartId; PayPalPaymentData response = new PayPal.Models.PayPalPaymentData(); PayPal.PayPalPaymentClient paypalClient = new PayPal.PayPalPaymentClient(); try { response = paypalClient.ExecutePayPalPayment(storeFrontConfig, cart); if (response.transactions == null || response.transactions.Count() == 0) { throw new ApplicationException("PayPal transactions missing from response. JSON: " + response.Json); } payment.SetFromPayPalPayment(response); payment.PaymentFailed = false; payment.FailureException = null; payment.IsProcessed = true; } catch (Exceptions.PayPalExceptionOAuthFailed exOAuth) { payment.PaymentFailed = true; payment.FailureException = exOAuth.ToString(); payment.Json = response.Json; payment.AmountPaid = 0M; payment.TransactionId = null; payment.IsProcessed = false; } catch (Exceptions.PayPalExceptionExecutePaymentFailed exPaymentFailed) { payment.PaymentFailed = true; payment.FailureException = exPaymentFailed.ToString(); payment.Json = response.Json; payment.AmountPaid = 0M; payment.TransactionId = null; payment.IsProcessed = false; } catch (Exception ex) { payment.PaymentFailed = true; payment.FailureException = ex.ToString(); payment.Json = response.Json; payment.AmountPaid = 0M; payment.TransactionId = null; payment.IsProcessed = false; } db.Payments.Add(payment); db.SaveChanges(); return payment; }
public static void HandleNewUserRegisteredNotifications(this StoreFront storeFront, IGstoreDb db, HttpRequestBase request, UserProfile newProfile, string notificationBaseUrl, bool sendUserWelcome, bool sendRegisteredNotify, string customFields) { UserProfile welcomeUserProfile = storeFront.CurrentConfig().WelcomePerson; //HttpRequestBase request = controller.Request; Notification notification = db.Notifications.Create(); notification.StoreFront = storeFront; notification.Client = storeFront.Client; notification.From = (welcomeUserProfile == null ? "System Administrator" : welcomeUserProfile.FullName); notification.FromUserProfileId = (welcomeUserProfile == null ? 0 : welcomeUserProfile.UserProfileId); notification.ToUserProfileId = newProfile.UserProfileId; notification.To = newProfile.FullName; notification.Importance = "Normal"; notification.Subject = "Welcome!"; notification.UrlHost = request.Url.Host; notification.IsPending = false; notification.StartDateTimeUtc = DateTime.UtcNow; notification.EndDateTimeUtc = DateTime.UtcNow; if (!request.Url.IsDefaultPort) { notification.UrlHost += ":" + request.Url.Port; } notification.BaseUrl = notificationBaseUrl; notification.Message = "Welcome to " + storeFront.CurrentConfig().Name + "!" + "\nEnjoy your stay, and email us if you have any questions, suggestions, feedback, or anything!" + "\n\n" + Settings.IdentitySendGridMailFromName + " - " + Settings.IdentitySendGridMailFromEmail; notification.Message = notification.Message.ToHtmlLines(); //NotificationLink link1 = db.NotificationLinks.Create(); //link1.StoreFront = storeFront; //link1.Client = storeFront.Client; //link1.Order = 1; //link1.IsExternal = false; //link1.LinkText = "My Songs"; //link1.Url = "/Songs"; //link1.Notification = notification; //db.NotificationLinks.Add(link1); //NotificationLink link2 = db.NotificationLinks.Create(); //link2.StoreFront = storeFront; //link2.Client = storeFront.Client; //link2.Order = 2; //link2.IsExternal = false; //link2.LinkText = "Kids Apps"; //link2.Url = "/KidApps"; //link2.Notification = notification; //db.NotificationLinks.Add(link2); //NotificationLink link3 = db.NotificationLinks.Create(); //link3.StoreFront = storeFront; //link3.Client = storeFront.Client; //link3.Order = 3; //link3.IsExternal = false; //link3.LinkText = "My Experimental Apps"; //link3.Url = "/PlayApps"; //link3.Notification = notification; //db.NotificationLinks.Add(link3); //NotificationLink link4 = db.NotificationLinks.Create(); //link4.StoreFront = storeFront; //link4.Client = storeFront.Client; //link4.Order = 4; //link4.IsExternal = true; //link4.LinkText = "Click Here to Email Me"; //link4.Url = "mailto:[email protected]"; //link4.Notification = notification; //db.NotificationLinks.Add(link4); db.Notifications.Add(notification); db.SaveChanges(); UserProfile registeredNotify = storeFront.CurrentConfig().RegisteredNotify; if (registeredNotify != null) { HttpSessionStateBase session = request.RequestContext.HttpContext.Session; string messageBody = "New User Registered on " + storeFront.CurrentConfig().Name + "!" + "\n-Name: " + newProfile.FullName + "\n-Email: " + newProfile.Email + "\n-Date/Time: " + DateTime.UtcNow.ToLocalTime().ToString() + "\n-Send Me More Info: " + newProfile.SendMoreInfoToEmail.ToString() + "\n-Notify Of Site Updates: " + newProfile.NotifyOfSiteUpdatesToEmail.ToString() + "\n-Sign-up Notes: " + newProfile.SignupNotes; if (!string.IsNullOrEmpty(customFields)) { messageBody += "\n-" + customFields; } messageBody += "\n - - - - - - - - - -" + "\n-User Profile Id: " + newProfile.UserProfileId + "\n-Url: " + request.Url.ToString() + "\n-Store Front: " + storeFront.CurrentConfig().Name + "\n-Client: " + storeFront.Client.Name + " [" + storeFront.ClientId + "]" + "\n-Host: " + request.Url.Host + "\n-Raw Url: " + request.RawUrl + "\n-IP Address: " + request.UserHostAddress + "\n-User Agent: " + request.UserAgent + "\n-Session Start Date Time: " + session.EntryDateTime().Value.ToString() + "\n-Session Entry Raw Url: " + session.EntryRawUrl() ?? "(none)" + "\n-Session Entry Url: " + session.EntryUrl() ?? "(none)" + "\n-Session Referrer: " + session.EntryReferrer() ?? "(none)"; Notification newUserNotify = db.Notifications.Create(); newUserNotify.StoreFront = storeFront; newUserNotify.Client = storeFront.Client; newUserNotify.From = (welcomeUserProfile == null ? "System Administrator" : welcomeUserProfile.FullName); newUserNotify.FromUserProfileId = welcomeUserProfile.UserProfileId; newUserNotify.ToUserProfileId = registeredNotify.UserProfileId; newUserNotify.To = registeredNotify.FullName; newUserNotify.Importance = "Normal"; newUserNotify.Subject = "New User Registered on " + storeFront.CurrentConfig().Name + " - " + newProfile.FullName + " <" + newProfile.Email + ">"; newUserNotify.UrlHost = request.Url.Host; newUserNotify.IsPending = false; newUserNotify.StartDateTimeUtc = DateTime.UtcNow; newUserNotify.EndDateTimeUtc = DateTime.UtcNow; if (!request.Url.IsDefaultPort) { newUserNotify.UrlHost += ":" + request.Url.Port; } newUserNotify.BaseUrl = notificationBaseUrl; newUserNotify.Message = messageBody; db.Notifications.Add(newUserNotify); db.SaveChanges(); } }
public static int ResetPagesToThemeId(this StoreFront storeFront, int themeId, IGstoreDb db) { int count = 0; IEnumerable<Page> pages = db.Pages.Where(p => p.StoreFrontId == storeFront.StoreFrontId && p.ThemeId != themeId); foreach (Page page in pages) { if (page.ThemeId != themeId) { page.ThemeId = themeId; db.Pages.Update(page); } count++; } if (count != 0) { db.SaveChanges(); } return count; }
protected string ChildRecordSummary(Client client, IGstoreDb db) { if (client == null) { throw new ArgumentNullException("client"); } if (db == null) { throw new ArgumentNullException("db"); } StringBuilder output = new StringBuilder(); int clientId = client.ClientId; output.AppendLine("--File and Child Record Summary for Client '" + client.Name.ToHtml() + " [" + client.ClientId + "]--"); output.AppendLine("--Client Linked Records--"); output.AppendLine("Client Roles: " + db.ClientRoles.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Client Role Actions: " + db.ClientRoleActions.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Page Templates: " + db.PageTemplates.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Page Template Sections: " + db.PageTemplateSections.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Themes: " + db.Themes.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Web Forms: " + db.WebForms.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Value Lists: " + db.ValueLists.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Value List Items: " + db.ValueListItems.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Web Forms: " + db.WebForms.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Web Form Fields: " + db.WebFormFields.Where(c => c.ClientId == clientId).Count()); output.AppendLine("--Store Front Linked Records--"); output.AppendLine("Store Fronts: " + db.StoreFronts.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Client User Roles: " + db.ClientUserRoles.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Carts: " + db.Carts.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Cart Items: " + db.CartItems.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Cart Bundles: " + db.CartBundles.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Discounts: " + db.Discounts.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Nav Bar Items: " + db.NavBarItems.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Notifications: " + db.Notifications.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Notification Links: " + db.NotificationLinks.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Pages: " + db.Pages.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Page Sections: " + db.PageSections.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Product Categories: " + db.ProductCategories.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Products: " + db.Products.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Product Bundles: " + db.ProductBundles.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Product Bundle Items: " + db.ProductBundleItems.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Store Bindings: " + db.StoreBindings.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Store Front Configurations: " + db.StoreFrontConfigurations.Where(c => c.ClientId == clientId).Count()); output.AppendLine("User Profiles: " + db.UserProfiles.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Web Form Responses: " + db.WebFormResponses.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Web Form FieldResponses: " + db.WebFormFieldResponses.Where(c => c.ClientId == clientId).Count()); output.AppendLine("--event logs--"); output.AppendLine("Bad Requests: " + db.BadRequests.Where(c => c.ClientId == clientId).Count()); output.AppendLine("File Not Found Logs: " + db.FileNotFoundLogs.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Page View Events: " + db.PageViewEvents.Where(c => c.ClientId == clientId).Count()); output.AppendLine("Security Events: " + db.SecurityEvents.Where(c => c.ClientId == clientId).Count()); output.AppendLine("System Events: " + db.SystemEvents.Where(c => c.ClientId == clientId).Count()); output.AppendLine("User Action Events: " + db.UserActionEvents.Where(c => c.ClientId == clientId).Count()); output.AppendLine("--File System--"); string clientFolderPath = Server.MapPath(client.ClientVirtualDirectoryToMap(Request.ApplicationPath)); output.AppendLine("Virtual Directory: '" + client.ClientVirtualDirectoryToMap(Request.ApplicationPath) + "'"); output.AppendLine("Physicial Directory: '" + clientFolderPath + "'"); output.AppendLine("Folder Exists: " + System.IO.Directory.Exists(clientFolderPath)); if (System.IO.Directory.Exists(clientFolderPath)) { output.AppendLine("SubFolders: " + System.IO.Directory.EnumerateDirectories(clientFolderPath, "*", System.IO.SearchOption.AllDirectories).Count()); output.AppendLine("Files: " + System.IO.Directory.EnumerateFiles(clientFolderPath, "*", System.IO.SearchOption.AllDirectories).Count()); } return output.ToString(); }
public BaseController(IGstoreDb dbContext) { _dbContext = dbContext; }
public static Order CreateOrderFromCartAndSave(this Cart cart, StoreFrontConfiguration config, Payment payment, IGstoreDb db) { if (cart == null) { throw new ArgumentNullException("cart"); } if (config == null) { throw new ArgumentNullException("config"); } Order order = db.Orders.Create(); lock (orderNumberLock) { order.OrderNumber = cart.StoreFront.GetAndIncrementOrderNumber(db).ToString(); } order.OriginalCartId = cart.CartId; order.Client = cart.Client; order.ClientId= cart.ClientId; order.CreateDateTimeUtc = DateTime.UtcNow; order.CreatedBy= cart.CreatedBy; order.CreatedBy_UserProfileId= cart.CreatedBy_UserProfileId; order.Discount= cart.Discount; order.DiscountCode= cart.DiscountCode; order.DiscountCodesAttempted= cart.DiscountCodesAttempted; order.DiscountCodesFailed= cart.DiscountCodesFailed; order.DiscountId= cart.DiscountId; order.Email= cart.Email; order.FullName = cart.FullName; order.EndDateTimeUtc= DateTime.UtcNow.AddYears(100); order.EntryDateTimeUtc= cart.EntryDateTimeUtc; order.EntryRawUrl= cart.EntryRawUrl; order.EntryReferrer= cart.EntryReferrer; order.EntryUrl= cart.EntryUrl; order.Handling= cart.Handling; order.IPAddress= cart.IPAddress; order.IsPending= false; order.ItemCount= cart.ItemCount; order.OrderDiscount= cart.OrderDiscount; order.LoginOrGuestWebFormResponse = cart.LoginOrGuestWebFormResponse; order.PaymentInfoWebFormResponse = cart.CartPaymentInfo == null ? null : cart.CartPaymentInfo.WebFormResponse; order.ConfirmOrderWebFormResponse = cart.ConfirmOrderWebFormResponse; order.DeliveryInfoDigital = cart.DeliveryInfoDigital; order.DeliveryInfoShipping = cart.DeliveryInfoShipping; order.AllItemsAreDigitalDownload = cart.AllItemsAreDigitalDownload; order.DigitalDownloadItemCount = cart.DigitalDownloadItemCount; order.ShippingItemCount = cart.ShippingItemCount; order.RefundedAmount = 0; order.SessionId= cart.SessionId; order.Shipping= cart.Shipping; order.StartDateTimeUtc= DateTime.UtcNow.AddMinutes(-1); order.StoreFront= cart.StoreFront; order.StoreFrontId= cart.StoreFrontId; order.Subtotal= cart.Subtotal; order.Tax= cart.Tax; order.Total= cart.Total; order.UpdateDateTimeUtc= DateTime.UtcNow; order.UpdatedBy= cart.UpdatedBy; order.UpdatedBy_UserProfileId= cart.UpdatedBy_UserProfileId; order.UserAgent= cart.UserAgent; order.UserProfile= cart.UserProfile; order.UserProfileId= cart.UserProfileId; order = db.Orders.Add(order); db.SaveChanges(); //note: payment can be null in a PO or invoicing scenario if (payment == null) { order.StatusOrderPaymentProcessed = false; } else { if (payment.IsProcessed) { order.StatusOrderPaymentProcessed = true; if (config.Orders_AutoAcceptPaid) { order.StatusOrderAccepted = true; } else if (order.AllItemsAreDigitalDownload) { //always auto-accept digital download orders because they are available immediately order.StatusOrderAccepted = true; } } //link payment to order payment.Order = order; payment.OrderId = order.OrderId; payment = db.Payments.Update(payment); } foreach (CartBundle cartBundle in cart.CartBundles.AsQueryable().ApplyDefaultSort()) { OrderBundle orderBundle = db.OrderBundles.Create(); orderBundle.ProductBundleId = cartBundle.ProductBundleId; orderBundle.Client = cartBundle.Client; orderBundle.ClientId = cartBundle.ClientId; orderBundle.StoreFront = cartBundle.StoreFront; orderBundle.StoreFrontId = cartBundle.StoreFrontId; orderBundle.CartBundleId = cartBundle.CartBundleId; orderBundle.Order = order; orderBundle.Quantity = cartBundle.Quantity; orderBundle.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1); orderBundle.EndDateTimeUtc = DateTime.UtcNow.AddYears(100); orderBundle.IsPending = false; orderBundle = db.OrderBundles.Add(orderBundle); } if (cart.CartBundles != null && cart.CartBundles.Count != 0) { db.SaveChanges(); } //add order items; foreach (CartItem item in cart.CartItems.AsQueryable().ApplyDefaultSort()) { OrderItem orderItem = db.OrderItems.Create(); orderItem.CartItem = item; orderItem.CartItemId = item.CartItemId; orderItem.Client = item.Client; orderItem.ClientId = item.ClientId; orderItem.CreateDateTimeUtc = DateTime.UtcNow; orderItem.CreatedBy = item.CreatedBy; orderItem.CreatedBy_UserProfileId = item.CreatedBy_UserProfileId; orderItem.EndDateTimeUtc = DateTime.UtcNow.AddYears(100); orderItem.IsPending = false; orderItem.ItemRefundedAmount = 0; orderItem.IsDigitalDownload = item.Product.DigitalDownload; if (payment != null && payment.IsProcessed) { orderItem.StatusItemPaymentReceived = true; } else { orderItem.StatusItemPaymentReceived = false; } orderItem.StatusItemPaymentReceived = order.StatusOrderPaymentProcessed; orderItem.StatusItemAccepted = order.StatusOrderAccepted; orderItem.LineDiscount = item.LineDiscount; orderItem.LineTotal = item.LineTotal; orderItem.ListPrice = item.ListPrice; orderItem.ListPriceExt = item.ListPriceExt; orderItem.Order = order; orderItem.OrderId = order.OrderId; orderItem.Product = item.Product; orderItem.ProductId = item.ProductId; orderItem.ProductVariantInfo = item.ProductVariantInfo; orderItem.Quantity = item.Quantity; orderItem.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1); orderItem.StoreFront = item.StoreFront; orderItem.StoreFrontId = item.StoreFrontId; orderItem.UnitPrice = item.UnitPrice; orderItem.UnitPriceExt = item.UnitPriceExt; orderItem.UpdateDateTimeUtc = DateTime.UtcNow; orderItem.UpdatedBy = item.UpdatedBy; orderItem.UpdatedBy_UserProfileId = item.UpdatedBy_UserProfileId; orderItem.ProductBundleItemId = item.ProductBundleItemId; if (item.CartBundleId.HasValue) { OrderBundle orderBundle = order.OrderBundles.Single(ob => ob.CartBundleId == item.CartBundleId); orderItem.OrderBundleId = orderBundle.OrderBundleId; } orderItem = db.OrderItems.Add(orderItem); } db.SaveChanges(); return order; }
private static IGstoreDb NewRepository(string userName) { //get setting for repositorysource and create repository switch (RepositoryProvider()) { case RepositoryProviderEnum.EntityFrameworkCodeFirstProvider: return new EntityFrameworkCodeFirstProvider.GStoreEFDbContext(userName); case RepositoryProviderEnum.ListProvider : //note ListProvider uses a single static list, no copies or real separate contexts _listDb = new ListProvider.ListContext(); SeedDataExtensions.AddSeedData(_listDb); return _listDb; //allow for other repositories, perhaps by class or project name; and config mapping here //Example: pull in a provider that takes some lists, some ef, some web services, some whoknowswhats default: break; } throw new ApplicationException("Unable to create repository:" + RepositoryProvider().ToString()); }
public static int GetAndIncrementOrderNumber(this StoreFront storeFront, IGstoreDb db) { lock (orderNumberLock) { IGstoreDb newDb = db.NewContext(); int orderNumber = 1001; StoreFront safeStoreFront = newDb.StoreFronts.Single(s => s.StoreFrontId == storeFront.StoreFrontId); if (safeStoreFront.NextOrderNumber > 0) { orderNumber = safeStoreFront.NextOrderNumber; } safeStoreFront.NextOrderNumber = orderNumber + 1; safeStoreFront = newDb.StoreFronts.Update(safeStoreFront); newDb.SaveChangesDirect(); storeFront = db.Refresh<StoreFront>(storeFront); return orderNumber; } }
/// <summary> /// Migrates anonymous orders to a new user profile; used when user signs up to bring their anonymous orders with them /// saves changes when done /// </summary> /// <param name="storeFront"></param> /// <param name="db"></param> /// <param name="userProfile"></param> /// <param name="controller"></param> public static void MigrateOrdersToNewProfile(this StoreFront storeFront, IGstoreDb db, UserProfile userProfile, BaseController controller) { if (storeFront == null) { throw new ArgumentNullException("storeFront"); } if (userProfile == null) { throw new ArgumentNullException("userProfile"); } if (controller == null) { throw new ArgumentNullException("controller"); } List<Order> orders = storeFront.Orders.Where(o => o.UserProfileId == null && o.Email.ToLower() == userProfile.Email.ToLower()).ToList(); foreach (Order order in orders) { order.UserProfileId = userProfile.UserProfileId; db.Orders.Update(order); } if (orders.Count != 0) { db.SaveChanges(); controller.AddUserMessage("Orders Available", "Your orders (" + orders.Count.ToString("N0") + ") are now available on your profile page.", UserMessageType.Info); } }
public static void HandleLockedOutNotification(this StoreFront storeFront, IGstoreDb db, HttpRequestBase request, UserProfile profile, string notificationBaseUrl, string forgotPasswordUrl) { //notify user through site message if their account is locked out, and it has been at least an hour since they were last told they are locked out if (profile.LastLockoutFailureNoticeDateTimeUtc != null && (DateTime.UtcNow - profile.LastLockoutFailureNoticeDateTimeUtc.Value).Hours < 1) { //user has been notified in the past hour, do not re-notify return; } UserProfile accountAdmin = storeFront.CurrentConfig().AccountAdmin; Notification notification = db.Notifications.Create(); notification.StoreFront = storeFront; notification.Client = storeFront.Client; notification.ToUserProfileId = profile.UserProfileId; notification.From = (accountAdmin == null ? "System Administrator" : accountAdmin.FullName); notification.FromUserProfileId = (accountAdmin == null ? 0 : accountAdmin.UserProfileId); notification.To = profile.FullName; notification.Importance = "Low"; notification.Subject = "Login failure for " + request.Url.Host; notification.IsPending = false; notification.EndDateTimeUtc = DateTime.UtcNow; notification.StartDateTimeUtc = DateTime.UtcNow; notification.UrlHost = request.Url.Host; if (!request.Url.IsDefaultPort) { notification.UrlHost += ":" + request.Url.Port; } notification.BaseUrl = notificationBaseUrl; notification.Message = "Somebody tried to log on as you with the wrong password at " + request.Url.Host + " \n\nFor security reasons, your account has been locked out for 5 minutes." + " \n\nIf this was you, please disregard this message and try again in 5 minutes." + " \n\nIf you forgot your password, you can reset it at " + forgotPasswordUrl + " \n\nIf this was not you, the below information may be helpful." + " \n\nIP Address: " + request.UserHostAddress + " \nHost Name: " + request.UserHostName; notification.Message = notification.Message.ToHtmlLines(); db.Notifications.Add(notification); db.SaveChanges(); UserProfile profileUpdate = db.UserProfiles.FindById(profile.UserProfileId); profileUpdate.LastLockoutFailureNoticeDateTimeUtc = DateTime.UtcNow; db.SaveChangesDirect(); }