public void If_data_store_thorws_exception_facade_state_is_reloaded()
        {
            var changeSetId = ChangeSetId.NewUniqueId();
            var objectId = ObjectId.NewUniqueId();
            var objectTypeId = ObjectTypeId.NewUniqueId();
            var commands = new List<AbstractCommand>
                               {
                                   new CreateObjectCommand(objectTypeId, objectId)
                               };
            dataStore.ChangeSets.Add(new ChangeSet(changeSetId, null, "Some comment", commands));
            dataStore.OnStored += (sender, args) => { throw new Exception("Some nasty exception happened AFTER storing value"); };
            var facade = new DataFacade(commandExecutor, dataStore, new IncrementalCachingSnapshotFactory());

            var newChangeSet = new UncommittedChangeSet(changeSetId, "Some comment");
            newChangeSet.Add(new ModifyAttributeCommand(objectId, "TextValue", "SomeText"));

            try
            {
                facade.Commit(newChangeSet);
            }
            catch (Exception)
            {
                //Intentionally swallowing exception
            }

            var o = facade.GetById(objectId, newChangeSet.Id); //Would throw if new change set was not loaded into memory.
        }
        public void It_throws_exception_when_trying_to_load_object_in_context_of_non_existing_change_set()
        {
            var objectId = ObjectId.NewUniqueId();
            var changeSetId = ChangeSetId.NewUniqueId();
            var facade = new DataFacade(commandExecutor, dataStore, new IncrementalCachingSnapshotFactory());

            Assert.Throws<InvalidOperationException>(() => facade.GetById(objectId, changeSetId));
        }
        public void It_creates_object_and_returns_it_by_id()
        {
            var changeSetId = ChangeSetId.NewUniqueId();
            var objectId = ObjectId.NewUniqueId();
            var objectTypeId = ObjectTypeId.NewUniqueId();
            var commands = new List<AbstractCommand>
                               {
                                   new CreateObjectCommand(objectTypeId, objectId)
                               };
            dataStore.ChangeSets.Add(new ChangeSet(changeSetId, null, "Some comment", commands));
            var facade = new DataFacade(commandExecutor, dataStore, new IncrementalCachingSnapshotFactory());

            var o = facade.GetById(objectId, changeSetId);

            Assert.IsNotNull(o);
        }
        public void SetUp()
        {
            var dataStore = new InMemoryDataStore();
            var commandExecutor = new CommandExecutor()
                .RegisterCommandHandler(new CreateUnitCommandHandler())
                .RegisterCommandHandler(new CreateHierarchyCommandHandler())
                .RegisterCommandHandler(new SetHierarchyRootCommandHandler())
                .RegisterCommandHandler(new MoveUnitCommandHandler())
                .RegisterCommandHandler(new CreateHierarchyNodeCommandHandler())
                .RegisterCommandHandler(new AttachToHierarchyCommandHandler())
                .RegisterCommandHandler(new AttachChildCommandHandler())
                .RegisterCommandHandler(new DetachChildCommandHandler())
                .RegisterCommandHandler(new SetParentCommandHandler());

            var typeRepository = new ObjectTypeDescriptorRepository()
                .RegisterUsingReflection<Unit>()
                .RegisterUsingReflection<HierarchyNode>()
                .RegisterUsingReflection<Hierarchy>();

            dataFacade = new DataFacade(commandExecutor, dataStore, new IncrementalCachingSnapshotFactory());
            objectFacade = new ObjectFacade(dataFacade, typeRepository, commandExecutor);
        }
        public void It_can_handle_1000_objects_with_10_changes_each()
        {
            var dataStore = new InMemoryDataStore();

            var objectIds = GenerateObjectIds(1000);

            ChangeSetId? previousChangeSetId = null;
            ChangeSetId currentChangeSetId = ChangeSetId.NewUniqueId();
            dataStore.ChangeSets.Add(new ChangeSet(currentChangeSetId, previousChangeSetId, "Some comment", GenerateCreateCommands(objectIds)));
            previousChangeSetId = currentChangeSetId;

            for (int i = 0; i < 9; i++)
            {
                currentChangeSetId = ChangeSetId.NewUniqueId();
                dataStore.ChangeSets.Add(new ChangeSet(currentChangeSetId, previousChangeSetId, "Some comment", GenerateUpdateCommands(i, objectIds)));
                previousChangeSetId = currentChangeSetId;
            }

            var commandExecutor = new CommandExecutor()
                .RegisterCommandHandler(new CreateObjectCommandHandler())
                .RegisterCommandHandler(new ModifyAttributeCommandHandler());
            var objectTypeRepository = new ObjectTypeDescriptorRepository()
                .RegisterUsingReflection<TestingObject>();
            var dataFacade = new DataFacade(commandExecutor, dataStore, new IncrementalCachingSnapshotFactory());
            var objectFacade = new ObjectFacade(dataFacade, objectTypeRepository, commandExecutor);

            var stopwatch = new Stopwatch();
            stopwatch.Start();
            var currentView = objectFacade.GetSnapshot(currentChangeSetId);
            var allObjects = currentView.List<TestingObject>().ToList();
            stopwatch.Stop();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            Assert.AreEqual(1000, allObjects.Count);
            foreach (var testingObject in allObjects)
            {
                Assert.AreEqual("8", testingObject.TextValue);
            }
        }
Ejemplo n.º 6
0
        /// <exclude />
        public static MethodInfo Create(IInlineFunction function, string code = null, InlineFunctionCreateMethodErrorHandler createMethodErrorHandler = null, List <string> selectedAssemblies = null)
        {
            if (string.IsNullOrWhiteSpace(code))
            {
                try
                {
                    code = GetFunctionCode(function);
                }
                catch (ThreadAbortException)
                {
                }
                catch (Exception ex)
                {
                    if (createMethodErrorHandler != null)
                    {
                        createMethodErrorHandler.OnLoadSourceError(ex);
                    }
                    else
                    {
                        LogMessageIfNotShuttingDown(function, ex.Message);
                    }
                    return(null);
                }
            }

            var compilerParameters = new CompilerParameters
            {
                GenerateExecutable = false,
                GenerateInMemory   = true
            };

            if (selectedAssemblies == null)
            {
                IEnumerable <IInlineFunctionAssemblyReference> assemblyReferences = DataFacade.GetData <IInlineFunctionAssemblyReference>(f => f.Function == function.Id).Evaluate();

                foreach (var assemblyReference in assemblyReferences)
                {
                    var assemblyPath = GetAssemblyFullPath(assemblyReference.Name, assemblyReference.Location);

                    compilerParameters.ReferencedAssemblies.Add(assemblyPath);
                }
            }
            else
            {
                foreach (var reference in selectedAssemblies)
                {
                    compilerParameters.ReferencedAssemblies.Add(reference);
                }
            }

            var appCodeAssembly = AssemblyFacade.GetAppCodeAssembly();

            if (appCodeAssembly != null)
            {
                compilerParameters.ReferencedAssemblies.Add(appCodeAssembly.Location);
            }

            var compiler = CSharpCodeProviderFactory.CreateCompiler();

            var results = compiler.CompileAssemblyFromSource(compilerParameters, code);

            if (results.Errors.HasErrors)
            {
                foreach (CompilerError error in results.Errors)
                {
                    if (createMethodErrorHandler != null)
                    {
                        createMethodErrorHandler.OnCompileError(error.Line, error.ErrorNumber, error.ErrorText);
                    }
                    else
                    {
                        LogMessageIfNotShuttingDown(function, error.ErrorText);
                    }
                }

                return(null);
            }

            var type = results.CompiledAssembly.GetTypes().SingleOrDefault(f => f.Name == MethodClassContainerName);

            if (type == null)
            {
                var message = Texts.CSharpInlineFunction_OnMissingContainerType(MethodClassContainerName);

                if (createMethodErrorHandler != null)
                {
                    createMethodErrorHandler.OnMissingContainerType(message);
                }
                else
                {
                    LogMessageIfNotShuttingDown(function, message);
                }

                return(null);
            }

            if (type.Namespace != function.Namespace)
            {
                var message = Texts.CSharpInlineFunction_OnNamespaceMismatch(type.Namespace, function.Namespace);

                if (createMethodErrorHandler != null)
                {
                    createMethodErrorHandler.OnNamespaceMismatch(message);
                }
                else
                {
                    LogMessageIfNotShuttingDown(function, message);
                }

                return(null);
            }

            var methodInfo = type.GetMethods(BindingFlags.Public | BindingFlags.Static).SingleOrDefault(f => f.Name == function.Name);

            if (methodInfo == null)
            {
                var message = Texts.CSharpInlineFunction_OnMissionMethod(function.Name, MethodClassContainerName);

                if (createMethodErrorHandler != null)
                {
                    createMethodErrorHandler.OnMissionMethod(message);
                }
                else
                {
                    LogMessageIfNotShuttingDown(function, message);
                }

                return(null);
            }

            return(methodInfo);
        }
        public void It_throws_exception_when_trying_to_load_two_change_sets_with_same_ids()
        {
            var changeSetId = ChangeSetId.NewUniqueId();
            dataStore.ChangeSets.Add(new ChangeSet(changeSetId, null, "Some comment", new AbstractCommand[] {}));
            dataStore.ChangeSets.Add(new ChangeSet(changeSetId, null, "Some comment", new AbstractCommand[] {}));

            var facade = new DataFacade(commandExecutor, dataStore, new IncrementalCachingSnapshotFactory());
            Assert.Throws<InvalidOperationException>(() => facade.GetById(ObjectId.NewUniqueId(), changeSetId));
        }
