public static image ReadAndSaveFromUrl(this string url, long subdomainid, long ownerid, long contextid, PhotoType type) { var req = WebRequest.Create(url); WebResponse resp = null; try { resp = req.GetResponse(); } catch (Exception ex) { Syslog.Write(ex); } if (resp == null) { return(null); } try { var image = new image(); using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); var extension = url.ToImageFormat().ToStringExtension(); var filename = BuildFilename(ownerid, extension); var handler = new FileHandler(filename, UploadFileType.IMAGE, sd.uniqueid); image.imageType = type.ToString(); image.subdomain = subdomainid; image.contextID = contextid; image.url = handler.Save(resp.GetResponseStream()); repository.AddImage(image); switch (type) { case PhotoType.PROFILE: var usr = repository.GetUserById(ownerid); if (usr != null) { usr.profilePhoto = image.id; } repository.Save("ReadAndSaveFromUrl:Profile"); break; default: break; } } return(image); } catch (Exception ex) { Syslog.Write(ex); return(null); } }
public static string ToSavedImageUrl(this string datauri, long sessionid, long subdomainid) { var segments = datauri.Split(new[] { ',' }); if (segments.Length != 2) { Syslog.Write("Invalid datauri: " + datauri); return(""); } var type = segments[0]; var data = segments[1]; Regex datauriRegex = new Regex("data:image/(.+);base64"); var match = datauriRegex.Match(type); string extension = ""; switch (match.Groups[1].Value) { case "jpeg": extension = ".jpg"; break; case "png": extension = ".png"; break; case "gif": extension = ".gif"; break; default: break; } if (String.IsNullOrEmpty(extension)) { Syslog.Write("Invalid datauri: " + datauri); return(""); } var bytes = Convert.FromBase64String(data); var ms = new MemoryStream(bytes); var filename = BuildFilename(sessionid, extension); string url = ""; using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); var handler = new FileHandler(filename, UploadFileType.IMAGE, sd.uniqueid); url = handler.Save(ms); } return(url); }
public static product_image ReadAndSaveProductImageFromUrl(this string url, long subdomainid, long ownerid, long?productid) { var req = WebRequest.Create(url); WebResponse resp = null; try { resp = req.GetResponse(); } catch (Exception ex) { Syslog.Write(ex); } if (resp == null) { return(null); } try { var image = new product_image(); using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); var extension = url.ToImageFormat().ToStringExtension(); var filename = BuildFilename(ownerid, extension); var handler = new FileHandler(filename, UploadFileType.IMAGE, sd.uniqueid); image.productid = productid; image.subdomainid = subdomainid; image.url = handler.Save(resp.GetResponseStream()); if (productid.HasValue) { repository.AddProductImage(image); var product = repository.GetProduct(productid.Value, subdomainid); if (product != null && !product.thumb.HasValue) { product.thumb = image.id; } repository.Save("ReadAndSaveProductImageFromUrl"); } } return(image); } catch (Exception ex) { Syslog.Write(ex); return(null); } }
public override void StartSynchronisation(bool?upload) { using (var repository = new TradelrRepository()) { // create default shipping profile var sd = repository.GetSubDomain(subdomainid); if (sd == null) { throw new ArgumentException("Cannot find domain for subdomainid " + subdomainid); } // create network location var inventoryLocation = new inventoryLocation { name = LOCATIONNAME_EBAY, subdomain = subdomainid, lastUpdate = DateTime.UtcNow }; repository.AddInventoryLocation(inventoryLocation, subdomainid); // add shipping profile if there's none foreach (var site in EbayService.SupportedSites) { if (sd.ebay_shippingprofiles.Count(x => x.siteid == site.ToString()) != 0) { continue; } var shippingprofile = new ebay_shippingprofile { title = "Default", siteid = site.ToString() }; sd.ebay_shippingprofiles.Add(shippingprofile); repository.Save("ebay.StartSynchronisation"); } } }
public GoogleBaseExporter(long subdomainid, string hostname, long? sessionid = null) : this(hostname) { ownerid = sessionid; service = new ContentForShoppingService("tradelr"); var authFactory = new GAuthSubRequestFactory("gbase", "tradelr"); using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); if (sd.gbaseid.HasValue && !string.IsNullOrEmpty(sd.googleBase.sessiontoken)) { service.RequestFactory = authFactory; service.SetAuthenticationToken(sd.googleBase.sessiontoken); accountid = sd.googleBase.accountid.ToString(); } else { // use tradelr as default service.setUserCredentials("*****@*****.**", "tuaki1976"); accountid = "8812401"; } // get feed if (sd.gbaseid.HasValue) { var query = new ProductQuery("schema", accountid); feed = service.Query(query); InitLocalisation(sd.gbaseid.HasValue ? sd.googleBase.country : COUNTRY_US, sd.currency.ToCurrency()); } } }
private void Update() { if (string.IsNullOrEmpty(warehouse)) { Syslog.Write(string.Format("Shipwire warehouse not specified: {0}", subdomainid)); return; } service.CreateInventoryUpdate(warehouse); var resp = service.SubmitInventoryUpdate(); if (resp != null) { // check for Error if (resp.Status == ShipwireService.StatusError && resp.ErrorMessage.ToLower().Contains("password")) { // clear invalid credentials using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); if (sd != null) { sd.shipwireEmail = ""; sd.shipwirePassword = ""; repository.Save(); } } } // we want to create a location only if there are products if (resp.Products.Count != 0) { Debug.WriteLine(string.Format("{0}: {1} products", warehouse, resp.Products.Count)); using (var repository = new TradelrRepository()) { // if items not zero then we create inventory location if it does not already exist var inventoryloc = new inventoryLocation { subdomain = subdomainid, name = warehouse, lastUpdate = DateTime.UtcNow }; var locid = repository.AddInventoryLocation(inventoryloc, subdomainid); // we go through each product foreach (var product in resp.Products) { var variant = repository.GetProductVariant(product.code, subdomainid, ProductFlag.ARCHIVED); // if product exist and not archived if (variant != null) { Debug.WriteLine("Existing product: " + product.code); // then we just update the inventorylocitem var ilocitem = repository.GetInventoryLocationItems(locid, subdomainid).SingleOrDefault(x => x.variantid == variant.id); if (ilocitem == null) { // can be null from do these updates from Shipwire as we're doing on a per location basis // anyway create an entry ilocitem = new inventoryLocationItem { variantid = variant.id, locationid = locid, lastUpdate = DateTime.UtcNow, available = product.quantity }; repository.AddInventoryLocationItem(ilocitem, subdomainid); } else { // just update as this is a sync ilocitem.available = product.quantity; ilocitem.lastUpdate = DateTime.UtcNow; repository.Save("InventoryUpdate Update"); } } else { Debug.WriteLine("New product: " + product.code); // create new product var productInfo = new ProductInfo(); // do product var p = new product { subdomainid = subdomainid, title = product.code, details = "", created = DateTime.UtcNow }; productInfo.p = p; variant = new product_variant(); variant.sku = product.code; // do inventory location item var ilocitem = new inventoryLocationItem { variantid = variant.id, locationid = locid, lastUpdate = DateTime.UtcNow }; var invWorker = new InventoryWorker(ilocitem, subdomainid, true, false); // assume not digital invWorker.SetValues("Shipwire Update", product.quantity, null, null, null); variant.inventoryLocationItems.Add(ilocitem); productInfo.p.product_variants.Add(variant); // finally add to db repository.AddProduct(productInfo, subdomainid); } } } } else { //Syslog.Write(ErrorLevel.WARNING,string.Format("{0}: No products", warehouse)); } } else { Syslog.Write("No response from warehouse " + warehouse); } }
public void ipn(string txn_id, string custom, string mc_gross, string payment_status, string receiver_email) { //Per PayPal Order Management / Integration Guide Pg.25 //we have to validate message by sending message back to paypal //Post back to either sandbox or live HttpWebRequest req = (HttpWebRequest)WebRequest.Create(PaymentConstants.PaypalPostAddress); //Set values for the request back req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; byte[] param = Request.BinaryRead(Request.ContentLength); string strRequest = Encoding.ASCII.GetString(param); strRequest += "&cmd=_notify-validate"; req.ContentLength = strRequest.Length; //for proxy //WebProxy proxy = new WebProxy(new Uri("http://url:port#")); //req.Proxy = proxy; //Send the request to PayPal and get the response StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII); streamOut.Write(strRequest); streamOut.Close(); StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()); string strResponse = streamIn.ReadToEnd(); streamIn.Close(); string response; Request.InputStream.Position = 0; using (var sr = new StreamReader(Request.InputStream)) { response = sr.ReadToEnd(); } var subdomainid = long.Parse(custom); try { if (strResponse == "VERIFIED") { using (var repository = new TradelrRepository()) { var sd = repository.GetSubDomain(subdomainid); if (payment_status.ToLower() == "completed" && receiver_email == PaymentConstants.PaypalSubscribeEmail) { // payment verified sd.accountTypeStatus = (int)AccountPlanPaymentStatus.NONE; sd.accountTransactionID = txn_id; Syslog.Write(string.Concat("SUBSCRIBE:", subdomainid, ":oldplan:", sd.accountType, ":newplan:", sd.accountTypeNew)); if (sd.accountType != sd.accountTypeNew) { sd.accountType = sd.accountTypeNew; } else { Syslog.Write("Payment received for subdomain ID:" + subdomainid); } repository.Save(); } } Syslog.Write("VALID IPN:" + HttpUtility.HtmlEncode(response)); } else { if (strResponse == "INVALID") { Syslog.Write("INVALID IPN:" + HttpUtility.HtmlEncode(response)); } else { Syslog.Write("UNKNOWN IPN:" + HttpUtility.HtmlEncode(response)); } } } catch (Exception ex) { Syslog.Write(ex); Syslog.Write(string.Format("Exception {0}: {1}", subdomainid, HttpUtility.HtmlEncode(response))); } }
public static void GenerateDefaultStructures(long subdomainid) { using (var repository = new TradelrRepository()) { var mastersubdomain = repository.GetSubDomain(subdomainid); if (mastersubdomain == null) { Syslog.Write("Can't generate liquid structures for domainid: " + subdomainid); return; } if (mastersubdomain.theme != null) { // already initialise, return return; } // init default theme (SOLO) mastersubdomain.theme = new DBML.theme() { created = DateTime.UtcNow, title = "Solo", preset = "", url = "/Content/templates/store/themes/solo/thumb.jpg" }; // do liquid stuff var page_about = new page() { name = "About Us", permalink = "about-us", creator = mastersubdomain.organisation.users.First().id, updated = DateTime.UtcNow, settings = (int)PageSettings.VISIBLE }; using (var reader = File.OpenText(GeneralConstants.APP_ROOT_DIR + "Content/templates/store/aboutus.txt")) { page_about.content = reader.ReadToEnd(); } mastersubdomain.pages.Add(page_about); var linklist_mainmenu = new linklist() { permalink = "main-menu", permanent = true, title = "Main Menu" }; mastersubdomain.linklists.Add(linklist_mainmenu); var link_home = new link { title = "Home", type = (int)LinkType.FRONTPAGE, url = "/" }; var link_catalog = new link() { title = "Catalog", type = (int)LinkType.WEB, url = "/collections/all" }; var link_about = new link() { title = "About Us", type = (int)LinkType.PAGE, url = "/pages/about-us" }; linklist_mainmenu.links.Add(link_home); linklist_mainmenu.links.Add(link_catalog); linklist_mainmenu.links.Add(link_about); var linklist_footer = new linklist() { permalink = "footer", permanent = true, title = "Footer" }; mastersubdomain.linklists.Add(linklist_footer); var link_search = new link { title = "Search", type = (int)LinkType.SEARCHPAGE, url = "/search" }; linklist_footer.links.Add(link_search); linklist_footer.links.Add(link_about); // create default collection var collection = new product_collection() { name = "Frontpage", permalink = "frontpage", settings = (int)(CollectionSettings.VISIBLE | CollectionSettings.PERMANENT) }; mastersubdomain.product_collections.Add(collection); // finally save repository.Save(); // copy theme files var handler = new ThemeHandler(mastersubdomain, false); new Thread(() => { var source = new DirectoryInfo(GeneralConstants.APP_ROOT_DIR + "Content/templates/store/themes/solo"); handler.CopyThemeToUserThemeDirectory(source); }).Start(); // copy mobile theme files var handler_mobile = new ThemeHandler(mastersubdomain, true); new Thread(() => { var source = handler.GetMobileThemeRepositorySourceDir(); handler_mobile.CopyThemeToUserThemeDirectory(source); }).Start(); } }
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 override void StartSynchronisation(bool?upload) { // pull items var gbase = new GoogleBaseExporter(subdomainid, hostName, sessionid); gbase.GetAllProducts(); using (var repository = new TradelrRepository()) { // create network location var inventoryLocation = new inventoryLocation { name = LOCATIONNAME_GBASE, subdomain = subdomainid, lastUpdate = DateTime.UtcNow }; locationid = repository.AddInventoryLocation(inventoryLocation, subdomainid); // init some settings locationid = repository.GetInventoryLocation(LOCATIONNAME_GBASE, subdomainid).id; currency = repository.GetSubDomain(subdomainid).currency.ToCurrency(); var products = repository.GetProducts(subdomainid); foreach (var entry in gbase.entries) { ProductEntry entry1 = entry; var oldTypeEntry = products.SingleOrDefault(x => x.gbaseID == entry1.Id.AbsoluteUri); if (oldTypeEntry != null) { // old type entry exists // remove id oldTypeEntry.gbaseID = null; // create gbase entry, don't need to create a variant since one would already exist oldTypeEntry.gbase_product = CreateGbaseInformationEntry(entry); } else { var newtypeEntry = products.Where(x => x.gbase_product.externalid == entry1.Id.AbsoluteUri).Select( x => x.gbase_product).SingleOrDefault(); if (newtypeEntry != null) { // new type entry exists // update status newtypeEntry.expirydate = entry.ExpirationDate; if (entry.IsDraft) { newtypeEntry.flags |= (int)InventoryItemFlag.DRAFT; } else { newtypeEntry.flags &= ~(int)InventoryItemFlag.DRAFT; } } else { // entry does not exist // create and add entry to tradelr var p = CreateProductFromEntry(entry); // create variant var variants = new List <product_variant>(); var variant = new product_variant() { sku = string.Concat("GBASE", entry.Id.AbsoluteUri.Substring( entry.Id.AbsoluteUri.LastIndexOf('/') + 1)) }; variants.Add(variant); // add gbase info p.gbase_product = CreateGbaseInformationEntry(entry); p.product_variants.AddRange(variants); var pinfo = new ProductInfo() { p = p }; repository.AddProduct(pinfo, subdomainid); // images foreach (var link in entry.AdditionalImageLinks) { var image = link.Value.ReadAndSaveProductImageFromUrl(subdomainid, sessionid, p.id); p.thumb = image.id; } } } } // upload to google base for each entry that does not have a special entry if (upload.HasValue && upload.Value) { var newproducts = repository.GetProducts(subdomainid).Where( x => !x.gbase.HasValue && (x.flags & (int)ProductFlag.ARCHIVED) == 0); foreach (var p in newproducts) { var gb = new GoogleBaseExporter(subdomainid, hostName, sessionid); gb.InitValues(p); #if !DEBUG IEnumerable <Photo> productPhotos = repository.GetImages(PhotoType.PRODUCT, p.id).ToModel(Imgsize.LARGE); gb.AddProductImages(productPhotos); #endif var worker = new GoogleBaseWorker(gb); new Thread(worker.Post).Start(); } } // save repository.Save(); } }