예제 #1
0
 internal static void CleanupOngoingEvents(IConfiguration configuration)
 {
     try
     {
         List <ConnectorEventSession> sessions = RemoteManager.ChannelService.GetOngoingConnectorEventSessions(configuration.ChannelId, configuration.Id);
         foreach (ConnectorEventSession connectorEventSession in sessions)
         {
             ConnectorEvent latestConnectorEvent = connectorEventSession.ConnectorEvents.First();
             var            connectorEvent       = new ConnectorEvent
             {
                 SessionId          = latestConnectorEvent.SessionId,
                 ChannelId          = latestConnectorEvent.ChannelId,
                 ConnectorId        = latestConnectorEvent.ConnectorId,
                 ConnectorEventType = latestConnectorEvent.ConnectorEventType,
                 Percentage         = latestConnectorEvent.Percentage,
                 IsError            = true,
                 Message            = "Event stopped due to closedown of connector",
                 EventTime          = DateTime.Now
             };
             ReportManager.Instance.WriteEvent(connectorEvent);
         }
     }
     catch (Exception e)
     {
         IntegrationLogger.Write(LogLevel.Error, e.Message);
     }
 }
        private void PubilshToEpiserver(ConnectorEvent connectorEvent,
                                        XDocument catalogDocument,
                                        List <StructureEntity> structureEntitiesToGetResourcesFor,
                                        Entity channelEntity)
        {
            ConnectorEventHelper.UpdateEvent(connectorEvent, "Done generating catalog.xml. Generating Resource.xml and saving files to disk...", 26);

            string folderNameTimestampComponent = DateTime.Now.ToString(Constants.PublicationFolderNameTimeComponent);

            string    resourcesBasePath    = Path.Combine(_config.ResourcesRootPath, folderNameTimestampComponent);
            XDocument resourceDocument     = _resourceElementFactory.GetResourcesNodeForChannelEntities(structureEntitiesToGetResourcesFor, resourcesBasePath);
            string    resourceDocumentPath = _documentFileHelper.SaveDocument(resourceDocument, resourcesBasePath);

            string savedCatalogDocument = _documentFileHelper.SaveCatalogDocument(channelEntity, catalogDocument, folderNameTimestampComponent);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Done generating/saving Resource.xml, sending Catalog.xml to EPiServer...", 50);

            _epiApi.ImportCatalog(savedCatalogDocument);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Done sending Catalog.xml to EPiServer", 75);

            _epiApi.NotifyEpiserverPostImport(savedCatalogDocument);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Sending Resources to EPiServer...", 76);

            _epiApi.ImportResources(resourceDocumentPath, resourcesBasePath);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Done sending Resources to EPiServer...", 99);

            _epiApi.NotifyEpiserverPostImport(resourceDocumentPath);
            string channelName = _mappingHelper.GetNameForEntity(channelEntity, 100);

            _epiApi.ImportUpdateCompleted(channelName, ImportUpdateCompletedEventType.Publish, true);
        }
예제 #3
0
        public async Task <ConnectorEvent> CVLValueUpdatedAsync(Entity channel, string cvlId, string cvlValueKey)
        {
            ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config,
                                                                               ConnectorEventType.CVLValueUpdated,
                                                                               $"CVL value updated, updating values in channel: {channel.DisplayName.Data}", 0);

            IEnumerable <FieldType> cvlFieldTypes = RemoteManager.ModelService.GetAllFieldTypes().Where(x => x.CVLId == cvlId);

            List <Criteria> criteria = cvlFieldTypes.Select(cvlFieldType => new Criteria
            {
                FieldTypeId = cvlFieldType.Id,
                Value       = cvlValueKey,
                Operator    = Operator.Equal
            }).ToList();

            var query = new Query {
                Criteria = criteria, Join = Join.Or
            };
            List <Entity> entities = RemoteManager.DataService.Search(query, LoadLevel.DataOnly);

            IntegrationLogger.Write(LogLevel.Debug, $"Found {entities.Count} entities with the CVL {cvlId} to update. Value-key to update: {cvlValueKey}.");

            XDocument updateDocument = _catalogDocumentFactory.CreateUpdateDocument(channel, entities);
            string    folderDateTime = DateTime.Now.ToString(Constants.PublicationFolderNameTimeComponent);

            string savedCatalogDocument = _documentFileHelper.SaveCatalogDocument(channel, updateDocument, folderDateTime);

            await _epiApi.ImportCatalogAsync(savedCatalogDocument);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Done sending Catalog.xml to EPiServer", 75);

            await _epiApi.NotifyEpiserverPostImportAsync(Path.Combine(_config.PublicationsRootPath, folderDateTime, savedCatalogDocument));

            return(connectorEvent);
        }
