Esempio n. 1
0
        public static IState OpenOrderByBarcode(string orderBarcode)
        {
            MenuList orderDocsMenu = new MenuList();
            String   label         = "";
            String   cashierId     = orderBarcode.Substring(0, 4);
            int      orderId       = int.Parse(orderBarcode.Substring(4, 4));

            List <DocumentFileHelper> orderDocuments = new List <DocumentFileHelper>(DocumentFileHelper.GetOpenOrders("", true));

            foreach (DocumentFileHelper helper in orderDocuments)
            {
                if (helper.Cashier.Id == cashierId &&
                    helper.Id == orderId)
                {
                    //SalesDocument doc = helper.LoadDocument();
                    String cashiername = helper.Cashier.Name;
                    cashiername = cashiername.Substring(0, Math.Min(14, cashiername.Length));
                    label       = "SIP NO:{0:D4}\t{1:dd/MM/yy}\n{2}\t{1:HH:mm}";
                    label       = String.Format(label, helper.Id, helper.CreationTime, cashiername);

                    orderDocsMenu.Add(new MenuLabel(label, helper));
                }
            }
            if (orderDocsMenu.Count == 0)
            {
                return(AlertCashier.Instance(new Confirm(PosMessage.NO_DOCUMENT_FOUND)));
            }
            else
            {
                return(List.Instance(orderDocsMenu, RepeatDocument));
            }
        }
Esempio n. 2
0
        private static IState OpenTables()
        {
            countToSellingState = 0;
            MenuList tableDocsMenu = new MenuList();
            String   label         = "";

            DisplayAdapter.Customer.ClearTableContent();
            List <DocumentFileHelper> tableDocuments = new List <DocumentFileHelper>(DocumentFileHelper.GetOpenTables());

            foreach (DocumentFileHelper helper in tableDocuments)
            {
                if (helper.FileInfo.Name.IndexOf("MASA10") > -1)
                {
                    label = "{0}:{1:D3}\t{2:dd/MM/yy}\n{3}\t{4}";
                    label = String.Format(label, PosMessage.TABLE_NUMBER, helper.Id, helper.CreationTime, PosMessage.TOTAL, 0);
                }
                else
                {
                    SalesDocument salesDocument = helper.LoadDocument();

                    label = "{0}:{1:D3}\t{2:dd/MM/yy}\n{3}\t{4}";
                    label = String.Format(label, PosMessage.TABLE_NUMBER, helper.Id, helper.CreationTime, PosMessage.TOTAL, salesDocument.TotalAmount);
                }

                tableDocsMenu.Add(new MenuLabel(label, helper));
            }

            return(List.Instance(tableDocsMenu, ShowTableOnDisp, Continue));
        }
Esempio n. 3
0
        /// <summary>
        /// - repeats document printed before.
        /// </summary>
        /// <returns>State of List.cs</returns>
        public static IState ResumeDocument()
        {
            List <DocumentFileHelper> suspendedDocuments = new List <DocumentFileHelper>();
            String format = "BEK" + (cr.PrinterLastZ + 1).ToString().PadLeft(4, '0') + "*." + cr.Id;

            String[] fileList = Dir.GetFiles(PosConfiguration.ArchivePath, format);


            foreach (String fileName in fileList)
            {
                int                receiptId     = 0;
                FileHelper         suspendedFile = new FileHelper(fileName);
                DocumentFileHelper receipt       = new DocumentFileHelper(suspendedFile);
                if (Parser.TryInt(suspendedFile.Name.Substring(7, 4), out receiptId) &&
                    suspendedFile.Name.Length > 14)
                {
                    receipt.Id = receiptId;
                    receipt.ResumedFromDocumentId = receiptId;
                    suspendedDocuments.Add(receipt);
                }
            }

            MenuList suspendedDocsMenu = new MenuList();

            foreach (DocumentFileHelper docFileHelper in suspendedDocuments)
            {
                suspendedDocsMenu.Add(docFileHelper);
            }
            return(List.Instance(suspendedDocsMenu, RepeatDocument));
        }
Esempio n. 4
0
 public CvlUpdater(IConfiguration config, CatalogDocumentFactory catalogDocumentFactory, EpiApi epiApi, DocumentFileHelper documentFileHelper)
 {
     _config = config;
     _catalogDocumentFactory = catalogDocumentFactory;
     _epiApi             = epiApi;
     _documentFileHelper = documentFileHelper;
 }