Ejemplo n.º 8
0
        private void initializeCodeActivity_Copy_ExecuteCode(object sender, EventArgs e)
        {
            var castedEntityToken = (DataEntityToken)this.EntityToken;

            IPage newPage;

            using (var transactionScope = TransactionsFacade.CreateNewScope())
            {
                CultureInfo sourceCultureInfo = UserSettings.ForeignLocaleCultureInfo;

                IPage sourcePage;
                List <IPagePlaceholderContent> sourcePagePlaceholders;
                List <IData> sourceMetaDataSet;

                using (new DataScope(sourceCultureInfo))
                {
                    Guid sourcePageId = ((IPage)castedEntityToken.Data).Id;

                    using (new DataScope(DataScopeIdentifier.Administrated))
                    {
                        sourcePage = DataFacade.GetData <IPage>(f => f.Id == sourcePageId).Single();
                        sourcePage = sourcePage.GetTranslationSource();

                        using (new DataScope(sourcePage.DataSourceId.DataScopeIdentifier))
                        {
                            sourcePagePlaceholders = DataFacade.GetData <IPagePlaceholderContent>(f => f.PageId == sourcePageId).ToList();
                            sourceMetaDataSet      = sourcePage.GetMetaData().ToList();
                        }
                    }
                }


                CultureInfo targetCultureInfo = UserSettings.ActiveLocaleCultureInfo;

                using (new DataScope(targetCultureInfo))
                {
                    newPage = DataFacade.BuildNew <IPage>();
                    sourcePage.ProjectedCopyTo(newPage);

                    newPage.SourceCultureName = targetCultureInfo.Name;
                    newPage.PublicationStatus = GenericPublishProcessController.Draft;
                    newPage = DataFacade.AddNew <IPage>(newPage);

                    foreach (IPagePlaceholderContent sourcePagePlaceholderContent in sourcePagePlaceholders)
                    {
                        IPagePlaceholderContent newPagePlaceholderContent = DataFacade.BuildNew <IPagePlaceholderContent>();
                        sourcePagePlaceholderContent.ProjectedCopyTo(newPagePlaceholderContent);

                        newPagePlaceholderContent.SourceCultureName = targetCultureInfo.Name;
                        newPagePlaceholderContent.PublicationStatus = GenericPublishProcessController.Draft;
                        DataFacade.AddNew <IPagePlaceholderContent>(newPagePlaceholderContent);
                    }

                    foreach (IData metaData in sourceMetaDataSet)
                    {
                        ILocalizedControlled localizedData = metaData as ILocalizedControlled;

                        if (localizedData == null)
                        {
                            continue;
                        }

                        IEnumerable <ReferenceFailingPropertyInfo> referenceFailingPropertyInfos = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(localizedData).Evaluate();

                        if (!referenceFailingPropertyInfos.Any())
                        {
                            IData newMetaData = DataFacade.BuildNew(metaData.DataSourceId.InterfaceType);
                            metaData.ProjectedCopyTo(newMetaData);

                            ILocalizedControlled localizedControlled = newMetaData as ILocalizedControlled;
                            localizedControlled.SourceCultureName = targetCultureInfo.Name;

                            IPublishControlled publishControlled = newMetaData as IPublishControlled;
                            publishControlled.PublicationStatus = GenericPublishProcessController.Draft;

                            DataFacade.AddNew(newMetaData);
                        }
                        else
                        {
                            foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingPropertyInfos)
                            {
                                Log.LogVerbose("LocalizePageWorkflow",
                                               "Meta data of type '{0}' is not localized because the field '{1}' is referring some not yet localzed data"
                                               .FormatWith(metaData.DataSourceId.InterfaceType, referenceFailingPropertyInfo.DataFieldDescriptor.Name));
                            }
                        }
                    }
                }

                EntityTokenCacheFacade.ClearCache(sourcePage.GetDataEntityToken());
                EntityTokenCacheFacade.ClearCache(newPage.GetDataEntityToken());

                foreach (var folderType in PageFolderFacade.GetDefinedFolderTypes(newPage))
                {
                    EntityTokenCacheFacade.ClearCache(new AssociatedDataElementProviderHelperEntityToken(
                                                          TypeManager.SerializeType(typeof(IPage)),
                                                          PageElementProvider.DefaultConfigurationName,
                                                          newPage.Id.ToString(),
                                                          TypeManager.SerializeType(folderType)));
                }


                transactionScope.Complete();
            }

            ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher();

            parentTreeRefresher.PostRefreshMesseges(newPage.GetDataEntityToken(), 2);

            this.ExecuteWorklow(newPage.GetDataEntityToken(), typeof(EditPageWorkflow));
        }
        private void undoCodeActivity_Undo_ExecuteCode(object sender, EventArgs e)
        {
            DataEntityToken dataEntityToken = (DataEntityToken)this.EntityToken;

            List <string> propertyNamesToIgnore = new List <string> {
                "PublicationStatus"
            };

            using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
            {
                IPage administrativePage = (IPage)dataEntityToken.Data;
                IPage publicPage         = DataFacade.GetDataFromOtherScope <IPage>(administrativePage, DataScopeIdentifier.Public).Single();

                List <IData> administrativeCompositions = administrativePage.GetMetaData(DataScopeIdentifier.Administrated).ToList();
                List <IData> publicCompositions         = publicPage.GetMetaData(DataScopeIdentifier.Public).ToList();

                Guid pageId    = administrativePage.Id;
                Guid versionId = administrativePage.VersionId;

                List <IPagePlaceholderContent> administrativePlaceholders;
                using (new DataScope(DataScopeIdentifier.Administrated))
                {
                    administrativePlaceholders =
                        (from ph in DataFacade.GetData <IPagePlaceholderContent>(false)
                         where ph.PageId == pageId && ph.VersionId == versionId
                         select ph).ToList();
                }

                List <IPagePlaceholderContent> publicPlaceholders;
                using (new DataScope(DataScopeIdentifier.Public))
                {
                    publicPlaceholders =
                        (from ph in DataFacade.GetData <IPagePlaceholderContent>(false)
                         where ph.PageId == pageId && ph.VersionId == versionId
                         select ph).ToList();
                }

                using (ProcessControllerFacade.NoProcessControllers)
                {
                    publicPage.FullCopyChangedTo(administrativePage, propertyNamesToIgnore);
                    DataFacade.Update(administrativePage);

                    foreach (IData publicComposition in publicCompositions)
                    {
                        IData administrativeComposition =
                            (from com in administrativeCompositions
                             where com.DataSourceId.DataId.CompareTo(publicComposition.DataSourceId.DataId, false)
                             select com).Single();

                        publicComposition.FullCopyChangedTo(administrativeComposition, propertyNamesToIgnore);
                        DataFacade.Update(administrativeComposition);
                    }

                    foreach (IPagePlaceholderContent publicPagePlaceholderContent in publicPlaceholders)
                    {
                        IPagePlaceholderContent administrativePagePlaceholderContent =
                            (from pc in administrativePlaceholders
                             where pc.PlaceHolderId == publicPagePlaceholderContent.PlaceHolderId
                             select pc).Single();

                        publicPagePlaceholderContent.FullCopyChangedTo(administrativePagePlaceholderContent, propertyNamesToIgnore);
                        DataFacade.Update(administrativePagePlaceholderContent);
                    }
                }

                transactionScope.Complete();
            }
        }
Ejemplo n.º 10
0
        /// <exclude />
        public override IEnumerable <PackageFragmentValidationResult> Validate()
        {
            var validationResult = new List <PackageFragmentValidationResult>();

            var foreignKeyReferences = new List <string>();

            if (this.Configuration.Count(f => f.Name == "Types") > 1)
            {
                validationResult.AddFatal(Texts.DynamicDataTypePackageFragmentInstaller_OnlyOneElement);
                return(validationResult);
            }

            XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types");

            if (typesElement == null)
            {
                validationResult.AddFatal(Texts.DynamicDataTypePackageFragmentInstaller_MissingElement);
                return(validationResult);
            }

            _dataTypeDescriptors = new List <DataTypeDescriptor>();

            foreach (XElement typeElement in typesElement.Elements("Type"))
            {
                XElement serializedDataTypeDescriptor;

                XAttribute fileAttribute = typeElement.Attribute("dataTypeDescriptorFile");
                if (fileAttribute != null)
                {
                    string relativeFilePath = (string)fileAttribute;

                    string markup;

                    using (var stream = this.InstallerContext.ZipFileSystem.GetFileStream(relativeFilePath))
                        using (var reader = new StreamReader(stream))
                        {
                            markup = reader.ReadToEnd();
                        }

                    serializedDataTypeDescriptor = XElement.Parse(markup);
                }
                else
                {
                    var dataTypeDescriptorAttribute = typeElement.Attribute("dataTypeDescriptor");
                    if (dataTypeDescriptorAttribute == null)
                    {
                        validationResult.AddFatal(Texts.DataTypePackageFragmentInstaller_MissingAttribute("dataTypeDescriptor"), typeElement);
                        continue;
                    }

                    try
                    {
                        serializedDataTypeDescriptor = XElement.Parse(dataTypeDescriptorAttribute.Value);
                    }
                    catch (Exception)
                    {
                        validationResult.AddFatal(Texts.DynamicDataTypePackageFragmentInstaller_DataTypeDescriptorParseError, dataTypeDescriptorAttribute);
                        continue;
                    }
                }

                DataTypeDescriptor dataTypeDescriptor;
                try
                {
                    bool inheritedFieldsIncluded = serializedDataTypeDescriptor.Descendants().Any(e => e.Attributes("inherited").Any(a => (string)a == "true"));

                    dataTypeDescriptor = DataTypeDescriptor.FromXml(serializedDataTypeDescriptor, inheritedFieldsIncluded);
                }
                catch (Exception e)
                {
                    validationResult.AddFatal(Texts.DynamicDataTypePackageFragmentInstaller_DataTypeDescriptorDeserializeError(e.Message));
                    continue;
                }

                Type type = TypeManager.TryGetType(dataTypeDescriptor.TypeManagerTypeName);
                if (type != null && DataFacade.GetAllKnownInterfaces().Contains(type))
                {
                    validationResult.AddFatal(Texts.DynamicDataTypePackageFragmentInstaller_TypeExists(type));
                }

                if (dataTypeDescriptor.SuperInterfaces.Any(f => f.Name == nameof(IVersioned)))
                {
                    if (dataTypeDescriptor.Fields.All(f => f.Name != nameof(IVersioned.VersionId)))
                    {
                        dataTypeDescriptor.Fields.Add(new DataFieldDescriptor(Guid.NewGuid(), nameof(IVersioned.VersionId), StoreFieldType.Guid, typeof(Guid), true));
                    }
                }

                foreach (var field in dataTypeDescriptor.Fields)
                {
                    if (!field.ForeignKeyReferenceTypeName.IsNullOrEmpty())
                    {
                        foreignKeyReferences.Add(field.ForeignKeyReferenceTypeName);
                    }
                }

                _dataTypeDescriptors.Add(dataTypeDescriptor);
                this.InstallerContext.AddPendingDataTypeDescritpor(dataTypeDescriptor.TypeManagerTypeName, dataTypeDescriptor);
            }

            foreach (string foreignKeyTypeName in foreignKeyReferences)
            {
                if (!TypeManager.HasTypeWithName(foreignKeyTypeName) &&
                    !_dataTypeDescriptors.Any(descriptor => descriptor.TypeManagerTypeName == foreignKeyTypeName))
                {
                    validationResult.AddFatal(Texts.DynamicDataTypePackageFragmentInstaller_MissingReferencedType(foreignKeyTypeName));
                }
            }

            if (validationResult.Count > 0)
            {
                _dataTypeDescriptors = null;
            }

            return(validationResult);
        }
Ejemplo n.º 11
0
 public virtual TData New <TData>()
     where TData : class, IData
 {
     return(DataFacade.BuildNew <TData>());
 }
