public ActionResult AddAddress(AddressModel addressModel) { try { LoginHelper.CheckAccess(Session); } catch (Exception) { return(RedirectToAction("Login", "Login")); } AddressHelper addressHelper = new AddressHelper(); if (!addressHelper.CheckAddress(addressModel)) { ViewBag.AddressMessage = addressHelper.AddressMessage; return(View("AddAddress")); } var userProfileId = (int)Session["userProfileId"]; var addressDataEntity = addressHelper.ToDataEntity(userProfileId, addressModel); var addressResponse = new AddressHandler().Add(addressDataEntity); if (!addressResponse.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = addressResponse.ErrorMessage.Replace(' ', '-') })); } return(RedirectToAction("UserProfile", "Account")); }
public IActionResult Index() { AddressHandler addressHandler = new AddressHandler(); List <Neighborhood> neighborhoods = addressHandler.GetAllNeighborhood().ToList(); return(View(neighborhoods)); }
public ActionResult EditAddress() { try { LoginHelper.CheckAccess(Session); } catch (Exception) { return(RedirectToAction("Login", "Login")); } var userProfileId = (int)Session["userProfileId"]; var addressResponse = new AddressHandler().GetForUserProfile(userProfileId); if (!addressResponse.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = addressResponse.ErrorMessage.Replace(' ', '-') })); } var model = new AddressHelper().GetAddressModel(addressResponse.Entity.AddressId); if (model == null) { return(RedirectToAction("Index", "Error", new { errorMessage = MessageConstants.ModelError.Replace(' ', '-') })); } return(View("EditAddress", model)); }
protected override void ProcessAccept(UDPPacket packet) { IPEndPoint remote = (IPEndPoint)packet.AsyncEventArgs.RemoteEndPoint; //Task.Run(() => //{ if (packet.BytesRecieved.Length < 6) { return; } BasePacket basePacket = new BasePacket(packet.BytesRecieved); try { //BytesRecieved[7] is nnpacket.PacketType. switch (basePacket.PacketType) { case NatPacketType.PreInit: //NatNegHandler.PreInitResponse(this, packet, nnpacket); break; case NatPacketType.Init: InitHandler.InitResponse(this, packet); break; case NatPacketType.AddressCheck: AddressHandler.AddressCheckResponse(this, packet); break; case NatPacketType.NatifyRequest: NatifyHandler.NatifyResponse(this, packet); break; case NatPacketType.ConnectAck: ConnectHandler.ConnectResponse(this, packet); break; case NatPacketType.Report: ReportHandler.ReportResponse(this, packet); break; default: LogWriter.Log.Write(LogLevel.Error, "{0,-8} [Recv] unknow data", ServerName); break; } } catch (Exception e) { LogWriter.Log.WriteException(e); } finally { if (Replied == true) { Release(packet.AsyncEventArgs); } } }
public ActionResult DeleteAddress() { try { LoginHelper.CheckAccess(Session); } catch (Exception) { return(RedirectToAction("Login", "Login")); } var userProfileId = (int)Session["userProfileId"]; var addressHandler = new AddressHandler(); var address = addressHandler.GetForUserProfile(userProfileId); if (!address.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = address.ErrorMessage.Replace(' ', '-') })); } var response = addressHandler.Delete(address.Entity.AddressId); if (!response.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = response.ErrorMessage.Replace(' ', '-') })); } return(RedirectToAction("UserProfile", "Account")); }
private APIGateway(UserHandler users, ImageHandler images, PostHandler posts, ProfileHandler profiles, AddressHandler addresses) { this.users = users; this.images = images; this.posts = posts; this.profiles = profiles; this.addresses = addresses; }
public string CreateAccountWithFacebookLogin(User fb_usr) { if (!repository.IsDomainAvailable(mastersubdomain.name)) { return("The selected site name is not available. Please choose another name."); } // check affiliate ID if (!string.IsNullOrEmpty(affiliate)) { var referrer = repository.GetSubDomains().SingleOrDefault(x => x.affiliateID == affiliate); if (referrer == null) { Syslog.Write("Invalid Affiliate ID: " + affiliate); return("Invalid Affiliate ID"); } mastersubdomain.affiliateReferrer = referrer.id; // valid id so give 60 days mastersubdomain.trialExpiry = DateTime.UtcNow.AddDays(60); } usr = new user { role = (int)UserRole.ADMIN, viewid = Utility.GetRandomString(), permissions = (int)UserPermission.ADMIN, FBID = fb_usr.id, email = email ?? "", externalProfileUrl = fb_usr.link, firstName = fb_usr.first_name, lastName = fb_usr.last_name, gender = fb_usr.gender, externalProfilePhoto = string.Format("{0}{1}/picture?type=large", GeneralConstants.FACEBOOK_GRAPH_HOST, fb_usr.id) }; repository.AddMasterSubdomain(mastersubdomain); // hash is created later // create organisation first mastersubdomain.organisation = new organisation { subdomain = mastersubdomain.id, name = fb_usr.name }; var addressHandler = new AddressHandler(mastersubdomain.organisation, repository); addressHandler.CopyShippingAndBillingAddressFromOrgAddress("", ""); CreateDataStructures(); return(""); }
public ActionResult UpdateAddresses(int?[] country, string[] states_canadian, string[] states_other, string[] states_us, string billing_first_name, string billing_last_name, string billing_company, string billing_address, string billing_city, long?billing_citySelected, string billing_postcode, string billing_phone, string shipping_first_name, string shipping_last_name, string shipping_company, string shipping_address, string shipping_city, long?shipping_citySelected, string shipping_postcode, string shipping_phone) { var ownerid = sessionid.Value; var profile = repository.GetUserById(ownerid, subdomainid.Value); if (profile == null) { return(SendJsonErrorResponse("Cannot find profile")); } var addressHandler = new AddressHandler(profile.organisation1, repository); addressHandler.SetShippingAndBillingAddresses(billing_first_name, billing_last_name, billing_company, billing_address, billing_city, billing_citySelected, billing_postcode, billing_phone, country.ElementAtOrDefault(0), states_canadian.ElementAtOrDefault(0), states_other.ElementAtOrDefault(0), states_us.ElementAtOrDefault(0), shipping_first_name, shipping_last_name, shipping_company, shipping_address, shipping_city, shipping_citySelected, shipping_postcode, shipping_phone, country.ElementAtOrDefault(1), states_canadian.ElementAtOrDefault(1), states_other.ElementAtOrDefault(1), states_us.ElementAtOrDefault(1), false); repository.Save(); CacheHelper.Instance.invalidate_dependency(DependencyType.products_subdomain, subdomainid.Value.ToString()); CacheHelper.Instance.invalidate_dependency(DependencyType.organisation, subdomainid.Value.ToString()); #if LUCENE // update index var indexer = new LuceneWorker(db, profile.organisation1.MASTERsubdomain.ToIdName()); indexer.AddToIndex(LuceneIndexType.CONTACTS, profile); #endif return(Json(OPERATION_SUCCESSFUL.ToJsonOKData())); }
public UserModel GetUserModel(UserModel userModel = null) { if (userModel == null) { userModel = new UserModel(); } int id = int.Parse(HttpContext.Current.Session["userId"].ToString()); var responseUser = new UserHandler().Get(id); if (!responseUser.CompletedRequest) { InvalidInfoMessage = responseUser.ErrorMessage; return(null); } var user = responseUser.Entity; var responseUserProfile = new UserProfileHandler().GetByUserId(user.UserId); if (!responseUserProfile.CompletedRequest) { InvalidInfoMessage = responseUser.ErrorMessage; return(null); } var address = new AddressHandler().GetForUserProfile(responseUserProfile.Entity.UserProfileId); if (!address.CompletedRequest) { if (string.Equals(address.ErrorMessage, ErrorConstants.AddressNotFound)) { userModel.Address = null; } else { InvalidInfoMessage = responseUser.ErrorMessage; return(null); } } else { userModel.Address = address.Entity; } PopulateModel(userModel, user, responseUserProfile.Entity); return(userModel); }
public static async Task <APIGateway> Create(string path, PrivateIdentity self, int port) { var conn = new SQLiteAsyncConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create | SQLiteOpenFlags.FullMutex); var users = await UserHandler.Create(conn, self.ID); var images = await ImageHandler.Create(conn, users); var posts = await PostHandler.Create(conn, users); var profiles = await ProfileHandler.Create(conn, users); var addresses = await AddressHandler.Create(conn, users, port, self); return(new APIGateway(users, images, posts, profiles, addresses)); }
public ActionResult EditAddress(AddressModel addressModel) { try { LoginHelper.CheckAccess(Session); } catch (Exception) { return(RedirectToAction("Login", "Login")); } AddressHelper addressHelper = new AddressHelper(); var userProfileId = (int)Session["userProfileId"]; var addressHandler = new AddressHandler(); var oldAddress = addressHandler.GetForUserProfile(userProfileId); if (!oldAddress.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = oldAddress.ErrorMessage.Replace(' ', '-') })); } if (!addressHelper.CheckAddress(addressModel)) { ViewBag.AddressMessage = addressHelper.AddressMessage; var newAddressModel = addressHelper.GetAddressModel(oldAddress.Entity.AddressId); return(View("EditAddress", newAddressModel)); } if (addressHelper.NoChanges(oldAddress.Entity, addressModel)) { ViewBag.AddressMessage = MessageConstants.NoChangesMade; var newAddressModel = addressHelper.GetAddressModel(oldAddress.Entity.AddressId); return(View("EditAddress", newAddressModel)); } var entity = addressHelper.ToDataEntity(oldAddress.Entity.AddressId, userProfileId, addressModel); var addressResponse = addressHandler.Update(entity); if (!addressResponse.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = addressResponse.ErrorMessage.Replace(' ', '-') })); } return(RedirectToAction("UserProfile", "Account")); }
public ActionResult ShowProfile(string id) { try { LoginHelper.CheckAccess(Session); } catch (Exception) { return(RedirectToAction("Login", "Login")); } var user = new UserHandler().GetByUsername(id); if (!user.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = user.ErrorMessage.Replace(' ', '-') })); } var userProfile = new UserProfileHandler().GetByUserId(user.Entity.UserId); if (!userProfile.CompletedRequest) { return(RedirectToAction("Index", "Error", new { errorMessage = userProfile.ErrorMessage.Replace(' ', '-') })); } var address = new AddressHandler().GetForUserProfile(userProfile.Entity.UserProfileId); if (!address.CompletedRequest) { if (!string.Equals(ErrorConstants.AddressNotFound, address.ErrorMessage)) { return(RedirectToAction("Index", "Error", new { errorMessage = address.ErrorMessage.Replace(' ', '-') })); } } var profileModel = new ProfileHelper().GetProfileModel(user.Entity, userProfile.Entity, address.Entity); if (profileModel == null) { return(RedirectToAction("Index", "Error", new { errorMessage = MessageConstants.ProfileError.Replace(' ', '-') })); } return(View("ShowProfile", profileModel)); }
public static void Switch(NatNegServer server, byte[] message) { BasePacket basePacket = new BasePacket(message); try { //BytesRecieved[7] is nnpacket.PacketType. switch (basePacket.PacketType) { case NatPacketType.PreInit: //NatNegHandler.PreInitResponse(this, packet, nnpacket); break; case NatPacketType.Init: InitHandler.InitResponse(server, message); break; case NatPacketType.AddressCheck: AddressHandler.AddressCheckResponse(server, message); break; case NatPacketType.NatifyRequest: NatifyHandler.NatifyResponse(server, message); break; case NatPacketType.ConnectAck: ConnectHandler.ConnectResponse(server, message); break; case NatPacketType.Report: ReportHandler.ReportResponse(server, message); break; default: server.UnknownDataRecived(message); break; } } catch (Exception e) { LogWriter.Log.WriteException(e); } }
public AddressModel GetAddressModel(int id, AddressModel addressModel = null) { if (addressModel == null) { addressModel = new AddressModel(); } var address = new AddressHandler().Get(id); if (address.CompletedRequest) { addressModel.Street = address.Entity.AddressStreet; addressModel.StreetNo = address.Entity.AddressStreetNo; addressModel.City = address.Entity.AddressCity; addressModel.Country = address.Entity.AddressCountry; } return(addressModel); }
public ActionResult SetAddressAndBillingForContactsWIthout() { var builder = new StringBuilder(); foreach (var org in db.organisations) { var usr = org.users.FirstOrDefault(); if (usr == null) { builder.AppendFormat("{0}{1}", org.id, Environment.NewLine); continue; } var addressHandler = new AddressHandler(org, repository); addressHandler.CopyShippingAndBillingAddressFromOrgAddress(usr.firstName ?? "", usr.lastName ?? ""); } db.SubmitChanges(); return(Content(builder.ToString())); }
public ActionResult update_addresses(string billing_first_name, string billing_last_name, string billing_company, string billing_address, string billing_city, long?billing_citySelected, string billing_postcode, string billing_phone, string shipping_first_name, string shipping_last_name, string shipping_company, string shipping_address, string shipping_city, long?shipping_citySelected, string shipping_postcode, string shipping_phone, int[] country, string[] states_canadian, string[] states_other, string[] states_us, bool ship_same_billing) { var handler = new AddressHandler(cart.user.organisation1, repository); handler.SetShippingAndBillingAddresses(billing_first_name, billing_last_name, billing_company, billing_address, billing_city, billing_citySelected, billing_postcode, billing_phone, country[0], states_canadian[0], states_other[0], states_us[0], shipping_first_name, shipping_last_name, shipping_company, shipping_address, shipping_city, shipping_citySelected, shipping_postcode, shipping_phone, country[1], states_canadian[1], states_other[1], states_us[1], ship_same_billing); repository.Save(); return(RedirectToAction("final_step")); }
private void SaveEbayOrders(OrderTypeCollection collection) { using (var repository = new TradelrRepository()) { foreach (OrderType entry in collection) { Transaction transaction; // check if order already exists var existingEbayOrder = repository.GetSubDomain(sd.id).ebay_orders.SingleOrDefault(x => x.orderid == entry.OrderID); if (existingEbayOrder != null) { var order = existingEbayOrder.orders.Single(); transaction = new Transaction(order, repository, seller.id); // update order status existingEbayOrder.status = entry.OrderStatus.ToString(); } else { // check if user already exists var buyer = repository.GetUserByEbayID(entry.BuyerUserID); if (buyer == null) { // get receiver and add to contact db var userService = new UserService(token); // get by itemid as invalid request seems to be returned when get by userid var ebaybuyer = userService.GetUser(entry.BuyerUserID); // we assume that same buyer for all transactions so we get the first email address var buyeremail = entry.TransactionArray.ItemAt(0).Buyer.Email; buyer = SaveEbayBuyer(ebaybuyer, buyeremail); } // add a shipping and billing address if (entry.ShippingAddress != null) { var buyername = Utility.SplitFullName(entry.ShippingAddress.Name); var handler = new AddressHandler(buyer.organisation1, repository); handler.SetShippingAndBillingAddresses(buyername[0], buyername[1], entry.ShippingAddress.CompanyName ?? "", entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2, entry.ShippingAddress.CityName, null, entry.ShippingAddress.PostalCode, entry.ShippingAddress.Phone, entry.ShippingAddress.Country.ToString().ToCountry().id, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, buyername[0], buyername[1], entry.ShippingAddress.CompanyName ?? "", entry.ShippingAddress.Street1 + "\r\n" + entry.ShippingAddress.Street2, entry.ShippingAddress.CityName, null, entry.ShippingAddress.PostalCode, entry.ShippingAddress.Phone, entry.ShippingAddress.Country.ToString().ToCountry().id, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, entry.ShippingAddress.StateOrProvince, true); } // add normal order transaction = new Transaction(sd, buyer, TransactionType.INVOICE, repository, seller.id); transaction.CreateTransaction(repository.GetNewOrderNumber(sd.id, TransactionType.INVOICE), entry.CreatedTime, "", entry.AmountPaid.currencyID.ToString().ToCurrency().id); // mark as sent var tradelr_orderstatus = GetOrderStatus(entry.OrderStatus); transaction.UpdateOrderStatus(tradelr_orderstatus); // add ebay specific order information var newEbayOrder = new ebay_order(); newEbayOrder.orderid = entry.OrderID; newEbayOrder.status = entry.OrderStatus.ToString(); newEbayOrder.created = entry.CreatedTime; newEbayOrder.subdomainid = sd.id; transaction.AddEbayOrderInformation(newEbayOrder); foreach (eBay.Service.Core.Soap.TransactionType trans in entry.TransactionArray) { var ebay_itemid = trans.Item.ItemID; // get product details var itemservice = new ItemService(token); var item = itemservice.GetItem(ebay_itemid); // add new product if necessary var existingproduct = repository.GetProducts(sd.id).SingleOrDefault(x => x.ebayID.HasValue && x.ebay_product.ebayid == ebay_itemid); if (existingproduct == null) { // add new product (triggered when synchronisation is carried out the first time) var newproduct = new Listing(); newproduct.Populate(item); var importer = new ProductImport(); var pinfo = importer.ImportEbay(newproduct, sd.id); repository.AddProduct(pinfo, sd.id); existingproduct = pinfo.p; } else { // if existing product is completed then we need to relist if (entry.OrderStatus == OrderStatusCodeType.Completed || entry.OrderStatus == OrderStatusCodeType.Shipped) { // see if product listing is still active if (item.SellingStatus.ListingStatus == ListingStatusCodeType.Completed || item.SellingStatus.ListingStatus == ListingStatusCodeType.Ended) { // set status to inactive existingproduct.ebay_product.isActive = false; // check if we should autorelist if (existingproduct.ebay_product.autorelist) { // check that product has enough stock if (existingproduct.HasStock(existingproduct.ebay_product.quantity)) { var exporter = new EbayExporter( existingproduct.ebay_product.siteid.ToEnum <SiteCodeType>(), sd.ToHostName(), token, sd); exporter.BuildItem(existingproduct.ebay_product); } } } } } // add tradelr order item var orderItem = new orderItem { description = item.Title, variantid = existingproduct.product_variants[0].id, unitPrice = (decimal)trans.TransactionPrice.Value, quantity = trans.QuantityPurchased }; if (trans.Taxes != null) { orderItem.tax = (decimal)(trans.Taxes.TotalTaxAmount.Value / trans.TransactionPrice.Value); } transaction.AddOrderItem(orderItem, null); // update inventory transaction.UpdateInventoryItem(orderItem, trans.QuantityPurchased); // add ebay order item var ebayorderitem = new ebay_orderitem(); ebayorderitem.lineid = trans.OrderLineItemID; newEbayOrder.ebay_orderitems.Add(ebayorderitem); } // update shipping transaction.UpdateShippingCost(entry.ShippingServiceSelected.ShippingServiceCost.Value.ToString()); transaction.UpdateShippingMethod(entry.ShippingServiceSelected.ShippingService); // update tax : ebay tax is the shipping tax which applies to the entire order total // may or may not include shipping cost if (entry.ShippingDetails.SalesTax != null) { transaction.UpdateOrderTax((decimal)entry.ShippingDetails.SalesTax.SalesTaxPercent, entry.ShippingDetails.SalesTax.ShippingIncludedInTax); } transaction.UpdateTotal(); transaction.SaveNewTransaction(); ////////////////////// SAVE INVOICE } // the following applies to both new and existing order var existingPayment = transaction.GetPayments().SingleOrDefault(x => x.reference == entry.OrderID); if (existingPayment != null) { var newstatus = GetPaymentStatus(entry.CheckoutStatus.Status); if (existingPayment.status != newstatus.ToString()) { transaction.UpdatePaymentStatus(existingPayment, newstatus); } } else { // if payment has been made then add payment if (entry.CheckoutStatus.Status == CompleteStatusCodeType.Complete) { var p = new DBML.payment(); p.status = GetPaymentStatus(entry.CheckoutStatus.Status).ToString(); p.method = entry.CheckoutStatus.PaymentMethod.ToString(); p.created = entry.CheckoutStatus.LastModifiedTime; p.notes = entry.BuyerCheckoutMessage; p.paidAmount = (decimal)entry.AmountPaid.Value; p.reference = entry.OrderID; transaction.AddPayment(p, false); } } // if there is a shipped date, mark as ship if not already done so if (transaction.GetOrderStatus() != OrderStatus.SHIPPED && entry.ShippedTimeSpecified) { transaction.UpdateOrderStatus(OrderStatus.SHIPPED); if (entry.ShippingDetails.ShipmentTrackingDetails.Count != 0) { foreach (ShipmentTrackingDetailsType trackentry in entry.ShippingDetails.ShipmentTrackingDetails) { var comment = string.Format(OrderComment.ORDER_SHIP_STANDARD, trackentry.ShippingCarrierUsed, trackentry.ShipmentTrackingNumber); transaction.AddComment(comment); } } else { transaction.AddComment(OrderComment.ORDER_SHIP, created: entry.ShippedTime); } } repository.Save(); // save per order } } }
public ActionResult UpdateProfile(string address, string city, string citySelected, string coPhone, string companyName, int?country, string fax, string firstName, string gender, string lastName, string notes, string phone, string postcode, string title, string currency, string timezone, string email, string states_canadian, string states_other, string states_us) { var ownerid = sessionid.Value; try { var profile = repository.GetUserById(ownerid, subdomainid.Value); if (profile == null) { return(SendJsonErrorResponse("Cannot find profile")); } // no need to take into account whether an organisation is there because it will always be created profile.organisation1.address = address; if (!string.IsNullOrEmpty(citySelected)) { profile.organisation1.city = int.Parse(citySelected); } else if (!string.IsNullOrEmpty(city)) { profile.organisation1.city = repository.AddCity(city).id; } profile.organisation1.phone = coPhone; profile.organisation1.name = companyName; profile.organisation1.fax = fax; if (country != null) { profile.organisation1.country = country; profile.organisation1.state = AddressHandler.GetState(country, states_us, states_canadian, states_other); } profile.firstName = firstName; profile.gender = gender; profile.lastName = lastName; profile.notes = notes; profile.phoneNumber = phone; profile.organisation1.postcode = postcode; profile.title = title; if (!string.IsNullOrEmpty(email) && email != profile.email) { profile.email = email.Trim(); var password = Crypto.Utility.GetRandomString(); // save password hash var hash = Crypto.Utility.ComputePasswordHash(email + password); profile.passwordHash = hash; // set flag profile.settings |= (int)UserSettings.PASSWORD_RESET; // email new password to user var data = new ViewDataDictionary() { { "password", password } }; EmailHelper.SendEmail(EmailViewType.ACCOUNT_PASSWORD_RESET, data, "Password Reset", email, profile.ToFullName(), null); } if (permission.HasFlag(UserPermission.NETWORK_SETTINGS)) { if (!string.IsNullOrEmpty(timezone)) { profile.timezone = timezone; } if (!string.IsNullOrEmpty(currency)) { profile.organisation1.MASTERsubdomain.currency = int.Parse(currency); } } repository.Save(); CacheHelper.Instance.invalidate_dependency(DependencyType.products_subdomain, subdomainid.Value.ToString()); CacheHelper.Instance.invalidate_dependency(DependencyType.organisation, subdomainid.Value.ToString()); #if LUCENE // update index var indexer = new LuceneWorker(db, profile.organisation1.MASTERsubdomain.ToIdName()); indexer.AddToIndex(LuceneIndexType.CONTACTS, profile); #endif } catch (Exception ex) { return(SendJsonErrorResponse(ex)); } // will be intepreted as an error if Content() is used return(Json(OPERATION_SUCCESSFUL.ToJsonOKData())); }
public ActionResult Create(long?profilePhotoID, string password, string organisationPhotoID, string address, string city, long?citySelected, string coPhone, int permissions, string companyName, string contactList, int?country, string email, string fax, string firstName, string gender, string lastName, string notes, string phone, string postcode, string title, long?existingOrg, string states_canadian, string states_other, string states_us, bool sendemail) { // add organisation even if fields are empty if (!string.IsNullOrEmpty(email)) { // check if email already added var emailExist = repository.IsEmailInUse(email, subdomainid.Value); if (emailExist) { return(Json("Email has already been added".ToJsonFail())); } } organisation o; long addedOrgID; if (!existingOrg.HasValue) { o = new organisation { subdomain = subdomainid.Value, address = address.Trim(), phone = coPhone, name = companyName, fax = fax, postcode = postcode }; if (!string.IsNullOrEmpty(organisationPhotoID)) { o.logo = long.Parse(organisationPhotoID); } if (citySelected.HasValue) { o.city = citySelected.Value; } else if (!string.IsNullOrEmpty(city)) { o.city = repository.AddCity(city).id; } if (country != null) { o.country = country; o.state = AddressHandler.GetState(country, states_us, states_canadian, states_other); } addedOrgID = repository.AddOrganisation(o); // update shipping and billing addresses var addressHandler = new AddressHandler(o, repository); addressHandler.CopyShippingAndBillingAddressFromOrgAddress("", ""); } else { o = repository.GetOrganisation(existingOrg.Value, subdomainid.Value); if (o == null) { return(SendJsonErrorResponse("Company is invalid")); } addedOrgID = o.id; } // add user var u = new user { created = DateTime.UtcNow, role = (int)UserRole.USER, email = email, passwordHash = Crypto.Utility.ComputePasswordHash(email + password), firstName = firstName, gender = gender, lastName = lastName, notes = notes, phoneNumber = phone, title = title, organisation = addedOrgID, viewid = Crypto.Utility.GetRandomString() }; // only allow user to create user with permissions equal to or less than themselves var currentuser = repository.GetUserById(sessionid.Value, subdomainid.Value); var allowedPermission = currentuser.permissions & permissions; u.permissions = allowedPermission; try { if (profilePhotoID.HasValue) { u.profilePhoto = profilePhotoID.Value; } repository.AddUser(u); // need to update entry in images table too since contextid will be the site creator's if (profilePhotoID.HasValue) { var dbImage = repository.GetImage(profilePhotoID.Value); if (dbImage != null) { dbImage.contextID = u.id; } } // log activity repository.AddActivity(sessionid.Value, new ActivityMessage(u.id, sessionid, ActivityMessageType.CONTACT_NEW, new HtmlLink(u.ToEmailName(true), u.id).ToContactString()), subdomainid.Value); // update total contacts count repository.UpdateCounters(subdomainid.Value, 1, CounterType.CONTACTS_PRIVATE); // add contact list filter if (!string.IsNullOrEmpty(contactList)) { var cf = new contactGroupMember() { groupid = long.Parse(contactList), userid = u.id }; repository.AddContactGroupMember(cf); } // email contact that was just added if (!string.IsNullOrEmpty(email) && sendemail) { var me = repository.GetUserById(sessionid.Value, subdomainid.Value); var viewmodel = new ContactNewViewModel { creatorEmail = me.email, creatorName = me.ToEmailName(true), hostName = accountHostname, email = email, password = password, note = notes, profile = u.ToProfileUrl() }; // link to view profile this.SendEmail(EmailViewType.CONTACT_NEWENTRY, viewmodel, "New Profile created", u.GetEmailAddress(), u.ToFullName(), u); } } catch (Exception ex) { return(SendJsonErrorResponse(ex)); } // return contact ID & org ID return(Json(new { uid = u.id, oid = addedOrgID }.ToJsonOKData())); }
public async Task <IActionResult> CreateOrder([FromBody] CustomerOrderDataModel customerDataModel) { try { CustomerOrderDataModel newCODM = new CustomerOrderDataModel(); if (customerDataModel != null) { if (customerDataModel.isNewCustomer) { var customer = await CustomerHandler.InsertCustomer(customerDataModel); if (customer == null) { return(StatusCode(505, "An unexpected error has ocurred, unable to create Customer")); } customerDataModel.userId = customer.UserId; newCODM.userId = customer.UserId; customerDataModel.measurements.UserId = customer.UserId; Measurements measurements = await MeasurementsHandler.UpdateMeasurements(customerDataModel.measurements); if (measurements == null) { measurements = await MeasurementsHandler.InsertMeasurments(customerDataModel, customer.MeasurementsId, customerDataModel.measurements.UserId); if (measurements == null) { return(StatusCode(505, "An unexpected error has ocurred, unable to create Customer measurements")); } } else { newCODM.measurements = measurements; } } if (customerDataModel.isGuest) { customerDataModel.order.isMemberCheckout = false; } if (customerDataModel.isExistingCustomer) { customerDataModel.order.isMemberCheckout = true; } var address = await AddressHandler.InsertAddress(customerDataModel); if (address == null) { return(StatusCode(505, "An unexpected error has ocurred, unable to insert address")); } newCODM.shippingAddress = address; customerDataModel.shippingAddress = address; var order = await CustomerHandler.InsertCustomerOrder(customerDataModel); if (order == null) { return(StatusCode(505, "An unexpected error has ocurred, unable to complete order")); } else { newCODM.order = order; } return(Ok(newCODM)); } return(StatusCode(404)); } catch (Exception ex) { Logger.LogError(ex.ToString()); return(StatusCode(505, ex.Message)); } }
// Licenses-Animal-Dog-License, Licenses-Animal-Dog-Application // DUB13-00000-00006, DUB13-00000-00005 // Active-LIC_PET, Issued-LIC_PET static void Main(string[] args) { PaginationInfo p = null; string filter = "module=Licenses"; string redirectUrl = "http://*****:*****@accela.com" }); //// Agency Agency ag = a.GetAgency(token, "SOLNDEV-ENG"); Stream sr = a.GetAgencyLogo(token, "SOLNDEV-ENG"); using (FileStream fs = new FileStream(@"C:\Swapnali\TestPurposes\logo.png", FileMode.Create)) { sr.CopyTo(fs); } // Record Contact //ResultDataPaged<Contact> contacts = rec.GetRecordContacts(recordId, token); //List<Contact> cs = new List<Contact> { // new Contact { isPrimary = "N", businessName = "test", // firstName = "Swapnali", lastName = "Dembla", email = "*****@*****.**", // address = new ContactAddress { addressLine1 = "500 San Blvd", city = "San Ramon", state = new State { value = "CA" }, // postalCode = "94566" }, // type = new ContactType { value = "Pet Owner" } }}; //rec.CreateRecordContact(cs, recordId, token); //contacts = rec.GetRecordContacts(recordId, token); //Contact c = ((List<Contact>)contacts.Data)[0]; //c.type.text = null; //c.middleName = "test for Oscar"; //c = rec.UpdateRecordContact(c, recordId, token); //contacts = rec.GetRecordContacts(recordId, token); ////rec.DeleteRecordContact(c.id, rId, token); //contacts = rec.GetRecordContacts(recordId, token); // Address //List<Country> cn = ad.GetCountries(token); //List<State> s = ad.GetStates(token); // Records //Record record = rec.GetRecord(recordId, token); //record.name = "Test Again & Again"; //List<Dictionary<string, string>> cf = rec.GetRecordCustomFields(record.id, token); //record.description = "Test Again & Again"; //record = rec.UpdateRecordDetail(record, token); //record = rec.GetRecord(recordId, token); //records = rec.SearchRecords(token, new RecordFilter { type = new RecordType { category = "Application" }, contact = new Contact { firstName = "Sam" } }, null); //records = rec.GetRecords(token, null); //Record record = new Record { type = new RecordType { id = "Licenses-Animal-Dog-Application" } }; //List<Contact> contactList = new List<Contact> { new Contact { type = new ContactType { value = "Pet Owner" }, firstName = "Swapnali", lastName = "Dembla", email = "*****@*****.**" } }; //Record r1 = rec.CreateRecordInitialize(new Record { type = new RecordType { id = "Licenses-Animal-Dog-Application" } }, token); ////Record r1 = record; //r1.name = "Test Renewal"; //r1.description = "Test Renewal"; //r1 = rec.UpdateRecordDetail(r1, token); //record = rec.GetRecord(r1.id, token); //rec.CreateRecordContact(contactList, r1.id, token); //ResultDataPaged<Contact> cons = rec.GetRecordContacts(r1.id, token); //Contact cn = ((Contact)cons.Data.First()); //cn.lastName = "Dembla"; //cn = rec.UpdateRecordContact(cn, r1.id, token); //List<Dictionary<string, string>> cf = rec.GetRecordCustomFields(r1.id, token); //Dictionary<string, string> temp = cf[1]; //temp["Pet Name"] = "Goof"; ////rec.UpdateRecordCustomFields(r1.id, cf, token); //cf = rec.GetRecordCustomFields(r1.id, token); //cons = rec.GetRecordContacts(r1.id, token); //FileInfo file = new FileInfo(@"C:\Swapnali\TestPurposes\Ducky.jpeg"); //if (file != null) //{ // AttachmentInfo at = new AttachmentInfo { FileType = "image/jpeg", FileName = "Ducky.jpeg", ServiceProviderCode = "BPTMSTR", Description = "Test" }; // at.FileContent = new StreamContent(file.OpenRead()); // rec.CreateRecordDocument(at, r1.id, token, "ooo"); //} //List<Document> docs = rec.GetRecordDocuments(r1.id, token); //record.contacts = new List<Contact> { new Contact { id = "1234", firstName = "Swapnali", lastName = "Dembla", email = "*****@*****.**", type = new ContactType { value = "Pet Owner" } } }; //record = rec.CreateRecordFinalize(new Record { id = "BPTMSTR-14EST-00000-00257", type = new RecordType { id = "Licenses-Animal-Dog-Application" } }, token); //record = rec.CreateRecordFinalize(r1, token); //record = rec.GetRecord(record.id, token); //cons = rec.GetRecordContacts(record.id, token); //cf = rec.GetRecordCustomFields(record.id, token); ////docs = rec.GetRecordDocuments(record.id, token); // Documents //List<DocumentType> d = rec.GetRecordDocumentTypes(recordId, token); //List<Document> docs = rec.GetRecordDocuments(recordId, token); //Stream sr = doc.DownloadDocument("1132", token); //using (FileStream fs = new FileStream(@"C:\Swapnali\TestPurposes\photo.jpeg", FileMode.Create)) //{ // sr.CopyTo(fs); //} //FileInfo file = new FileInfo(@"C:\Swapnali\TestPurposes\Ducky.jpeg"); //if (file != null) //{ // AttachmentInfo at = new AttachmentInfo { FileType = "image/jpeg", FileName = "Ducky.jpeg", ServiceProviderCode = "BPTMSTR", Description = "Test" }; // at.FileContent = new StreamContent(file.OpenRead()); // rec.CreateRecordDocument(at, recordId, token, "ooo"); //} //rec.DeleteRecordDocument("1012", recordId, token); //docs = rec.GetRecordDocuments(recordId, token); // Status //List<Status> s = rec.GetRecordStatuses("Licenses-Animal-Pig-Application", token); //// Workflow //List<WorkflowTask> w2 = rec.GetWorkflowTasks(record.id, token); //WorkflowTask w = rec.GetWorkflowTask(record.id, taskId, token); //UpdateWorkflowTaskRequest uw = new UpdateWorkflowTaskRequest { comment = "testing", status = new Status { value = "In Review" } }; //w = rec.UpdateWorkflowTask("BPTMSTR-DUB14-00000-00059", taskId, uw, token); // Fees //List<RecordFees> fs = rec.GetRecordFees(recordId, token); // Custom Fields //cf = rec.GetRecordCustomFields(recordId, token); //temp = cf[0]; //temp["Pet Name"] = "Toffy"; ////List<Dictionary<string, string>> cfs = new List<Dictionary<string, string>>(); ////Dictionary<string, string> val = new Dictionary<string,string>(); ////val.Add("id", "LIC_DOG_LIC-GENERAL.cINFORMATION"); ////val.Add("Name", "Woofy"); ////cfs.Add(val); //rec.UpdateRecordCustomFields(recordId, cf, token); //cf = rec.GetRecordCustomFields(recordId, token); }
public ActionResult Setup(string timezone, string currency, string organisation, string country, string address, string city, string citySelected, string postcode, string phone, string tos, string states_canadian, string states_other, string states_us) { if (sessionid == null) { return(RedirectToLogin()); } try { if (!string.IsNullOrEmpty(timezone) && !string.IsNullOrEmpty(organisation) && !string.IsNullOrEmpty(country) && !string.IsNullOrEmpty(address) && (!string.IsNullOrEmpty(city) || !string.IsNullOrEmpty(citySelected)) && !string.IsNullOrEmpty(postcode) && !string.IsNullOrEmpty(tos)) { long?finalCity = null; if (!string.IsNullOrEmpty(citySelected)) { finalCity = long.Parse(citySelected); } else if (!string.IsNullOrEmpty(city)) { finalCity = repository.AddCity(city).id; } var usr = repository.GetUserById(sessionid.Value); if (usr == null) { throw new Exception("User not found"); } // add organisation var org = usr.organisation1; org.name = organisation; org.address = address; org.city = finalCity; org.postcode = postcode; org.phone = phone; org.country = int.Parse(country); if (string.IsNullOrEmpty(currency)) { currency = "432"; } org.MASTERsubdomain.currency = int.Parse(currency); if (!string.IsNullOrEmpty(country) && country == "185" && !string.IsNullOrEmpty(states_us)) { org.state = states_us; } else if (!string.IsNullOrEmpty(country) && country == "32" && !string.IsNullOrEmpty(states_canadian)) { org.state = states_canadian; } else { org.state = states_other; } // update shop name org.MASTERsubdomain.storeName = org.name; // update user information usr.timezone = timezone; // update shipping and billing addresses var addressHandler = new AddressHandler(org, repository); addressHandler.CopyShippingAndBillingAddressFromOrgAddress("", ""); // first name and last name is null here repository.Save(); var homeUrl = org.MASTERsubdomain.ToHostName().ToDomainUrl(); return(Json(homeUrl.ToJsonOKData())); } #region find out which field is 'missing' var missingfields = new List <string>(); if (string.IsNullOrEmpty(timezone)) { missingfields.Add("timezone"); } if (string.IsNullOrEmpty(currency)) { missingfields.Add("currency"); } if (string.IsNullOrEmpty(organisation)) { missingfields.Add("organisation"); } if (string.IsNullOrEmpty(country)) { missingfields.Add("country"); } if (string.IsNullOrEmpty(address)) { missingfields.Add("address"); } if (string.IsNullOrEmpty(city) && string.IsNullOrEmpty(citySelected)) { missingfields.Add("city"); } if (string.IsNullOrEmpty(postcode)) { missingfields.Add("postcode"); } if (string.IsNullOrEmpty(phone)) { missingfields.Add("phone"); } if (string.IsNullOrEmpty(tos)) { missingfields.Add("tos"); } #endregion return(SendJsonErrorResponse("Missing fields: " + string.Join(",", missingfields))); } catch (Exception ex) { return(SendJsonErrorResponse(ex)); } }
public ActionResult Update(long?id, string email, string address, string city, long?citySelected, string coPhone, string companyName, IEnumerable <int?> country, string fax, string firstName, int?permissions, string gender, string lastName, string notes, string phone, string postcode, string title, string password, IEnumerable <string> states_canadian, IEnumerable <string> states_other, IEnumerable <string> states_us, string billing_first_name, string billing_last_name, string billing_company, string billing_address, string billing_city, long?billing_citySelected, string billing_postcode, string billing_phone, string shipping_first_name, string shipping_last_name, string shipping_company, string shipping_address, string shipping_city, long?shipping_citySelected, string shipping_postcode, string shipping_phone) { if (!id.HasValue) { return(SendJsonErrorResponse("Missing ID")); } try { var contact = repository.GetContact(subdomainid.Value, id.Value); if (contact == null) { return(SendJsonErrorResponse("Missing ID")); } var original = contact.ToModel(sessionid, subdomainid.Value); // no need to take into account whether an organisation is there because it will always be created contact.organisation1.address = address.Trim(); if (citySelected.HasValue) { var mcity = repository.GetCity(citySelected.Value); contact.organisation1.MASTERcity = mcity; } else if (!string.IsNullOrEmpty(city)) { contact.organisation1.MASTERcity = repository.AddCity(city); } if (coPhone != null) { contact.organisation1.phone = coPhone; } if (companyName != null) { contact.organisation1.name = companyName; } if (country != null) { contact.organisation1.country = country.ElementAtOrDefault(0); contact.organisation1.state = AddressHandler.GetState(country.ElementAtOrDefault(0), states_us.ElementAtOrDefault(0), states_canadian.ElementAtOrDefault(0), states_other.ElementAtOrDefault(0)); } if (fax != null) { contact.organisation1.fax = fax; } if (email != null) { contact.email = email; } if (firstName != null) { contact.firstName = firstName; } if (gender != null) { contact.gender = gender; } if (lastName != null) { contact.lastName = lastName; } if (phone != null) { contact.phoneNumber = phone; } if (postcode != null) { contact.organisation1.postcode = postcode; } // handle addresses var addressHandler = new AddressHandler(contact.organisation1, repository); addressHandler.SetShippingAndBillingAddresses(billing_first_name, billing_last_name, billing_company, billing_address, billing_city, billing_citySelected, billing_postcode, billing_phone, country.ElementAtOrDefault(1), states_canadian.ElementAtOrDefault(1), states_other.ElementAtOrDefault(1), states_us.ElementAtOrDefault(1), shipping_first_name, shipping_last_name, shipping_company, shipping_address, shipping_city, shipping_citySelected, shipping_postcode, shipping_phone, country.ElementAtOrDefault(2), states_canadian.ElementAtOrDefault(2), states_other.ElementAtOrDefault(2), states_us.ElementAtOrDefault(2), false); if (title != null) { contact.title = title; } if (!string.IsNullOrEmpty(password)) { // password specified contact.passwordHash = Crypto.Utility.ComputePasswordHash(email + password); } else { // password removed contact.passwordHash = null; } // list of fields that are allowed to be modified if (notes != null) { contact.notes = notes; } // handle permissions if (permissions.HasValue) { contact.permissions = permissions; } repository.AddActivity(sessionid.Value, new ActivityMessage(id.Value, sessionid, ActivityMessageType.CONTACT_UPDATED, new HtmlLink(contact.ToEmailName(true), id.Value).ToContactString()), subdomainid.Value); repository.Save(); #if LUCENE // update search index var indexer = new LuceneWorker(db, MASTERdomain.ToIdName()); indexer.AddToIndex(LuceneIndexType.CONTACTS, contact); #endif // get changed and store in database var changed = contact.ToModel(sessionid, subdomainid.Value); var comparer = new CompareObject(); var diff = comparer.Compare(original, changed); if (diff.Count != 0) { repository.AddChangeHistory(sessionid.Value, contact.id, ChangeHistoryType.CONTACT, diff); } } catch (Exception ex) { return(SendJsonErrorResponse(ex)); } return(Json(id.ToJsonOKData())); }
// Creates a new client user public ActionResult CreateClient() { // Ensures logged in if (Session["loggedInState"] == null) { return(Redirect("/403.html")); } // Checks if logged in bool state = (bool)Session["loggedInState"]; if (state == true) { // Establishes models ClientUserModel cModel = new ClientUserModel(); // Establishes handlers AccountHandler accHand = new AccountHandler(); AddressHandler addHand = new AddressHandler(); BankHandler banHand = new BankHandler(); ContactHandler conHand = new ContactHandler(); CustomerHandler cusHand = new CustomerHandler(); // Extract for account details int accountType = int.Parse(Request.Form["accountTypes"]); // Extract for bank details String sortCode = Request.Form["sortCode"]; int accountNumber = int.Parse(Request.Form["accountNumber"]); // Extract for client details String username = Request.Form["username"]; String password = Request.Form["password1"]; String name = Request.Form["clientName"]; // Extract contact details String forename = Request.Form["contactForename"]; String surname = Request.Form["contactSurname"]; String position = Request.Form["contactPosition"]; String phoneNumber = Request.Form["contactPhone"]; // Extract bank address details //String blineOne = Request.Form["bankL1"]; //String blineTwo = Request.Form["bankL2"]; ; //String blineThree = Request.Form["bankL3"]; //String blineFour = Request.Form["bankL4"]; //String blineFive = Request.Form["bankL5"]; //String bcState = Request.Form["bankState"]; //String bcounty = Request.Form["bankCounty"]; //String bcountry = Request.Form["bankCountry"]; //String bpostalCode = Request.Form["bankPostalCode"]; // Extract for customer details String compName = Request.Form["clientName"]; // Extract customer address details String clineOne = Request.Form["address1"]; String clineTwo = Request.Form["address2"];; String clineThree = Request.Form["address3"]; String clineFour = Request.Form["address4"]; String clineFive = Request.Form["address5"]; String ccState = Request.Form["state"]; String ccounty = Request.Form["county"]; String ccountry = Request.Form["country"]; String cpostalCode = Request.Form["postcode"]; // Creates objects for user //int bankAddressID = addHand.create(blineOne, blineTwo, blineThree, blineFour, blineFive, bcState, // bcounty, bcountry, bpostalCode); int custAddressID = addHand.create(clineOne, clineTwo, clineThree, clineFour, clineFive, ccState, ccounty, ccountry, cpostalCode); int bankID = banHand.create(sortCode, accountNumber); int contactID = conHand.create(forename, surname, position, phoneNumber); int customerID = cusHand.create(compName, custAddressID); int accountID = accHand.create(accountType, bankID, customerID, contactID); // Holds new objects ClientUser newClient = new ClientUser(); // Acquires needed Account ID newClient.Username = username; // Stored details for the customer newClient.Name = name; newClient.Username = username; newClient.Password = password; newClient.AccountID = accountID; // Creates the customer int clientID = cModel.CreateClientUser(newClient); // Return created department to view return(Redirect("/Index/adminIndex")); } else { // If not logged in return(Redirect("/login.html")); } }