Esempio n. 5
0
        /// <summary>
        /// - repeates document printed before.
        /// - Documents:Receipt,Invoice,Waybill,ReturnDocument,DiplomaticSale
        /// </summary>
        /// <param name="o"></param>
        public static void RepeatDocument(Object o)
        {
            DocumentFileHelper docHelper = null;

            if (o is DocumentFileHelper)
            {
                docHelper = o as DocumentFileHelper;
            }
            else
            {
                MenuLabel label = o as MenuLabel;
                docHelper = label.Value as DocumentFileHelper;
            }
            Hashtable data = new Hashtable();

            SalesDocument document = null;

            document            = docHelper.LoadDocument();
            document.FileOnDisk = docHelper.FileInfo;



            data.Add("Document", document);
            cr.State = RepeatConfirmed(data);
            //cr.Document.Id = docHelper.Id;
            cr.Document.Id = cr.Printer.CurrentDocumentId;
            docHelper.Remove(cr.Document);
        }
        public new void Start()
        {
            ConnectorEvent startEvent = null;

            try
            {
                _config = new Configuration(Id);
                ConnectorEventHelper.CleanupOngoingEvents(_config);
                startEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.Start, "Connector is starting", 0);

                Entity channel = RemoteManager.DataService.GetEntity(_config.ChannelId, LoadLevel.Shallow);
                if (channel == null || channel.EntityType.Id != "Channel")
                {
                    _started = false;
                    ConnectorEventHelper.UpdateEvent(startEvent, "Channel id is not valid: Entity with given ID is not a channel, or doesn't exist. Unable to start", -1, true);
                    return;
                }

                _pimFieldAdapter      = new PimFieldAdapter(_config);
                _epiMappingHelper     = new EpiMappingHelper(_config, _pimFieldAdapter);
                _entityService        = new EntityService(_config, _epiMappingHelper);
                _catalogCodeGenerator = new CatalogCodeGenerator(_config, _entityService);
                _epiApi = new EpiApi(_config, _catalogCodeGenerator, _pimFieldAdapter);
                _catalogElementFactory  = new CatalogElementFactory(_config, _epiMappingHelper, _catalogCodeGenerator, _pimFieldAdapter);
                _channelHelper          = new ChannelHelper(_config, _entityService);
                _catalogDocumentFactory = new CatalogDocumentFactory(_config, _epiApi, _catalogElementFactory, _epiMappingHelper, _channelHelper, _catalogCodeGenerator, _entityService);
                _resourceElementFactory = new ResourceElementFactory(_catalogElementFactory, _epiMappingHelper, _catalogCodeGenerator, _config, _entityService);

                _documentFileHelper = new DocumentFileHelper(_config, _channelHelper);
                _cvlUpdater         = new CvlUpdater(_config, _catalogDocumentFactory, _epiApi, _documentFileHelper);

                _publisher = new ChannelPublisher(_config,
                                                  _catalogDocumentFactory,
                                                  _catalogElementFactory,
                                                  _resourceElementFactory,
                                                  _epiApi,
                                                  _epiMappingHelper,
                                                  _documentFileHelper,
                                                  _pimFieldAdapter,
                                                  _entityService,
                                                  _catalogCodeGenerator);

                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;

                InitConnector();

                base.Start();
                _started = true;
                ConnectorEventHelper.UpdateEvent(startEvent, "Connector has started", 100);
            }
            catch (Exception ex)
            {
                IntegrationLogger.Write(LogLevel.Error, "Error while starting connector", ex);
                ConnectorEventHelper.UpdateEvent(startEvent, "Issue while starting connector, see log.", 100, true);
                throw;
            }
        }
Esempio n. 7
0
        public static void ShowTableOnDisp(Object o)
        {
            DocumentFileHelper docHelper      = null;
            SalesDocument      document       = null;
            decimal            totalAdjAmount = 0.0m;

            if (o is DocumentFileHelper)
            {
                docHelper = o as DocumentFileHelper;
            }
            else
            {
                MenuLabel label = o as MenuLabel;
                docHelper = label.Value as DocumentFileHelper;
            }

            if (docHelper.FileInfo.Name.IndexOf("MASA10") > -1)
            {
                cr.State = AlertCashier.Instance(new Confirm("MASA BOÞ", OpenTables));
            }
            else if (countToSellingState == 1)
            {
                document            = docHelper.LoadDocument();
                document.FileOnDisk = docHelper.FileInfo;
                document.Id         = cr.Document.Id;
                String label = "{0}:{1:D3}\t{2}\n{3}?({4})";
                label = String.Format(label, PosMessage.TABLE_NUMBER, docHelper.Id, document.TotalAmount, PosMessage.CLOSE_TABLE, PosMessage.ENTER);
                Confirm e = new Confirm(label,
                                        new StateInstance <Hashtable>(RepeatConfirmed),
                                        new StateInstance(OpenTables));

                countToSellingState = 0;
                e.Data["Document"]  = document;
                cr.State            = ConfirmCashier.Instance(e);
                docHelper.Id        = cr.Document.Id;
                docHelper.Remove(cr.Document);
            }
            else
            {
                document = docHelper.LoadDocument();
                foreach (Adjustment adj in document.Adjustments)
                {
                    totalAdjAmount += adj.NetAmount;
                }

                DisplayAdapter.Customer.ShowTableContent(document, totalAdjAmount);
                countToSellingState++;
            }
        }
Esempio n. 8
0
        public override void Repeat()
        {
            DocumentFileHelper[] orders = DocumentFileHelper.GetOpenOrders();

            if (orders.Length > 0)
            {
                SalesDocument doc         = orders[0].LoadDocument();
                String        cashiername = doc.SalesPerson.Name;
                cashiername = cashiername.Substring(0, Math.Min(14, cashiername.Length));
                String label = doc.Name.Substring(0, 3) + " NO:{0:D4}\t{1:dd/MM/yy}\n{2}\t{1:HH:mm}";
                label = String.Format(label, doc.Id, doc.CreatedDate, cashiername);
                CommandMenu.RepeatDocument(new MenuLabel(label, orders[0]));
            }
            BackgroundWorker.ProcessTcpOrder();
        }
Esempio n. 9
0
        private static IState OpenOrders()
        {
            MenuList orderDocsMenu = new MenuList();
            String   label         = "";

            List <DocumentFileHelper> orderDocuments = new List <DocumentFileHelper>(DocumentFileHelper.GetOpenOrders("", false));

            foreach (DocumentFileHelper helper in orderDocuments)
            {
                //SalesDocument doc = helper.LoadDocument();
                String cashiername = helper.Cashier.Name;
                cashiername = cashiername.Substring(0, Math.Min(14, cashiername.Length));
                label       = "BEL NO:{0:D4}\t{1:dd/MM/yy}\n{2}\t{1:HH:mm}";
                label       = String.Format(label, helper.Id, helper.CreationTime, cashiername);

                orderDocsMenu.Add(new MenuLabel(label, helper));
            }
            return(List.Instance(orderDocsMenu, RepeatDocument));
        }