예제 #4
0
        public async Task <ConnectorEvent> PublishAsync(Entity channel)
        {
            ConnectorEvent publishEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.Publish, $"Publish started for channel: {channel.DisplayName.Data}", 0);

            ConnectorEventHelper.UpdateEvent(publishEvent, "Fetching all channel entities...", 1);

            List <StructureEntity> channelStructureEntities = _entityService.GetAllStructureEntitiesInChannel(_config.ExportEnabledEntityTypes);

            ConnectorEventHelper.UpdateEvent(publishEvent, "Fetched all channel entities. Generating catalog.xml...", 10);

            CatalogElementContainer epiElements = await _catalogDocumentFactory.GetEPiElementsAsync(channelStructureEntities);

            XElement metaClasses      = _catalogElementFactory.GetMetaClassesFromFieldSets();
            XElement associationTypes = _catalogDocumentFactory.GetAssociationTypes();

            XDocument catalogDocument = _catalogDocumentFactory.CreateImportDocument(channel, metaClasses, associationTypes, epiElements);

            LogCatalogProperties(epiElements);

            List <StructureEntity> resourceEntities = RemoteManager.ChannelService.GetAllChannelStructureEntitiesForTypeFromPath(channel.Id.ToString(), "Resource");

            await PublishToEpiserverAsync(publishEvent, catalogDocument, resourceEntities, channel);

            return(publishEvent);
        }
        public ConnectorEvent ChannelEntityAdded(Entity channel, int entityId)
        {
            ConnectorEvent connectorEvent =
                ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.ChannelEntityAdded, $"Received entity added for entity {entityId} in channel {channel.DisplayName}", 0);

            var structureEntities = new List <StructureEntity>();
            List <StructureEntity> addedStructureEntities = _entityService.GetStructureEntitiesForEntityInChannel(_config.ChannelId, entityId);

            foreach (StructureEntity addedEntity in addedStructureEntities)
            {
                StructureEntity parentEntity = _entityService.GetParentStructureEntity(_config.ChannelId, addedEntity.ParentId, addedEntity.EntityId, addedStructureEntities);
                structureEntities.Add(parentEntity);
            }

            structureEntities.AddRange(addedStructureEntities);

            string targetEntityPath           = _entityService.GetTargetEntityPath(entityId, addedStructureEntities);
            List <StructureEntity> childLinks = _entityService.GetChildrenEntitiesInChannel(entityId, targetEntityPath);

            foreach (StructureEntity linkStructureEntity in childLinks)
            {
                List <StructureEntity> childLinkedEntities = _entityService.GetChildrenEntitiesInChannel(linkStructureEntity.EntityId, linkStructureEntity.Path);
                structureEntities.AddRange(childLinkedEntities);
            }

            structureEntities.AddRange(childLinks);

            PublishEntities(channel, connectorEvent, structureEntities);

            string channelName = _mappingHelper.GetNameForEntity(channel, 100);

            _epiApi.ImportUpdateCompleted(channelName, ImportUpdateCompletedEventType.EntityAdded, true);
            return(connectorEvent);
        }
        private void DoWithInitCheck(int channelId, ConnectorEventType eventType, Func <Entity, ConnectorEvent> thingsToDo)
        {
            if (channelId != _config.ChannelId)
            {
                return;
            }

            Entity channelEntity = _channelHelper.InitiateChannelConfiguration(channelId);

            if (channelEntity == null)
            {
                ConnectorEventHelper.InitiateEvent(_config, eventType, $"Failed perform {eventType}. Could not find the channel.", -1, true);
                return;
            }

            try
            {
                ConnectorEvent connectorEvent = thingsToDo(channelEntity);

                _entityService.FlushCache();
                _resourceElementFactory.FlushCache();

                string message = $"{eventType} done for channel {channelEntity.Id} ({channelEntity.DisplayName.Data})";

                ConnectorEventHelper.UpdateEvent(connectorEvent, message, 100);
            }
            catch (Exception ex)
            {
                IntegrationLogger.Write(LogLevel.Error, "Exception in ChannelEntityAdded", ex);
                ConnectorEventHelper.InitiateEvent(_config, eventType, ex.Message, -1, true);

                _entityService.FlushCache();
                _resourceElementFactory.FlushCache();
            }
        }
        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;
            }
        }
        internal void PublishEntities(Entity channel, ConnectorEvent connectorEvent, List <StructureEntity> structureEntities)
        {
            ConnectorEventHelper.UpdateEvent(connectorEvent, "Generating catalog.xml...", 11);
            CatalogElementContainer epiElements = _catalogDocumentFactory.GetEPiElements(structureEntities);

            XDocument catalogDocument = _catalogDocumentFactory.CreateImportDocument(channel, null, null, epiElements);

            LogCatalogProperties(epiElements);

            PubilshToEpiserver(connectorEvent, catalogDocument, structureEntities, channel);
        }