Ejemplo n.º 12
0
        public IEnumerable <Element> GetRoots(SearchToken searchToken)
        {
            int pages;

            using (new DataScope(DataScopeIdentifier.Administrated))
            {
                pages = PageServices.GetChildrenCount(Guid.Empty);
            }

            EntityToken entityToken = new PageElementProviderEntityToken(_context.ProviderName);

            var dragAndDropInfo = new ElementDragAndDropInfo();

            dragAndDropInfo.AddDropType(typeof(IPage));
            dragAndDropInfo.SupportsIndexedPosition = true;

            var element = new Element(_context.CreateElementHandle(entityToken), dragAndDropInfo)
            {
                VisualData = new ElementVisualizedData
                {
                    Label       = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.RootLabel"),
                    ToolTip     = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.RootLabelToolTip"),
                    HasChildren = pages != 0,
                    Icon        = PageElementProvider.RootClosed,
                    OpenedIcon  = PageElementProvider.RootOpen
                }
            };

            var allPageTypes = DataFacade.GetData <IPageType>().AsEnumerable();

            foreach (
                var pageType in
                allPageTypes.Where(f => f.HomepageRelation != nameof(PageTypeHomepageRelation.OnlySubPages))
                .OrderByDescending(f => f.Id))
            {
                element.AddAction(
                    new ElementAction(
                        new ActionHandle(new PageAddActionToken(pageType.Id, ActionIdentifier.Add, AddPermissionTypes)
                {
                    DoIgnoreEntityTokenLocking = true
                }))
                {
                    VisualData = new ActionVisualizedData
                    {
                        Label = string.Format(StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider",
                                                                                   "PageElementProvider.AddPageAtRootFormat"), pageType.Name),
                        ToolTip =
                            StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider",
                                                                 "PageElementProvider.AddPageAtRootToolTip"),
                        Icon           = PageElementProvider.AddPage,
                        Disabled       = false,
                        ActionLocation = new ActionLocation
                        {
                            ActionType   = ActionType.Add,
                            IsInFolder   = false,
                            IsInToolbar  = true,
                            ActionGroup  = PrimaryActionGroup,
                            ActionBundle = "AddWebsite"
                        }
                    }
                });
            }


            element.AddAction(new ElementAction(new ActionHandle(new ViewUnpublishedItemsActionToken()))
            {
                VisualData = new ActionVisualizedData
                {
                    //Label = "List unpublished Pages and Folder Data",
                    //ToolTip = "Get an overview of pages and page folder data that haven't been published yet.",
                    Label          = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.ViewUnpublishedItems"),
                    ToolTip        = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.ViewUnpublishedItemsToolTip"),
                    Icon           = PageElementProvider.ListUnpublishedItems,
                    Disabled       = false,
                    ActionLocation = new ActionLocation
                    {
                        ActionType  = ActionType.Other,
                        IsInFolder  = false,
                        IsInToolbar = true,
                        ActionGroup = ViewActionGroup
                    }
                }
            });

            element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.AddMetaDataWorkflow"), AssociatedDataElementProviderHelper <IPage> .AddAssociatedTypePermissionTypes)
            {
                DoIgnoreEntityTokenLocking = true
            }))
            {
                VisualData = new ActionVisualizedData
                {
                    Label          = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataTypeLabel"),
                    ToolTip        = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.AddMetaDataTypeToolTip"),
                    Icon           = AddDataAssociationTypeIcon,
                    Disabled       = false,
                    ActionLocation = new ActionLocation
                    {
                        ActionType  = ActionType.Add,
                        IsInFolder  = false,
                        IsInToolbar = false,
                        ActionGroup = MetaDataAppendedActionGroup
                    }
                }
            });

            element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.EditMetaDataWorkflow"), AssociatedDataElementProviderHelper <IPage> .EditAssociatedTypePermissionTypes)))
            {
                VisualData = new ActionVisualizedData
                {
                    Label          = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataTypeLabel"),
                    ToolTip        = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.EditMetaDataTypeToolTip"),
                    Icon           = EditDataAssociationTypeIcon,
                    Disabled       = false,
                    ActionLocation = new ActionLocation
                    {
                        ActionType  = ActionType.Edit,
                        IsInFolder  = false,
                        IsInToolbar = false,
                        ActionGroup = MetaDataAppendedActionGroup
                    }
                }
            });

            element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.C1Console.Elements.ElementProviderHelpers.AssociatedDataElementProviderHelper.DeleteMetaDataWorkflow"), AssociatedDataElementProviderHelper <IPage> .RemoveAssociatedTypePermissionTypes)))
            {
                VisualData = new ActionVisualizedData
                {
                    Label          = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.RemoveMetaDataTypeLabel"),
                    ToolTip        = StringResourceSystemFacade.GetString("Composite.Management", "AssociatedDataElementProviderHelper.RemoveMetaDataTypeToolTip"),
                    Icon           = RemoveDataAssociationTypeIcon,
                    Disabled       = false,
                    ActionLocation = new ActionLocation
                    {
                        ActionType  = ActionType.Delete,
                        IsInFolder  = false,
                        IsInToolbar = false,
                        ActionGroup = MetaDataAppendedActionGroup
                    }
                }
            });

            // Creates a problem for the front-end "toolbar caching" mechanism - dont re-introduce this right befroe a release
            // Reason: ActionTokin is always unique for a page, making the ActionKey (hash) unique
            //if (RuntimeInformation.IsDebugBuild)
            //{
            //    element.AddAction(new ElementAction(new ActionHandle(new DisplayLocalOrderingActionToken(Guid.Empty)))
            //    {
            //        VisualData = new ActionVisualizedData
            //        {
            //            Label = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.DisplayLocalOrderingLabel"),
            //            ToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.DisplayLocalOrderingToolTip"),
            //            Icon = CommonElementIcons.Nodes,
            //            Disabled = false,
            //            ActionLocation = new ActionLocation
            //            {
            //                ActionType = ActionType.DeveloperMode,
            //                IsInFolder = false,
            //                IsInToolbar = false,
            //                ActionGroup = AppendedActionGroup
            //            }
            //        }
            //    });
            //}

            yield return(element);
        }
Ejemplo n.º 13
0
        public static IEnumerable <SupplierRequest> GetSupplierRequests(SupplierRequest suppliersearch)
        {
            var paramList = new List <ParameterValue>();

            if (!String.IsNullOrEmpty(suppliersearch.RequesterID.ToString()))
            {
                paramList.Add(new ParameterValue("RequesterID", suppliersearch.RequesterID));
            }

            var dataSet = DataFacade.GetDataSet("SupplierRequestGet", paramList.ToArray());

            var returnList = new List <SupplierRequest>();

            foreach (var requestItem in dataSet.Tables["Table"].Rows.Cast <DataRow>().Select(x => new SupplierRequest
            {
                Requester =
                    dataSet.Tables["Table1"].Rows.Cast <DataRow>().Where(
                        y => (int)y["RequesterID"] == (int)x["RequesterID"]).Select(
                        y => new Requester
                {
                    RequesterID = Convert.ToInt32(y["RequesterID"]),
                    RequestDate = Convert.ToDateTime(y["RequestDate"]),
                    SiteName = y["SiteName"].ToString(),
                    SiteNumber = y["SiteNumber"].ToString(),
                    EmailAddress = y["EmailAddress"].ToString(),
                    ContactNo = y["ContactNo"].ToString(),
                    RequesterName = y["RequesterName"].ToString()
                }).FirstOrDefault(),
                Supplier =
                    dataSet.Tables["Table2"].Rows.Cast <DataRow>().Where(
                        y => (int)y["RequesterID"] == (int)x["RequesterID"]).Select(
                        y => new Supplier
                {
                    SupplierID = (int)y["SupplierID"],
                    SupplierName = y["SupplierName"].ToString(),
                    Address1 = y["Address1"].ToString(),
                    Address2 = y["Address2"].ToString(),
                    City = y["City"].ToString(),
                    Province = y["Province"].ToString(),
                    PostalCode = Convert.ToInt32(y["PostalCode"]),
                    Phone = y["Phone"].ToString(),
                    ContactName = y["ContactName"].ToString(),
                    Cellphone = y["Cellphone"].ToString(),
                    VATNo = y["VATNo"].ToString(),
                    Fax = y["Fax"].ToString(),
                    EMail = y["EMail"].ToString()
                }).FirstOrDefault()
            }))
            {
                requestItem.SupplierProduct =
                    dataSet.Tables["Table3"].Rows.Cast <DataRow>().Where(
                        x => (int)x["SupplierID"] == requestItem.Supplier.SupplierID).Select(x => new SupplierProduct
                {
                    SupplierID           = (int)x["SupplierID"],
                    RetailBarcode        = x["RetailBarcode"].ToString(),
                    RetailPackSize       = x["RetailPackSize"].ToString(),
                    Ranging              = x["Ranging"].ToString(),
                    OuterCaseCode        = x["OuterCaseCode"].ToString(),
                    PackBarcode          = x["PackBarcode"].ToString(),
                    ProductCode          = x["ProductCode"].ToString(),
                    ProductDescription   = x["ProductDescription"].ToString(),
                    ISISRetailItemNaming = x["ISISRetailItemNaming"].ToString(),
                    Category             = x["Category"].ToString(),
                    Brand        = x["Brand"].ToString(),
                    UOMType      = x["UOMType"].ToString(),
                    PackSizeCase = Convert.ToInt32(x["PackSizeCase"]),
                    CaseCost     = Convert.ToDecimal(x["CaseCost"]),
                    Cost         = Convert.ToDecimal(x["Cost"])
                })
                    .ToList();

                returnList.Add(requestItem);
            }

            return(returnList);
        }
Ejemplo n.º 14
0
            public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
            {
                DataEntityToken token = (DataEntityToken)entityToken;

                IPublishControlled publishControlled = (IPublishControlled)DataFacade.GetDataFromDataSourceId(token.DataSourceId);

                ValidationResults validationResults = ValidationFacade.Validate((IData)publishControlled);

                if (validationResults.IsValid)
                {
                    UpdateTreeRefresher treeRefresher = new UpdateTreeRefresher(token.Data.GetDataEntityToken(), flowControllerServicesContainer);

                    if (actionToken is PublishActionToken)
                    {
                        publishControlled.PublicationStatus = Published;
                    }
                    else if (actionToken is DraftActionToken)
                    {
                        publishControlled.PublicationStatus = Draft;
                    }
                    else if (actionToken is AwaitingApprovalActionToken)
                    {
                        publishControlled.PublicationStatus = AwaitingApproval;
                    }
                    else if (actionToken is AwaitingPublicationActionToken)
                    {
                        publishControlled.PublicationStatus = AwaitingPublication;
                    }
                    else if (actionToken is UnpublishActionToken)
                    {
                        publishControlled.PublicationStatus = Draft;

                        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
                        {
                            IData data = DataFacade.GetDataFromOtherScope(token.Data, DataScopeIdentifier.Public).SingleOrDefault();

                            if (data != null)
                            {
                                IPage page = data as IPage;
                                if (page != null)
                                {
                                    IEnumerable <IData> referees;
                                    using (new DataScope(DataScopeIdentifier.Public))
                                    {
                                        referees = page.GetMetaData();
                                    }

                                    DataFacade.Delete(referees, CascadeDeleteType.Disable);
                                }


                                DataFacade.Delete(data, CascadeDeleteType.Disable);
                            }

                            transactionScope.Complete();
                        }
                    }
                    else if (actionToken is UndoPublishedChangesActionToken)
                    {
                        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
                        {
                            using (ProcessControllerFacade.NoProcessControllers)
                            {
                                var   administrativeData = (IPublishControlled)token.Data;
                                IData publishedData      = DataFacade.GetDataFromOtherScope(token.Data, DataScopeIdentifier.Public).Single();

                                publishedData.FullCopyChangedTo(administrativeData);
                                administrativeData.PublicationStatus = Draft;

                                DataFacade.Update(administrativeData);
                            }

                            transactionScope.Complete();
                        }
                    }
                    else
                    {
                        throw new ArgumentException("Unknown action token", "actionToken");
                    }

                    DataFacade.Update(publishControlled);

                    treeRefresher.PostRefreshMesseges(publishControlled.GetDataEntityToken());
                }
                else
                {
                    var managementConsoleMessageService = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>();

                    StringBuilder sb = new System.Text.StringBuilder();
                    sb.AppendLine(StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "ValidationErrorMessage"));
                    foreach (ValidationResult result in validationResults)
                    {
                        sb.AppendLine(result.Message);
                    }

                    managementConsoleMessageService.ShowMessage(DialogType.Error, StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "ValidationErrorTitle"), sb.ToString());
                }

                return(null);
            }