Esempio n. 10
0
        public void DeleteLinkEntity(Entity channelEntity, int linkEntityId)
        {
            XDocument deleteXml = new XDocument(new XElement("xml", new XAttribute("action", "deleted")));

            var channelHelper = new ChannelHelper(_context);

            if (deleteXml.Root != null && deleteXml.Root.Elements().FirstOrDefault(e => e.Name.LocalName == "entry") != null)
            {
                string channelIdentifier = channelHelper.GetChannelIdentifier(channelEntity);
                string folderDateTime    = DateTime.Now.ToString("yyyyMMdd-HHmmss.fff");


                if (!DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Catalog, deleteXml, DeleteUtilConfig, folderDateTime))
                {
                    _context.Log(LogLevel.Information, "Failed to zip and upload the catalog file to azure from delete utility DeleteLinkEntity() method");
                }
                _context.Log(LogLevel.Debug, "catalog saved");
            }
        }
Esempio n. 11
0
        private void DeleteResource(Entity targetEntity, Entity parentEnt, string channelIdentifier, string folderDateTime, string resourceZipFile)
        {
            var       resource = new Resources(_context);
            XDocument doc      = resource.HandleResourceUnlink(targetEntity, parentEnt, DeleteUtilConfig);

            DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Resources, doc, DeleteUtilConfig, folderDateTime /*, _context*/);

            if (DeleteUtilConfig.ActivePublicationMode.Equals(PublicationMode.Automatic))
            {
                _context.Log(LogLevel.Debug, "Starting automatic import!");

                if (_epiApi.StartAssetImportIntoEpiServerCommerce(
                        DeleteUtilConfig.ResourceNameInCloud,             /*Path.Combine(this.DeleteUtilConfig.ResourcesRootPath, folderDateTime, "Resources.xml")*/
                        Path.Combine(DeleteUtilConfig.ResourcesRootPath, folderDateTime),
                        DeleteUtilConfig))
                {
                    _epiApi.SendHttpPost(DeleteUtilConfig, Path.Combine(DeleteUtilConfig.ResourcesRootPath, folderDateTime, resourceZipFile));
                }
            }
        }
        public new void Stop()
        {
            base.Stop();
            var connectorEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.Stop, "Connector is stopping", 0);

            _started = false;
            _epiApi  = null;
            _catalogElementFactory  = null;
            _catalogDocumentFactory = null;
            _channelHelper          = null;
            _resourceElementFactory = null;
            _epiMappingHelper       = null;
            _catalogCodeGenerator   = null;
            _publisher          = null;
            _config             = null;
            _documentFileHelper = null;
            _entityService      = null;
            _cvlUpdater         = null;

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Connector has stopped.", 100);
        }
 public ChannelPublisher(IConfiguration config,
                         CatalogDocumentFactory catalogDocumentFactory,
                         CatalogElementFactory catalogElementFactory,
                         ResourceElementFactory resourceElementFactory,
                         EpiApi epiApi,
                         EpiMappingHelper mappingHelper,
                         DocumentFileHelper documentFileHelper,
                         PimFieldAdapter pimFieldAdapter,
                         IEntityService entityService,
                         CatalogCodeGenerator catalogCodeGenerator)
 {
     _config = config;
     _catalogDocumentFactory = catalogDocumentFactory;
     _catalogElementFactory  = catalogElementFactory;
     _resourceElementFactory = resourceElementFactory;
     _epiApi               = epiApi;
     _mappingHelper        = mappingHelper;
     _documentFileHelper   = documentFileHelper;
     _pimFieldAdapter      = pimFieldAdapter;
     _entityService        = entityService;
     _catalogCodeGenerator = catalogCodeGenerator;
 }
Esempio n. 14
0
        static IState RepeatConfirmed(Hashtable data)
        {
            SalesDocument      document = null;
            DocumentFileHelper helper   = null;

            if (data["Document"] is DocumentFileHelper)
            {
                helper = ((DocumentFileHelper)data["Document"]);
                helper.LoadDocument();
            }
            else
            {
                document = (SalesDocument)data["Document"];
            }
            if (document.Status == DocumentStatus.Suspended)
            {
                document.Resume();
            }

            /*ICustomer customer = cr.Document.Customer;
             * cr.Document = (SalesDocument)document.Clone();
             *
             * if (customer != null)
             *  cr.Document.Customer = customer;
             */
            if (document.FileOnDisk != null)
            {
                if (document.FileOnDisk.Name.IndexOf("MASA") > -1)
                {
                    DisplayAdapter.Cashier.ClearTableContent();
                }
            }
            cr.ChangeDocumentType((SalesDocument)document.Clone());
            cr.Document.Id = cr.Printer.CurrentDocumentId;

            return(cr.State);
        }