예제 #9
0
        public async Task <ConnectorEvent> ChannelEntityUpdatedAsync(Entity channel, int entityId, string data)
        {
            ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.ChannelEntityUpdated,
                                                                               $"Received entity update for entity {entityId} in channel {channel.DisplayName}", 0);


            Entity updatedEntity = _entityService.GetEntity(entityId, LoadLevel.DataAndLinks);

            if (updatedEntity.EntityType.IsLinkEntityType)
            {
                return(connectorEvent);
            }

            string folderDateTime   = DateTime.Now.ToString(Constants.PublicationFolderNameTimeComponent);
            bool   resourceIncluded = false;
            List <StructureEntity> structureEntities = _entityService.GetStructureEntitiesForEntityInChannel(_config.ChannelId, entityId);

            if (updatedEntity.EntityType.Id.Equals("Resource"))
            {
                resourceIncluded = await HandleResourceUpdateAsync(updatedEntity, folderDateTime);
            }
            else
            {
                IntegrationLogger.Write(LogLevel.Debug, $"Updated entity found. Type: {updatedEntity.EntityType.Id}, id: {updatedEntity.Id}");

                if (updatedEntity.EntityType.Id.Equals("Item") && data != null && data.Split(',').Contains("SKUs"))
                {
                    resourceIncluded = await HandleSkuUpdateAsync(entityId, channel, connectorEvent, structureEntities);
                }
                else if (updatedEntity.EntityType.Id.Equals("ChannelNode"))
                {
                    await HandleChannelNodeUpdateAsync(channel, structureEntities, connectorEvent);

                    return(connectorEvent);
                }

                XDocument doc = _catalogDocumentFactory.CreateUpdateDocument(channel, updatedEntity);

                string catalogDocumentName = _documentFileHelper.SaveCatalogDocument(channel, doc, folderDateTime);

                IntegrationLogger.Write(LogLevel.Debug, "Starting automatic import!");

                await _epiApi.ImportCatalogAsync(catalogDocumentName);

                await _epiApi.NotifyEpiserverPostImportAsync(catalogDocumentName);
            }

            string channelName = _mappingHelper.GetNameForEntity(channel, 100);
            await _epiApi.ImportUpdateCompletedAsync(channelName, ImportUpdateCompletedEventType.EntityUpdated, resourceIncluded);

            return(connectorEvent);
        }
        public void ChannelEntityUpdated(int channelId, int entityId, string data)
        {
            DoWithInitCheck(channelId, ConnectorEventType.ChannelEntityUpdated, channel =>
            {
                if (channel.Id == entityId)
                {
                    ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.ChannelEntityUpdated, "Updated Entity is the Channel, no action required", 100);
                    return(connectorEvent);
                }

                return(AsyncHelper.RunSync(() => _publisher.ChannelEntityUpdatedAsync(channel, entityId, data)));
            });
        }
        public ConnectorEvent ChannelEntityDeleted(Entity channel, Entity deletedEntity)
        {
            string         channelName    = _mappingHelper.GetNameForEntity(channel, 100);
            ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config,
                                                                               ConnectorEventType.ChannelEntityDeleted,
                                                                               $"Received entity deleted for entity {deletedEntity.Id} in channel {channelName}.", 0);

            Delete(channel, deletedEntity);

            _epiApi.DeleteCompleted(channelName, DeleteCompletedEventType.EntitiyDeleted);

            return(connectorEvent);
        }
        public ConnectorEvent ChannelLinkAdded(Entity channel, int sourceEntityId, int targetEntityId, string linkTypeId, int?linkEntityId)
        {
            ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.ChannelLinkAdded,
                                                                               $"Received link added for sourceEntityId {sourceEntityId} and targetEntityId {targetEntityId} in channel {channel.DisplayName}", 0);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Fetching channel entities...", 1);

            List <StructureEntity> existingEntitiesInChannel = _entityService.GetStructureEntitiesForEntityInChannel(_config.ChannelId, targetEntityId);

            var structureEntities = new List <StructureEntity>();

            foreach (StructureEntity existingEntity in existingEntitiesInChannel)
            {
                List <string> parentIds = existingEntity.Path.Split('/').ToList();
                parentIds.Reverse();
                parentIds.RemoveAt(0);

                for (var i = 0; i < parentIds.Count - 1; i++)
                {
                    int entityId = int.Parse(parentIds[i]);
                    int parentId = int.Parse(parentIds[i + 1]);

                    structureEntities.AddRange(RemoteManager.ChannelService.GetAllStructureEntitiesForEntityWithParentInChannel(channel.Id, entityId, parentId));
                }
            }

            foreach (StructureEntity existingEntity in existingEntitiesInChannel)
            {
                string targetEntityPath = _entityService.GetTargetEntityPath(existingEntity.EntityId, existingEntitiesInChannel, existingEntity.ParentId);
                structureEntities.AddRange(RemoteManager.ChannelService.GetAllChannelStructureEntitiesFromPath(targetEntityPath));
            }



            // Remove duplicates
            structureEntities = structureEntities.GroupBy(x => x.EntityId).Select(x => x.First()).ToList();

            //Adding existing Entities. If it occurs more than one time in channel. We can not remove duplicates.
            structureEntities.AddRange(existingEntitiesInChannel);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Done fetching channel entities", 10);

            PublishEntities(channel, connectorEvent, structureEntities);

            string channelName = _mappingHelper.GetNameForEntity(channel, 100);

            _epiApi.ImportUpdateCompleted(channelName, ImportUpdateCompletedEventType.LinkAdded, true);

            return(connectorEvent);
        }
