//------------------------------------------------------------------------------------------- protected void LedgerItemAdd_Click(object sender, EventArgs e) { //List.ShowFooter = true; //List.EditItemIndex = List.Items.Count; LedgerType ledgerType = (LedgerType)Enum.Parse(typeof(LedgerType), Request["ledgertype"], true); using (WeavverEntityContainer data = new WeavverEntityContainer()) { Accounting_LedgerItems item = new Accounting_LedgerItems(); item.Id = Guid.NewGuid(); item.OrganizationId = BasePage.SelectedOrganization.Id; item.LedgerType = ledgerType.ToString(); item.Code = ((CodeType)Enum.Parse(typeof(CodeType), CodeTypeList.SelectedValue, true)).ToString(); item.PostAt = DateTime.Parse(LedgerItemPostAt.Text).ToUniversalTime(); item.AccountId = new Guid(Request["AccountId"]); item.Memo = LedgerItemName.Text; item.Amount = Decimal.Parse(LedgerItemAmount.Text); data.Accounting_LedgerItems.AddObject(item); try { data.SaveChanges(); ErrorMsg.Text = ""; OnDataSaved(this, EventArgs.Empty); } catch (IValidatorException ex) { ErrorMsg.Text = ex.Message; } } }
//------------------------------------------------------------------------------------------- public void UpdateTotals() { using (WeavverEntityContainer data = new WeavverEntityContainer()) { foreach (DataGridItem dataitem in List.Items) { Guid key = (Guid)List.DataKeys[dataitem.ItemIndex]; foreach (Sales_ShoppingCartItems item in ShoppingCart.Items) { if (item.Id == key) { int quantity = item.Quantity; TextBox tbQuantity = (TextBox)dataitem.Cells[1].Controls[0]; Int32.TryParse(tbQuantity.Text, out quantity); bool changed = false; if (quantity == 0) { data.Sales_ShoppingCartItems.Attach(item); ShoppingCart.Items.Remove(item); data.Sales_ShoppingCartItems.DeleteObject(item); continue; } else if (quantity != item.Quantity) { data.Sales_ShoppingCartItems.Attach(item); item.Quantity = quantity; } } } } data.SaveChanges(); } }
//------------------------------------------------------------------------------------------- protected void TransferFunds_Click(object sender, EventArgs e) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { DateTime postAtDate = DateTime.UtcNow; if (DateTime.TryParse(PostAt.Text, out postAtDate)) { postAtDate = postAtDate.ToUniversalTime(); } Accounting_Accounts accountFrom = (from accounts in data.Accounting_Accounts where accounts.Id == new Guid(FromAccount.SelectedValue) select accounts).FirstOrDefault(); Accounting_Accounts accountTo = (from toAccounts in data.Accounting_Accounts where toAccounts.Id == new Guid(ToAccount.SelectedValue) select toAccounts).FirstOrDefault(); Guid transactionId = Guid.NewGuid(); Accounting_LedgerItems debitAccount1 = new Accounting_LedgerItems(); debitAccount1.OrganizationId = BasePage.SelectedOrganization.Id; debitAccount1.TransactionId = transactionId; debitAccount1.PostAt = postAtDate; debitAccount1.AccountId = accountFrom.Id; debitAccount1.LedgerType = accountFrom.LedgerType; debitAccount1.Code = CodeType.Withdrawal.ToString(); debitAccount1.Memo = String.Format("Transfer to {0}", accountTo.Name); debitAccount1.Amount = Decimal.Parse(Amount.Text) * -1.0m; data.Accounting_LedgerItems.AddObject(debitAccount1); Accounting_LedgerItems creditAccount2 = new Accounting_LedgerItems(); creditAccount2.OrganizationId = BasePage.SelectedOrganization.Id; creditAccount2.TransactionId = transactionId; creditAccount2.PostAt = postAtDate; creditAccount2.AccountId = new Guid(ToAccount.SelectedValue); creditAccount2.LedgerType = accountTo.LedgerType; creditAccount2.Code = CodeType.Deposit.ToString(); creditAccount2.Memo = String.Format("Transfer from {0}", accountFrom.Name); creditAccount2.Amount = Decimal.Parse(Amount.Text); data.Accounting_LedgerItems.AddObject(creditAccount2); data.SaveChanges(); // Response.Redirect("~/Accounting_LedgerItems/List.aspx?TransactionId=" + transactionId.ToString()); } OnDataSaved(this, EventArgs.Empty); }
//------------------------------------------------------------------------------------------- protected void MakePayment_Click(object sender, EventArgs e) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { DateTime postAtDate = DateTime.UtcNow; if (DateTime.TryParse(PostAt.Text, out postAtDate)) { postAtDate = postAtDate.ToUniversalTime(); } Logistics_Organizations accountFrom = (from accounts in data.Logistics_Organizations where accounts.Id == new Guid(FromAccount.SelectedValue) select accounts).FirstOrDefault(); Accounting_Accounts accountTo = (from toAccounts in data.Accounting_Accounts where toAccounts.Id == new Guid(ToAccount.SelectedValue) select toAccounts).FirstOrDefault(); Guid transactionId = Guid.NewGuid(); Accounting_LedgerItems creditFinancialAccount = new Accounting_LedgerItems(); creditFinancialAccount.OrganizationId = SelectedOrganization.Id; creditFinancialAccount.TransactionId = transactionId; creditFinancialAccount.PostAt = postAtDate; creditFinancialAccount.AccountId = accountFrom.Id; creditFinancialAccount.LedgerType = LedgerType.Receivable.ToString(); creditFinancialAccount.Code = CodeType.Deposit.ToString(); creditFinancialAccount.Memo = String.Format("Check {0} to {1}", CheckNum.Text, accountTo.Name); creditFinancialAccount.Amount = Decimal.Parse(Amount.Text); data.Accounting_LedgerItems.AddObject(creditFinancialAccount); Accounting_LedgerItems creditReceivableAccount = new Accounting_LedgerItems(); creditReceivableAccount.OrganizationId = SelectedOrganization.Id; creditReceivableAccount.TransactionId = transactionId; creditReceivableAccount.PostAt = postAtDate; creditReceivableAccount.LedgerType = accountTo.LedgerType; creditReceivableAccount.AccountId = new Guid(ToAccount.SelectedValue); creditReceivableAccount.Code = CodeType.Payment.ToString(); creditReceivableAccount.Memo = String.Format("Check {0} from {1}", CheckNum.Text, accountFrom.Name); creditReceivableAccount.Amount = Decimal.Parse(Amount.Text); data.Accounting_LedgerItems.AddObject(creditReceivableAccount); data.SaveChanges(); Response.Redirect("~/Accounting_LedgerItems/List.aspx?TransactionId=" + transactionId.ToString()); } }
//------------------------------------------------------------------------------------------- protected void OFXImport_Click(object sender, EventArgs e) { List <Accounting_OFXLedgerItem> PreviewLedgerItems = (List <Accounting_OFXLedgerItem>)Session["Import_Transactions"]; using (WeavverEntityContainer data = new WeavverEntityContainer()) { for (int i = 0; i < TransactionsDetected.Items.Count; i++) { Guid rowId = new Guid(TransactionsDetected.Items[i].Cells[0].Text); CheckBox importRow = (CheckBox)FindControlRecursive(TransactionsDetected.Items[i].Cells[1], "ImportRow"); if (importRow == null || !importRow.Checked) { continue; } // Load from safe server side dataset var item = (from y in PreviewLedgerItems where y.LedgerItem.Id == rowId select y).First(); TextBox memoField = (TextBox)FindControlRecursive(TransactionsDetected.Items[i].Cells[5], "Memo"); if (memoField != null && item.LedgerItem.Memo != memoField.Text) { item.LedgerItem.Memo = memoField.Text; } data.Accounting_LedgerItems.AddObject(item.LedgerItem); } ClearError(); decimal successCount = data.SaveChanges(); ShowError("Imported " + successCount.ToString() + " row(s)."); } List <Accounting_LedgerItems> LedgerItems = new List <Accounting_LedgerItems>(); foreach (var item in PreviewLedgerItems) { LedgerItems.Add(item.LedgerItem); } var sortedItems = LedgerItems.OrderByDescending(x => x.PostAt); TransactionsDetected.DataSource = sortedItems; TransactionsDetected.DataBind(); }
//------------------------------------------------------------------------------------------- void List_ItemCommand(object source, DataGridCommandEventArgs e) { Guid key = (Guid)List.DataKeys[e.Item.ItemIndex]; //ShoppingCart.Items.Remove(item); using (WeavverEntityContainer data = new WeavverEntityContainer()) { var cartItem = (from item in data.Sales_ShoppingCartItems where item.Id == key && item.OrganizationId == SelectedOrganization.Id && item.SessionId == Session.SessionID select item).FirstOrDefault(); if (cartItem != null) { data.Sales_ShoppingCartItems.DeleteObject(cartItem); data.SaveChanges(); } } UpdatePage(); }
//------------------------------------------------------------------------------------------- void Session_End(object sender, EventArgs e) { if (ConfigurationManager.AppSettings["install_mode"] == "false") { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. using (WeavverEntityContainer data = new WeavverEntityContainer()) { var cartItems = from item in data.Sales_ShoppingCartItems where item.SessionId == Session.SessionID select item; foreach (Sales_ShoppingCartItems item in cartItems) { data.Sales_ShoppingCartItems.DeleteObject(item); } data.SaveChanges(); } } }
protected void Page_Load(object sender, EventArgs e) { // add a check to see that the user has access to this object //Response.WriteFile("C:\\.rnd"); if (Request["redir"] != null) { using (WeavverEntityContainer dataContext = new WeavverEntityContainer()) { IT_DownloadLogs downloadLog = new IT_DownloadLogs(); downloadLog.Id = Guid.NewGuid(); downloadLog.OrganizationId = SelectedOrganization.Id; downloadLog.FileName = System.IO.Path.GetFileName(Request["redir"]); downloadLog.DownloadedAt = DateTime.UtcNow; downloadLog.DownloadedByIP = Request.UserHostAddress; downloadLog.DownloadedBy = LoggedInUser.Id; dataContext.AddToIT_DownloadLogs(downloadLog); dataContext.SaveChanges(); Response.Redirect(Request["redir"]); } } }
//------------------------------------------------------------------------------------------- protected void CaptchaStepNext_Click(object sender, EventArgs e) { if (Request["checkingout"] == "true" || Request["recaptcha_response_field"] == ConfigurationManager.AppSettings["recaptcha_bypasskey"] || Weavver.Vendors.Google.reCAPTCHA.Verify(ConfigurationManager.AppSettings["recaptcha_privatekey"], Request.UserHostAddress, Request["recaptcha_challenge_field"], Request["recaptcha_response_field"])) { string emailaddress = ((TextBox)GetControlFromWizard(UserInfoStep, "EmailAddress")).Text; string username = ((TextBox)GetControlFromWizard(UserInfoStep, "UserName")).Text; string password = ((TextBox)GetControlFromWizard(UserInfoStep, "Password")).Text; string firstname = ((TextBox)GetControlFromWizard(UserInfoStep, "FirstName")).Text; string lastname = ((TextBox)GetControlFromWizard(UserInfoStep, "LastName")).Text; string orgname = ((TextBox)GetControlFromWizard(UserInfoStep, "OrganizationName")).Text; string referredby = (Session["ReferredBy"] == null) ? null : Session["referredby"].ToString(); WeavverMembershipProvider provider = (WeavverMembershipProvider)System.Web.Security.Membership.Provider; MembershipCreateStatus status = MembershipCreateStatus.Success; MembershipUser user = provider.CreateUser(username, Session["UserPassword"].ToString(), emailaddress, "NONE", "", false, Guid.NewGuid(), Request.UserHostAddress, referredby, out status); if (status == MembershipCreateStatus.Success) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { System_Users newUser = provider.GetUser(username); Logistics_Organizations newOrg = new Logistics_Organizations(); newOrg.Id = Guid.NewGuid(); newOrg.OrganizationId = new Guid(ConfigurationManager.AppSettings["default_organizationid"]); newOrg.OrganizationType = OrganizationTypes.Personal.ToString(); newOrg.Name = (!String.IsNullOrEmpty(orgname)) ? orgname : firstname + " " + lastname; newOrg.EIN = ""; newOrg.Founded = DateTime.UtcNow; newOrg.Bio = "My bio"; newOrg.CreatedAt = DateTime.UtcNow; newOrg.CreatedBy = newUser.Id; newOrg.UpdatedAt = DateTime.UtcNow; newOrg.UpdatedBy = newUser.Id; data.Logistics_Organizations.AddObject(newOrg); data.System_Users.Attach(newUser); newUser.OrganizationId = newOrg.Id; newUser.FirstName = firstname; newUser.LastName = lastname; int changedRows = data.SaveChanges(); if (changedRows > 0) { // add this user as an administrator to their ORG string oldAppName = Roles.ApplicationName; Roles.ApplicationName = newOrg.Id.ToString(); Roles.CreateRole("Administrators"); Roles.AddUserToRole(newUser.Username, "Administrators"); Roles.ApplicationName = oldAppName; } } //newOrg.Commit(); MailMessage mNewUser = new MailMessage("*****@*****.**", System.Configuration.ConfigurationManager.AppSettings["admin_address"]); mNewUser.Subject = "New user"; //mm.Body = CreateUserWizard1.Email; mNewUser.Body = "User: "******"\r\n" + "Created At: " + DateTime.Now.ToString() + "\r\n" + "By IP: " + Request.UserHostAddress + "\r\n" + "Referred By: " + Session["ReferredBy"]; SmtpClient client2 = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["smtp_server"]); client2.Send(mNewUser); FormsAuthentication.SetAuthCookie(username, true); if (Request.QueryString["checkingout"] == "true") { Response.Redirect("~/workflows/sales_orderplace"); } else { provider.SendUserActivationInstructions(user.UserName, Request.Url.Scheme + "://" + Request.Url.Host); Wizard1.ActiveStepIndex++; } } else { throw new Exception("We could not create your account. Please try again later."); } } else { ReloadCaptcha(); ((Literal)GetControlFromWizard(CaptchaStep, "CaptchaError")).Text = "Please try again."; } }
//------------------------------------------------------------------------------------------- protected void Page_Load(object sender, EventArgs e) { IsPublic = true; if (Request["x_response_code"] == "1") { using (WeavverEntityContainer data = new WeavverEntityContainer()) { Accounting_LedgerItems item = new Accounting_LedgerItems(); item.OrganizationId = SelectedOrganization.Id; item.Id = Guid.NewGuid(); item.PostAt = DateTime.UtcNow; item.AccountId = new Guid(Request["accountid"]); item.LedgerType = LedgerType.Savings.ToString(); item.Code = CodeType.Deposit.ToString(); item.Memo = Request["x_first_name"] + " " + Request["x_last_name"] + ", TXNID#" + Request["x_trans_id"] + ", ACCT#" + Request["x_account_number"]; item.Amount = Decimal.Parse(Request["x_amount"]); item.CreatedAt = DateTime.UtcNow; item.CreatedBy = (LoggedInUser == null) ? Guid.Empty : LoggedInUser.Id; item.UpdatedAt = DateTime.UtcNow; item.UpdatedBy = (LoggedInUser == null) ? Guid.Empty : LoggedInUser.Id; Guid orderId = Guid.Empty; if (Guid.TryParse(Request["OrderId"], out orderId)) { item.TransactionId = orderId; } data.Accounting_LedgerItems.AddObject(item); data.SaveChanges(); } } else { string toHash = ConfigurationManager.AppSettings["authorize.net_hash"] + Request["authorize.net_loginid"] + Request["x_trans_id"] + Request["x_amount"]; MailMessage message = new MailMessage(); message.From = new MailAddress("*****@*****.**"); message.To.Add(new MailAddress(ConfigurationManager.AppSettings["admin_address"])); message.Subject = "Unhandled Silent Post"; message.Body = "Silent post to: \r\n\r\n"; //message.Body += Request["aspxerrorpath"] + "\r\n\r\n"; message.Body += "To hash: " + toHash + "\r\n"; for (int i = 0; i < Request.ServerVariables.Count; i++) { message.Body += Request.ServerVariables.Keys[i] + ": " + Request.ServerVariables[i] + "\r\n"; } message.Body += "\r\nQuery String:\r\n"; for (int i = 0; i < Request.QueryString.Count; i++) { message.Body += Request.QueryString.Keys[i] + ": " + Request.QueryString[i] + "\r\n"; } message.Body += "\r\nPOST:\r\n"; for (int i = 0; i < Request.Form.Count; i++) { message.Body += Request.Form.Keys[i] + ": " + Request.Form[i] + "\r\n"; } SmtpClient client = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]); client.Send(message); } }
//------------------------------------------------------------------------------------------- private void PlaceOrder() { if (Page.IsValid) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { Communication_MessageTemplates orderPlacedTemplate = (from x in data.Communication_MessageTemplates where x.Id == new Guid("f6df7db7-5efb-475d-8e32-3dd7e293ce3b") select x).First(); string msgBody = orderPlacedTemplate.Body.Replace("{cart}", ShoppingCart.ToString()); string placedat = DateTime.Now.ToString("MM/dd/yy"); // (ShoppingCart.CreatedAt.HasValue) ? ShoppingCart.CreatedAt.Value.ToString("MM/dd/yy") : "unknown"; string orderee = PrimaryContact.FirstName.Text + " " + PrimaryContact.LastName.Text; string mPrimaryAddress = PrimaryContact.AddressLine1.Text + "\r\n" + PrimaryContact.AddressLine2.Text; string mBillingAddress = BillingContact.AddressLine1.Text + "\r\n" + BillingContact.AddressLine2.Text; msgBody = msgBody.Replace("{name}", orderee); msgBody = msgBody.Replace("{placed}", placedat); string primarycontact = "Name: " + orderee + "\r\n"; primarycontact += "Organization: " + PrimaryContact.Organization.Text + "\r\n"; primarycontact += "Address: " + mPrimaryAddress.Trim() + "\r\n"; primarycontact += "Zip Code: " + PrimaryContact.ZipCode.Text; msgBody = msgBody.Replace("{primary_contact}", primarycontact.Trim()); string billingcontact = "Name: " + BillingContact.FirstName.Text + " " + BillingContact.LastName.Text + "\r\n"; billingcontact += "Organization: " + BillingContact.Organization.Text + "\r\n"; billingcontact += "Address: " + mBillingAddress.Trim() + "\r\n"; billingcontact += "Zip Code: " + BillingContact.ZipCode.Text; msgBody = msgBody.Replace("{billing_contact}", billingcontact.Trim()); Logistics_Addresses primaryAddress = new Logistics_Addresses(); primaryAddress.OrganizationId = SelectedOrganization.Id; primaryAddress.Id = Guid.NewGuid(); primaryAddress.Name = "Primary Address"; primaryAddress.Line1 = PrimaryContact.AddressLine1.Text; primaryAddress.Line2 = PrimaryContact.AddressLine2.Text; primaryAddress.City = ""; primaryAddress.State = ""; primaryAddress.ZipCode = PrimaryContact.ZipCode.Text; data.Logistics_Addresses.AddObject(primaryAddress); // DatabaseHelper.Link(newOrder, primaryAddress); // newOrder.PrimaryAddress = primaryAddress; Logistics_Addresses billingAddress = new Logistics_Addresses(); billingAddress.OrganizationId = SelectedOrganization.Id; billingAddress.Id = Guid.NewGuid(); billingAddress.Name = "Billing Address"; billingAddress.Line1 = BillingContact.AddressLine1.Text; billingAddress.Line2 = BillingContact.AddressLine2.Text; billingAddress.City = ""; billingAddress.State = ""; billingAddress.ZipCode = BillingContact.ZipCode.Text; data.Logistics_Addresses.AddObject(billingAddress); // DatabaseHelper.Link(newOrder, billingAddress); // newOrder.BillingAddress = billingAddress; Sales_Orders newOrder = new Sales_Orders(); newOrder.Id = Guid.NewGuid(); newOrder.OrganizationId = SelectedOrganization.Id; if (LoggedInUser != null) { newOrder.Orderee = LoggedInUser.OrganizationId; } newOrder.Cart = msgBody; newOrder.Status = "Placed"; newOrder.Total = ShoppingCart.Total; newOrder.PrimaryContactEmail = PrimaryContact.EmailAddress.Text; newOrder.PrimaryContactNameFirst = PrimaryContact.FirstName.Text; newOrder.PrimaryContactNameLast = PrimaryContact.LastName.Text; newOrder.PrimaryContactOrganization = PrimaryContact.Organization.Text; newOrder.PrimaryContactPhoneNum = PrimaryContact.PhoneNumber.Text; newOrder.PrimaryContactPhoneExt = PrimaryContact.PhoneExtension.Text; newOrder.PrimaryContactAddress = primaryAddress.Id; newOrder.BillingContactEmail = BillingContact.EmailAddress.Text; newOrder.BillingContactNameFirst = BillingContact.FirstName.Text; newOrder.BillingContactNameLast = BillingContact.LastName.Text; newOrder.BillingContactOrganization = BillingContact.Organization.Text; newOrder.BillingContactPhoneNum = BillingContact.PhoneNumber.Text; newOrder.BillingContactPhoneExt = BillingContact.PhoneExtension.Text; newOrder.BillingContactAddress = billingAddress.Id; newOrder.Notes = SpecialInstructions.Text; data.Sales_Orders.AddObject(newOrder); Accounting_CreditCards card = new Accounting_CreditCards(); card.Id = Guid.NewGuid(); card.OrganizationId = SelectedOrganization.Id; card.Number = PaymentMethod1.CardNumber.Text; card.SecurityCode = PaymentMethod1.SecCode.Text; card.ExpirationMonth = Int32.Parse(PaymentMethod1.ExpMonth.SelectedValue); card.ExpirationYear = Int32.Parse(PaymentMethod1.ExpYear.SelectedValue); data.Accounting_CreditCards.AddObject(card); // DatabaseHelper.Link(newOrder, card); foreach (Sales_ShoppingCartItems item in ShoppingCart.Items) { item.SessionId = null; item.OrderId = newOrder.Id; data.Sales_ShoppingCartItems.Attach(item); if (item.Monthly > 0m && item.Quantity > 0) { // Set up the ARB process Accounting_RecurringBillables rBillable = new Accounting_RecurringBillables(); rBillable.Id = Guid.NewGuid(); rBillable.OrganizationId = SelectedOrganization.Id; rBillable.Service = item.Id; rBillable.BillingDirection = "Pre-Bill"; rBillable.BillingPeriod = BillingPeriodType.Monthly.ToString(); rBillable.Memo = item.Name + ", %timespan%\r\n" + item.Notes; rBillable.StartAt = DateTime.UtcNow; rBillable.Status = RecurringBillableStatus.Enabled.ToString(); rBillable.Position = DateTime.UtcNow.AddMonths(1); rBillable.AccountFrom = LoggedInUser.OrganizationId; rBillable.AccountTo = SelectedOrganization.Id; rBillable.Amount = item.Monthly; data.Accounting_RecurringBillables.AddObject(rBillable); //DatabaseHelper.Link(newOrder, rBillable); } for (int i = 0; i < item.Quantity; i++) { // Insert the initial ledger items Accounting_LedgerItems ledgerItemDebit = new Accounting_LedgerItems(); ledgerItemDebit.OrganizationId = SelectedOrganization.Id; ledgerItemDebit.Id = Guid.NewGuid(); ledgerItemDebit.TransactionId = newOrder.Id; ledgerItemDebit.PostAt = DateTime.UtcNow; ledgerItemDebit.AccountId = newOrder.Id; ledgerItemDebit.LedgerType = LedgerType.Receivable.ToString(); ledgerItemDebit.Code = CodeType.Sale.ToString(); ledgerItemDebit.Memo = item.Name + "\r\n" + item.Notes; ledgerItemDebit.Amount = Math.Abs(item.UnitCost) * -1.0m; data.Accounting_LedgerItems.AddObject(ledgerItemDebit); // It is unnecessary to link these since we provide a link to the Receivable ledger. //// DatabaseHelper.Link(newOrder, ledgerItemDebit); } } AuthorizeNet.IGatewayResponse resp = card.Bill(data, newOrder, primaryAddress, billingAddress); if (resp.Approved) { // Accounting.ProcessCommision(newOrder, SelectedOrganization.ReferredBy); if (LoggedInUser != null && !LoggedInUser.Activated) { data.System_Users.Attach(LoggedInUser); LoggedInUser.Activated = true; } data.SaveChanges(); ShoppingCart.Items.Clear(); // Send receipt MailMessage msg = new MailMessage("Weavver Sales <*****@*****.**>", PrimaryContact.EmailAddress.Text); msg.Subject = orderPlacedTemplate.Subject; msg.Body = msgBody; SmtpClient sClient = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]); try { sClient.Send(msg); var type = typeof(IOrderEvents); var types = AppDomain.CurrentDomain.GetAssemblies().ToList() .Where(y => y.FullName.Contains("WeavverExtension")) .SelectMany(s => s.GetTypes()) .Where(p => type.IsAssignableFrom(p) && p.IsClass); foreach (var interfacedClassType in types) { foreach (Sales_ShoppingCartItems purchasedItem in ShoppingCart.Items) { if (purchasedItem.Quantity > 0) { object o = Activator.CreateInstance(interfacedClassType); var orderEvents = o as IOrderEvents; orderEvents.Provision(newOrder, purchasedItem); } } } } catch (Exception ex) { Weavver.Utilities.ErrorHandling.LogError(Request, "/workflows/sales_orderplace", ex); ShowError("Your order was placed but a receipt could not be sent due to a system error. Please contact customer service for further assistance."); return; } Response.Redirect("~/CMS_Pages/Details.aspx?id=071c0768-84ed-4770-9519-a98806a87c68&OrderId=" + newOrder.Id.ToString()); } else { ShowError("Your card did not go through because '" + resp.Message + "'. Please check the card number and try again."); return; } } } }
//------------------------------------------------------------------------------------------- protected void Next_Click(object sender, EventArgs e) { string notes = item.BillingNotes; if (!String.IsNullOrEmpty(notes)) { notes += "\r\n"; } using (WeavverEntityContainer data = new WeavverEntityContainer()) { var features = from x in data.Logistics_Features where x.OrganizationId == SelectedOrganization.Id && x.ParentId == item.Id orderby x.Name select x; int idPos = 0; Sales_ShoppingCartItems shoppingCartItem = Sales_ShoppingCartItems.GetInstance(Server.MapPath("~/bin"), item.PluginURL); int i = 0; foreach (Logistics_Features feature in features) { DropDownList ddl = (DropDownList)UpdatePanel1.ContentTemplateContainer.FindControl("OrderFormControls").FindControl("feature-" + i.ToString()); Guid featureOptionId = new Guid(ddl.SelectedValue); Logistics_FeatureOptions option = (from x in data.Logistics_FeatureOptions where x.Id == featureOptionId select x).First(); notes += "- " + data.GetName(option.ParentId) + ": " + option.Name; if (i < features.Count() - 1) { notes += "\r\n"; } i++; } shoppingCartItem.SessionId = Session.SessionID; shoppingCartItem.OrganizationId = SelectedOrganization.Id; shoppingCartItem.ProductId = item.Id; if (LoggedInUser != null) { shoppingCartItem.UserId = LoggedInUser.Id; } shoppingCartItem.Name = item.Name; shoppingCartItem.Notes = notes; shoppingCartItem.Deposit = item.Deposit; shoppingCartItem.SetUp = item.SetUp; // TODO: add set-up summing for sub features - add provisioning time tracking to sub-features shoppingCartItem.UnitCost = CalculateOneTimeCosts(); shoppingCartItem.Monthly = CalculateMonthlyTotal(); shoppingCartItem.Quantity = Int32.Parse(Quantity.Text); shoppingCartItem.RequiresOrganizationId = true; shoppingCartItem.BackLink = Request.Url.ToString(); var customForm = (ISales_OrderForm)OrderFormCell.FindControlR <Control>("CustomOrderForm"); if (customForm != null) { customForm.BeforeAddingToCart(shoppingCartItem); } data.Sales_ShoppingCartItems.AddObject(shoppingCartItem); data.SaveChanges(); string reviewurl = "~/workflows/sales_orderreview"; if (Request["IFrame"] == "true") { reviewurl += "?IFrame=true"; } Response.Redirect(reviewurl); } }
//------------------------------------------------------------------------------------------- protected void Page_Load(object sender, EventArgs e) { IsPublic = true; Response.ContentType = "text/plain"; MemoryStream ms = new MemoryStream(); writer = new XmlTextWriter(ms, new UTF8Encoding(false)); //writer.Indentation = 5; writer.Formatting = Formatting.Indented; writer.WriteStartDocument(); if (Request["action"] == "resettestkey") { using (WeavverEntityContainer data = new WeavverEntityContainer()) { string testKey = System.Configuration.ConfigurationManager.AppSettings["sales_licensekeys_locatortestkey"]; var key = (from a in data.Sales_LicenseKeys where a.Key == testKey select a).FirstOrDefault(); if (key == null) { writer.WriteStartElement("FAIL_NO_KEY_FOUND"); writer.WriteEndElement(); } else { var activations = (from b in data.Sales_LicenseKeyActivations where b.LicenseKeyId == key.Id select b); var rows = activations.ToList(); rows.ForEach(x => data.Sales_LicenseKeyActivations.DeleteObject(x)); data.SaveChanges(); writer.WriteStartElement("OK"); writer.WriteEndElement(); } } } else { try { IssueKey(); } catch (Exception ex) { writer.WriteStartElement("ActivationRequestRejected"); WriteAttribute("Reason", ex.Message); writer.WriteEndElement(); } } writer.WriteEndDocument(); writer.Flush(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string xmlOutput = reader.ReadToEnd(); string signedXML = SignXML(xmlOutput); Response.Write(signedXML); }
//------------------------------------------------------------------------------------------- private void IssueKey() { string LicenseKey = GetRequiredParam("LicenseKey"); string ProductId = GetRequiredParam("ProductId"); string ProductVersion = GetRequiredParam("ProductVersion"); string RemoteMachineCode = GetRequiredParam("MachineCode"); string RemoteMachineName = GetRequiredParam("MachineName"); using (WeavverEntityContainer data = new WeavverEntityContainer()) { var key = (from y in data.Sales_LicenseKeys where y.Key == LicenseKey select y).FirstOrDefault(); if (key == null) { writer.WriteStartElement("ActivationRequestRejected"); WriteAttribute("Reason", "The license key could not be found."); writer.WriteEndElement(); } else { data.Detach(key); int activations = key.Activations.Value; // FIND AN EXISTING ACTIVATION FOR THIS MACHINE var existingActivation = (from x in data.Sales_LicenseKeyActivations where x.LicenseKeyId == key.Id && x.MachineCode == RemoteMachineCode select x).FirstOrDefault(); if (existingActivation == null) { if (key.Activations.Value < key.MachineCount) { Sales_LicenseKeyActivations activation = new Sales_LicenseKeyActivations(); activation.Id = Guid.NewGuid(); activation.OrganizationId = SelectedOrganization.Id; activation.LicenseKeyId = key.Id; activation.MachineCode = RemoteMachineCode; activation.LastHeardFrom = DateTime.UtcNow; data.Sales_LicenseKeyActivations.AddObject(activation); activations++; } else { writer.WriteStartElement("ActivationRequestRejected"); WriteAttribute("Reason", "Too many activations."); writer.WriteEndElement(); return; } } else { existingActivation.LastHeardFrom = DateTime.UtcNow; } data.SaveChanges(); if (key != null) { writer.WriteStartElement("MachineLicense"); WriteAttribute("LicenseKey", key.Key); WriteAttribute("MachineCode", RemoteMachineCode); WriteAttribute("FullName", key.FullName); WriteAttribute("Organization", key.Organization); WriteAttribute("ConcurrentUsersPerMachine", key.ConcurrentUsersPerMachine.ToString()); WriteAttribute("ExpirationDate", key.ExpirationDate.ToString()); WriteAttribute("ActivationCount", activations.ToString()); if (!String.IsNullOrEmpty(key.ExtraXML)) { writer.WriteRaw(Environment.NewLine + " " + key.ExtraXML + Environment.NewLine); } writer.WriteEndElement(); } } } }
//------------------------------------------------------------------------------------------- private void ConfigureDatabase() { using (WeavverEntityContainer data = new WeavverEntityContainer()) { // Run SQL Deploy script string connectionString = ConfigurationManager.ConnectionStrings["WeavverEntityContainer"].ConnectionString; var entityBuilder = new System.Data.EntityClient.EntityConnectionStringBuilder(connectionString); SqlConnection connection = new SqlConnection(entityBuilder.ProviderConnectionString); connection.Open(); string script = System.IO.File.ReadAllText(Server.MapPath(@"\bin\Database.sql")); //data.CreateDatabaseScript(); script = script.Replace("%dalpath%", Server.MapPath(@"\bin\Weavver.DAL.dll")); script = script.Replace("%databasename%", connection.Database); string[] blocks = System.Text.RegularExpressions.Regex.Split(script, "\nGO"); foreach (string block in blocks) { if (block.Trim() != String.Empty) { SqlCommand createDb = new SqlCommand(block, connection); try { createDb.ExecuteNonQuery(); } catch (Exception ex) { throw new Exception("Block: " + block, ex); } } } // CREATE INITIAL DATA Guid orgId = Guid.NewGuid(); Session["SelectedOrganizationId"] = orgId; // deploy first org Weavver.Data.Logistics_Organizations org = new Weavver.Data.Logistics_Organizations(); org.Id = orgId; org.OrganizationId = org.Id; // THIS IS OVERRIDDEN ANYWAY BY AUDITUTILITY AS A SECURITY PRECAUTION org.OrganizationType = "Personal"; org.Name = Organization.Text; org.VanityURL = "default"; org.EIN = ""; org.Founded = DateTime.UtcNow; org.Bio = "This is a sample organization."; org.CreatedAt = DateTime.UtcNow; org.CreatedBy = Guid.Empty; org.UpdatedAt = DateTime.UtcNow; org.UpdatedBy = Guid.Empty; data.Logistics_Organizations.AddObject(org); data.SaveChanges(); Weavver.Data.System_Users user = new Weavver.Data.System_Users(); user.Id = orgId; user.OrganizationId = org.Id; // THIS IS OVERRIDDEN ANYWAY BY AUDITUTILITY AS A SECURITY PRECAUTION user.FirstName = "Enlightened"; user.LastName = "User"; user.Activated = true; user.Locked = false; user.Username = Username.Text; user.Password = Password.Text; user.CreatedAt = DateTime.UtcNow; user.CreatedBy = Guid.Empty; user.UpdatedAt = DateTime.UtcNow; user.UpdatedBy = Guid.Empty; data.System_Users.AddObject(user); data.SaveChanges(); Roles.ApplicationName = orgId.ToString(); string adminuser = user.Username; Roles.CreateRole("Administrators"); Roles.AddUsersToRoles(new string[] { adminuser }, new string[] { "Administrators" }); Roles.CreateRole("Accountants"); Roles.AddUsersToRoles(new string[] { adminuser }, new string[] { "Accountants" }); if (data.SaveChanges() > 0) { Response.Redirect("~/install/step2"); } } }