Esempio n. 15
0
        public void AddCvl(string cvlId, string folderDateTime)
        {
            List <XElement>  metafields         = new List <XElement>();
            List <FieldType> affectedFieldTypes = _businessHelper.GetFieldTypesWithCVL(cvlId, CvlUtilConfig);

            foreach (FieldType fieldType in affectedFieldTypes)
            {
                if (_epiMappingHelper.SkipField(fieldType, CvlUtilConfig))
                {
                    continue;
                }

                XElement metaField = _epiElement.InRiverFieldTypeToMetaField(fieldType, CvlUtilConfig);

                if (fieldType.DataType.Equals(DataType.CVL))
                {
                    metaField.Add(_epiMappingHelper.GetDictionaryValues(fieldType, CvlUtilConfig));
                }

                if (metafields.Any(
                        mf =>
                {
                    XElement nameElement = mf.Element("Name");
                    return(nameElement != null && nameElement.Value.Equals(_epiMappingHelper.GetEPiMetaFieldNameFromField(fieldType, CvlUtilConfig)));
                }))
                {
                    XElement existingMetaField =
                        metafields.FirstOrDefault(
                            mf =>
                    {
                        XElement nameElement = mf.Element("Name");
                        return(nameElement != null && nameElement.Value.Equals(_epiMappingHelper.GetEPiMetaFieldNameFromField(fieldType, CvlUtilConfig)));
                    });

                    if (existingMetaField == null)
                    {
                        continue;
                    }

                    var movefields = metaField.Elements("OwnerMetaClass");
                    existingMetaField.Add(movefields);
                }
                else
                {
                    metafields.Add(metaField);
                }
            }

            XElement  metaData = new XElement("MetaDataPlusBackup", new XAttribute("version", "1.0"), metafields.ToArray());
            XDocument doc      = _epiDocument.CreateDocument(null, metaData, null, CvlUtilConfig);

            Entity channelEntity = _context.ExtensionManager.DataService.GetEntity(CvlUtilConfig.ChannelId, LoadLevel.DataOnly);

            if (channelEntity == null)
            {
                _context.Log(LogLevel.Error, string.Format("Could not find channel {0} for cvl add", CvlUtilConfig.ChannelId));
                return;
            }

            string channelIdentifier = _channelHelper.GetChannelIdentifier(channelEntity);

            if (!DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Catalog, doc, CvlUtilConfig, folderDateTime))
            {
                _context.Log(LogLevel.Information, "Failed to zip and upload the catalog file to azure from cvl utility AddCvl() method");
            }

            _context.Log(LogLevel.Debug, string.Format("catalog {0} saved", channelIdentifier));

            if (CvlUtilConfig.ActivePublicationMode.Equals(PublicationMode.Automatic))
            {
                _context.Log(LogLevel.Debug, "Starting automatic import!");

                _epiApi.StartImportIntoEpiServerCommerce(
                    Path.Combine(CvlUtilConfig.PublicationsRootPath, folderDateTime, Configuration.ExportFileName),
                    _channelHelper.GetChannelGuid(channelEntity, CvlUtilConfig), CvlUtilConfig);
            }
        }