예제 #13
0
        internal ConnectorEvent UpdateConnectorEvent(ConnectorEvent connectorEvent, string message, int percentage, bool error = false)
        {
            if (percentage >= 0)
            {
                connectorEvent.Percentage = percentage;
            }

            connectorEvent.Message   = message;
            connectorEvent.IsError   = error;
            connectorEvent.EventTime = DateTime.Now;

            _context.Log(LogLevel.Information, connectorEvent.Message);

            return(connectorEvent);
        }
예제 #14
0
        internal static ConnectorEvent UpdateEvent(ConnectorEvent connectorEvent, string message, int percentage, bool error = false)
        {
            IntegrationLogger.Write(LogLevel.Debug, message);

            if (percentage >= 0)
            {
                connectorEvent.Percentage = percentage;
            }

            connectorEvent.Message   = message;
            connectorEvent.IsError   = error;
            connectorEvent.EventTime = DateTime.Now;
            ReportManager.Instance.WriteEvent(connectorEvent);
            return(connectorEvent);
        }
        private void HandleSkuUpdate(int entityId,
                                     Entity channelEntity,
                                     ConnectorEvent connectorEvent,
                                     List <StructureEntity> structureEntities,
                                     out bool resourceIncluded)
        {
            resourceIncluded = false;
            Field currentField = RemoteManager.DataService.GetField(entityId, "SKUs");

            List <Field> fieldHistory = RemoteManager.DataService.GetFieldHistory(entityId, "SKUs");

            Field previousField = fieldHistory.FirstOrDefault(f => f.Revision == currentField.Revision - 1);

            string oldXml = string.Empty;

            if (previousField != null && previousField.Data != null)
            {
                oldXml = (string)previousField.Data;
            }

            string newXml = string.Empty;

            if (currentField.Data != null)
            {
                newXml = (string)currentField.Data;
            }

            List <XElement> skusToDelete, skusToAdd;

            PimFieldAdapter.CompareAndParseSkuXmls(oldXml, newXml, out skusToAdd, out skusToDelete);

            foreach (XElement skuToDelete in skusToDelete)
            {
                string skuId = skuToDelete.Attribute("id").Value;
                _epiApi.DeleteSku(skuId);
            }

            if (skusToAdd.Count > 0)
            {
                PublishEntities(channelEntity, connectorEvent, structureEntities);
                resourceIncluded = true;
            }
        }