Ejemplo n.º 15
0
        private void codeActivity1_ExecuteCode(object sender, EventArgs e)
        {
            try
            {
                string typeName             = this.GetBinding <string>(BindingNames.NewTypeName);
                string typeNamespace        = this.GetBinding <string>(BindingNames.NewTypeNamespace);
                string typeTitle            = this.GetBinding <string>(BindingNames.NewTypeTitle);
                bool   hasCaching           = this.GetBinding <bool>(BindingNames.HasCaching);
                bool   hasPublishing        = this.GetBinding <bool>(BindingNames.HasPublishing);
                bool   hasLocalization      = this.GetBinding <bool>(BindingNames.HasLocalization);
                string keyFieldName         = this.GetBinding <string>(BindingNames.KeyFieldName);
                string labelFieldName       = this.GetBinding <string>(BindingNames.LabelFieldName);
                string internalUrlPrefix    = this.GetBinding <string>(BindingNames.InternalUrlPrefix);
                var    dataFieldDescriptors = this.GetBinding <List <DataFieldDescriptor> >(BindingNames.DataFieldDescriptors);

                GeneratedTypesHelper helper;
                Type interfaceType = null;
                if (this.BindingExist(BindingNames.InterfaceType))
                {
                    interfaceType = this.GetBinding <Type>(BindingNames.InterfaceType);

                    helper = new GeneratedTypesHelper(interfaceType);
                }
                else
                {
                    helper = new GeneratedTypesHelper();
                }

                string errorMessage;
                if (!helper.ValidateNewTypeName(typeName, out errorMessage))
                {
                    this.ShowFieldMessage(BindingNames.NewTypeName, errorMessage);
                    return;
                }

                if (!helper.ValidateNewTypeNamespace(typeNamespace, out errorMessage))
                {
                    this.ShowFieldMessage(BindingNames.NewTypeNamespace, errorMessage);
                    return;
                }

                if (!helper.ValidateNewTypeFullName(typeName, typeNamespace, out errorMessage))
                {
                    this.ShowFieldMessage(BindingNames.NewTypeName, errorMessage);
                    return;
                }

                if (!helper.ValidateNewFieldDescriptors(dataFieldDescriptors, keyFieldName, out errorMessage))
                {
                    this.ShowMessage(
                        DialogType.Warning,
                        Texts.AddNewInterfaceTypeStep1_ErrorTitle,
                        errorMessage
                        );
                    return;
                }

                if (interfaceType != null)
                {
                    if (hasLocalization != DataLocalizationFacade.IsLocalized(interfaceType) &&
                        DataFacade.GetData(interfaceType).ToDataEnumerable().Any())
                    {
                        this.ShowMessage(
                            DialogType.Error,
                            Texts.AddNewInterfaceTypeStep1_ErrorTitle,
                            "It's not possible to change localization through the current tab"
                            );
                        return;
                    }
                }


                if (helper.IsEditProcessControlledAllowed)
                {
                    helper.SetCachable(hasCaching);
                    helper.SetPublishControlled(hasPublishing);
                    helper.SetLocalizedControlled(hasLocalization);
                }

                helper.SetNewTypeFullName(typeName, typeNamespace);
                helper.SetNewTypeTitle(typeTitle);
                helper.SetNewInternalUrlPrefix(internalUrlPrefix);
                helper.SetNewFieldDescriptors(dataFieldDescriptors, keyFieldName, labelFieldName);


                if (IsPageDataFolder && !this.BindingExist(BindingNames.InterfaceType))
                {
                    Type targetType = TypeManager.GetType(this.Payload);

                    helper.SetForeignKeyReference(targetType, Composite.Data.DataAssociationType.Aggregation);
                }

                bool originalTypeDataExists = false;
                if (interfaceType != null)
                {
                    originalTypeDataExists = DataFacade.HasDataInAnyScope(interfaceType);
                }

                if (!helper.TryValidateUpdate(originalTypeDataExists, out errorMessage))
                {
                    this.ShowMessage(
                        DialogType.Warning,
                        Texts.AddNewInterfaceTypeStep1_ErrorTitle,
                        errorMessage
                        );
                    return;
                }


                helper.CreateType(originalTypeDataExists);

                string serializedTypeName = TypeManager.SerializeType(helper.InterfaceType);

                EntityToken entityToken = new GeneratedDataTypesElementProviderTypeEntityToken(
                    serializedTypeName,
                    this.EntityToken.Source,
                    IsPageDataFolder ? GeneratedDataTypesElementProviderRootEntityToken.PageDataFolderTypeFolderId
                                     : GeneratedDataTypesElementProviderRootEntityToken.GlobalDataTypeFolderId
                    );

                if (originalTypeDataExists)
                {
                    SetSaveStatus(true);
                }
                else
                {
                    SetSaveStatus(true, entityToken);
                }


                if (!this.BindingExist(BindingNames.InterfaceType))
                {
                    this.AcquireLock(entityToken);
                }

                this.UpdateBinding(BindingNames.InterfaceType, helper.InterfaceType);
                this.UpdateBinding(BindingNames.KeyFieldReadOnly, true);

                this.UpdateBinding(BindingNames.ViewLabel, typeTitle);
                RerenderView();

                //this.WorkflowResult = TypeManager.SerializeType(helper.InterfaceType);


                UserSettings.LastSpecifiedNamespace = typeNamespace;

                var parentTreeRefresher = this.CreateParentTreeRefresher();
                parentTreeRefresher.PostRefreshMessages(entityToken);
            }
            catch (Exception ex)
            {
                Log.LogCritical("Add New Interface Failed", ex);

                this.ShowMessage(DialogType.Error, ex.Message, ex.Message);
            }
        }
Ejemplo n.º 16
0
        /// <exclude />
        public List <ElementAction> GetActions(IData data, Type elementProviderType)
        {
            if (!(data is IPublishControlled) ||
                !data.DataSourceId.DataScopeIdentifier.Equals(DataScopeIdentifier.Administrated))
            {
                return(new List <ElementAction>());
            }

            if (data is ILocalizedControlled && !UserSettings.ActiveLocaleCultureInfo.Equals(data.DataSourceId.LocaleScope))
            {
                return(new List <ElementAction>());
            }

            var publishControlled = (IPublishControlled)data;

            IList <string> visualTrans;

            if (!_visualTransitions.TryGetValue(publishControlled.PublicationStatus, out visualTrans))
            {
                throw new InvalidOperationException($"Unknown publication state '{publishControlled.PublicationStatus}'");
            }

            var clientActions = visualTrans.Select(newState => _visualTransitionsActions[newState]()).ToList();


            IData publicData = DataFacade.GetDataFromOtherScope(data, DataScopeIdentifier.Public, true, false).FirstOrDefault();

            if (publicData != null)
            {
                var unpublishAction = new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Unpublish)
                {
                    DoIgnoreEntityTokenLocking = true
                }))
                {
                    VisualData = new ActionVisualizedData
                    {
                        Label          = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "Unpublish"),
                        ToolTip        = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "UnpublishToolTip"),
                        Icon           = GenericPublishProcessController.Unpublish,
                        Disabled       = false,
                        ActionLocation = new ActionLocation
                        {
                            ActionType  = ActionType.Other,
                            IsInFolder  = false,
                            IsInToolbar = true,
                            ActionGroup = WorkflowActionGroup
                        }
                    }
                };

                clientActions.Add(unpublishAction);



                if (publishControlled.PublicationStatus == Draft)
                {
                    if (!ProcessControllerAttributesFacade.IsActionIgnored(elementProviderType, GenericPublishProcessControllerActionTypeNames.UndoUnpublishedChanges))
                    {
                        IActionTokenProvider actionTokenProvider = ProcessControllerAttributesFacade.GetActionTokenProvider(elementProviderType, GenericPublishProcessControllerActionTypeNames.UndoUnpublishedChanges);

                        var actionToken = actionTokenProvider?.GetActionToken(GenericPublishProcessControllerActionTypeNames.UndoUnpublishedChanges, data)
                                          ?? new UndoPublishedChangesActionToken();

                        var undoPublishedChangesAction = new ElementAction(new ActionHandle(actionToken))
                        {
                            VisualData = new ActionVisualizedData
                            {
                                Label          = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "UndoPublishedChanges"),
                                ToolTip        = StringResourceSystemFacade.GetString("Composite.Plugins.GenericPublishProcessController", "UndoPublishedChangesToolTip"),
                                Icon           = GenericPublishProcessController.UndoUnpublishedChanges,
                                Disabled       = false,
                                ActionLocation = new ActionLocation
                                {
                                    ActionType  = ActionType.Other,
                                    IsInFolder  = false,
                                    IsInToolbar = true,
                                    ActionGroup = WorkflowActionGroup
                                }
                            }
                        };

                        clientActions.Add(undoPublishedChangesAction);
                    }
                }
            }

            return(clientActions);
        }
Ejemplo n.º 17
0
 public WizardController(DataFacade dataFacade)
 {
     this.dataFacade = dataFacade;
 }