Esempio n. 16
0
        private void DeleteEntityThatStillExistInChannel(Entity channelEntity, Entity targetEntity, Entity parentEnt, string linkTypeId, List <StructureEntity> existingEntities, string channelIdentifier, string folderDateTime, string resourceZipFile)
        {
            var channelHelper = new ChannelHelper(_context);

            Dictionary <string, Dictionary <string, bool> > entitiesToUpdate = new Dictionary <string, Dictionary <string, bool> >();

            var channelNodes = _context.ExtensionManager.ChannelService.GetAllChannelStructureEntitiesForType(channelEntity.Id, "ChannelNode").ToList();

            if (!channelNodes.Any() && parentEnt.EntityType.Id == "Channel")
            {
                channelNodes.Add(_context.ExtensionManager.ChannelService.GetAllStructureEntitiesForEntityInChannel(channelEntity.Id, parentEnt.Id).First());
            }

            List <string> linkEntityIds = new List <string>();

            if (channelHelper.LinkTypeHasLinkEntity(linkTypeId))
            {
                DeleteUtilConfig.ChannelStructureEntities = channelHelper.GetAllEntitiesInChannel(
                    channelEntity.Id,
                    DeleteUtilConfig.ExportEnabledEntityTypes);

                List <StructureEntity> newEntityNodes = channelHelper.FindEntitiesElementInStructure(DeleteUtilConfig.ChannelStructureEntities, parentEnt.Id, targetEntity.Id, linkTypeId);

                List <string> pars = new List <string>();
                if (parentEnt.EntityType.Id == "Item" && DeleteUtilConfig.ItemsToSkus)
                {
                    pars = _epiElement.SkuItemIds(parentEnt, DeleteUtilConfig);

                    if (DeleteUtilConfig.UseThreeLevelsInCommerce)
                    {
                        pars.Add(parentEnt.Id.ToString(CultureInfo.InvariantCulture));
                    }
                }
                else
                {
                    pars.Add(parentEnt.Id.ToString(CultureInfo.InvariantCulture));
                }

                List <string> targets = new List <string>();
                if (targetEntity.EntityType.Id == "Item" && DeleteUtilConfig.ItemsToSkus)
                {
                    targets = _epiElement.SkuItemIds(targetEntity, DeleteUtilConfig);

                    if (DeleteUtilConfig.UseThreeLevelsInCommerce)
                    {
                        targets.Add(targetEntity.Id.ToString(CultureInfo.InvariantCulture));
                    }
                }
                else
                {
                    targets.Add(targetEntity.Id.ToString(CultureInfo.InvariantCulture));
                }

                linkEntityIds = _epiApi.GetLinkEntityAssociationsForEntity(linkTypeId, channelEntity.Id, channelEntity, DeleteUtilConfig, pars, targets);

                linkEntityIds.RemoveAll(i => newEntityNodes.Any(n => i == _channelPrefixHelper.GetEPiCodeWithChannelPrefix(n.ParentId, DeleteUtilConfig)));
            }

            // Add the removed entity element together with all the underlying entity elements
            List <XElement> elementList = new List <XElement>();

            foreach (StructureEntity existingEntity in existingEntities)
            {
                XElement copyOfElement = new XElement(existingEntity.Type + "_" + existingEntity.EntityId);
                if (elementList.All(p => p.Name.LocalName != copyOfElement.Name.LocalName))
                {
                    elementList.Add(copyOfElement);
                }

                if (DeleteUtilConfig.ChannelEntities.ContainsKey(existingEntity.EntityId))
                {
                    foreach (Link outboundLinks in DeleteUtilConfig.ChannelEntities[existingEntity.EntityId].OutboundLinks)
                    {
                        XElement copyOfDescendant = new XElement(outboundLinks.Target.EntityType.Id + "_" + outboundLinks.Target.Id);
                        if (elementList.All(p => p.Name.LocalName != copyOfDescendant.Name.LocalName))
                        {
                            elementList.Add(copyOfDescendant);
                        }
                    }
                }
            }

            List <XElement> updatedElements = elementList;

            foreach (XElement element in updatedElements)
            {
                string elementEntityType = element.Name.LocalName.Split('_')[0];
                string elementEntityId   = element.Name.LocalName.Split('_')[1];

                Dictionary <string, bool> shouldExsistInChannelNodes = channelHelper.ShouldEntityExistInChannelNodes(int.Parse(elementEntityId), channelNodes, channelEntity.Id);

                if (elementEntityType == "Link")
                {
                    continue;
                }

                if (elementEntityType == "Item" && DeleteUtilConfig.ItemsToSkus)
                {
                    Entity deletedEntity = null;

                    try
                    {
                        deletedEntity = _context.ExtensionManager.DataService.GetEntity(
                            int.Parse(elementEntityId),
                            LoadLevel.DataOnly);
                    }
                    catch (Exception ex)
                    {
                        _context.Log(LogLevel.Warning, "Error when getting entity:" + ex);
                    }

                    if (deletedEntity != null)
                    {
                        List <XElement> skus = _epiElement.GenerateSkuItemElemetsFromItem(deletedEntity, DeleteUtilConfig);
                        foreach (XElement sku in skus)
                        {
                            XElement skuCode = sku.Element("Code");
                            if (skuCode != null && !entitiesToUpdate.ContainsKey(skuCode.Value))
                            {
                                entitiesToUpdate.Add(skuCode.Value, shouldExsistInChannelNodes);
                            }
                        }
                    }

                    if (!DeleteUtilConfig.UseThreeLevelsInCommerce)
                    {
                        continue;
                    }
                }

                if (!entitiesToUpdate.ContainsKey(elementEntityId))
                {
                    entitiesToUpdate.Add(elementEntityId, shouldExsistInChannelNodes);
                }
            }

            List <string> parents = new List <string> {
                parentEnt.Id.ToString(CultureInfo.InvariantCulture)
            };

            if (parentEnt.EntityType.Id == "Item")
            {
                if (DeleteUtilConfig.ItemsToSkus)
                {
                    parents = _epiElement.SkuItemIds(parentEnt, DeleteUtilConfig);

                    if (DeleteUtilConfig.UseThreeLevelsInCommerce)
                    {
                        parents.Add(parentEnt.Id.ToString(CultureInfo.InvariantCulture));
                    }
                }
            }

            XDocument updateXml = new XDocument(new XElement("xml", new XAttribute("action", "updated")));

            if (updateXml.Root != null)
            {
                List <XElement> parentElements = channelHelper.GetParentXElements(parentEnt, DeleteUtilConfig);
                foreach (var parentElement in parentElements)
                {
                    updateXml.Root.Add(parentElement);
                }
            }

            foreach (KeyValuePair <string, Dictionary <string, bool> > entityIdToUpdate in entitiesToUpdate)
            {
                foreach (string parentId in parents)
                {
                    _epiApi.UpdateEntryRelations(entityIdToUpdate.Key, channelEntity.Id, channelEntity, DeleteUtilConfig, parentId, entityIdToUpdate.Value, linkTypeId, linkEntityIds);
                }

                updateXml.Root?.Add(new XElement("entry", _channelPrefixHelper.GetEPiCodeWithChannelPrefix(entityIdToUpdate.Key, DeleteUtilConfig)));
            }


            if (!DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Catalog, updateXml, DeleteUtilConfig, folderDateTime))
            {
                _context.Log(LogLevel.Information, "Failed to zip and upload the catalog file to azure from delete utility DeleteEntityThatStillExistInChannel() method");
            }

            _context.Log(LogLevel.Debug, "catalog saved");
        }
