//------------------------------------------------------------------------------------------- private void ImportEmails(Communication_EmailAccounts account) { Console.WriteLine("Importing e-mails for " + account.Id + " -- " + account.Host); using (Pop3Client client = new Pop3Client()) { // connect client.Connect(account.Host, account.Port, (account.Type == "pops")); client.Authenticate(account.Username, account.Password); // iterate over the messages int messageCount = client.GetMessageCount(); List<Message> allMessages = new List<Message>(messageCount); for (int i = 1; i <= messageCount; i++) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { //data.SearchAllTables("asdf"); // save to database Message m = (Message) client.GetMessage(i); if (m.MessagePart.IsText) { Communication_Emails item = new Communication_Emails(); item.From = m.Headers.From.Raw; item.Subject = m.Headers.Subject; item.Raw = System.Text.ASCIIEncoding.ASCII.GetString(m.RawMessage); data.SaveChanges(); client.DeleteMessage(i); } } } } }
//------------------------------------------------------------------------------------------- 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 int BillAccount(Guid recurringBillableId) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { Accounting_RecurringBillables billable = (from x in data.Accounting_RecurringBillables where x.Id == recurringBillableId select x).First(); if (billable.Status == "Enabled") { int unbilledPeriods = billable.UnbilledPeriods.Value; var billables = billable.ProjectLedgerItems(unbilledPeriods); foreach (var item in billables) { data.Accounting_LedgerItems.Add(item); } // we have to convert it to local time first! or there will have some weird bug where 11/01/11 goes to 11/30/11 instead of 12/01/11 billable.Position = billable.Position.ToLocalTime().AddMonths(unbilledPeriods).ToUniversalTime(); if (billable.EndAt.HasValue && billable.Position > billable.EndAt.Value) billable.Status = "Disabled"; data.SaveChanges(); return billables.Count; } else { return 0; } } }
//------------------------------------------------------------------------------------------- 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 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"]); } } }
//------------------------------------------------------------------------------------------- public override bool ChangePassword(string username, string oldPassword, string newPassword) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { var user = (from x in data.System_Users where x.Username == username && x.Password == oldPassword select x).FirstOrDefault(); if (user != null) { user.Password = newPassword; data.SaveChanges(); return true; } return false; } }
//------------------------------------------------------------------------------------------- public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { var user = (from x in data.System_Users where x.Username == username && x.Password == password select x).First(); if (user != null) { user.PasswordQuestion = newPasswordQuestion; user.PasswordAnswer = newPasswordAnswer; data.SaveChanges(); return true; } else { return false; } } }
//------------------------------------------------------------------------------------------- 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; } } } }
//------------------------------------------------------------------------------------------- public bool ActivateUser(string username, string keyToTest) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { var user = (from x in data.System_Users where x.Username == username select x).First(); if (user != null && (user.ActivationKey == keyToTest || keyToTest == ConfigurationManager.AppSettings["activation_bypasskey"])) { user.Activated = true; data.SaveChanges(); return true; } return false; } }
//------------------------------------------------------------------------------------------- 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 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(); }
//------------------------------------------------------------------------------------------- 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); } }
//------------------------------------------------------------------------------------------- public override string ResetPassword(string username, string answer) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { System_Users item = (from x in data.System_Users where x.Username == username select x).First(); Random r = new Random(); string newPass = ""; for (int i = 0; i < 8; i++) { newPass += (char)r.Next(57) + 65; } item.Password = newPass; data.SaveChanges(); return item.Password; } }
//------------------------------------------------------------------------------------------- /// <summary> /// /// </summary> /// <returns>Returns added check count</returns> private int ImportScheduledPayments() { var financialAccount = GetAccount(); if (financialAccount.LedgerType != LedgerType.Checking.ToString()) return -1; Billpayment billPaymentData = GetOFXBillPaymentObject(); billPaymentData.SynchronizePayments("REFRESH"); billPaymentData.SynchronizePayees("REFRESH"); using (WeavverEntityContainer data = new WeavverEntityContainer()) { foreach (var remotePayment in billPaymentData.SyncPayments) { Accounting_Checks matchingCheck = (from check in data.Accounting_Checks where check.OrganizationId == financialAccount.OrganizationId && check.ExternalId == remotePayment.Id select check).FirstOrDefault(); if (matchingCheck == null) { Accounting_Checks check = new Accounting_Checks(); check.Id = Guid.NewGuid(); check.OrganizationId = financialAccount.OrganizationId; check.ExternalId = remotePayment.Id; check.AccountId = financialAccount.Id; check.PostAt = DateTime.Parse(remotePayment.DateDue); check.CheckNumber = Int32.Parse(remotePayment.CheckNumber); check.Status = GetStandardCheckStatus(remotePayment.Status); check.Payee = GetOrganizationIdForPayee(remotePayment.PayeeListId); check.Memo = remotePayment.Memo; check.Amount = Decimal.Parse(remotePayment.Amount); data.Accounting_Checks.Add(check); } else { if (matchingCheck.Status != "Cleared" && matchingCheck.Status != GetStandardCheckStatus(remotePayment.Status)) { matchingCheck.Status = GetStandardCheckStatus(remotePayment.Status); } } } return data.SaveChanges(); } }
public DynamicDataWebMethodReturnType ImportLedgerItems() { DynamicDataWebMethodReturnType ret = new DynamicDataWebMethodReturnType(); ret.Status = "Import Status"; using (WeavverEntityContainer data = new WeavverEntityContainer()) { //data.Accounting_OFXSettings.Attach(this); DateTime startAt = DateTime.Now.Subtract(TimeSpan.FromDays(7)); if (LastSuccessfulConnection.HasValue) startAt = LastSuccessfulConnection.Value; List<Accounting_OFXLedgerItem> items = GetRemoteLedgerItems(startAt, DateTime.Now); foreach (var item in items) { if (!item.HasBeenImported) { data.Accounting_LedgerItems.Add(item.LedgerItem); } } LastSuccessfulConnection = DateTime.UtcNow; int results = data.SaveChanges(); ret.Message = "Ledger items added/updated: " + results.ToString(); } return ret; }
//------------------------------------------------------------------------------------------- /// <summary> /// </summary> public void RunCronTasks(CommandLineArguments args) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { DateTime sleepDateTime = DateTime.Now.Subtract(TimeSpan.FromMinutes(60)); // only load ofx enabled accounts var ofxBanks = from x in data.Accounting_OFXSettings where x.Enabled == true && x.LastSuccessfulConnection < sleepDateTime select x; try { int totalBanksInSystem = ofxBanks.Count(); Console.WriteLine("-Processing " + totalBanksInSystem + " OFXSettings objects (database wide count)"); } catch (Exception ex) { Console.WriteLine("Exception .." + ex.Message); return; } foreach (Accounting_OFXSettings ofxSetting in data.Accounting_OFXSettings) { Console.WriteLine("--Processing ofxSetting item " + ofxSetting.Id.ToString()); //data.Entry(ofxSetting) = System.Data.Entity.EntityState.Detached; // 1. Only import Bill Payment data for checking accounts // We do this before ImportingLedgerItems so we can sync the check numbers var account = ofxSetting.GetAccount(); if (account != null) { if (account.LedgerType == LedgerType.Checking.ToString()) { int count = ofxSetting.ImportScheduledPayments(); Console.WriteLine("---Imported " + count.ToString() + " scheduled payments"); } // 2. Import any Ledger Items && Match to checks in our database // -- this should be done AFTER Bill Payment data is imported System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage("Weavver Cron <*****@*****.**>", ConfigurationManager.AppSettings["audit_address"]); try { DynamicDataWebMethodReturnType response = ofxSetting.ImportLedgerItems(); ofxSetting.LastSuccessfulConnection = DateTime.UtcNow; data.SaveChanges(); Console.WriteLine("---Imported " + response.Message); message.Subject = "Daily Accounting Import Ledger Items Result"; message.Body = response.Message; } catch (Exception ex) { Console.WriteLine("---Error " + ex.Message); message.Subject = "Daily Accounting Import Ledger Items Result - ERROR"; message.Body = "ObjectId: " + ofxSetting.Id.ToString() + "\r\n\r\n" + ex.ToString(); } SmtpClient smtpClient = new SmtpClient(ConfigurationManager.AppSettings["smtp_server"]); smtpClient.Send(message); } } } }
//------------------------------------------------------------------------------------------- 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(); } } } }
//------------------------------------------------------------------------------------------- public MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, string userhostaddress, string referredby, out MembershipCreateStatus status) { username = username.ToLower(); email = email.ToLower(); using (WeavverEntityContainer data = new WeavverEntityContainer()) { System_Users user = new System_Users(); user.EmailAddress = email; user.Username = username; user.Password = password; user.ReferredBy = referredby; Random rHash = new Random(); string seed = rHash.Next().ToString() + rHash.Next().ToString() + rHash.Next().ToString() + rHash.Next().ToString(); user.ActivationKey = MD5Hash(seed); user.LastLoggedIn = DateTime.UtcNow; user.UpdatedAt = DateTime.UtcNow; user.UpdatedBy = Guid.Empty; user.CreatedAt = DateTime.UtcNow; user.CreatedBy = Guid.Empty; // todo: add account note, signed up from "ip address" - user.CreatedBy = userhostaddress; data.System_Users.Add(user); if (data.SaveChanges() > 0) { status = MembershipCreateStatus.Success; return GetUser(username, false); } else { status = MembershipCreateStatus.ProviderError; return null; } } }
//------------------------------------------------------------------------------------------- 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(); }
//------------------------------------------------------------------------------------------- public override bool DeleteUser(string username, bool deleteAllRelatedData) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { var user = (from x in data.System_Users where x.Username == username select x).First(); if (user != null) { user.Locked = true; data.SaveChanges(); return true; } else { return false; } } }
//------------------------------------------------------------------------------------------- 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); }
public DynamicDataWebMethodReturnType UpdateCachedBalances() { // call UpdateCachedBalances() instead ?? DynamicDataWebMethodReturnType ret = new DynamicDataWebMethodReturnType(); ret.Status = "Balance Update"; decimal remoteAvailableBalance = 0.0m; decimal remoteLedgerBalance = 0.0m; bool retrieved = GetBalances(GetAccount(), out remoteAvailableBalance, out remoteLedgerBalance); if (retrieved) { using (WeavverEntityContainer data = new WeavverEntityContainer()) { var ofxSettings = (from x in data.Accounting_OFXSettings where x.Id == Id select x).FirstOrDefault(); ofxSettings.AvailableBalance = remoteAvailableBalance; ofxSettings.LedgerBalance = remoteLedgerBalance; int changes = data.SaveChanges(); if (changes > 0) { ret.Message = "Balances updated."; ret.RefreshData = true; return ret; } } } ret.Message = "Could not update the balance."; return ret; }
//------------------------------------------------------------------------------------------- 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"); } }
//------------------------------------------------------------------------------------------- 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); } }
//------------------------------------------------------------------------------------------- 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(); } } }