예제 #16
0
        public async Task <ConnectorEvent> ChannelLinkUpdatedAsync(Entity channel, int sourceEntityId, int targetEntityId, string linkTypeId, int?linkEntityId)
        {
            List <StructureEntity> targetEntityStructure = _entityService.GetEntityInChannelWithParent(_config.ChannelId, targetEntityId, sourceEntityId);

            StructureEntity parentStructureEntity = _entityService.GetParentStructureEntity(_config.ChannelId, sourceEntityId, targetEntityId, targetEntityStructure);

            string channelName = _mappingHelper.GetNameForEntity(channel, 100);

            if (parentStructureEntity == null)
            {
                ConnectorEvent deleteEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.ChannelLinkDeleted,
                                                                                $"Received link deleted for sourceEntityId {sourceEntityId} and targetEntityId {targetEntityId} in channel {channel.DisplayName.Data}", 0);
                Entity removalTarget = _entityService.GetEntity(targetEntityId, LoadLevel.DataAndLinks);
                Entity removalSource = _entityService.GetEntity(sourceEntityId, LoadLevel.DataAndLinks);
                await DeleteLinkAsync(removalSource, removalTarget, linkTypeId, true);

                await _epiApi.DeleteCompletedAsync(channelName, DeleteCompletedEventType.LinkDeleted);

                return(deleteEvent);
            }

            ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.ChannelLinkAdded,
                                                                               $"Received link update for sourceEntityId {sourceEntityId} and targetEntityId {targetEntityId} in channel {channel.DisplayName}.", 0);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Fetching channel entities...", 1);

            var structureEntities = new List <StructureEntity>
            {
                parentStructureEntity
            };

            List <StructureEntity> entities = _entityService.GetChildrenEntitiesInChannel(parentStructureEntity.EntityId, parentStructureEntity.Path);

            structureEntities.AddRange(entities);

            ConnectorEventHelper.UpdateEvent(connectorEvent, "Done fetching channel entities", 10);

            await PublishEntitiesAsync(channel, connectorEvent, structureEntities);

            await _epiApi.ImportUpdateCompletedAsync(channelName, ImportUpdateCompletedEventType.LinkUpdated, true);

            return(connectorEvent);
        }
예제 #17
0
        internal ConnectorEvent InitiateConnectorEvent(ConnectorEventType messageType, string message, int percentage, bool error = false)
        {
            string channelId;

            _context.Settings.TryGetValue("CHANNEL_ID", out channelId);
            ConnectorEvent connectorEvent = new ConnectorEvent
            {
                ChannelId          = int.Parse(channelId ?? "0"),
                ConnectorEventType = messageType,
                ConnectorId        = _context.ExtensionId,
                EventTime          = DateTime.Now,
                SessionId          = Guid.NewGuid(),
                Percentage         = percentage,
                IsError            = error,
                Message            = message
            };

            _context.Log(LogLevel.Information, connectorEvent.Message);
            return(connectorEvent);
        }
        public new void Stop()
        {
            base.Stop();
            ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.Stop, "Connector is stopping", 0);

            IsStarted = 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);
        }
예제 #19
0
        public async Task <ConnectorEvent> ChannelLinkDeletedAsync(Entity channel, int sourceEntityId, int targetEntityId, string linkTypeId, int?linkEntityId)
        {
            ConnectorEvent connectorEvent = ConnectorEventHelper.InitiateEvent(_config, ConnectorEventType.ChannelLinkDeleted,
                                                                               $"Received link deleted for sourceEntityId {sourceEntityId} and targetEntityId {targetEntityId} in channel {channel.DisplayName.Data}", 0);

            Entity removalTarget = _entityService.GetEntity(targetEntityId, LoadLevel.DataAndLinks);
            Entity removalSource = _entityService.GetEntity(sourceEntityId, LoadLevel.DataAndLinks);

            if (removalTarget.EntityType.Id == "Resource")
            {
                await DeleteResourceLinkAsync(removalTarget, removalSource);
            }
            else
            {
                await DeleteLinkAsync(removalSource, removalTarget, linkTypeId);
            }

            string channelName = _mappingHelper.GetNameForEntity(channel, 100);
            await _epiApi.DeleteCompletedAsync(channelName, DeleteCompletedEventType.LinkDeleted);

            return(connectorEvent);
        }
예제 #20
0
        internal static ConnectorEvent InitiateEvent(IConfiguration config, ConnectorEventType messageType, string message, int percentage, bool error = false)
        {
            if (!error)
            {
                IntegrationLogger.Write(LogLevel.Debug, message);
            }

            ConnectorEvent connectorEvent = new ConnectorEvent
            {
                ChannelId          = config.ChannelId,
                ConnectorEventType = messageType,
                ConnectorId        = config.Id,
                EventTime          = DateTime.Now,
                SessionId          = Guid.NewGuid(),
                Percentage         = percentage,
                IsError            = error,
                Message            = message
            };

            ReportManager.Instance.WriteEvent(connectorEvent);
            return(connectorEvent);
        }