Esempio n. 17
0
        private void DeleteEntity(Entity channelEntity, int parentEntityId, Entity targetEntity, string linkTypeId, string channelIdentifier, string folderDateTime, List <int> productParentIds = null)
        {
            var channelHelper = new ChannelHelper(_context);

            XElement removedElement = new XElement(targetEntity.EntityType.Id + "_" + targetEntity.Id);

            List <XElement> deletedElements = new List <XElement>();


            deletedElements.Add(removedElement);

            XDocument deleteXml    = new XDocument(new XElement("xml", new XAttribute("action", "deleted")));
            Entity    parentEntity = _context.ExtensionManager.DataService.GetEntity(parentEntityId, LoadLevel.DataOnly);

            if (parentEntity != null && !DeleteUtilConfig.ChannelEntities.ContainsKey(parentEntity.Id))
            {
                DeleteUtilConfig.ChannelEntities.Add(parentEntity.Id, parentEntity);
            }

            List <XElement> parentElements = channelHelper.GetParentXElements(parentEntity, DeleteUtilConfig);

            foreach (var parentElement in parentElements)
            {
                deleteXml.Root?.Add(parentElement);
            }

            deletedElements = deletedElements.GroupBy(elem => elem.Name.LocalName).Select(grp => grp.First()).ToList();

            var resources = new Resources(_context);

            foreach (XElement deletedElement in deletedElements)
            {
                if (!deletedElement.Name.LocalName.Contains('_'))
                {
                    continue;
                }

                string deletedElementEntityType = deletedElement.Name.LocalName.Split('_')[0];
                int    deletedElementEntityId;
                int.TryParse(deletedElement.Name.LocalName.Split('_')[1], out deletedElementEntityId);

                if (deletedElementEntityType == "Link")
                {
                    continue;
                }

                List <string> deletedResources = new List <string>();

                switch (deletedElementEntityType)
                {
                case "Channel":
                    _epiApi.DeleteCatalog(deletedElementEntityId, DeleteUtilConfig);
                    deletedResources = channelHelper.GetResourceIds(deletedElement, DeleteUtilConfig);
                    break;

                case "ChannelNode":
                    _epiApi.DeleteCatalogNode(deletedElementEntityId, channelEntity.Id, DeleteUtilConfig);

                    deleteXml.Root?.Add(new XElement("entry", _channelPrefixHelper.GetEPiCodeWithChannelPrefix(deletedElementEntityId, DeleteUtilConfig)));

                    Entity channelNode = targetEntity.Id == deletedElementEntityId
                                                 ? targetEntity
                                                 : _context.ExtensionManager.DataService.GetEntity(
                        deletedElementEntityId,
                        LoadLevel.DataAndLinks);

                    if (channelNode == null)
                    {
                        break;
                    }

                    if (deletedElement.Elements().Any())
                    {
                        foreach (XElement linkElement in deletedElement.Elements())
                        {
                            foreach (XElement entityElement in linkElement.Elements())
                            {
                                string elementEntityId = entityElement.Name.LocalName.Split('_')[1];

                                Entity child = _context.ExtensionManager.DataService.GetEntity(int.Parse(elementEntityId), LoadLevel.DataAndLinks);
                                Delete(channelEntity, targetEntity.Id, child, linkTypeId);
                            }
                        }
                    }
                    else
                    {
                        foreach (Link link in targetEntity.OutboundLinks)
                        {
                            Entity child = _context.ExtensionManager.DataService.GetEntity(link.Target.Id, LoadLevel.DataAndLinks);

                            Delete(channelEntity, targetEntity.Id, child, link.LinkType.Id);
                        }
                    }

                    deletedResources = channelHelper.GetResourceIds(deletedElement, DeleteUtilConfig);
                    break;

                case "Item":
                    deletedResources = channelHelper.GetResourceIds(deletedElement, DeleteUtilConfig);
                    if ((DeleteUtilConfig.ItemsToSkus && DeleteUtilConfig.UseThreeLevelsInCommerce) || !DeleteUtilConfig.ItemsToSkus)
                    {
                        _epiApi.DeleteCatalogEntry(deletedElementEntityId.ToString(CultureInfo.InvariantCulture), DeleteUtilConfig);

                        deleteXml.Root?.Add(new XElement("entry", _channelPrefixHelper.GetEPiCodeWithChannelPrefix(deletedElementEntityId, DeleteUtilConfig)));
                    }

                    if (DeleteUtilConfig.ItemsToSkus)
                    {
                        // delete skus if exist
                        List <string> entitiesToDelete = new List <string>();

                        Entity deletedEntity = null;

                        try
                        {
                            deletedEntity = _context.ExtensionManager.DataService.GetEntity(
                                deletedElementEntityId,
                                LoadLevel.DataOnly);
                        }
                        catch (Exception ex)
                        {
                            _context.Log(LogLevel.Warning, "Error when getting entity:" + ex);
                        }

                        if (deletedEntity != null)
                        {
                            List <XElement> skus = _epiElement.GenerateSkuItemElemetsFromItem(deletedEntity, DeleteUtilConfig);

                            foreach (XElement sku in skus)
                            {
                                XElement skuCodElement = sku.Element("Code");
                                if (skuCodElement != null)
                                {
                                    entitiesToDelete.Add(skuCodElement.Value);
                                }
                            }
                        }

                        foreach (string entityIdToDelete in entitiesToDelete)
                        {
                            _epiApi.DeleteCatalogEntry(entityIdToDelete, DeleteUtilConfig);

                            deleteXml.Root?.Add(new XElement("entry", _channelPrefixHelper.GetEPiCodeWithChannelPrefix(entityIdToDelete, DeleteUtilConfig)));
                        }
                    }

                    break;

                case "Resource":
                    deletedResources = new List <string> {
                        _channelPrefixHelper.GetEPiCodeWithChannelPrefix(deletedElementEntityId, DeleteUtilConfig)
                    };
                    break;

                case "Product":
                    _epiApi.DeleteCatalogEntry(deletedElementEntityId.ToString(CultureInfo.InvariantCulture), DeleteUtilConfig);
                    deletedResources = channelHelper.GetResourceIds(deletedElement, DeleteUtilConfig);

                    deleteXml.Root?.Add(new XElement("entry", _channelPrefixHelper.GetEPiCodeWithChannelPrefix(deletedElementEntityId, DeleteUtilConfig)));

                    Entity delEntity = _context.ExtensionManager.DataService.GetEntity(
                        deletedElementEntityId,
                        LoadLevel.DataAndLinks);

                    if (delEntity == null)
                    {
                        break;
                    }

                    foreach (Link link in delEntity.OutboundLinks)
                    {
                        if (link.Target.EntityType.Id == "Product")
                        {
                            if (productParentIds != null && productParentIds.Contains(link.Target.Id))
                            {
                                _context.Log(LogLevel.Information, string.Format("Entity with id {0} has already been deleted, break the chain to avoid circular relations behaviors (deadlocks)", link.Target.Id));
                                continue;
                            }

                            if (productParentIds == null)
                            {
                                productParentIds = new List <int>();
                            }

                            productParentIds.Add(delEntity.Id);
                        }

                        Entity child = _context.ExtensionManager.DataService.GetEntity(link.Target.Id, LoadLevel.DataAndLinks);

                        Delete(channelEntity, delEntity.Id, child, link.LinkType.Id, productParentIds);
                    }

                    break;

                default:

                    _epiApi.DeleteCatalogEntry(deletedElementEntityId.ToString(CultureInfo.InvariantCulture), DeleteUtilConfig);
                    deletedResources = channelHelper.GetResourceIds(deletedElement, DeleteUtilConfig);

                    deleteXml.Root?.Add(new XElement("entry", _channelPrefixHelper.GetEPiCodeWithChannelPrefix(deletedElementEntityId, DeleteUtilConfig)));

                    Entity prodEntity;
                    if (targetEntity.Id == deletedElementEntityId)
                    {
                        prodEntity = targetEntity;
                    }
                    else
                    {
                        prodEntity = _context.ExtensionManager.DataService.GetEntity(
                            deletedElementEntityId,
                            LoadLevel.DataAndLinks);
                    }

                    if (prodEntity == null)
                    {
                        break;
                    }

                    foreach (Link link in prodEntity.OutboundLinks)
                    {
                        if (link.Target.EntityType.Id == "Product")
                        {
                            if (productParentIds != null && productParentIds.Contains(link.Target.Id))
                            {
                                _context.Log(LogLevel.Information, string.Format("Entity with id {0} has already been deleted, break the chain to avoid circular relations behaviors (deadlocks)", link.Target.Id));
                                continue;
                            }

                            if (productParentIds == null)
                            {
                                productParentIds = new List <int>();
                            }

                            productParentIds.Add(prodEntity.Id);
                        }

                        Entity child = _context.ExtensionManager.DataService.GetEntity(link.Target.Id, LoadLevel.DataAndLinks);

                        Delete(channelEntity, parentEntityId, child, link.LinkType.Id);
                    }

                    break;
                }

                foreach (string resourceId in deletedResources)
                {
                    string resourceIdWithoutPrefix = resourceId.Substring(DeleteUtilConfig.ChannelIdPrefix.Length);

                    int resourceIdAsInt;

                    if (Int32.TryParse(resourceIdWithoutPrefix, out resourceIdAsInt))
                    {
                        if (_context.ExtensionManager.ChannelService.EntityExistsInChannel(channelEntity.Id, resourceIdAsInt))
                        {
                            deletedResources.Remove(resourceId);
                        }
                    }
                }

                if (deletedResources != null && deletedResources.Count != 0)
                {
                    XDocument resDoc          = resources.HandleResourceDelete(deletedResources);
                    string    folderDateTime2 = DateTime.Now.ToString("yyyyMMdd-HHmmss.fff");

                    string zipFileDelete = string.Format(
                        "resource_{0}{1}.zip",
                        folderDateTime2,
                        deletedElementEntityId);

                    DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Resources, resDoc, DeleteUtilConfig, folderDateTime2);
                    string zipDeleteFileNameInCloud = DeleteUtilConfig.ResourceNameInCloud;

                    foreach (string resourceIdString in deletedResources)
                    {
                        int    resourceId               = int.Parse(resourceIdString);
                        bool   sendUnlinkResource       = false;
                        string zipFileUnlink            = string.Empty;
                        string zipUnlinkFileNameInCloud = string.Empty;

                        Entity resource = _context.ExtensionManager.DataService.GetEntity(resourceId, LoadLevel.DataOnly);
                        if (resource != null)
                        {
                            // Only do this when removing an link (unlink)
                            Entity parentEnt = _context.ExtensionManager.DataService.GetEntity(parentEntityId, LoadLevel.DataOnly);
                            var    unlinkDoc = resources.HandleResourceUnlink(resource, parentEnt, DeleteUtilConfig);

                            zipFileUnlink = string.Format("resource_{0}{1}.zip", folderDateTime, deletedElementEntityId);
                            DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Resources, unlinkDoc, DeleteUtilConfig, folderDateTime);
                            zipUnlinkFileNameInCloud = DeleteUtilConfig.ResourceNameInCloud;
                        }

                        _context.Log(LogLevel.Debug, "Resources saved!");

                        if (DeleteUtilConfig.ActivePublicationMode.Equals(PublicationMode.Automatic))
                        {
                            _context.Log(LogLevel.Debug, "Starting automatic import!");

                            if (sendUnlinkResource && _epiApi.StartAssetImportIntoEpiServerCommerce(
                                    zipUnlinkFileNameInCloud /*Path.Combine(this.DeleteUtilConfig.ResourcesRootPath, folderDateTime, "Resources.xml")*/,
                                    Path.Combine(DeleteUtilConfig.ResourcesRootPath, folderDateTime),
                                    DeleteUtilConfig))
                            {
                                _epiApi.SendHttpPost(DeleteUtilConfig, Path.Combine(DeleteUtilConfig.ResourcesRootPath, folderDateTime, zipFileUnlink));
                            }

                            if (_epiApi.StartAssetImportIntoEpiServerCommerce(
                                    zipDeleteFileNameInCloud /*Path.Combine(this.DeleteUtilConfig.ResourcesRootPath, folderDateTime2, "Resources.xml")*/,
                                    Path.Combine(DeleteUtilConfig.ResourcesRootPath, folderDateTime2),
                                    DeleteUtilConfig))
                            {
                                _epiApi.SendHttpPost(DeleteUtilConfig, Path.Combine(DeleteUtilConfig.ResourcesRootPath, folderDateTime2, zipFileDelete));
                            }
                        }
                    }
                }
            }

            if (deleteXml.Root != null && deleteXml.Root.Elements().FirstOrDefault(e => e.Name.LocalName == "entry") != null)
            {
                if (!DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Catalog, deleteXml, DeleteUtilConfig, folderDateTime))
                {
                    _context.Log(LogLevel.Information, "Failed to zip and upload the catalog file to azure from delete utility DeleteEntity() method");
                }

                _context.Log(LogLevel.Debug, "catalog saved");
            }
        }