Ejemplo n.º 18
0
        private void finalizeCodeActivity_Finalize_ExecuteCode(object sender, EventArgs e)
        {
            AddNewTreeRefresher addNewTreeRefresher = this.CreateAddNewTreeRefresher(this.EntityToken);

            UploadedFile uploadedFile = this.GetBinding <UploadedFile>("UploadedFile");
            string       filename;

            if (this.BindingExist("Filename"))
            {
                filename = this.GetBinding <string>("Filename");
            }
            else
            {
                filename = uploadedFile.FileName;
            }

            using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
            {
                IMediaFileStore store = DataFacade.GetData <IMediaFileStore>(x => x.Id == this.StoreId).First();

                IMediaFile existingFile = GetExistingFile(this.FolderPath, filename);

                if (existingFile == null)
                {
                    WorkflowMediaFile mediaFile = new WorkflowMediaFile();
                    mediaFile.FileName    = System.IO.Path.GetFileName(filename);
                    mediaFile.FolderPath  = this.FolderPath;
                    mediaFile.Title       = this.GetBinding <string>("Title");
                    mediaFile.Description = this.GetBinding <string>("Description");
                    mediaFile.Tags        = this.GetBinding <string>("Tags");
                    mediaFile.Culture     = C1Console.Users.UserSettings.ActiveLocaleCultureInfo.Name;
                    mediaFile.Length      = uploadedFile.ContentLength;
                    mediaFile.MimeType    = MimeTypeInfo.GetMimeType(uploadedFile);

                    using (System.IO.Stream readStream = uploadedFile.FileStream)
                    {
                        using (System.IO.Stream writeStream = mediaFile.GetNewWriteStream())
                        {
                            readStream.CopyTo(writeStream);
                        }
                    }

                    IMediaFile addedFile = DataFacade.AddNew <IMediaFile>(mediaFile, store.DataSourceId.ProviderName);

                    addNewTreeRefresher.PostRefreshMesseges(addedFile.GetDataEntityToken());

                    SelectElement(addedFile.GetDataEntityToken());
                }
                else
                {
                    Guid           fileId   = existingFile.Id;
                    IMediaFileData fileData = DataFacade.GetData <IMediaFileData>(file => file.Id == fileId).FirstOrDefault();

                    fileData.Title       = this.GetBinding <string>("Title");
                    fileData.Description = this.GetBinding <string>("Description");
                    fileData.Tags        = this.GetBinding <string>("Tags");
                    fileData.MimeType    = MimeTypeInfo.GetMimeType(uploadedFile);
                    fileData.Length      = uploadedFile.ContentLength;

                    using (System.IO.Stream readStream = uploadedFile.FileStream)
                    {
                        using (System.IO.Stream writeStream = existingFile.GetNewWriteStream())
                        {
                            readStream.CopyTo(writeStream);
                        }
                    }

                    DataFacade.Update(existingFile);
                    DataFacade.Update(fileData);

                    addNewTreeRefresher.PostRefreshMesseges(existingFile.GetDataEntityToken());

                    SelectElement(existingFile.GetDataEntityToken());
                }

                transactionScope.Complete();
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Returns a pagemeta data definition given the defining item id or null if none exists.
 /// </summary>
 /// <param name="definingItemId"></param>
 /// <param name="name"></param>
 /// <returns></returns>
 public static IPageMetaDataDefinition GetMetaDataDefinition(Guid definingItemId, string name)
 {
     return(DataFacade.GetData <IPageMetaDataDefinition>().
            Where(f => f.DefiningItemId == definingItemId && f.Name == name).
            SingleOrDefaultOrException("Multiple metadata definitions on the same item. Name: '{0}', ItemId: '{1}'", name, definingItemId));
 }
Ejemplo n.º 20
0
        public IEnumerable <Element> GetForeignChildren(EntityToken entityToken, SearchToken searchToken)
        {
            if (entityToken is DataEntityToken && ((DataEntityToken)entityToken).Data == null)
            {
                return new Element[] { }
            }
            ;

            if (entityToken is AssociatedDataElementProviderHelperEntityToken)
            {
                return(_pageAssociatedHelper.GetChildren((AssociatedDataElementProviderHelperEntityToken)entityToken, true));
            }

            if (entityToken is DataGroupingProviderHelperEntityToken)
            {
                return(_pageAssociatedHelper.GetChildren((DataGroupingProviderHelperEntityToken)entityToken, true));
            }

            IEnumerable <IPage> pages;

            using (new DataScope(DataScopeIdentifier.Administrated))
            {
                pages = GetChildrenPages(entityToken, searchToken).ToList();
            }


            IEnumerable <IPage> foreignAdministratedPages;

            using (new DataScope(DataScopeIdentifier.Administrated, UserSettings.ForeignLocaleCultureInfo))
            {
                foreignAdministratedPages = GetChildrenPages(entityToken, searchToken).ToList();
            }

            IEnumerable <IPage> foreignPublicPages;

            using (new DataScope(DataScopeIdentifier.Public, UserSettings.ForeignLocaleCultureInfo))
            {
                foreignPublicPages = GetChildrenPages(entityToken, searchToken).ToList();
            }


            Guid?itemId = GetParentPageId(entityToken);

            if (itemId.HasValue == false)
            {
                return new Element[] { }
            }
            ;

            IEnumerable <Guid> childPageIds =
                (from ps in DataFacade.GetData <IPageStructure>()
                 where ps.ParentId == itemId.Value
                 orderby ps.LocalOrdering
                 select ps.Id).ToList();


            var resultPages = new List <KeyValuePair <PageLocaleState, IPage> >();

            foreach (Guid pageId in childPageIds)
            {
                if (pages.Any(f => f.Id == pageId))
                {
                    resultPages.AddRange(
                        pages.Where(f => f.Id == pageId)
                        .Select(p => new KeyValuePair <PageLocaleState, IPage>(PageLocaleState.Own, p)));
                }
                else if (foreignAdministratedPages.Any(f => f.Id == pageId && f.IsTranslatable()))
                {
                    resultPages.AddRange(
                        foreignAdministratedPages.Where(f => f.Id == pageId && f.IsTranslatable())
                        .Select(p => new KeyValuePair <PageLocaleState, IPage>(PageLocaleState.ForeignActive, p)));
                }
                else if (foreignPublicPages.Any(f => f.Id == pageId))
                {
                    resultPages.AddRange(
                        foreignPublicPages.Where(f => f.Id == pageId)
                        .Select(p => new KeyValuePair <PageLocaleState, IPage>(PageLocaleState.ForeignActive, p)));
                }
                else if (foreignAdministratedPages.Any(f => f.Id == pageId))
                {
                    resultPages.AddRange(
                        foreignAdministratedPages.Where(f => f.Id == pageId)
                        .Select(p => new KeyValuePair <PageLocaleState, IPage>(PageLocaleState.ForeignDisabled, p)));
                }
            }

            List <Element> childPageElements = GetElements(resultPages, entityToken is PageElementProviderEntityToken);

            return(GetChildElements(entityToken, childPageElements));
        }
Ejemplo n.º 21
0
 public static void SupplierArchive(string suppliersid, bool archive)
 {
     DataFacade.ExecuteNonQuery("SupplierArchive",
                                new ParameterValue("SuppliersID", suppliersid),
                                new ParameterValue("Archive", archive));
 }
Ejemplo n.º 22
0
        public bool OnElementDraggedAndDropped(EntityToken draggedEntityToken, EntityToken newParentEntityToken, int dropIndex, DragAndDropType dragAndDropType, FlowControllerServicesContainer flowControllerServicesContainer)
        {
            IPage draggedPage = (IPage)((DataEntityToken)draggedEntityToken).Data;

            Verify.IsNotNull(draggedPage, "Dragged page does not exist");

            Guid newParentPageId;

            if (newParentEntityToken is PageElementProviderEntityToken)
            {
                newParentPageId = Guid.Empty;
            }
            else if (newParentEntityToken is DataEntityToken)
            {
                IPage newParentPage = (IPage)((DataEntityToken)newParentEntityToken).Data;
                newParentPageId = newParentPage.Id;
            }
            else
            {
                throw new NotImplementedException();
            }

            IPage oldParent   = null;
            Guid  oldParentId = draggedPage.GetParentId();

            if (oldParentId != Guid.Empty)
            {
                oldParent = DataFacade.GetData <IPage>(f => f.Id == oldParentId).FirstOrDefault();
            }

            if (dragAndDropType == DragAndDropType.Move)
            {
                using (var transactionScope = TransactionsFacade.CreateNewScope())
                {
                    string urlTitle = draggedPage.UrlTitle;
                    int    counter  = 1;

                    while (true)
                    {
                        bool urlTitleClash =
                            (from p in PageServices.GetChildren(newParentPageId).AsEnumerable()
                             where p.UrlTitle == urlTitle && p.Id != draggedPage.Id
                             select p).Any();


                        if (!urlTitleClash)
                        {
                            break;
                        }

                        urlTitle = $"{draggedPage.UrlTitle}{counter++}";
                    }

                    draggedPage.UrlTitle = urlTitle;

                    // Real drop index takes into account pages from other locales
                    int realDropIndex = GetRealDropIndex(draggedPage, newParentPageId, dropIndex);

                    draggedPage.MoveTo(newParentPageId, realDropIndex, false);

                    DataFacade.Update(draggedPage);

                    EntityTokenCacheFacade.ClearCache(draggedPage.GetDataEntityToken());

                    transactionScope.Complete();
                }
            }
            else
            {
                throw new NotImplementedException();
            }


            if (oldParent != null)
            {
                var oldParentParentTreeRefresher = new ParentTreeRefresher(flowControllerServicesContainer);
                oldParentParentTreeRefresher.PostRefreshMesseges(oldParent.GetDataEntityToken());
            }
            else
            {
                var oldParentspecificTreeRefresher = new SpecificTreeRefresher(flowControllerServicesContainer);
                oldParentspecificTreeRefresher.PostRefreshMesseges(new PageElementProviderEntityToken(_context.ProviderName));
            }

            var newParentParentTreeRefresher = new ParentTreeRefresher(flowControllerServicesContainer);

            newParentParentTreeRefresher.PostRefreshMesseges(newParentEntityToken);

            return(true);
        }
Ejemplo n.º 23
0
            public FlowToken Execute(EntityToken entityToken, ActionToken actionToken, FlowControllerServicesContainer flowControllerServicesContainer)
            {
                var xslFunction = (IXsltFunction)((DataEntityToken)entityToken).Data;

                string @namespace       = xslFunction.Namespace;
                string name             = xslFunction.Name;
                string functionFullName = @namespace + "." + name;

                Guid xslFunctionId = xslFunction.Id;
                var  function      = FunctionFacade.GetFunction(functionFullName);

                // TODO: default values convertion

                var cshtml = new StringBuilder();

                cshtml.Append(
                    @"@inherits RazorFunction

@functions {
");

                if (!function.Description.IsNullOrEmpty())
                {
                    cshtml.Append(
                        @"    public override string FunctionDescription
    {
        get { return @""" + function.Description.Replace("\"", "\"\"") + @"""; }
    }
");
                }

                if (function.ReturnType != typeof(XhtmlDocument))
                {
                    cshtml.Append(
                        @"    public override Type FunctionReturnType
    {
        get { return typeof(" + function.ReturnType.FullName + @"); }
    }
");
                }

                foreach (var parameterProfile in function.ParameterProfiles)
                {
                    string parameterTemplate =
                        @"  
    [FunctionParameter(%Properties%)]
    public %Type% %Name% { get; set; }%DefaultValueNote%

";
                    var parameterProperties = new List <string>();

                    if (!parameterProfile.Label.IsNullOrEmpty() &&
                        parameterProfile.Label != parameterProfile.Name)
                    {
                        parameterProperties.Add("Label=\"{0}\"".FormatWith(parameterProfile.Label));
                    }

                    if (parameterProfile.HelpDefinition != null &&
                        !string.IsNullOrEmpty(parameterProfile.HelpDefinition.HelpText))
                    {
                        parameterProperties.Add("Help=@\"{0}\""
                                                .FormatWith(parameterProfile.HelpDefinition.HelpText.Replace("\"", "\"\"")));
                    }

                    string parameterName = parameterProfile.Name;

                    IParameter parameter = DataFacade.GetData <IParameter>()
                                           .FirstOrDefault(p => p.OwnerId == xslFunctionId && p.Name == parameterName);

                    string defaultValueTodoHint = string.Empty;
                    if (!parameter.DefaultValueFunctionMarkup.IsNullOrEmpty())
                    {
                        XElement markup = XElement.Parse(parameter.DefaultValueFunctionMarkup);

                        defaultValueTodoHint = @"// TODO: convert default value function markup
    /*" + markup + "*/";
                    }

                    string typeName = GetCSharpFriendlyTypeName(parameterProfile.Type);

                    Verify.IsNotNull(parameter, "Failed to get information about parameter " + parameterName);
                    if (!parameter.WidgetFunctionMarkup.IsNullOrEmpty())
                    {
                        const string start = @"<f:widgetfunction xmlns:f=""http://www.composite.net/ns/function/1.0"" name=""";
                        const string end1  = @""" label="""" bindingsourcename=""""><f:helpdefinition xmlns:f=""http://www.composite.net/ns/function/1.0"" helptext="""" /></f:widgetfunction>";
                        const string end2  = @""" />";


                        if (parameter.WidgetFunctionMarkup.StartsWith(start) &&
                            (parameter.WidgetFunctionMarkup.EndsWith(end1) ||
                             parameter.WidgetFunctionMarkup.EndsWith(end2)))
                        {
                            string str1 = parameter.WidgetFunctionMarkup.Substring(start.Length);
                            string widgetFunctionName = str1.Substring(0, str1.IndexOf("\""));

                            // Skipping default widget for string fields
                            if (widgetFunctionName != GetDefaultWidgetFunctionName(parameterProfile.Type))
                            {
                                parameterProperties.Add("WidgetFunctionName=\"{0}\"".FormatWith(widgetFunctionName));
                            }
                        }
                        else
                        {
                            parameterProperties.Add("WidgetMarkup=@\"{0}\"".FormatWith(parameter.WidgetFunctionMarkup.Replace("\"", "\"\"")));
                        }
                    }

                    cshtml.Append(parameterTemplate
                                  .Replace("%Properties%", string.Join(", ", parameterProperties))
                                  .Replace("%Type%", typeName)
                                  .Replace("%Name%", parameterProfile.Name)
                                  .Replace("%DefaultValueNote%", defaultValueTodoHint));
                }

                cshtml.Append(
                    @"}

@{
");
                var functionCalls = DataFacade.GetData <INamedFunctionCall>().Where(fc => fc.XsltFunctionId == xslFunctionId).ToList();

                foreach (var functionCall in functionCalls)
                {
                    cshtml.Append(@"// TODO: convert function call '{0}' 
/* ".FormatWith(functionCall.Name));

                    XElement markup = XElement.Parse(functionCall.SerializedFunction);

                    cshtml.Append(markup);

                    cshtml.Append(@"*/
");
                }


                cshtml.Append(@"}

<html xmlns=""http://www.w3.org/1999/xhtml"">
<head>
</head>
<body>

@* TODO: convert XSL template: *@

@*
");
                try
                {
                    IFile file = IFileServices.TryGetFile <IXsltFile>(xslFunction.XslFilePath);
                    cshtml.Append(file.ReadAllText());
                }
                catch (Exception ex)
                {
                    cshtml.Append("Failed to load the file: " + ex);
                }

                cshtml.Append(@"
*@
</body>
</html>");

                string fileFolder = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/Razor/" + @namespace.Replace('.', '/'));

                Directory.CreateDirectory(fileFolder);

                string filePath = fileFolder + "/" + name + ".cshtml";

                File.WriteAllText(filePath, cshtml.ToString(), Encoding.UTF8);


                xslFunction.Name = xslFunction.Name + "_backup";
                DataFacade.Update(xslFunction);

                var consoleMsgService = flowControllerServicesContainer.GetService <IManagementConsoleMessageService>();

                consoleMsgService.RefreshTreeSection(new BaseFunctionFolderElementEntityToken("ROOT:XsltBasedFunctionProviderElementProvider"));
                consoleMsgService.RefreshTreeSection(new BaseFunctionFolderElementEntityToken("ROOT:RazorFunctionProviderElementProvider"));

                consoleMsgService.ShowMessage(DialogType.Message, "XSL -> CSHTML",
                                              (@"Template for the razor function '{0}'  have been added. Parts that have to be converted manually:
a) Default values for parameters
b) Function calls
c) Transformation template itself".FormatWith(functionFullName)));

                return(null);
            }
Ejemplo n.º 24
0
        private List <Element> GetElements(List <KeyValuePair <PageLocaleState, IPage> > pages, bool rootPages)
        {
            //ElementDragAndDropInfo dragAndDropInfo = new ElementDragAndDropInfo(typeof(IPage));
            //dragAndDropInfo.AddDropType(typeof(IPage));
            //dragAndDropInfo.SupportsIndexedPosition = true;



            string editPageLabel       = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.EditPage");
            string editPageToolTip     = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.EditPageToolTip");
            string localizePageLabel   = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.LocalizePage");
            string localizePageToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.LocalizePageToolTip");
            string addNewPageLabel     = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.AddSubPageFormat");
            //string addNewPageToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.AddSubPageToolTip");
            string deletePageLabel      = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.Delete");
            string deletePageToolTip    = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.DeleteToolTip");
            string duplicatePageLabel   = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.Duplicate");
            string duplicatePageToolTip = StringResourceSystemFacade.GetString("Composite.Plugins.PageElementProvider", "PageElementProvider.DuplicateToolTip");

            string urlMappingName = null;

            if (UserSettings.ForeignLocaleCultureInfo != null)
            {
                urlMappingName = DataLocalizationFacade.GetCultureTitle(UserSettings.ForeignLocaleCultureInfo);
            }

            var elements     = new Element[pages.Count];
            var allPageTypes = DataFacade.GetData <IPageType>().AsEnumerable();

            ParallelFacade.For("PageElementProvider. Getting elements", 0, pages.Count, i =>
            {
                var kvp    = pages[i];
                IPage page = kvp.Value;

                EntityToken entityToken = page.GetDataEntityToken();

                var dragAndDropInfo = new ElementDragAndDropInfo(typeof(IPage));
                dragAndDropInfo.AddDropType(typeof(IPage));
                dragAndDropInfo.SupportsIndexedPosition = true;

                var element = new Element(_context.CreateElementHandle(entityToken), MakeVisualData(page, kvp.Key, urlMappingName, rootPages), dragAndDropInfo);

                element.PropertyBag.Add("Uri", $"~/page({page.Id})");
                element.PropertyBag.Add("ElementType", "application/x-composite-page");
                element.PropertyBag.Add("DataId", page.Id.ToString());

                if (kvp.Key == PageLocaleState.Own)
                {
                    // Normal actions
                    element.AddAction(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Edit, EditPermissionTypes)))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = editPageLabel,
                            ToolTip        = editPageToolTip,
                            Icon           = PageElementProvider.EditPage,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Edit,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });

                    IPageType parentPageType = allPageTypes.FirstOrDefault(f => f.Id == page.PageTypeId);
                    Verify.IsNotNull(parentPageType, "Failed to find page type by id '{0}'", page.PageTypeId);
                    element.AddAction(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Duplicate, DuplicatePermissionTypes)))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = duplicatePageLabel,
                            ToolTip        = duplicatePageToolTip,
                            Icon           = PageElementProvider.DuplicatePage,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Add,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });

                    foreach (var pageType in page.GetChildPageSelectablePageTypes().OrderByDescending(pt => pt.Id == parentPageType.DefaultChildPageType))
                    {
                        element.AddAction(new ElementAction(new ActionHandle(new PageAddActionToken(pageType.Id, ActionIdentifier.Add, AddPermissionTypes)
                        {
                            DoIgnoreEntityTokenLocking = true
                        }))
                        {
                            VisualData = new ActionVisualizedData
                            {
                                Label          = string.Format(addNewPageLabel, pageType.Name),
                                ToolTip        = pageType.Description,
                                Icon           = PageElementProvider.AddPage,
                                Disabled       = false,
                                ActionLocation = new ActionLocation
                                {
                                    ActionType   = ActionType.Add,
                                    IsInFolder   = false,
                                    IsInToolbar  = true,
                                    ActionGroup  = PrimaryActionGroup,
                                    ActionBundle = "AddPage"
                                }
                            }
                        });
                    }


                    element.AddAction(new ElementAction(new ActionHandle(new ProxyDataActionToken(ActionIdentifier.Delete, DeletePermissionTypes)))
                    {
                        VisualData = new ActionVisualizedData
                        {
                            Label          = deletePageLabel,
                            ToolTip        = deletePageToolTip,
                            Icon           = DeletePage,
                            Disabled       = false,
                            ActionLocation = new ActionLocation
                            {
                                ActionType  = ActionType.Delete,
                                IsInFolder  = false,
                                IsInToolbar = true,
                                ActionGroup = PrimaryActionGroup
                            }
                        }
                    });

                    _pageAssociatedHelper.AttachElementActions(element, page);
                }
                else if (kvp.Key == PageLocaleState.ForeignActive)
                {
                    // Localized actions
                    bool addAction = false;

                    Guid parentId = page.GetParentId();
                    if (parentId == Guid.Empty)
                    {
                        addAction = true;
                    }
                    else
                    {
                        using (new DataScope(DataScopeIdentifier.Administrated, UserSettings.ActiveLocaleCultureInfo))
                        {
                            bool exists = DataFacade.GetData <IPage>(f => f.Id == parentId).Any();
                            if (exists)
                            {
                                addAction = true;
                            }
                        }
                    }


                    if (addAction)
                    {
                        element.AddAction(new ElementAction(new ActionHandle(new WorkflowActionToken(WorkflowFacade.GetWorkflowType("Composite.Plugins.Elements.ElementProviders.PageElementProvider.LocalizePageWorkflow"), LocalizePermissionTypes)))
                        {
                            VisualData = new ActionVisualizedData
                            {
                                Label          = localizePageLabel,
                                ToolTip        = localizePageToolTip,
                                Icon           = PageElementProvider.LocalizePage,
                                Disabled       = false,
                                ActionLocation = new ActionLocation
                                {
                                    ActionType  = ActionType.Edit,
                                    IsInFolder  = false,
                                    IsInToolbar = true,
                                    ActionGroup = PrimaryActionGroup
                                }
                            }
                        });
                    }
                }

                elements[i] = element;
            });

            return(new List <Element>(elements));
        }
Ejemplo n.º 25
0
 /// <exclude />
 public static void DeleteAll(Guid userGroupId)
 {
     DataFacade.Delete <IUserGroupActivePerspective>(f => f.UserGroupId == userGroupId);
 }
Ejemplo n.º 26
0
        public static string Edit(IssueResult log)
        {
            var paramList = new List <ParameterValue> {
                new ParameterValue("idInstance", log.IDInstance)
            };

            if (!String.IsNullOrEmpty(log.DateDryTo))
            {
                paramList.Add(new ParameterValue("DateDryTo", log.DateDryTo)); //
            }
            if (!String.IsNullOrEmpty(log.ATGCommFail))
            {
                paramList.Add(new ParameterValue("ATGCommFail", Convert.ToBoolean(log.ATGCommFail) ? 1 : 0)); //
            }
            if (!String.IsNullOrEmpty(log.ATGOperational))
            {
                paramList.Add(new ParameterValue("ATGOperational", Convert.ToBoolean(log.ATGOperational) ? 1 : 0)); //
            }
            if (!String.IsNullOrEmpty(log.DateDryFrom))
            {
                paramList.Add(new ParameterValue("DateDryFrom", log.DateDryFrom)); //
            }

            if (!String.IsNullOrEmpty(log.DateLogged))
            {
                paramList.Add(new ParameterValue("DateLogged", log.DateLogged)); //
            }

            if (!String.IsNullOrEmpty(log.PODReference))
            {
                paramList.Add(new ParameterValue("PODReference", log.PODReference)); //
            }

            if (!String.IsNullOrEmpty(log.Comment))
            {
                paramList.Add(new ParameterValue("Comment", log.Comment)); //
            }
            if (!String.IsNullOrEmpty(log.Claim))
            {
                paramList.Add(new ParameterValue("Claim", Convert.ToBoolean(log.Claim) ? 1 : 0)); //
            }
            if (!String.IsNullOrEmpty(log.ClaimComment))
            {
                paramList.Add(new ParameterValue("ClaimComment", log.ClaimComment)); //
            }
            if (!String.IsNullOrEmpty(log.Volume))
            {
                paramList.Add(new ParameterValue("Volume", log.Volume)); //
            }

            if (!String.IsNullOrEmpty(log.DealerUser))
            {
                paramList.Add(new ParameterValue("DealerUser", log.DealerUser));
            }
            if (log.IDInstance != null)
            {
                paramList.Add(new ParameterValue("idInstance", log.IDInstance));
            }

            if (!String.IsNullOrEmpty(log.IDIssueType))
            {
                paramList.Add(new ParameterValue("idIssueType", log.IDIssueType)); //
            }
            if (log.IDProduct != null)
            {
                paramList.Add(new ParameterValue("idProduct", log.IDProduct)); //
            }
            if (log.IDRequestStatus != null)
            {
                paramList.Add(new ParameterValue("idRequestStatus", log.IDRequestStatus)); //
            }
            if (log.IDSOC != null)
            {
                paramList.Add(new ParameterValue("idSOC", log.IDSOC)); //
            }
            if (log.IDTank != null)
            {
                paramList.Add(new ParameterValue("idTank", log.IDTank)); //
            }
            if (!String.IsNullOrEmpty(log.Name))
            {
                paramList.Add(new ParameterValue("Name", log.Name)); //
            }
            if (!String.IsNullOrEmpty(log.UserId))
            {
                paramList.Add(new ParameterValue("UserId", log.UserId)); //
            }

            paramList.Add(new ParameterValue("Adding", log.Adding ? 1 : 0)); //


            var r = DataFacade.GetDataRow("InstanceEdit",
                                          paramList.ToArray());

            string idInstance = r["idInstance"].ToString();

            return(idInstance);
        }
Ejemplo n.º 27
0
        public static IEnumerable <Dealer> SearchDealerUpdates(Dealer dealer)
        {
            var paramList = new List <ParameterValue>();

            if ((dealer.StartYear == dealer.EndYear) && (dealer.StartMonth == dealer.EndMonth))
            {
                if (dealer.EndMonth == 12)
                {
                    dealer.EndYear++;
                    dealer.EndMonth = 1;
                }
                else
                {
                    dealer.EndMonth++;
                }
            }


            if (dealer.StartYear != null)
            {
                paramList.Add(new ParameterValue("StartYear", dealer.StartYear));
            }
            if (dealer.StartMonth != null)
            {
                paramList.Add(new ParameterValue("StartMonth", dealer.StartMonth));
            }
            if (dealer.EndYear != null)
            {
                paramList.Add(new ParameterValue("EndYear", dealer.EndYear));
            }
            if (dealer.EndMonth != null)
            {
                paramList.Add(new ParameterValue("EndMonth", dealer.EndMonth));
            }


            var dataTable = DataFacade.GetDataTable("SearchDealerUpdates",
                                                    paramList.ToArray());


            return((from DataRow r in dataTable.Rows
                    select new Dealer
            {
                DealerId = r["DealerId"].ToString(),
                DealerName = (r["DealerName"].ToString()),
                DealerEmail = r["DealerEmail"].ToString(),
                DealerTelCountry = r["DealerTelCountry"].ToString(),
                DealerTelCode = r["DealerTelCode"].ToString(),
                DealerTelNo = r["DealerTelNo"].ToString(),
                DealerAltTelCountry = r["DealerAltTelCountry"].ToString(),
                DealerAltTelCode = r["DealerAltTelCode"].ToString(),
                DealerAltTelNo = r["DealerAltTelNo"].ToString(),
                DealerFaxCountry = r["DealerFaxCountry"].ToString(),
                DealerFaxCode = r["DealerFaxCode"].ToString(),
                DealerFaxNo = r["DealerFaxNo"].ToString(),
                DealerPostalAddress = r["DealerPostalAddress"].ToString(),
                DealerPostalSuburb = r["DealerPostalSuburb"].ToString(),
                DealerPostalCode = r["DealerPostalCode"].ToString(),
                DealerPhysicalAddress = r["DealerPhysicalAddress"].ToString(),
                DealerPhysicalSuburb = r["DealerPhysicalSuburb"].ToString(),
                DealerPhysicalCode = r["DealerPhysicalCode"].ToString(),
                UpdateDate = r["UpdateDate"].ToString()
            }).ToList());
        }
Ejemplo n.º 28
0
        public static IEnumerable <IssueResult> Search(Issue log)
        {
            var paramList = new List <ParameterValue> {
                new ParameterValue("DateDryFrom", log.DateDryFrom), new ParameterValue("DateDryTo", log.DateDryTo)
            };


            if (!String.IsNullOrEmpty(log.DealerUser) && log.DealerUser.Trim() != "0")
            {
                paramList.Add(new ParameterValue("DealerUser", log.DealerUser));
            }
            if (log.IDInstance != null)
            {
                paramList.Add(new ParameterValue("idInstance", log.IDInstance));
            }
            if (log.IDProduct != null && log.IDProduct != 0)
            {
                paramList.Add(new ParameterValue("idProduct", log.IDProduct));
            }
            if (!String.IsNullOrEmpty(log.IDRequestStatus) && log.IDRequestStatus != "0")
            {
                paramList.Add(new ParameterValue("idRequestStatus", log.IDRequestStatus));
            }
            if (log.IDSoc != null && log.IDSoc != 0)
            {
                paramList.Add(new ParameterValue("idSoc", log.IDSoc));
            }
            if (log.IDTank != null && log.IDTank != 0)
            {
                paramList.Add(new ParameterValue("idTank", log.IDTank));
            }
            if (!String.IsNullOrEmpty(log.Name))
            {
                paramList.Add(new ParameterValue("Name", log.Name));
            }
            if (!String.IsNullOrEmpty(log.OutletNo))
            {
                paramList.Add(new ParameterValue("OutletNo", log.OutletNo));
            }
            if (!String.IsNullOrEmpty(log.UserId))
            {
                paramList.Add(new ParameterValue("UserId", log.UserId));
            }

            var dataTable = DataFacade.GetDataTable("InstanceSearch",
                                                    paramList.ToArray());


            return((from DataRow r in dataTable.Rows
                    select new IssueResult
            {
                DateDryFrom = r["DateDryFrom"].ToString(),
                DateDryTo = r["DateDryTo"].ToString(),
                ATGCommFail = r["ATGCommFail"].ToString(),
                ATGOperational = r["ATGOperational"].ToString(),
                Claim = r["Claim"].ToString(),
                ClaimComment = r["ClaimComment"].ToString(),
                DealerName = r["DealerName"].ToString(),
                IDInstance = (r["idInstance"].ToString()),
                IDIssueType = (r["idIssueType"].ToString()),
                IDProduct = (r["idProduct"].ToString()),
                ProductName = (r["ProductName"].ToString()),
                IDRequestStatus = (r["idRequestStatus"].ToString()),
                RequestStatusName = (r["RequestStatusName"].ToString()),
                IDSOC = (r["idSOC"].ToString()),
                IDTank = (r["idTank"].ToString()),
                TankName = (r["TankName"].ToString()),
                UserId = r["UserId"].ToString()
            }).ToList());
        }
        private void saveTypeCodeActivity_Save_ExecuteCode(object sender, EventArgs e)
        {
            try
            {
                string typeName             = this.GetBinding <string>(this.NewTypeNameBindingName);
                string typeNamespace        = this.GetBinding <string>(this.NewTypeNamespaceBindingName);
                string typeTitle            = this.GetBinding <string>(this.NewTypeTitleBindingName);
                bool   hasCaching           = this.GetBinding <bool>(this.HasCachingNameBindingName);
                bool   hasPublishing        = this.GetBinding <bool>(this.HasPublishingBindingName);
                bool   hasLocalization      = this.GetBinding <bool>("HasLocalization");
                string labelFieldName       = this.GetBinding <string>(this.LabelFieldNameBindingName);
                var    dataFieldDescriptors = this.GetBinding <List <DataFieldDescriptor> >(this.DataFieldDescriptorsBindingName);


                GeneratedTypesHelper helper;

                Type interfaceType = null;
                if (this.BindingExist("InterfaceType"))
                {
                    interfaceType = this.GetBinding <Type>("InterfaceType");

                    helper = new GeneratedTypesHelper(interfaceType);
                }
                else
                {
                    helper = new GeneratedTypesHelper();
                }

                string errorMessage;
                if (!helper.ValidateNewTypeName(typeName, out errorMessage))
                {
                    this.ShowFieldMessage("NewTypeName", errorMessage);
                    return;
                }

                if (!helper.ValidateNewTypeNamespace(typeNamespace, out errorMessage))
                {
                    this.ShowFieldMessage("NewTypeNamespace", errorMessage);
                    return;
                }

                if (!helper.ValidateNewTypeFullName(typeName, typeNamespace, out errorMessage))
                {
                    this.ShowFieldMessage("NewTypeName", errorMessage);
                    return;
                }

                if (!helper.ValidateNewFieldDescriptors(dataFieldDescriptors, null, out errorMessage))
                {
                    this.ShowMessage(
                        DialogType.Warning,
                        "${Composite.Plugins.GeneratedDataTypesElementProvider, AddNewCompositionTypeWorkflow.ErrorTitle}",
                        errorMessage
                        );
                    return;
                }

                if (helper.IsEditProcessControlledAllowed)
                {
                    helper.SetPublishControlled(hasPublishing);
                    helper.SetLocalizedControlled(hasLocalization);
                }

                helper.SetCachable(hasCaching);
                helper.SetNewTypeFullName(typeName, typeNamespace);
                helper.SetNewTypeTitle(typeTitle);
                helper.SetNewFieldDescriptors(dataFieldDescriptors, null, labelFieldName);

                if (!this.BindingExist("InterfaceType"))
                {
                    Type targetType = TypeManager.GetType(this.Payload);

                    helper.SetForeignKeyReference(targetType, Composite.Data.DataAssociationType.Composition);
                }

                bool originalTypeDataExists = false;
                if (interfaceType != null)
                {
                    originalTypeDataExists = DataFacade.HasDataInAnyScope(interfaceType);
                }

                if (helper.TryValidateUpdate(originalTypeDataExists, out errorMessage) == false)
                {
                    this.ShowMessage(
                        DialogType.Warning,
                        "${Composite.Plugins.GeneratedDataTypesElementProvider, AddNewCompositionTypeWorkflow.ErrorTitle}",
                        errorMessage
                        );
                    return;
                }

                helper.CreateType(originalTypeDataExists);

                if (originalTypeDataExists)
                {
                    SetSaveStatus(true);
                }
                else
                {
                    string      serializedTypeName = TypeManager.SerializeType(helper.InterfaceType);
                    EntityToken entityToken        = new GeneratedDataTypesElementProviderTypeEntityToken(
                        serializedTypeName,
                        this.EntityToken.Source,
                        GeneratedDataTypesElementProviderRootEntityToken.PageMetaDataTypeFolderId);

                    SetSaveStatus(true, entityToken);
                }



                this.UpdateBinding("InterfaceType", helper.InterfaceType);

                this.WorkflowResult = TypeManager.SerializeType(helper.InterfaceType);

                UserSettings.LastSpecifiedNamespace = typeNamespace;

                ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher();
                parentTreeRefresher.PostRefreshMesseges(this.EntityToken);
            }
            catch (Exception ex)
            {
                LoggingService.LogCritical("AddNewCompositionTypeWorkflow", ex);

                this.ShowMessage(DialogType.Error, ex.Message, ex.Message);
            }
        }
Ejemplo n.º 30
0
 public static void TemplateQuestionsDelete(string articles)
 {
     DataFacade.ExecuteNonQuery("TemplateQuestionDelete",
                                new ParameterValue("idTemplateQuestions", articles));
 }
Ejemplo n.º 31
0
        private void Delete <T>(IEnumerable <T> dataset, bool suppressEventing, CascadeDeleteType cascadeDeleteType, bool referencesFromAllScopes, HashSet <DataSourceId> dataPendingDeletion)
            where T : class, IData
        {
            Verify.ArgumentNotNull(dataset, nameof(dataset));

            dataset = dataset.Evaluate();

            foreach (var data in dataset)
            {
                var dataSourceId = data.DataSourceId;
                if (!dataPendingDeletion.Contains(dataSourceId))
                {
                    dataPendingDeletion.Add(dataSourceId);
                }
            }

            if (cascadeDeleteType != CascadeDeleteType.Disable)
            {
                foreach (IData element in dataset)
                {
                    Verify.ArgumentCondition(element != null, nameof(dataset), "dataset may not contain nulls");

                    if (!element.IsDataReferred())
                    {
                        continue;
                    }

                    Type interfaceType = element.DataSourceId.InterfaceType;

                    // Not deleting references if the data is versioned and not all of the
                    // versions of the element are to be deleted
                    if (element is IVersioned)
                    {
                        var key      = element.GetUniqueKey();
                        var versions = DataFacade.TryGetDataVersionsByUniqueKey(interfaceType, key).ToList();

                        if (versions.Count > 1 &&
                            (dataset.Count() < versions.Count ||
                             !versions.All(v => dataPendingDeletion.Contains(v.DataSourceId))))
                        {
                            continue;
                        }
                    }

                    Verify.IsTrue(cascadeDeleteType != CascadeDeleteType.Disallow, "One of the given datas is referenced by one or more datas");

                    element.RemoveOptionalReferences();

                    IEnumerable <IData> referees;
                    using (new DataScope(element.DataSourceId.DataScopeIdentifier))
                    {
                        // For some weird reason, this line does not work.... /MRJ
                        // IEnumerable<IData> referees = dataset.GetRefereesRecursively();
                        referees = element.GetReferees(referencesFromAllScopes)
                                   .Where(reference => !dataPendingDeletion.Contains(reference.DataSourceId))
                                   .Evaluate();
                    }

                    foreach (IData referee in referees)
                    {
                        if (!referee.CascadeDeleteAllowed(interfaceType))
                        {
                            throw new InvalidOperationException("One of the given datas is referenced by one or more datas that does not allow cascade delete");
                        }
                    }

                    Delete <IData>(referees, suppressEventing, cascadeDeleteType, referencesFromAllScopes);
                }
            }


            Dictionary <string, Dictionary <Type, List <IData> > > sortedDatas = dataset.ToDataProviderAndInterfaceTypeSortedDictionary();

            foreach (KeyValuePair <string, Dictionary <Type, List <IData> > > providerPair in sortedDatas)
            {
                foreach (KeyValuePair <Type, List <IData> > interfaceTypePair in providerPair.Value)
                {
                    DataProviderPluginFacade.Delete(providerPair.Key, interfaceTypePair.Value.Select(d => d.DataSourceId));

                    if (DataCachingFacade.IsTypeCacheable(interfaceTypePair.Key))
                    {
                        DataCachingFacade.ClearCache(interfaceTypePair.Key, interfaceTypePair.Value.First().DataSourceId.DataScopeIdentifier);
                    }
                }
            }


            if (!suppressEventing)
            {
                foreach (IData element in dataset)
                {
                    DataEventSystemFacade.FireDataDeletedEvent(element.DataSourceId.InterfaceType, element);
                }
            }
        }
Ejemplo n.º 32
0
        public void Import(string rssPath, Guid pageId)
        {
            using (var conn = new DataConnection(PublicationScope.Unpublished))
            {
                var mapLinks = new Dictionary <string, string>();

                var       client = new WebClient();
                XmlReader reader = new SyndicationFeedXmlReader(client.OpenRead(rssPath));


                var feed = SyndicationFeed.Load(reader);
                reader.Close();

                var links         = feed.Links.Select(d => d.Uri.ToString()).ToList();
                var defaultAuthor = DataFacade.GetData <Authors>().Select(d => d.Name).TheOneOrDefault() ?? "Anonymous";
                var blogAuthor    = feed.Authors.Select(d => d.Name).FirstOrDefault()
                                    ?? feed.ElementExtensions.ReadElementExtensions <string>("creator", "http://purl.org/dc/elements/1.1/").FirstOrDefault();;


                foreach (var item in feed.Items)
                {
                    using (new DataScope(PublicationScope.Published))
                    {
                        var itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime;
                        foreach (var itemLink in item.Links)
                        {
                            mapLinks[itemLink.Uri.OriginalString] = BlogFacade.BuildBlogInternalPageUrl(itemDate, item.Title.Text, pageId);
                        }
                    }
                }

                foreach (var item in feed.Items)
                {
                    try
                    {
                        var    content  = new XDocument();
                        string text     = null;
                        var    itemDate = item.PublishDate == DateTimeOffset.MinValue ? DateTime.Now : item.PublishDate.DateTime;
                        string folder   = string.Format(FolderFormat, itemDate, CleanFileName(item.Title.Text));

                        if (text == null && item.Content != null)
                        {
                            var syndicationContent = item.Content as TextSyndicationContent;
                            if (syndicationContent != null)
                            {
                                text = syndicationContent.Text;
                            }
                        }
                        if (text == null)
                        {
                            text = item.ElementExtensions.ReadElementExtensions <string>("encoded", "http://purl.org/rss/1.0/modules/content/")
                                   .FirstOrDefault();
                        }
                        if (text == null && item.Summary != null)
                        {
                            text = item.Summary.Text;
                        }

                        content = MarkupTransformationServices.TidyHtml(text).Output;

                        //somewhere empty <title></title> created
                        foreach (var title in content.Descendants(Namespaces.Xhtml + "title").ToList())
                        {
                            if (string.IsNullOrWhiteSpace(title.Value))
                            {
                                title.Remove();
                            }
                        }


                        foreach (var img in content.Descendants(Namespaces.Xhtml + "img"))
                        {
                            var src = img.GetAttributeValue("src");
                            if (!string.IsNullOrEmpty(src))
                            {
                                foreach (var link in links)
                                {
                                    if (src.StartsWith(link))
                                    {
                                        var newImage = ImportMedia(src, folder);
                                        if (newImage != null)
                                        {
                                            img.SetAttributeValue("src", MediaUrlHelper.GetUrl(newImage, true));
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        foreach (var a in content.Descendants(Namespaces.Xhtml + "a"))
                        {
                            var href = a.GetAttributeValue("href");
                            if (!string.IsNullOrEmpty(href))
                            {
                                foreach (var link in links)
                                {
                                    if (href.StartsWith(link))
                                    {
                                        if (mapLinks.ContainsKey(href))
                                        {
                                            a.SetAttributeValue("href", mapLinks[href]);
                                        }
                                        else
                                        {
                                            var extension = Path.GetExtension(href).ToLower();
                                            switch (extension)
                                            {
                                            case ".jpg":
                                            case ".png":
                                            case ".gif":
                                            case ".pdf":
                                            case ".doc":
                                            case ".docx":
                                                var newMedia = ImportMedia(href, folder);
                                                a.SetAttributeValue("href", MediaUrlHelper.GetUrl(newMedia, true));
                                                break;

                                            default:
                                                a.SetAttributeValue("href", new Uri(href).PathAndQuery);
                                                break;
                                            }
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                        string blogImage      = null;
                        var    enclosureImage = item.Links.Where(f => f.RelationshipType == "enclosure" && f.MediaType.StartsWith("image/")).FirstOrDefault();

                        if (enclosureImage != null)
                        {
                            blogImage = ImportMedia(enclosureImage.Uri.ToString(), folder).KeyPath;
                        }

                        var blogItem = DataFacade.BuildNew <Entries>();

                        var match = Regex.Match(item.Id, @"\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\b", RegexOptions.IgnoreCase);
                        if (match.Success)
                        {
                            var id = Guid.Empty;
                            Guid.TryParse(match.Groups[0].Value, out id);
                            if (id != Guid.Empty && !DataFacade.GetData <Entries>(d => d.Id == id).Any())
                            {
                                blogItem.Id = id;
                            }
                        }

                        blogItem.Title  = item.Title.Text;
                        blogItem.PageId = pageId;
                        blogItem.Teaser = string.Empty;

                        var blogItemAuthor = item.Authors.Select(d => d.Name ?? d.Email).FirstOrDefault() ??
                                             item.ElementExtensions.ReadElementExtensions <string>("creator",
                                                                                                   "http://purl.org/dc/elements/1.1/").FirstOrDefault();


                        blogItem.Author = ImportAuthor(blogItemAuthor ?? blogAuthor ?? defaultAuthor);

                        var tagType = DataFacade.GetData <TagType>().FirstOrDefault();
                        if (tagType == null)
                        {
                            tagType      = DataFacade.BuildNew <TagType>();
                            tagType.Name = "Categories";
                            DataFacade.AddNew(tagType);
                        }

                        foreach (var tag in item.Categories)
                        {
                            ImportTag(tag.Name, tagType.Id);
                        }
                        blogItem.Tags = string.Join(",", item.Categories.Select(d => d.Name));

                        blogItem.Content = content.ToString();
                        blogItem.Date    = itemDate;
                        blogItem.Image   = blogImage;

                        blogItem.PublicationStatus = GenericPublishProcessController.Draft;
                        blogItem = DataFacade.AddNew(blogItem);
                        blogItem.PublicationStatus = GenericPublishProcessController.Published;
                        DataFacade.Update(blogItem);



                        //break;
                    }
                    catch (Exception ex)
                    {
                        Log.LogError("Import Blog", ex);
                    }
                }

                //1st redirect
                var mapLinks2 = new Dictionary <string, string>();
                foreach (var maplink in mapLinks.ToList())
                {
                    var request = (HttpWebRequest)WebRequest.Create(maplink.Key);
                    request.AllowAutoRedirect = false;
                    var response = (HttpWebResponse)request.GetResponse();
                    var location = response.Headers["Location"];
                    if (!string.IsNullOrWhiteSpace(location))
                    {
                        location = new Uri(new Uri(maplink.Key), location).OriginalString;
                        foreach (var link in links)
                        {
                            if (location.StartsWith(link))
                            {
                                if (!mapLinks.ContainsKey(location))
                                {
                                    mapLinks[location]  = maplink.Value;
                                    mapLinks2[location] = maplink.Value;
                                }
                            }
                        }
                    }
                }
                //2nd redirect
                foreach (var maplink in mapLinks2.ToList())
                {
                    var request = (HttpWebRequest)WebRequest.Create(maplink.Key);
                    request.AllowAutoRedirect = false;
                    var response = (HttpWebResponse)request.GetResponse();
                    var location = response.Headers["Location"];
                    if (!string.IsNullOrWhiteSpace(location))
                    {
                        location = new Uri(new Uri(maplink.Key), location).OriginalString;
                        foreach (var link in links)
                        {
                            if (location.StartsWith(link))
                            {
                                if (!mapLinks.ContainsKey(location))
                                {
                                    mapLinks[location] = maplink.Value;
                                }
                            }
                        }
                    }
                }


                var mapFile = PathUtil.Resolve(@"~\App_Data\RequestUrlRemappings.xml");
                var map     = new XElement("RequestUrlRemappings");
                if (File.Exists(mapFile))
                {
                    map = XElement.Load(mapFile);
                }

                map.Add(new XComment(" Imported Blog " + DateTime.Now));
                map.Add(
                    mapLinks.Select(d => new XElement("Remapping",
                                                      new XAttribute("requestPath", new Uri(d.Key).PathAndQuery),
                                                      new XAttribute("rewritePath", d.Value)
                                                      ))

                    );
                map.Add(new XComment(" "));

                map.Save(mapFile);
            }
        }
Ejemplo n.º 33
0
 public static void TemplateQuestionnaireDelete(string list)
 {
     DataFacade.ExecuteNonQuery("TemplateQuestionnaireDelete",
                                new[] { new ParameterValue("idTemplateQuestionnaires", list) });
 }
Ejemplo n.º 34
0
        public static IEnumerable <SupplierSearch> Search(SupplierSearch suppliersearch)
        {
            var paramList = new List <ParameterValue>
            {
                new ParameterValue("StartDate", suppliersearch.StartDate),
                new ParameterValue("EndDate", suppliersearch.EndDate),
                new ParameterValue("Archive", suppliersearch.Supplier.Archive ? 1 : 0)
            };

            if (!String.IsNullOrEmpty(suppliersearch.Requester.RequesterID.ToString()))
            {
                paramList.Add(new ParameterValue("RequesterID", suppliersearch.Requester.RequesterID));
            }

            if (!String.IsNullOrEmpty(suppliersearch.Supplier.SupplierName))
            {
                paramList.Add(new ParameterValue("SupplierName", suppliersearch.Supplier.SupplierName));
            }
            if (!String.IsNullOrEmpty(suppliersearch.Supplier.MasterDataStatus))
            {
                paramList.Add(new ParameterValue("MasterDataStatus", suppliersearch.Supplier.MasterDataStatus));
            }
            if (!String.IsNullOrEmpty(suppliersearch.Supplier.Province))
            {
                paramList.Add(new ParameterValue("Province", suppliersearch.Supplier.Province));
            }
            if (!String.IsNullOrEmpty(suppliersearch.Requester.RequesterName))
            {
                paramList.Add(new ParameterValue("RequesterName", suppliersearch.Requester.RequesterName));
            }

            var dataTable = DataFacade.GetDataTable("SupplierSearch",
                                                    paramList.ToArray());

            //null approved date
            DateTime?nullDate;

            nullDate = null;

            return((from DataRow r in dataTable.Rows
                    select new SupplierSearch
            {
                Supplier = new Supplier
                {
                    SupplierName = r["SupplierName"].ToString(),
                    Province = r["Province"].ToString(),
                    SupplierSpecialistStatus = r["SupplierSpecialistStatus"].ToString(),
                    CategoryManager = r["CategoryManager"].ToString(),
                    MasterDataComment = r["MasterDataComment"].ToString(),
                    MasterDataStatusDate = !String.IsNullOrEmpty(r["MasterDataStatusDate"].ToString()) ? Convert.ToDateTime(r["MasterDataStatusDate"]) : nullDate,
                    MasterDataStatus = r["MasterDataStatus"].ToString(),
                    CategoryManagerStatus = r["CategoryManagerStatus"].ToString(),
                    SupplierID = (int)r["SupplierID"],
                    Archive = Convert.ToBoolean(r["Archive"].ToString())
                },
                Requester = new Requester
                {
                    RequestDate = Convert.ToDateTime(r["RequestDate"]),
                    Motivation = r["Motivation"].ToString(),
                    RequesterName = r["RequesterName"].ToString(),
                    RequesterID = (int)r["RequesterID"],
                    ContactNo = r["ContactNo"].ToString(),
                    EmailAddress = r["EmailAddress"].ToString(),
                    SiteName = r["SiteName"].ToString(),
                    SiteNumber = r["SiteNumber"].ToString()
                }
            }).ToList());
        }
Ejemplo n.º 35
0
 private static bool Exists(IMediaFile file)
 {
     return(DataFacade.GetData <IMediaFile>().Any(x => x.FolderPath == file.FolderPath && x.FileName == file.FileName));
 }
Ejemplo n.º 36
0
 /// <exclude />
 public static IEnumerable <IPage> GetMetaDataAffectedPagesByPageTypeId(Guid definingPageTypeId)
 {
     return(DataFacade.GetData <IPage>().Where(f => f.PageTypeId == definingPageTypeId));
 }