예제 #21
0
        internal void CleanupOngoingConnectorEvents(Configuration configuration)
        {
            List <ConnectorEventSession> sessions = _context.ExtensionManager.ChannelService.GetOngoingConnectorEventSessions(null, configuration.Id);

            foreach (ConnectorEventSession connectorEventSession in sessions)
            {
                ConnectorEvent latestConnectorEvent = connectorEventSession.ConnectorEvents.First();
                ConnectorEvent connectorEvent       = new ConnectorEvent
                {
                    SessionId          = latestConnectorEvent.SessionId,
                    ChannelId          = latestConnectorEvent.ChannelId,
                    ConnectorId        = latestConnectorEvent.ConnectorId,
                    ConnectorEventType = latestConnectorEvent.ConnectorEventType,
                    Percentage         = latestConnectorEvent.Percentage,
                    IsError            = true,
                    Message            = "Event stopped due to closedown of connector",
                    EventTime          = DateTime.Now
                };

                _context.Log(LogLevel.Information, connectorEvent.Message);
            }
        }
예제 #22
0
        private async Task HandleChannelNodeUpdateAsync(Entity channel, List <StructureEntity> structureEntities, ConnectorEvent entityUpdatedConnectorEvent)
        {
            await PublishEntitiesAsync(channel, entityUpdatedConnectorEvent, structureEntities);

            await _epiApi.ImportUpdateCompletedAsync(_pimFieldAdapter.GetDisplayName(channel, 100), ImportUpdateCompletedEventType.EntityUpdated, true);
        }
 private void HandleChannelNodeUpdate(Entity channel, List <StructureEntity> structureEntities, ConnectorEvent entityUpdatedConnectorEvent)
 {
     PublishEntities(channel, entityUpdatedConnectorEvent, structureEntities);
     _epiApi.ImportUpdateCompleted(_pimFieldAdapter.GetDisplayName(channel, 100), ImportUpdateCompletedEventType.EntityUpdated, true);
 }
예제 #24
0
 public bool WriteConnectorEvent(ConnectorEvent connectorEvent)
 {
     throw new NotImplementedException();
 }
예제 #25
0
        private void HandleConnectorEvent(ConnectorEvent evt)
        {
            ConnectorParameter ctxParameter;

            if (connectorTable != null && connectorTable.TryGetValue(evt.ctx, out ctxParameter))
            {
                switch (evt.eventID)
                {
                case EConnectorEvent.ON_CONNECT_SUCCEEDED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnConnected(evt.ctx);
                    }
                    break;

                case EConnectorEvent.ON_CONNECT_FAILED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnConnectFailed(evt.ctx, (string)evt.extraParam);
                    }
                    break;

                case EConnectorEvent.ON_DISCONNECT_SUCCEEDED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnDisconnected(evt.ctx);
                    }
                    break;

                case EConnectorEvent.ON_DISCONNECT_FAILED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnDisconnectFailed(evt.ctx, (string)evt.extraParam);
                    }
                    break;

                case EConnectorEvent.ON_CONNECTION_LOST:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnConnectionLost(evt.ctx);
                    }
                    break;

                case EConnectorEvent.ON_RECONNECT_SUCCEEDED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnReconnected(evt.ctx);
                    }
                    break;

                case EConnectorEvent.ON_RECONNECT_FAILED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnReconnectFailed(evt.ctx, (string)evt.extraParam);
                    }
                    break;

                case EConnectorEvent.ON_DATASEND_SUCCEEDED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnDataSent(evt.ctx, (int)evt.extraParam);
                    }
                    break;

                case EConnectorEvent.ON_DATASEND_FAILED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnDataSendFailed(evt.ctx, (string)evt.extraParam);
                    }
                    break;

                case EConnectorEvent.ON_DATARECEIVE_SUCCEEDED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnDataReceived(evt.ctx, (int)evt.extraParam);
                    }
                    break;

                case EConnectorEvent.ON_DATARECEIVE_FAILED:
                    if (ctxParameter.eventHandler != null)
                    {
                        ctxParameter.eventHandler.OnDataReceiveFailed(evt.ctx, (string)evt.extraParam);
                    }
                    break;

                default:
                    break;
                }
            }
        }
예제 #26
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);
                }
            }
        }