Esempio n. 18
0
        internal void Add(Entity channelEntity, ConnectorEvent connectorEvent, out bool resourceIncluded)
        {
            resourceIncluded = false;

            var channelHelper        = new ChannelHelper(_context);
            var epiApi               = new EpiApi(_context);
            var connectorEventHelper = new ConnectorEventHelper(_context);


            connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Generating catalog.xml...", 11);
            Dictionary <string, List <XElement> > epiElements = _epiDocument.GetEPiElements(ConnectorConfig);

            XDocument doc = _epiDocument.CreateImportDocument(
                channelEntity,
                null,
                null,
                epiElements,
                ConnectorConfig);

            string folderDateTime = DateTime.Now.ToString("yyyyMMdd-HHmmss.fff");

            if (!DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Catalog, doc, ConnectorConfig, folderDateTime))
            {
                _context.Log(LogLevel.Information, "Failed to zip and upload the catalog file to azure from add utility Add() method");
            }

            _context.Log(LogLevel.Information, "Catalog saved with the following:");
            _context.Log(LogLevel.Information, string.Format("Nodes: {0}", epiElements["Nodes"].Count));
            _context.Log(LogLevel.Information, string.Format("Entries: {0}", epiElements["Entries"].Count));
            _context.Log(LogLevel.Information, string.Format("Relations: {0}", epiElements["Relations"].Count));
            _context.Log(LogLevel.Information, string.Format("Associations: {0}", epiElements["Associations"].Count));
            connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Done generating catalog.xml", 25);

            connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Generating Resource.xml and saving files to disk...", 26);

            Resources resourceHelper = new Resources(_context);

            XDocument resourceDocument = resourceHelper.GetResourcesDocument(ConnectorConfig.ChannelStructureEntities, ConnectorConfig);

            // Add all files included in resource document
            Dictionary <string, byte[]> files = new Dictionary <string, byte[]>();

            IEnumerable <XElement> resourceFileElements = resourceDocument.Document.Element("Resources")?.Element("ResourceFiles")?.Elements("Resource");

            if (resourceFileElements != null && resourceFileElements.Any())
            {
                _context.Log(LogLevel.Information, $"Adding {resourceFileElements.Count()} resource files to zip archive.");
                foreach (XElement resourceFileElement in resourceFileElements)
                {
                    int resourceEntityId;
                    if (int.TryParse(resourceFileElement.Attribute("id").Value, out resourceEntityId))
                    {
                        Entity targetEntity = _context.ExtensionManager.DataService.GetEntity(resourceEntityId, LoadLevel.DataOnly);

                        _context.Log(LogLevel.Debug, $"Adding image file {targetEntity.DisplayName}({targetEntity.Id})");
                        int resourceFileId = resourceHelper.GetResourceFileId(targetEntity);

                        foreach (string displayConfig in resourceHelper.GetDisplayConfigurations(targetEntity, ConnectorConfig))
                        {
                            string fileName = resourceHelper.GetResourceFileName(targetEntity, resourceFileId, displayConfig, ConnectorConfig);

                            byte[] resourceData = _context.ExtensionManager.UtilityService.GetFile(resourceFileId, displayConfig);

                            if (resourceData != null)
                            {
                                files.Add($"{displayConfig}/{fileName}", resourceData);
                            }
                        }
                    }
                }
            }
            else
            {
                string elementCount = resourceFileElements == null ? "null" : resourceFileElements.Count().ToString();
                _context.Log(LogLevel.Information, $"No files linked to resource document. Document contains {elementCount} elements");
            }


            DocumentFileHelper.ZipDocumentAndUploadToAzure(XmlDocumentType.Resources, resourceDocument, ConnectorConfig, folderDateTime, files);

            connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Done generating/saving Resource.xml", 50);

            if (ConnectorConfig.ActivePublicationMode.Equals(PublicationMode.Automatic))
            {
                _context.Log(LogLevel.Debug, "Starting automatic import!");
                connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Sending Catalog.xml to EPiServer...", 51);
                if (epiApi.StartImportIntoEpiServerCommerce(ConnectorConfig.CatalogPathInCloud, channelHelper.GetChannelGuid(channelEntity, ConnectorConfig), ConnectorConfig))
                {
                    connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Done sending Catalog.xml to EPiServer", 75);
                }
                else
                {
                    connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Error while sending Catalog.xml to EPiServer", -1, true);

                    return;
                }

                connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Sending Resources to EPiServer...", 76);
                if (epiApi.StartAssetImportIntoEpiServerCommerce(ConnectorConfig.ResourceNameInCloud, Path.Combine(ConnectorConfig.ResourcesRootPath, folderDateTime), ConnectorConfig))
                {
                    connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Done sending Resources to EPiServer...", 99);
                    resourceIncluded = true;
                }
                else
                {
                    connectorEventHelper.UpdateConnectorEvent(connectorEvent, "Error while sending resources to EPiServer", -1, true);
                }
            }
        }